Added BeefCore for multiblock api
This commit is contained in:
parent
bb58ae8632
commit
d7ae47e956
18 changed files with 2563 additions and 2 deletions
21
src/main/java/erogenousbeef/LICENSE.txt
Normal file
21
src/main/java/erogenousbeef/LICENSE.txt
Normal file
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 "Erogenous Beef"
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
5
src/main/java/erogenousbeef/README.txt
Normal file
5
src/main/java/erogenousbeef/README.txt
Normal file
|
@ -0,0 +1,5 @@
|
|||
This code is not ours! We are using BeefCore.
|
||||
|
||||
https://github.com/erogenousbeef/BeefCore
|
||||
|
||||
For Licence infomation look at https://github.com/erogenousbeef/BeefCore/blob/master/README.md
|
45
src/main/java/erogenousbeef/coreTR/common/BeefCoreLog.java
Normal file
45
src/main/java/erogenousbeef/coreTR/common/BeefCoreLog.java
Normal file
|
@ -0,0 +1,45 @@
|
|||
package erogenousbeef.coreTR.common;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
|
||||
public class BeefCoreLog {
|
||||
|
||||
private static final String CHANNEL = "BeefCore";
|
||||
|
||||
public static void log(Level level, String format, Object... data)
|
||||
{
|
||||
FMLLog.log(level, format, data);
|
||||
}
|
||||
|
||||
public static void fatal(String format, Object... data)
|
||||
{
|
||||
log(Level.FATAL, format, data);
|
||||
}
|
||||
|
||||
public static void error(String format, Object... data)
|
||||
{
|
||||
log(Level.ERROR, format, data);
|
||||
}
|
||||
|
||||
public static void warning(String format, Object... data)
|
||||
{
|
||||
log(Level.WARN, format, data);
|
||||
}
|
||||
|
||||
public static void info(String format, Object... data)
|
||||
{
|
||||
log(Level.INFO, format, data);
|
||||
}
|
||||
|
||||
public static void debug(String format, Object... data)
|
||||
{
|
||||
log(Level.DEBUG, format, data);
|
||||
}
|
||||
|
||||
public static void trace(String format, Object... data)
|
||||
{
|
||||
log(Level.TRACE, format, data);
|
||||
}
|
||||
}
|
128
src/main/java/erogenousbeef/coreTR/common/CoordTriplet.java
Normal file
128
src/main/java/erogenousbeef/coreTR/common/CoordTriplet.java
Normal file
|
@ -0,0 +1,128 @@
|
|||
package erogenousbeef.coreTR.common;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public CoordTriplet[] getNeighbors() {
|
||||
return new CoordTriplet[]{
|
||||
new CoordTriplet(x + 1, y, z),
|
||||
new CoordTriplet(x - 1, y, z),
|
||||
new CoordTriplet(x, y + 1, z),
|
||||
new CoordTriplet(x, y - 1, z),
|
||||
new CoordTriplet(x, y, z + 1),
|
||||
new CoordTriplet(x, y, z - 1)
|
||||
};
|
||||
}
|
||||
|
||||
///// IComparable
|
||||
|
||||
@Override
|
||||
public int compareTo(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;
|
||||
}
|
||||
|
||||
///// Really confusing code that should be cleaned up
|
||||
|
||||
public ForgeDirection getDirectionFromSourceCoords(int x, int y, int z) {
|
||||
if(this.x < x) { return ForgeDirection.WEST; }
|
||||
else if(this.x > x) { return ForgeDirection.EAST; }
|
||||
else if(this.y < y) { return ForgeDirection.DOWN; }
|
||||
else if(this.y > y) { return ForgeDirection.UP; }
|
||||
else if(this.z < z) { return ForgeDirection.SOUTH; }
|
||||
else if(this.z > z) { return ForgeDirection.NORTH; }
|
||||
else { return ForgeDirection.UNKNOWN; }
|
||||
}
|
||||
|
||||
public ForgeDirection getOppositeDirectionFromSourceCoords(int x, int y, int z) {
|
||||
if(this.x < x) { return ForgeDirection.EAST; }
|
||||
else if(this.x > x) { return ForgeDirection.WEST; }
|
||||
else if(this.y < y) { return ForgeDirection.UP; }
|
||||
else if(this.y > y) { return ForgeDirection.DOWN; }
|
||||
else if(this.z < z) { return ForgeDirection.NORTH; }
|
||||
else if(this.z > z) { return ForgeDirection.SOUTH; }
|
||||
else { return ForgeDirection.UNKNOWN; }
|
||||
}
|
||||
|
||||
@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,15 @@
|
|||
package erogenousbeef.coreTR.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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,191 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
|
||||
/**
|
||||
* 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 erogenousbeef.coreTR.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,15 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import cpw.mods.fml.common.gameevent.TickEvent;
|
||||
|
||||
public class MultiblockClientTickHandler {
|
||||
|
||||
@SubscribeEvent
|
||||
public void onClientTick(TickEvent.ClientTickEvent event) {
|
||||
if(event.phase == TickEvent.Phase.START) {
|
||||
MultiblockRegistry.tickStart(Minecraft.getMinecraft().theWorld);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,905 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.chunk.Chunk;
|
||||
import net.minecraft.world.chunk.IChunkProvider;
|
||||
import erogenousbeef.coreTR.common.BeefCoreLog;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
|
||||
/**
|
||||
* This class contains the base logic for "multiblock controllers". Conceptually, they are
|
||||
* meta-TileEntities. They govern the logic for an associated group of TileEntities.
|
||||
*
|
||||
* Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop.
|
||||
*/
|
||||
public abstract class MultiblockControllerBase {
|
||||
public static final short DIMENSION_UNBOUNDED = -1;
|
||||
|
||||
// Multiblock stuff - do not mess with
|
||||
protected World worldObj;
|
||||
|
||||
// Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled
|
||||
protected enum AssemblyState { Disassembled, Assembled, Paused };
|
||||
protected AssemblyState assemblyState;
|
||||
|
||||
protected HashSet<IMultiblockPart> connectedParts;
|
||||
|
||||
/** This is a deterministically-picked coordinate that identifies this
|
||||
* multiblock uniquely in its dimension.
|
||||
* Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation.
|
||||
* i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference.
|
||||
* If something has the same X but a lower Y coordinate, it will be the reference. Etc.
|
||||
*/
|
||||
private CoordTriplet referenceCoord;
|
||||
|
||||
/**
|
||||
* Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine
|
||||
* is not a cube/rectangular prism.
|
||||
*/
|
||||
private CoordTriplet minimumCoord;
|
||||
|
||||
/**
|
||||
* Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine
|
||||
* is not a cube/rectangular prism.
|
||||
*/
|
||||
private CoordTriplet maximumCoord;
|
||||
|
||||
/**
|
||||
* Set to true whenever a part is removed from this controller.
|
||||
*/
|
||||
private boolean shouldCheckForDisconnections;
|
||||
|
||||
/**
|
||||
* Set whenever we validate the multiblock
|
||||
*/
|
||||
private MultiblockValidationException lastValidationException;
|
||||
|
||||
protected boolean debugMode;
|
||||
|
||||
protected MultiblockControllerBase(World world) {
|
||||
// Multiblock stuff
|
||||
worldObj = world;
|
||||
connectedParts = new HashSet<IMultiblockPart>();
|
||||
|
||||
referenceCoord = null;
|
||||
assemblyState = AssemblyState.Disassembled;
|
||||
|
||||
minimumCoord = null;
|
||||
maximumCoord = null;
|
||||
|
||||
shouldCheckForDisconnections = true;
|
||||
lastValidationException = null;
|
||||
|
||||
debugMode = false;
|
||||
}
|
||||
|
||||
public void setDebugMode(boolean active) {
|
||||
debugMode = active;
|
||||
}
|
||||
|
||||
public boolean isDebugMode() { return debugMode; }
|
||||
|
||||
/**
|
||||
* Call when a block with cached save-delegate data is added to the multiblock.
|
||||
* The part will be notified that the data has been used after this call completes.
|
||||
* @param part The NBT tag containing this controller's data.
|
||||
*/
|
||||
public abstract void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data);
|
||||
|
||||
/**
|
||||
* Check if a block is being tracked by this machine.
|
||||
* @param blockCoord Coordinate to check.
|
||||
* @return True if the tile entity at blockCoord is being tracked by this machine, false otherwise.
|
||||
*/
|
||||
public boolean hasBlock(CoordTriplet blockCoord) {
|
||||
return connectedParts.contains(blockCoord);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach a new part to this machine.
|
||||
* @param part The part to add.
|
||||
*/
|
||||
public void attachBlock(IMultiblockPart part) {
|
||||
IMultiblockPart candidate;
|
||||
CoordTriplet coord = part.getWorldLocation();
|
||||
|
||||
if(!connectedParts.add(part)) {
|
||||
BeefCoreLog.warning("[%s] Controller %s is double-adding part %d @ %s. This is unusual. If you encounter odd behavior, please tear down the machine and rebuild it.", (worldObj.isRemote?"CLIENT":"SERVER"), hashCode(), part.hashCode(), coord);
|
||||
}
|
||||
|
||||
part.onAttached(this);
|
||||
this.onBlockAdded(part);
|
||||
|
||||
if(part.hasMultiblockSaveData()) {
|
||||
NBTTagCompound savedData = part.getMultiblockSaveData();
|
||||
onAttachedPartWithMultiblockData(part, savedData);
|
||||
part.onMultiblockDataAssimilated();
|
||||
}
|
||||
|
||||
if(this.referenceCoord == null) {
|
||||
referenceCoord = coord;
|
||||
part.becomeMultiblockSaveDelegate();
|
||||
}
|
||||
else if(coord.compareTo(referenceCoord) < 0) {
|
||||
TileEntity te = this.worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
|
||||
((IMultiblockPart)te).forfeitMultiblockSaveDelegate();
|
||||
|
||||
referenceCoord = coord;
|
||||
part.becomeMultiblockSaveDelegate();
|
||||
}
|
||||
else {
|
||||
part.forfeitMultiblockSaveDelegate();
|
||||
}
|
||||
|
||||
if(minimumCoord != null) {
|
||||
if(part.xCoord < minimumCoord.x) { minimumCoord.x = part.xCoord; }
|
||||
if(part.yCoord < minimumCoord.y) { minimumCoord.y = part.yCoord; }
|
||||
if(part.zCoord < minimumCoord.z) { minimumCoord.z = part.zCoord; }
|
||||
}
|
||||
|
||||
if(maximumCoord != null) {
|
||||
if(part.xCoord > maximumCoord.x) { maximumCoord.x = part.xCoord; }
|
||||
if(part.yCoord > maximumCoord.y) { maximumCoord.y = part.yCoord; }
|
||||
if(part.zCoord > maximumCoord.z) { maximumCoord.z = part.zCoord; }
|
||||
}
|
||||
|
||||
MultiblockRegistry.addDirtyController(worldObj, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a new part is added to the machine. Good time to register things into lists.
|
||||
* @param newPart The part being added.
|
||||
*/
|
||||
protected abstract void onBlockAdded(IMultiblockPart newPart);
|
||||
|
||||
/**
|
||||
* Called when a part is removed from the machine. Good time to clean up lists.
|
||||
* @param oldPart The part being removed.
|
||||
*/
|
||||
protected abstract void onBlockRemoved(IMultiblockPart oldPart);
|
||||
|
||||
/**
|
||||
* Called when a machine is assembled from a disassembled state.
|
||||
*/
|
||||
protected abstract void onMachineAssembled();
|
||||
|
||||
/**
|
||||
* Called when a machine is restored to the assembled state from a paused state.
|
||||
*/
|
||||
protected abstract void onMachineRestored();
|
||||
|
||||
/**
|
||||
* Called when a machine is paused from an assembled state
|
||||
* This generally only happens due to chunk-loads and other "system" events.
|
||||
*/
|
||||
protected abstract void onMachinePaused();
|
||||
|
||||
/**
|
||||
* Called when a machine is disassembled from an assembled state.
|
||||
* This happens due to user or in-game actions (e.g. explosions)
|
||||
*/
|
||||
protected abstract void onMachineDisassembled();
|
||||
|
||||
/**
|
||||
* Callback whenever a part is removed (or will very shortly be removed) from a controller.
|
||||
* Do housekeeping/callbacks, also nulls min/max coords.
|
||||
* @param part The part being removed.
|
||||
*/
|
||||
private void onDetachBlock(IMultiblockPart part) {
|
||||
// Strip out this part
|
||||
part.onDetached(this);
|
||||
this.onBlockRemoved(part);
|
||||
part.forfeitMultiblockSaveDelegate();
|
||||
|
||||
minimumCoord = maximumCoord = null;
|
||||
|
||||
if(referenceCoord != null && referenceCoord.equals(part.xCoord, part.yCoord, part.zCoord)) {
|
||||
referenceCoord = null;
|
||||
}
|
||||
|
||||
shouldCheckForDisconnections = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call to detach a block from this machine. Generally, this should be called
|
||||
* when the tile entity is being released, e.g. on block destruction.
|
||||
* @param part The part to detach from this machine.
|
||||
* @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken.
|
||||
*/
|
||||
public void detachBlock(IMultiblockPart part, boolean chunkUnloading) {
|
||||
if(chunkUnloading && this.assemblyState == AssemblyState.Assembled) {
|
||||
this.assemblyState = AssemblyState.Paused;
|
||||
this.onMachinePaused();
|
||||
}
|
||||
|
||||
// Strip out this part
|
||||
onDetachBlock(part);
|
||||
if(!connectedParts.remove(part)) {
|
||||
BeefCoreLog.warning("[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. If you encounter anomalies, please tear down the reactor and rebuild it.", worldObj.isRemote?"CLIENT":"SERVER", part.hashCode(), part.xCoord, part.yCoord, part.zCoord);
|
||||
}
|
||||
|
||||
if(connectedParts.isEmpty()) {
|
||||
// Destroy/unregister
|
||||
MultiblockRegistry.addDeadController(this.worldObj, this);
|
||||
return;
|
||||
}
|
||||
|
||||
MultiblockRegistry.addDirtyController(this.worldObj, this);
|
||||
|
||||
// Find new save delegate if we need to.
|
||||
if(referenceCoord == null) {
|
||||
selectNewReferenceCoord();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method so we don't check for a whole machine until we have enough blocks
|
||||
* to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines
|
||||
* or for machines with hollow/complex interiors.
|
||||
* @return The minimum number of blocks connected to the machine for it to be assembled.
|
||||
*/
|
||||
protected abstract int getMinimumNumberOfBlocksForAssembledMachine();
|
||||
|
||||
/**
|
||||
* Returns the maximum X dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable
|
||||
* dimension checking in X. (This is not recommended.)
|
||||
* @return The maximum X dimension size of the machine, or -1
|
||||
*/
|
||||
protected abstract int getMaximumXSize();
|
||||
|
||||
/**
|
||||
* Returns the maximum Z dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable
|
||||
* dimension checking in X. (This is not recommended.)
|
||||
* @return The maximum Z dimension size of the machine, or -1
|
||||
*/
|
||||
protected abstract int getMaximumZSize();
|
||||
|
||||
/**
|
||||
* Returns the maximum Y dimension size of the machine, or -1 (DIMENSION_UNBOUNDED) to disable
|
||||
* dimension checking in X. (This is not recommended.)
|
||||
* @return The maximum Y dimension size of the machine, or -1
|
||||
*/
|
||||
protected abstract int getMaximumYSize();
|
||||
|
||||
/**
|
||||
* Returns the minimum X dimension size of the machine. Must be at least 1, because nothing else makes sense.
|
||||
* @return The minimum X dimension size of the machine
|
||||
*/
|
||||
protected int getMinimumXSize() { return 1; }
|
||||
|
||||
/**
|
||||
* Returns the minimum Y dimension size of the machine. Must be at least 1, because nothing else makes sense.
|
||||
* @return The minimum Y dimension size of the machine
|
||||
*/
|
||||
protected int getMinimumYSize() { return 1; }
|
||||
|
||||
/**
|
||||
* Returns the minimum Z dimension size of the machine. Must be at least 1, because nothing else makes sense.
|
||||
* @return The minimum Z dimension size of the machine
|
||||
*/
|
||||
protected int getMinimumZSize() { return 1; }
|
||||
|
||||
|
||||
/**
|
||||
* @return An exception representing the last error encountered when trying to assemble this
|
||||
* multiblock, or null if there is no error.
|
||||
*/
|
||||
public MultiblockValidationException getLastValidationException() { return lastValidationException; }
|
||||
|
||||
/**
|
||||
* Checks if a machine is whole. If not, throws an exception with the reason why.
|
||||
*/
|
||||
protected abstract void isMachineWhole() throws MultiblockValidationException;
|
||||
|
||||
/**
|
||||
* Check if the machine is whole or not.
|
||||
* If the machine was not whole, but now is, assemble the machine.
|
||||
* If the machine was whole, but no longer is, disassemble the machine.
|
||||
* @return
|
||||
*/
|
||||
public void checkIfMachineIsWhole() {
|
||||
AssemblyState oldState = this.assemblyState;
|
||||
boolean isWhole;
|
||||
lastValidationException = null;
|
||||
try {
|
||||
isMachineWhole();
|
||||
isWhole = true;
|
||||
} catch (MultiblockValidationException e) {
|
||||
lastValidationException = e;
|
||||
isWhole = false;
|
||||
}
|
||||
|
||||
if(isWhole) {
|
||||
// This will alter assembly state
|
||||
assembleMachine(oldState);
|
||||
}
|
||||
else if(oldState == AssemblyState.Assembled) {
|
||||
// This will alter assembly state
|
||||
disassembleMachine();
|
||||
}
|
||||
// Else Paused, do nothing
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a machine becomes "whole" and should begin
|
||||
* functioning as a game-logically finished machine.
|
||||
* Calls onMachineAssembled on all attached parts.
|
||||
*/
|
||||
private void assembleMachine(AssemblyState oldState) {
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
part.onMachineAssembled(this);
|
||||
}
|
||||
|
||||
this.assemblyState = AssemblyState.Assembled;
|
||||
if(oldState == assemblyState.Paused) {
|
||||
onMachineRestored();
|
||||
}
|
||||
else {
|
||||
onMachineAssembled();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the machine needs to be disassembled.
|
||||
* It is not longer "whole" and should not be functional, usually
|
||||
* as a result of a block being removed.
|
||||
* Calls onMachineBroken on all attached parts.
|
||||
*/
|
||||
private void disassembleMachine() {
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
part.onMachineBroken();
|
||||
}
|
||||
|
||||
this.assemblyState = AssemblyState.Disassembled;
|
||||
onMachineDisassembled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Assimilate another controller into this controller.
|
||||
* Acquire all of the other controller's blocks and attach them
|
||||
* to this one.
|
||||
*
|
||||
* @param other The controller to merge into this one.
|
||||
*/
|
||||
public void assimilate(MultiblockControllerBase other) {
|
||||
CoordTriplet otherReferenceCoord = other.getReferenceCoord();
|
||||
if(otherReferenceCoord != null && getReferenceCoord().compareTo(otherReferenceCoord) >= 0) {
|
||||
throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords");
|
||||
}
|
||||
|
||||
TileEntity te;
|
||||
Set<IMultiblockPart> partsToAcquire = new HashSet<IMultiblockPart>(other.connectedParts);
|
||||
|
||||
// releases all blocks and references gently so they can be incorporated into another multiblock
|
||||
other._onAssimilated(this);
|
||||
|
||||
for(IMultiblockPart acquiredPart : partsToAcquire) {
|
||||
// By definition, none of these can be the minimum block.
|
||||
if(acquiredPart.isInvalid()) { continue; }
|
||||
|
||||
connectedParts.add(acquiredPart);
|
||||
acquiredPart.onAssimilated(this);
|
||||
this.onBlockAdded(acquiredPart);
|
||||
}
|
||||
|
||||
this.onAssimilate(other);
|
||||
other.onAssimilated(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when this machine is consumed by another controller.
|
||||
* Essentially, forcibly tear down this object.
|
||||
* @param otherController The controller consuming this controller.
|
||||
*/
|
||||
private void _onAssimilated(MultiblockControllerBase otherController) {
|
||||
if(referenceCoord != null) {
|
||||
if(worldObj.getChunkProvider().chunkExists(referenceCoord.getChunkX(), referenceCoord.getChunkZ())) {
|
||||
TileEntity te = this.worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
|
||||
if(te instanceof IMultiblockPart) {
|
||||
((IMultiblockPart)te).forfeitMultiblockSaveDelegate();
|
||||
}
|
||||
}
|
||||
this.referenceCoord = null;
|
||||
}
|
||||
|
||||
connectedParts.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback. Called after this controller assimilates all the blocks
|
||||
* from another controller.
|
||||
* Use this to absorb that controller's game data.
|
||||
* @param assimilated The controller whose uniqueness was added to our own.
|
||||
*/
|
||||
protected abstract void onAssimilate(MultiblockControllerBase assimilated);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
protected abstract void onAssimilated(MultiblockControllerBase assimilator);
|
||||
|
||||
/**
|
||||
* Driver for the update loop. If the machine is assembled, runs
|
||||
* the game logic update method.
|
||||
* @see erogenousbeef.coreTR.multiblock.MultiblockControllerBase#update() //TODO Fix this Javadoc
|
||||
*/
|
||||
public final void updateMultiblockEntity() {
|
||||
if(connectedParts.isEmpty()) {
|
||||
// This shouldn't happen, but just in case...
|
||||
MultiblockRegistry.addDeadController(this.worldObj, this);
|
||||
return;
|
||||
}
|
||||
|
||||
if(this.assemblyState != AssemblyState.Assembled) {
|
||||
// Not assembled - don't run game logic
|
||||
return;
|
||||
}
|
||||
|
||||
if(worldObj.isRemote) {
|
||||
updateClient();
|
||||
}
|
||||
else if(updateServer()) {
|
||||
// If this returns true, the server has changed its internal data.
|
||||
// If our chunks are loaded (they should be), we must mark our chunks as dirty.
|
||||
if(minimumCoord != null && maximumCoord != null &&
|
||||
this.worldObj.checkChunksExist(minimumCoord.x, minimumCoord.y, minimumCoord.z,
|
||||
maximumCoord.x, maximumCoord.y, maximumCoord.z)) {
|
||||
int minChunkX = minimumCoord.x >> 4;
|
||||
int minChunkZ = minimumCoord.z >> 4;
|
||||
int maxChunkX = maximumCoord.x >> 4;
|
||||
int maxChunkZ = maximumCoord.z >> 4;
|
||||
|
||||
for(int x = minChunkX; x <= maxChunkX; x++) {
|
||||
for(int z = minChunkZ; z <= maxChunkZ; z++) {
|
||||
// Ensure that we save our data, even if the our save delegate is in has no TEs.
|
||||
Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z);
|
||||
chunkToSave.setChunkModified();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Else: Server, but no need to save data.
|
||||
}
|
||||
|
||||
/**
|
||||
* The server-side update loop! Use this similarly to a TileEntity's update loop.
|
||||
* You do not need to call your superclass' update() if you're directly
|
||||
* derived from MultiblockControllerBase. This is a callback.
|
||||
* Note that this will only be called when the machine is assembled.
|
||||
* @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise.
|
||||
*/
|
||||
protected abstract boolean updateServer();
|
||||
|
||||
/**
|
||||
* Client-side update loop. Generally, this shouldn't do anything, but if you want
|
||||
* to do some interpolation or something, do it here.
|
||||
*/
|
||||
protected abstract void updateClient();
|
||||
|
||||
// Validation helpers
|
||||
/**
|
||||
* The "frame" consists of the outer edges of the machine, plus the corners.
|
||||
*
|
||||
* @param world World object for the world in which this controller is located.
|
||||
* @param x X coordinate of the block being tested
|
||||
* @param y Y coordinate of the block being tested
|
||||
* @param z Z coordinate of the block being tested
|
||||
* @throws MultiblockValidationException if the tested block is not allowed on the machine's frame
|
||||
*/
|
||||
protected void isBlockGoodForFrame(World world, int x, int y, int z) throws MultiblockValidationException {
|
||||
throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* The top consists of the top face, minus the edges.
|
||||
* @param world World object for the world in which this controller is located.
|
||||
* @param x X coordinate of the block being tested
|
||||
* @param y Y coordinate of the block being tested
|
||||
* @param z Z coordinate of the block being tested
|
||||
* @throws MultiblockValidationException if the tested block is not allowed on the machine's top face
|
||||
*/
|
||||
protected void isBlockGoodForTop(World world, int x, int y, int z) throws MultiblockValidationException {
|
||||
throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* The bottom consists of the bottom face, minus the edges.
|
||||
* @param world World object for the world in which this controller is located.
|
||||
* @param x X coordinate of the block being tested
|
||||
* @param y Y coordinate of the block being tested
|
||||
* @param z Z coordinate of the block being tested
|
||||
* @throws MultiblockValidationException if the tested block is not allowed on the machine's bottom face
|
||||
*/
|
||||
protected void isBlockGoodForBottom(World world, int x, int y, int z) throws MultiblockValidationException {
|
||||
throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* The sides consists of the N/E/S/W-facing faces, minus the edges.
|
||||
* @param world World object for the world in which this controller is located.
|
||||
* @param x X coordinate of the block being tested
|
||||
* @param y Y coordinate of the block being tested
|
||||
* @param z Z coordinate of the block being tested
|
||||
* @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces
|
||||
*/
|
||||
protected void isBlockGoodForSides(World world, int x, int y, int z) throws MultiblockValidationException {
|
||||
throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* The interior is any block that does not touch blocks outside the machine.
|
||||
* @param world World object for the world in which this controller is located.
|
||||
* @param x X coordinate of the block being tested
|
||||
* @param y Y coordinate of the block being tested
|
||||
* @param z Z coordinate of the block being tested
|
||||
* @throws MultiblockValidationException if the tested block is not allowed in the machine's interior
|
||||
*/
|
||||
protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException {
|
||||
throw new MultiblockValidationException(String.format("%d, %d, %d - Block is not valid for use in the machine's interior", x, y, z));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order.
|
||||
*/
|
||||
public CoordTriplet getReferenceCoord() {
|
||||
if(referenceCoord == null) { selectNewReferenceCoord(); }
|
||||
return referenceCoord;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The number of blocks connected to this controller.
|
||||
*/
|
||||
public int getNumConnectedBlocks() { return connectedParts.size(); }
|
||||
|
||||
public abstract void writeToNBT(NBTTagCompound data);
|
||||
public abstract void readFromNBT(NBTTagCompound data);
|
||||
|
||||
/**
|
||||
* Force this multiblock to recalculate its minimum and maximum coordinates
|
||||
* from the list of connected parts.
|
||||
*/
|
||||
public void recalculateMinMaxCoords() {
|
||||
minimumCoord = new CoordTriplet(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE);
|
||||
maximumCoord = new CoordTriplet(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE);
|
||||
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
if(part.xCoord < minimumCoord.x) { minimumCoord.x = part.xCoord; }
|
||||
if(part.xCoord > maximumCoord.x) { maximumCoord.x = part.xCoord; }
|
||||
if(part.yCoord < minimumCoord.y) { minimumCoord.y = part.yCoord; }
|
||||
if(part.yCoord > maximumCoord.y) { maximumCoord.y = part.yCoord; }
|
||||
if(part.zCoord < minimumCoord.z) { minimumCoord.z = part.zCoord; }
|
||||
if(part.zCoord > maximumCoord.z) { maximumCoord.z = part.zCoord; }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The minimum bounding-box coordinate containing this machine's blocks.
|
||||
*/
|
||||
public CoordTriplet getMinimumCoord() {
|
||||
if(minimumCoord == null) { recalculateMinMaxCoords(); }
|
||||
return minimumCoord.copy();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return The maximum bounding-box coordinate containing this machine's blocks.
|
||||
*/
|
||||
public CoordTriplet getMaximumCoord() {
|
||||
if(maximumCoord == null) { recalculateMinMaxCoords(); }
|
||||
return maximumCoord.copy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the save delegate's tile entity is being asked for its description packet
|
||||
* @param data A fresh compound tag to write your multiblock data into
|
||||
*/
|
||||
public abstract void formatDescriptionPacket(NBTTagCompound data);
|
||||
|
||||
/**
|
||||
* Called when the save delegate's tile entity receiving a description packet
|
||||
* @param data A compound tag containing multiblock data to import
|
||||
*/
|
||||
public abstract void decodeDescriptionPacket(NBTTagCompound data);
|
||||
|
||||
/**
|
||||
* @return True if this controller has no associated blocks, false otherwise
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return connectedParts.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether this multiblock should consume the other multiblock
|
||||
* and become the new multiblock master when the two multiblocks
|
||||
* are adjacent. Assumes both multiblocks are the same type.
|
||||
* @param otherController The other multiblock controller.
|
||||
* @return True if this multiblock should consume the other, false otherwise.
|
||||
*/
|
||||
public boolean shouldConsume(MultiblockControllerBase otherController) {
|
||||
if(!otherController.getClass().equals(getClass())) {
|
||||
throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!");
|
||||
}
|
||||
|
||||
if(otherController == this) { return false; } // Don't be silly, don't eat yourself.
|
||||
|
||||
int res = _shouldConsume(otherController);
|
||||
if(res < 0) { return true; }
|
||||
else if(res > 0) { return false; }
|
||||
else {
|
||||
// Strip dead parts from both and retry
|
||||
BeefCoreLog.warning("[%s] Encountered two controllers with the same reference coordinate. Auditing connected parts and retrying.", worldObj.isRemote?"CLIENT":"SERVER");
|
||||
auditParts();
|
||||
otherController.auditParts();
|
||||
|
||||
res = _shouldConsume(otherController);
|
||||
if(res < 0) { return true; }
|
||||
else if(res > 0) { return false; }
|
||||
else {
|
||||
BeefCoreLog.error("My Controller (%d): size (%d), parts: %s", hashCode(), connectedParts.size(), getPartsListString());
|
||||
BeefCoreLog.error("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.connectedParts.size(), otherController.getPartsListString());
|
||||
throw new IllegalArgumentException("[" + (worldObj.isRemote?"CLIENT":"SERVER") + "] Two controllers with the same reference coord that somehow both have valid parts - this should never happen!");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private int _shouldConsume(MultiblockControllerBase otherController) {
|
||||
CoordTriplet myCoord = getReferenceCoord();
|
||||
CoordTriplet theirCoord = otherController.getReferenceCoord();
|
||||
|
||||
// Always consume other controllers if their reference coordinate is null - this means they're empty and can be assimilated on the cheap
|
||||
if(theirCoord == null) { return -1; }
|
||||
else { return myCoord.compareTo(theirCoord); }
|
||||
}
|
||||
|
||||
private String getPartsListString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean first = true;
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
if(!first) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), part.xCoord, part.yCoord, part.zCoord));
|
||||
first = false;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks all of the parts in the controller. If any are dead or do not exist in the world, they are removed.
|
||||
*/
|
||||
private void auditParts() {
|
||||
HashSet<IMultiblockPart> deadParts = new HashSet<IMultiblockPart>();
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
if(part.isInvalid() || worldObj.getTileEntity(part.xCoord, part.yCoord, part.zCoord) != part) {
|
||||
onDetachBlock(part);
|
||||
deadParts.add(part);
|
||||
}
|
||||
}
|
||||
|
||||
connectedParts.removeAll(deadParts);
|
||||
BeefCoreLog.warning("[%s] Controller found %d dead parts during an audit, %d parts remain attached", worldObj.isRemote?"CLIENT":"SERVER", deadParts.size(), connectedParts.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when this machine may need to check for blocks that are no
|
||||
* longer physically connected to the reference coordinate.
|
||||
* @return
|
||||
*/
|
||||
public Set<IMultiblockPart> checkForDisconnections() {
|
||||
if(!this.shouldCheckForDisconnections) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if(this.isEmpty()) {
|
||||
MultiblockRegistry.addDeadController(worldObj, this);
|
||||
return null;
|
||||
}
|
||||
|
||||
TileEntity te;
|
||||
IChunkProvider chunkProvider = worldObj.getChunkProvider();
|
||||
|
||||
// Invalidate our reference coord, we'll recalculate it shortly
|
||||
referenceCoord = null;
|
||||
|
||||
// Reset visitations and find the minimum coordinate
|
||||
Set<IMultiblockPart> deadParts = new HashSet<IMultiblockPart>();
|
||||
CoordTriplet c;
|
||||
IMultiblockPart referencePart = null;
|
||||
|
||||
int originalSize = connectedParts.size();
|
||||
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
// This happens during chunk unload.
|
||||
if(!chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4) || part.isInvalid()) {
|
||||
deadParts.add(part);
|
||||
onDetachBlock(part);
|
||||
continue;
|
||||
}
|
||||
|
||||
if(worldObj.getTileEntity(part.xCoord, part.yCoord, part.zCoord) != part) {
|
||||
deadParts.add(part);
|
||||
onDetachBlock(part);
|
||||
continue;
|
||||
}
|
||||
|
||||
part.setUnvisited();
|
||||
part.forfeitMultiblockSaveDelegate();
|
||||
|
||||
c = part.getWorldLocation();
|
||||
if(referenceCoord == null) {
|
||||
referenceCoord = c;
|
||||
referencePart = part;
|
||||
}
|
||||
else if(c.compareTo(referenceCoord) < 0) {
|
||||
referenceCoord = c;
|
||||
referencePart = part;
|
||||
}
|
||||
}
|
||||
|
||||
connectedParts.removeAll(deadParts);
|
||||
deadParts.clear();
|
||||
|
||||
if(referencePart == null || isEmpty()) {
|
||||
// There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt.
|
||||
shouldCheckForDisconnections = false;
|
||||
MultiblockRegistry.addDeadController(worldObj, this);
|
||||
return null;
|
||||
}
|
||||
else {
|
||||
referencePart.becomeMultiblockSaveDelegate();
|
||||
}
|
||||
|
||||
// Now visit all connected parts, breadth-first, starting from reference coord's part
|
||||
IMultiblockPart part;
|
||||
LinkedList<IMultiblockPart> partsToCheck = new LinkedList<IMultiblockPart>();
|
||||
IMultiblockPart[] nearbyParts = null;
|
||||
int visitedParts = 0;
|
||||
|
||||
partsToCheck.add(referencePart);
|
||||
|
||||
while(!partsToCheck.isEmpty()) {
|
||||
part = partsToCheck.removeFirst();
|
||||
part.setVisited();
|
||||
visitedParts++;
|
||||
|
||||
nearbyParts = part.getNeighboringParts(); // Chunk-safe on server, but not on client
|
||||
for(IMultiblockPart nearbyPart : nearbyParts) {
|
||||
// Ignore different machines
|
||||
if(nearbyPart.getMultiblockController() != this) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if(!nearbyPart.isVisited()) {
|
||||
nearbyPart.setVisited();
|
||||
partsToCheck.add(nearbyPart);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally, remove all parts that remain disconnected.
|
||||
Set<IMultiblockPart> removedParts = new HashSet<IMultiblockPart>();
|
||||
for(IMultiblockPart orphanCandidate : connectedParts) {
|
||||
if (!orphanCandidate.isVisited()) {
|
||||
deadParts.add(orphanCandidate);
|
||||
orphanCandidate.onOrphaned(this, originalSize, visitedParts);
|
||||
onDetachBlock(orphanCandidate);
|
||||
removedParts.add(orphanCandidate);
|
||||
}
|
||||
}
|
||||
|
||||
// Trim any blocks that were invalid, or were removed.
|
||||
connectedParts.removeAll(deadParts);
|
||||
|
||||
// Cleanup. Not necessary, really.
|
||||
deadParts.clear();
|
||||
|
||||
// Juuuust in case.
|
||||
if(referenceCoord == null) {
|
||||
selectNewReferenceCoord();
|
||||
}
|
||||
|
||||
// We've run the checks from here on out.
|
||||
shouldCheckForDisconnections = false;
|
||||
|
||||
return removedParts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detach all parts. Return a set of all parts which still
|
||||
* have a valid tile entity. Chunk-safe.
|
||||
* @return A set of all parts which still have a valid tile entity.
|
||||
*/
|
||||
public Set<IMultiblockPart> detachAllBlocks() {
|
||||
if(worldObj == null) { return new HashSet<IMultiblockPart>(); }
|
||||
|
||||
IChunkProvider chunkProvider = worldObj.getChunkProvider();
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
if(chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4)) {
|
||||
onDetachBlock(part);
|
||||
}
|
||||
}
|
||||
|
||||
Set<IMultiblockPart> detachedParts = connectedParts;
|
||||
connectedParts = new HashSet<IMultiblockPart>();
|
||||
return detachedParts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if this multiblock machine is considered assembled and ready to go.
|
||||
*/
|
||||
public boolean isAssembled() {
|
||||
return this.assemblyState == AssemblyState.Assembled;
|
||||
}
|
||||
|
||||
private void selectNewReferenceCoord() {
|
||||
IChunkProvider chunkProvider = worldObj.getChunkProvider();
|
||||
TileEntity theChosenOne = null;
|
||||
referenceCoord = null;
|
||||
|
||||
for(IMultiblockPart part : connectedParts) {
|
||||
if(part.isInvalid() || !chunkProvider.chunkExists(part.xCoord >> 4, part.zCoord >> 4)) {
|
||||
// Chunk is unloading, skip this coord to prevent chunk thrashing
|
||||
continue;
|
||||
}
|
||||
|
||||
if(referenceCoord == null || referenceCoord.compareTo(part.xCoord, part.yCoord, part.zCoord) > 0) {
|
||||
referenceCoord = part.getWorldLocation();
|
||||
theChosenOne = part;
|
||||
}
|
||||
}
|
||||
|
||||
if(theChosenOne != null) {
|
||||
((IMultiblockPart)theChosenOne).becomeMultiblockSaveDelegate();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the reference coord dirty & updateable.
|
||||
*
|
||||
* On the server, this will mark the for a data-update, so that
|
||||
* nearby clients will receive an updated description packet from the server
|
||||
* after a short time. The block's chunk will also be marked dirty and the
|
||||
* block's chunk will be saved to disk the next time chunks are saved.
|
||||
*
|
||||
* On the client, this will mark the block for a rendering update.
|
||||
*/
|
||||
protected void markReferenceCoordForUpdate() {
|
||||
CoordTriplet rc = getReferenceCoord();
|
||||
if(worldObj != null && rc != null) {
|
||||
worldObj.markBlockForUpdate(rc.x, rc.y, rc.z);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the reference coord dirty.
|
||||
*
|
||||
* On the server, this marks the reference coord's chunk as dirty; the block (and chunk)
|
||||
* will be saved to disk the next time chunks are saved. This does NOT mark it dirty for
|
||||
* a description-packet update.
|
||||
*
|
||||
* On the client, does nothing.
|
||||
* @see MultiblockControllerBase#markReferenceCoordForUpdate()
|
||||
*/
|
||||
protected void markReferenceCoordDirty() {
|
||||
if(worldObj == null || worldObj.isRemote) { return; }
|
||||
|
||||
CoordTriplet referenceCoord = getReferenceCoord();
|
||||
if(referenceCoord == null) { return; }
|
||||
|
||||
TileEntity saveTe = worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z);
|
||||
worldObj.markTileEntityChunkModified(referenceCoord.x, referenceCoord.y, referenceCoord.z, saveTe);
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.chunk.Chunk;
|
||||
import net.minecraftforge.event.world.ChunkEvent;
|
||||
import net.minecraftforge.event.world.WorldEvent;
|
||||
import cpw.mods.fml.common.eventhandler.EventPriority;
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
|
||||
/**
|
||||
* In your mod, subscribe this on both the client and server sides side to handle chunk
|
||||
* load events for your multiblock machines.
|
||||
* Chunks can load asynchronously in environments like MCPC+, so we cannot
|
||||
* process any blocks that are in chunks which are still loading.
|
||||
*/
|
||||
public class MultiblockEventHandler {
|
||||
@SubscribeEvent(priority = EventPriority.NORMAL)
|
||||
public void onChunkLoad(ChunkEvent.Load loadEvent) {
|
||||
Chunk chunk = loadEvent.getChunk();
|
||||
World world = loadEvent.world;
|
||||
MultiblockRegistry.onChunkLoaded(world, chunk.xPosition, chunk.zPosition);
|
||||
}
|
||||
|
||||
// Cleanup, for nice memory usageness
|
||||
@SubscribeEvent(priority = EventPriority.NORMAL)
|
||||
public void onWorldUnload(WorldEvent.Unload unloadWorldEvent) {
|
||||
MultiblockRegistry.onWorldUnloaded(unloadWorldEvent.world);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
import erogenousbeef.coreTR.common.BeefCoreLog;
|
||||
|
||||
/**
|
||||
* This is a very static singleton registry class which directs incoming events to sub-objects, which
|
||||
* actually manage each individual world's multiblocks.
|
||||
* @author Erogenous Beef
|
||||
*/
|
||||
public class MultiblockRegistry {
|
||||
// World > WorldRegistry map
|
||||
private static HashMap<World, MultiblockWorldRegistry> registries = new HashMap<World, MultiblockWorldRegistry>();
|
||||
|
||||
/**
|
||||
* Called before Tile Entities are ticked in the world. Do bookkeeping here.
|
||||
* @param world The world being ticked
|
||||
*/
|
||||
public static void tickStart(World world) {
|
||||
if(registries.containsKey(world)) {
|
||||
MultiblockWorldRegistry registry = registries.get(world);
|
||||
registry.processMultiblockChanges();
|
||||
registry.tickStart();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the world has finished loading a chunk.
|
||||
* @param world The world which has finished loading a chunk
|
||||
* @param chunkX The X coordinate of the chunk
|
||||
* @param chunkZ The Z coordinate of the chunk
|
||||
*/
|
||||
public static void onChunkLoaded(World world, int chunkX, int chunkZ) {
|
||||
if(registries.containsKey(world)) {
|
||||
registries.get(world).onChunkLoaded(chunkX, chunkZ);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new part in the system. The part has been created either through user action or via a chunk loading.
|
||||
* @param world The world into which this part is loading.
|
||||
* @param part The part being loaded.
|
||||
*/
|
||||
public static void onPartAdded(World world, IMultiblockPart part) {
|
||||
MultiblockWorldRegistry registry = getOrCreateRegistry(world);
|
||||
registry.onPartAdded(part);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call to remove a part from world lists.
|
||||
* @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) {
|
||||
if(registries.containsKey(world)) {
|
||||
registries.get(world).onPartRemovedFromWorld(part);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Called whenever a world is unloaded. Unload the relevant registry, if we have one.
|
||||
* @param world The world being unloaded.
|
||||
*/
|
||||
public static void onWorldUnloaded(World world) {
|
||||
if(registries.containsKey(world)) {
|
||||
registries.get(world).onWorldUnloaded();
|
||||
registries.remove(world);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call to mark a controller as dirty. Dirty means that parts have
|
||||
* been added or removed this tick.
|
||||
* @param world The world containing the multiblock
|
||||
* @param controller The dirty controller
|
||||
*/
|
||||
public static void addDirtyController(World world,
|
||||
MultiblockControllerBase controller) {
|
||||
if(registries.containsKey(world)) {
|
||||
registries.get(world).addDirtyController(controller);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Adding a dirty controller to a world that has no registered controllers!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call to mark a controller as dead. It should only be marked as dead
|
||||
* when it has no connected parts. It will be removed after the next world tick.
|
||||
* @param world The world formerly containing the multiblock
|
||||
* @param controller The dead controller
|
||||
*/
|
||||
public static void addDeadController(World world, MultiblockControllerBase controller) {
|
||||
if(registries.containsKey(world)) {
|
||||
registries.get(world).addDeadController(controller);
|
||||
}
|
||||
else {
|
||||
BeefCoreLog.warning("Controller %d in world %s marked as dead, but that world is not tracked! Controller is being ignored.", controller.hashCode(), world);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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) {
|
||||
if(registries.containsKey(world)) {
|
||||
return registries.get(world).getControllers();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// *** PRIVATE HELPERS *** ///
|
||||
|
||||
private static MultiblockWorldRegistry getOrCreateRegistry(World world) {
|
||||
if(registries.containsKey(world)) {
|
||||
return registries.get(world);
|
||||
}
|
||||
else {
|
||||
MultiblockWorldRegistry newRegistry = new MultiblockWorldRegistry(world);
|
||||
registries.put(world, newRegistry);
|
||||
return newRegistry;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import cpw.mods.fml.common.gameevent.TickEvent;
|
||||
|
||||
/**
|
||||
* This is a generic multiblock tick handler. If you are using this code on your own,
|
||||
* you will need to register this with the Forge TickRegistry on both the
|
||||
* client AND server sides.
|
||||
* Note that different types of ticks run on different parts of the system.
|
||||
* CLIENT ticks only run on the client, at the start/end of each game loop.
|
||||
* SERVER and WORLD ticks only run on the server.
|
||||
* WORLDLOAD ticks run only on the server, and only when worlds are loaded.
|
||||
*/
|
||||
public class MultiblockServerTickHandler {
|
||||
|
||||
@SubscribeEvent
|
||||
public void onWorldTick(TickEvent.WorldTickEvent event) {
|
||||
if(event.phase == TickEvent.Phase.START) {
|
||||
MultiblockRegistry.tickStart(event.world);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,357 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
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.world.chunk.IChunkProvider;
|
||||
import erogenousbeef.coreTR.common.BeefCoreLog;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
private MultiblockControllerBase controller;
|
||||
private boolean visited;
|
||||
|
||||
private boolean saveMultiblockData;
|
||||
private NBTTagCompound cachedMultiblockData;
|
||||
private boolean paused;
|
||||
|
||||
public MultiblockTileEntityBase() {
|
||||
super();
|
||||
controller = null;
|
||||
visited = false;
|
||||
saveMultiblockData = false;
|
||||
paused = false;
|
||||
cachedMultiblockData = null;
|
||||
}
|
||||
|
||||
///// Multiblock Connection Base Logic
|
||||
@Override
|
||||
public 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<MultiblockControllerBase>();
|
||||
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 void assertDetached() {
|
||||
if(this.controller != null) {
|
||||
BeefCoreLog.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");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeToNBT(NBTTagCompound data) {
|
||||
super.writeToNBT(data);
|
||||
|
||||
if(isMultiblockSaveDelegate() && isConnected()) {
|
||||
NBTTagCompound multiblockData = new NBTTagCompound();
|
||||
this.controller.writeToNBT(multiblockData);
|
||||
data.setTag("multiblockData", multiblockData);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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 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 void validate() {
|
||||
super.validate();
|
||||
MultiblockRegistry.onPartAdded(this.worldObj, this);
|
||||
}
|
||||
|
||||
// Network Communication
|
||||
@Override
|
||||
public Packet getDescriptionPacket() {
|
||||
NBTTagCompound packetData = new NBTTagCompound();
|
||||
encodeDescriptionPacket(packetData);
|
||||
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, packetData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public 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 erogenousbeef.coreTR.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 erogenousbeef.coreTR.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 boolean hasMultiblockSaveData() {
|
||||
return this.cachedMultiblockData != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public NBTTagCompound getMultiblockSaveData() {
|
||||
return this.cachedMultiblockData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public 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 boolean isConnected() {
|
||||
return (controller != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MultiblockControllerBase getMultiblockController() {
|
||||
return controller;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CoordTriplet getWorldLocation() {
|
||||
return new CoordTriplet(this.xCoord, this.yCoord, this.zCoord);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void becomeMultiblockSaveDelegate() {
|
||||
this.saveMultiblockData = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forfeitMultiblockSaveDelegate() {
|
||||
this.saveMultiblockData = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isMultiblockSaveDelegate() { return this.saveMultiblockData; }
|
||||
|
||||
@Override
|
||||
public void setUnvisited() {
|
||||
this.visited = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVisited() {
|
||||
this.visited = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isVisited() {
|
||||
return this.visited;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAssimilated(MultiblockControllerBase newController) {
|
||||
assert(this.controller != newController);
|
||||
this.controller = newController;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAttached(MultiblockControllerBase newController) {
|
||||
this.controller = newController;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDetached(MultiblockControllerBase oldController) {
|
||||
this.controller = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract MultiblockControllerBase createNewMultiblock();
|
||||
|
||||
@Override
|
||||
public 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<IMultiblockPart>();
|
||||
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 void onOrphaned(MultiblockControllerBase controller, int oldSize, int newSize) {
|
||||
this.markDirty();
|
||||
worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this);
|
||||
}
|
||||
|
||||
//// Helper functions for notifying neighboring blocks
|
||||
protected 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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
/**
|
||||
* An exception thrown when trying to validate a multiblock. Requires a string describing why the multiblock
|
||||
* could not assemble.
|
||||
* @author Erogenous Beef
|
||||
*/
|
||||
public class MultiblockValidationException extends Exception {
|
||||
|
||||
public MultiblockValidationException(String reason) {
|
||||
super(reason);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,417 @@
|
|||
package erogenousbeef.coreTR.multiblock;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.world.ChunkCoordIntPair;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.chunk.IChunkProvider;
|
||||
import erogenousbeef.coreTR.common.BeefCoreLog;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
|
||||
/**
|
||||
* This class manages all the multiblock controllers that exist in a given world,
|
||||
* either client- or server-side.
|
||||
* You must create different registries for server and client worlds.
|
||||
*
|
||||
* @author Erogenous Beef
|
||||
*/
|
||||
public class MultiblockWorldRegistry {
|
||||
|
||||
private World worldObj;
|
||||
|
||||
private Set<MultiblockControllerBase> controllers; // Active controllers
|
||||
private Set<MultiblockControllerBase> dirtyControllers; // Controllers whose parts lists have changed
|
||||
private Set<MultiblockControllerBase> 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;
|
||||
|
||||
// A list of parts which have been detached during internal operations
|
||||
private Set<IMultiblockPart> 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 HashMap<Long, Set<IMultiblockPart>> partsAwaitingChunkLoad;
|
||||
|
||||
// Mutexes to protect lists which may be changed due to asynchronous events, such as chunk loads
|
||||
private Object partsAwaitingChunkLoadMutex;
|
||||
private Object orphanedPartsMutex;
|
||||
|
||||
public MultiblockWorldRegistry(World world) {
|
||||
worldObj = world;
|
||||
|
||||
controllers = new HashSet<MultiblockControllerBase>();
|
||||
deadControllers = new HashSet<MultiblockControllerBase>();
|
||||
dirtyControllers = new HashSet<MultiblockControllerBase>();
|
||||
|
||||
detachedParts = new HashSet<IMultiblockPart>();
|
||||
orphanedParts = new HashSet<IMultiblockPart>();
|
||||
|
||||
partsAwaitingChunkLoad = new HashMap<Long, Set<IMultiblockPart>>();
|
||||
partsAwaitingChunkLoadMutex = new Object();
|
||||
orphanedPartsMutex = new Object();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called before Tile Entities are ticked in the world. Run game logic.
|
||||
*/
|
||||
public void tickStart() {
|
||||
if(controllers.size() > 0) {
|
||||
for(MultiblockControllerBase controller : controllers) {
|
||||
if(controller.worldObj == worldObj && controller.worldObj.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.
|
||||
deadControllers.add(controller);
|
||||
}
|
||||
else {
|
||||
// Run the game logic for this world
|
||||
controller.updateMultiblockEntity();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called prior to processing multiblock controllers. Do bookkeeping.
|
||||
*/
|
||||
public void processMultiblockChanges() {
|
||||
IChunkProvider chunkProvider = worldObj.getChunkProvider();
|
||||
CoordTriplet coord;
|
||||
|
||||
// Merge pools - sets of adjacent machines which should be merged later on in processing
|
||||
List<Set<MultiblockControllerBase>> mergePools = null;
|
||||
if(orphanedParts.size() > 0) {
|
||||
Set<IMultiblockPart> 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()
|
||||
// is not chunk-safe on the client, because Minecraft is stupid.
|
||||
// It's possible to polyfill this, but the polyfill is too slow for comfort.
|
||||
synchronized(orphanedPartsMutex) {
|
||||
if(orphanedParts.size() > 0) {
|
||||
orphansToProcess = orphanedParts;
|
||||
orphanedParts = new HashSet<IMultiblockPart>();
|
||||
}
|
||||
}
|
||||
|
||||
if(orphansToProcess != null && orphansToProcess.size() > 0) {
|
||||
Set<MultiblockControllerBase> 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())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// This can occur on slow machines.
|
||||
if(orphan.isInvalid()) { continue; }
|
||||
|
||||
if(worldObj.getTileEntity(coord.x, coord.y, coord.z) != 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) {
|
||||
// FOREVER ALONE! Create and register a new controller.
|
||||
// THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED.
|
||||
MultiblockControllerBase newController = orphan.createNewMultiblock();
|
||||
newController.attachBlock(orphan);
|
||||
this.controllers.add(newController);
|
||||
}
|
||||
else if(compatibleControllers.size() > 1) {
|
||||
if(mergePools == null) { mergePools = new ArrayList<Set<MultiblockControllerBase>>(); }
|
||||
|
||||
// THIS IS THE ONLY PLACE WHERE MERGES ARE DETECTED
|
||||
// Multiple compatible controllers indicates an impending merge.
|
||||
// Locate the appropriate merge pool(s)
|
||||
boolean hasAddedToPool = false;
|
||||
List<Set<MultiblockControllerBase>> candidatePools = new ArrayList<Set<MultiblockControllerBase>>();
|
||||
for(Set<MultiblockControllerBase> 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);
|
||||
}
|
||||
}
|
||||
|
||||
if(candidatePools.size() <= 0) {
|
||||
// No pools nearby, create a new merge pool
|
||||
mergePools.add(compatibleControllers);
|
||||
}
|
||||
else if(candidatePools.size() == 1) {
|
||||
// Only one pool nearby, simply add to that one
|
||||
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;
|
||||
for(int i = 1; i < candidatePools.size(); i++) {
|
||||
consumedPool = candidatePools.get(i);
|
||||
masterPool.addAll(consumedPool);
|
||||
mergePools.remove(consumedPool);
|
||||
}
|
||||
masterPool.addAll(compatibleControllers);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(mergePools != null && mergePools.size() > 0) {
|
||||
// Process merges - any machines that have been marked for merge should be merged
|
||||
// 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) {
|
||||
// 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) {
|
||||
if(newMaster == null || controller.shouldConsume(newMaster)) {
|
||||
newMaster = controller;
|
||||
}
|
||||
}
|
||||
|
||||
if(newMaster == null) {
|
||||
BeefCoreLog.fatal("Multiblock system checked a merge pool of size %d, found no master candidates. This should never happen.", mergePool.size());
|
||||
}
|
||||
else {
|
||||
// Merge all the other machines into the master machine, then unregister them
|
||||
addDirtyController(newMaster);
|
||||
for(MultiblockControllerBase controller : mergePool) {
|
||||
if(controller != newMaster) {
|
||||
newMaster.assimilate(controller);
|
||||
addDeadController(controller);
|
||||
addDirtyController(newMaster);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process splits and assembly
|
||||
// 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) {
|
||||
Set<IMultiblockPart> newlyDetachedParts = null;
|
||||
for(MultiblockControllerBase controller : dirtyControllers) {
|
||||
// Tell the machine to check if any parts are disconnected.
|
||||
// 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.
|
||||
newlyDetachedParts = controller.checkForDisconnections();
|
||||
|
||||
if(!controller.isEmpty()) {
|
||||
controller.recalculateMinMaxCoords();
|
||||
controller.checkIfMachineIsWhole();
|
||||
}
|
||||
else {
|
||||
addDeadController(controller);
|
||||
}
|
||||
|
||||
if(newlyDetachedParts != null && newlyDetachedParts.size() > 0) {
|
||||
// Controller has shed some parts - add them to the detached list for delayed processing
|
||||
detachedParts.addAll(newlyDetachedParts);
|
||||
}
|
||||
}
|
||||
|
||||
dirtyControllers.clear();
|
||||
}
|
||||
|
||||
// Unregister dead controllers
|
||||
if(deadControllers.size() > 0) {
|
||||
for(MultiblockControllerBase 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()) {
|
||||
BeefCoreLog.fatal("Found a non-empty controller. Forcing it to shed its blocks and die. This should never happen!");
|
||||
detachedParts.addAll(controller.detachAllBlocks());
|
||||
}
|
||||
|
||||
// THIS IS THE ONLY PLACE WHERE CONTROLLERS ARE UNREGISTERED.
|
||||
this.controllers.remove(controller);
|
||||
}
|
||||
|
||||
deadControllers.clear();
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Ensure parts know they're detached
|
||||
part.assertDetached();
|
||||
}
|
||||
|
||||
addAllOrphanedPartsThreadsafe(detachedParts);
|
||||
detachedParts.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
if(!worldObj.getChunkProvider().chunkExists(worldLocation.getChunkX(), worldLocation.getChunkZ())) {
|
||||
// Part goes into the waiting-for-chunk-load list
|
||||
Set<IMultiblockPart> partSet;
|
||||
long chunkHash = worldLocation.getChunkXZHash();
|
||||
synchronized(partsAwaitingChunkLoadMutex) {
|
||||
if(!partsAwaitingChunkLoad.containsKey(chunkHash)) {
|
||||
partSet = new HashSet<IMultiblockPart>();
|
||||
partsAwaitingChunkLoad.put(chunkHash, partSet);
|
||||
}
|
||||
else {
|
||||
partSet = partsAwaitingChunkLoad.get(chunkHash);
|
||||
}
|
||||
|
||||
partSet.add(part);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Part goes into the orphan queue, to be checked this tick
|
||||
addOrphanedPartThreadsafe(part);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a part is removed from the world, via user action or via chunk unloads.
|
||||
* 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();
|
||||
if(coord != null) {
|
||||
long hash = coord.getChunkXZHash();
|
||||
|
||||
if(partsAwaitingChunkLoad.containsKey(hash)) {
|
||||
synchronized(partsAwaitingChunkLoadMutex) {
|
||||
if(partsAwaitingChunkLoad.containsKey(hash)) {
|
||||
partsAwaitingChunkLoad.get(hash).remove(part);
|
||||
if(partsAwaitingChunkLoad.get(hash).size() <= 0) {
|
||||
partsAwaitingChunkLoad.remove(hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
detachedParts.remove(part);
|
||||
if(orphanedParts.contains(part)) {
|
||||
synchronized(orphanedPartsMutex) {
|
||||
orphanedParts.remove(part);
|
||||
}
|
||||
}
|
||||
|
||||
part.assertDetached();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the world which this World Registry represents is fully unloaded from the system.
|
||||
* Does some housekeeping just to be nice.
|
||||
*/
|
||||
public void onWorldUnloaded() {
|
||||
controllers.clear();
|
||||
deadControllers.clear();
|
||||
dirtyControllers.clear();
|
||||
|
||||
detachedParts.clear();
|
||||
|
||||
synchronized(partsAwaitingChunkLoadMutex) {
|
||||
partsAwaitingChunkLoad.clear();
|
||||
}
|
||||
|
||||
synchronized(orphanedPartsMutex) {
|
||||
orphanedParts.clear();
|
||||
}
|
||||
|
||||
worldObj = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a chunk has finished loading. Adds all of the parts which are awaiting
|
||||
* load to the list of parts which are orphans and therefore will be added to machines
|
||||
* after the next world tick.
|
||||
*
|
||||
* @param chunkX Chunk X coordinate (world coordate >> 4) of the chunk that was loaded
|
||||
* @param chunkZ Chunk Z coordinate (world coordate >> 4) of the chunk that was loaded
|
||||
*/
|
||||
public void onChunkLoaded(int chunkX, int chunkZ) {
|
||||
long chunkHash = ChunkCoordIntPair.chunkXZ2Int(chunkX, chunkZ);
|
||||
if(partsAwaitingChunkLoad.containsKey(chunkHash)) {
|
||||
synchronized(partsAwaitingChunkLoadMutex) {
|
||||
if(partsAwaitingChunkLoad.containsKey(chunkHash)) {
|
||||
addAllOrphanedPartsThreadsafe(partsAwaitingChunkLoad.get(chunkHash));
|
||||
partsAwaitingChunkLoad.remove(chunkHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a controller as dead. It will be cleaned up at the end of the next world tick.
|
||||
* Note that a controller must shed all of its blocks before being marked as dead, or the system
|
||||
* will complain at you.
|
||||
*
|
||||
* @param deadController The controller which is dead.
|
||||
*/
|
||||
public void addDeadController(MultiblockControllerBase deadController) {
|
||||
this.deadControllers.add(deadController);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a controller as dirty - its list of attached blocks has changed, and it
|
||||
* must be re-checked for assembly and, possibly, for orphans.
|
||||
*
|
||||
* @param dirtyController The dirty controller.
|
||||
*/
|
||||
public void addDirtyController(MultiblockControllerBase dirtyController) {
|
||||
this.dirtyControllers.add(dirtyController);
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this only if you know what you're doing. You should rarely need to iterate
|
||||
* over all controllers in a world!
|
||||
*
|
||||
* @return An (unmodifiable) set of controllers which are active in this world.
|
||||
*/
|
||||
public Set<MultiblockControllerBase> getControllers() {
|
||||
return Collections.unmodifiableSet(controllers);
|
||||
}
|
||||
|
||||
/* *** PRIVATE HELPERS *** */
|
||||
|
||||
private void addOrphanedPartThreadsafe(IMultiblockPart part) {
|
||||
synchronized(orphanedPartsMutex) {
|
||||
orphanedParts.add(part);
|
||||
}
|
||||
}
|
||||
|
||||
private void addAllOrphanedPartsThreadsafe(Collection<? extends IMultiblockPart> parts) {
|
||||
synchronized(orphanedPartsMutex) {
|
||||
orphanedParts.addAll(parts);
|
||||
}
|
||||
}
|
||||
|
||||
private String clientOrServer() { return worldObj.isRemote ? "CLIENT" : "SERVER"; }
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package erogenousbeef.coreTR.multiblock.rectangular;
|
||||
|
||||
public enum PartPosition {
|
||||
Unknown,
|
||||
Interior,
|
||||
FrameCorner,
|
||||
Frame,
|
||||
TopFace,
|
||||
BottomFace,
|
||||
NorthFace,
|
||||
SouthFace,
|
||||
EastFace,
|
||||
WestFace;
|
||||
|
||||
public boolean isFace(PartPosition position) {
|
||||
switch(position) {
|
||||
case TopFace:
|
||||
case BottomFace:
|
||||
case NorthFace:
|
||||
case SouthFace:
|
||||
case EastFace:
|
||||
case WestFace:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,130 @@
|
|||
package erogenousbeef.coreTR.multiblock.rectangular;
|
||||
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.world.World;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
import erogenousbeef.coreTR.multiblock.MultiblockControllerBase;
|
||||
import erogenousbeef.coreTR.multiblock.MultiblockValidationException;
|
||||
|
||||
public abstract class RectangularMultiblockControllerBase extends
|
||||
MultiblockControllerBase {
|
||||
|
||||
protected RectangularMultiblockControllerBase(World world) {
|
||||
super(world);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the machine is "whole" and should be assembled. False otherwise.
|
||||
*/
|
||||
protected void isMachineWhole() throws MultiblockValidationException {
|
||||
if(connectedParts.size() < getMinimumNumberOfBlocksForAssembledMachine()) {
|
||||
throw new MultiblockValidationException("Machine is too small.");
|
||||
}
|
||||
|
||||
CoordTriplet maximumCoord = getMaximumCoord();
|
||||
CoordTriplet 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 maxX = getMaximumXSize();
|
||||
int maxY = getMaximumYSize();
|
||||
int maxZ = getMaximumZSize();
|
||||
int minX = getMinimumXSize();
|
||||
int minY = getMinimumYSize();
|
||||
int minZ = getMinimumZSize();
|
||||
|
||||
if(maxX > 0 && deltaX > maxX) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the X dimension", maxX)); }
|
||||
if(maxY > 0 && deltaY > maxY) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Y dimension", maxY)); }
|
||||
if(maxZ > 0 && deltaZ > maxZ) { throw new MultiblockValidationException(String.format("Machine is too large, it may be at most %d blocks in the Z dimension", maxZ)); }
|
||||
if(deltaX < minX) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the X dimension", minX)); }
|
||||
if(deltaY < minY) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Y dimension", minY)); }
|
||||
if(deltaZ < minZ) { throw new MultiblockValidationException(String.format("Machine is too small, it must be at least %d blocks in the Z dimension", minZ)); }
|
||||
|
||||
// Now we run a simple check on each block within that volume.
|
||||
// Any block deviating = NO DEAL SIR
|
||||
TileEntity te;
|
||||
RectangularMultiblockTileEntityBase 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++) {
|
||||
// Okay, figure out what sort of block this should be.
|
||||
|
||||
te = this.worldObj.getTileEntity(x, y, z);
|
||||
if(te instanceof RectangularMultiblockTileEntityBase) {
|
||||
part = (RectangularMultiblockTileEntityBase)te;
|
||||
|
||||
// Ensure this part should actually be allowed within a cube of this controller's type
|
||||
if(!myClass.equals(part.getMultiblockControllerType()))
|
||||
{
|
||||
throw new MultiblockValidationException(String.format("Part @ %d, %d, %d is incompatible with machines of type %s", x, y, z, myClass.getSimpleName()));
|
||||
}
|
||||
}
|
||||
else {
|
||||
// This is permitted so that we can incorporate certain non-multiblock parts inside interiors
|
||||
part = null;
|
||||
}
|
||||
|
||||
// Validate block type against both part-level and material-level validators.
|
||||
int extremes = 0;
|
||||
if(x == minimumCoord.x) { extremes++; }
|
||||
if(y == minimumCoord.y) { extremes++; }
|
||||
if(z == minimumCoord.z) { extremes++; }
|
||||
|
||||
if(x == maximumCoord.x) { extremes++; }
|
||||
if(y == maximumCoord.y) { extremes++; }
|
||||
if(z == maximumCoord.z) { extremes++; }
|
||||
|
||||
if(extremes >= 2) {
|
||||
if(part != null) {
|
||||
part.isGoodForFrame();
|
||||
}
|
||||
else {
|
||||
isBlockGoodForFrame(this.worldObj, x, y, z);
|
||||
}
|
||||
}
|
||||
else if(extremes == 1) {
|
||||
if(y == maximumCoord.y) {
|
||||
if(part != null) {
|
||||
part.isGoodForTop();
|
||||
}
|
||||
else {
|
||||
isBlockGoodForTop(this.worldObj, x, y, z);
|
||||
}
|
||||
}
|
||||
else if(y == minimumCoord.y) {
|
||||
if(part != null) {
|
||||
part.isGoodForBottom();
|
||||
}
|
||||
else {
|
||||
isBlockGoodForBottom(this.worldObj, x, y, z);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Side
|
||||
if(part != null) {
|
||||
part.isGoodForSides();
|
||||
}
|
||||
else {
|
||||
isBlockGoodForSides(this.worldObj, x, y, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if(part != null) {
|
||||
part.isGoodForInterior();
|
||||
}
|
||||
else {
|
||||
isBlockGoodForInterior(this.worldObj, x, y, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
package erogenousbeef.coreTR.multiblock.rectangular;
|
||||
|
||||
import net.minecraftforge.common.util.ForgeDirection;
|
||||
import erogenousbeef.coreTR.common.CoordTriplet;
|
||||
import erogenousbeef.coreTR.multiblock.MultiblockControllerBase;
|
||||
import erogenousbeef.coreTR.multiblock.MultiblockTileEntityBase;
|
||||
import erogenousbeef.coreTR.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 isGoodForFrame() throws MultiblockValidationException;
|
||||
|
||||
public abstract void isGoodForSides() throws MultiblockValidationException;
|
||||
|
||||
public abstract void isGoodForTop() throws MultiblockValidationException;
|
||||
|
||||
public abstract void isGoodForBottom() throws MultiblockValidationException;
|
||||
|
||||
public abstract void isGoodForInterior() throws MultiblockValidationException;
|
||||
}
|
|
@ -13,8 +13,6 @@ public class TileBlastFurnace extends TileMachineBase implements IWrenchable {
|
|||
public BasicSink energy;
|
||||
public Inventory inventory = new Inventory(3, "TileBlastFurnace", 64);
|
||||
|
||||
public TileBlastFurnace() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean wrenchCanSetFacing(EntityPlayer entityPlayer, int side) {
|
||||
|
@ -45,4 +43,8 @@ public class TileBlastFurnace extends TileMachineBase implements IWrenchable {
|
|||
return new ItemStack(ModBlocks.BlastFurnace, 1);
|
||||
}
|
||||
|
||||
public boolean isComplete(){
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue