diff --git a/codechicken/microblock/BlockMicroMaterial.scala b/codechicken/microblock/BlockMicroMaterial.scala index 99ac11b..93bfaee 100644 --- a/codechicken/microblock/BlockMicroMaterial.scala +++ b/codechicken/microblock/BlockMicroMaterial.scala @@ -25,6 +25,9 @@ import net.minecraftforge.common.MinecraftForge import net.minecraft.client.renderer.RenderBlocks import codechicken.microblock.handler.MicroblockProxy +/** + * Standard micro material class suitable for most blocks. + */ class BlockMicroMaterial(val block:Block, val meta:Int = 0) extends IMicroMaterial { @SideOnly(Side.CLIENT) @@ -110,6 +113,9 @@ class BlockMicroMaterial(val block:Block, val meta:Int = 0) extends IMicroMateri def getSound = block.stepSound } +/** + * Utility functions for cleaner registry code + */ object BlockMicroMaterial { def createAndRegister(block:Block) diff --git a/codechicken/microblock/IMicroMaterialRender.scala b/codechicken/microblock/IMicroMaterialRender.scala index 7f28f76..19a8d59 100644 --- a/codechicken/microblock/IMicroMaterialRender.scala +++ b/codechicken/microblock/IMicroMaterialRender.scala @@ -3,6 +3,9 @@ package codechicken.microblock import codechicken.lib.vec.Cuboid6 import net.minecraft.world.World +/** + * Wrapper class blocks/tiles/parts wanting to use the micro material system to render part of their models. + */ trait IMicroMaterialRender { /** * May be null for inventory rendering. diff --git a/codechicken/microblock/ItemSaw.scala b/codechicken/microblock/ItemSaw.scala index 50eb4d3..025ca9c 100644 --- a/codechicken/microblock/ItemSaw.scala +++ b/codechicken/microblock/ItemSaw.scala @@ -22,8 +22,14 @@ import codechicken.lib.math.MathHelper._ import net.minecraft.util.ResourceLocation import net.minecraft.client.renderer.texture.IconRegister +/** + * Interface for items that are 'saws' + */ trait Saw { + /** + * The harvest level this saw is capable of cutting + */ def getCuttingStrength:Int } diff --git a/codechicken/microblock/MicroMaterialRegistry.scala b/codechicken/microblock/MicroMaterialRegistry.scala index 8070e25..9b17183 100644 --- a/codechicken/microblock/MicroMaterialRegistry.scala +++ b/codechicken/microblock/MicroMaterialRegistry.scala @@ -23,38 +23,81 @@ import net.minecraft.world.World object MicroMaterialRegistry { + /** + * Interface for defining a micro material + */ trait IMicroMaterial { + /** + * The icon to be used for breaking particles on side + */ @SideOnly(Side.CLIENT) def getBreakingIcon(side:Int):Icon + /** + * Callback to load icons from the underlying block/etc + */ @SideOnly(Side.CLIENT) def loadIcons(){} + /** + * This function must render the quad face specified by verts facing on side, at pos (x, y, z) + * @param lightMatrix A helper class provided for calculating minecraft smooth lighting on the face. + * @param part An IMicroMaterialRender callback for some information about the caller such as bounds and world for grass decals. + */ @SideOnly(Side.CLIENT) def renderMicroFace(verts:Array[Vertex5], side:Int, pos:Vector3, lightMatrix:LightMatrix, part:IMicroMaterialRender) + /** + * Get the render pass for which this material renders in. + */ @SideOnly(Side.CLIENT) def getRenderPass():Int + /** + * Return true if this material is not opaque (glass, ice). + */ def isTransparent():Boolean + /** + * Return the light level emitted by this material (glowstone) + */ def getLightValue():Int + /** + * Return the strength of this material + */ def getStrength(player:EntityPlayer):Float + /** + * Return the localised name of this material (normally the block name) + */ def getLocalizedName():String + /** + * Get the item that this material is cut from (full block -> slabs) + */ def getItem():ItemStack + /** + * Get the strength of saw requried to cut this material + */ def getCutterStrength():Int + /** + * Get the breaking/walking sound + */ def getSound():StepSound + /** + * Return true if this material is solid and opaque (can run wires on etc) + */ def isSolid() = !isTransparent - //todo, get material properties } + /** + * Interface for overriding the default micro placement highlight handler to show the effect of placement on a certain block/part + */ trait IMicroHighlightRenderer { /** @@ -66,10 +109,13 @@ object MicroMaterialRegistry private val typeMap:HashMap[String, IMicroMaterial] = new HashMap private val nameMap:HashMap[String, Int] = new HashMap private var idMap:Array[(String, IMicroMaterial)] = _ - private val idWriter = IDWriter() + private val idWriter = new IDWriter private val highlightRenderers = ListBuffer[IMicroHighlightRenderer]() + /** + * Register a micro material with unique identifier name + */ def registerMaterial(material:IMicroMaterial, name:String) { if(MultiPartRegistry.loaded) @@ -83,6 +129,9 @@ object MicroMaterialRegistry typeMap.put(name, material) } + /** + * Replace a micro material with unique identifier name + */ def replaceMaterial(material:IMicroMaterial, name:String) { if(MultiPartRegistry.loaded) throw new IllegalStateException("You must register your materials in the init methods.") @@ -95,6 +144,9 @@ object MicroMaterialRegistry typeMap.put(name, material) } + /** + * Registers a highlight renderer + */ def registerHighlightRenderer(handler:IMicroHighlightRenderer) { highlightRenderers+=handler diff --git a/codechicken/microblock/TMicroOcclusion.scala b/codechicken/microblock/TMicroOcclusion.scala index c32d5b3..cb570b9 100644 --- a/codechicken/microblock/TMicroOcclusion.scala +++ b/codechicken/microblock/TMicroOcclusion.scala @@ -7,6 +7,9 @@ import cpw.mods.fml.relauncher.Side import codechicken.multipart.TileMultipart import codechicken.multipart.PartMap._ +/** + * Suite of classes for performing microblock style occlusion and shrink rendering. Use at your own peril. + */ object MicroOcclusion { def shrink(renderBounds:Cuboid6, b:Cuboid6, side:Int) = side match diff --git a/codechicken/multipart/BlockMultipart.scala b/codechicken/multipart/BlockMultipart.scala index 3641fea..b7e051d 100644 --- a/codechicken/multipart/BlockMultipart.scala +++ b/codechicken/multipart/BlockMultipart.scala @@ -52,18 +52,27 @@ object BlockMultipart null } + def reduceMOP(hit:MovingObjectPosition):(Int, ExtendedMOP) = { + val ehit = hit.asInstanceOf[ExtendedMOP] + val data:(Int, _) = ExtendedMOP.getData(hit) + return (data._1, new ExtendedMOP(ehit, data._2, ehit.dist)) + } + def drawHighlight(world:World, player:EntityPlayer, hit:MovingObjectPosition, frame:Float):Boolean = { val tile = getTile(world, hit.blockX, hit.blockY, hit.blockZ) if(tile == null) return false - val hitInfo:(Int, _) = ExtendedMOP.getData(hit) - return tile.partList(hitInfo._1).drawHighlight(hit, player, frame) + val (index, mop) = reduceMOP(hit) + return tile.partList(index).drawHighlight(mop, player, frame) } } -trait BlockMultipart extends Block +/** + * Block class for all multiparts, should be internal use only. + */ +class BlockMultipart(id:Int) extends Block(id, Material.rock) { import BlockMultipart._ @@ -141,6 +150,7 @@ trait BlockMultipart extends Block val tile = getTile(world, x, y, z) if(tile != null) tile.partList.foreach(part => part.getDrops.foreach(item => ai.add(item))) + return ai } @@ -160,8 +170,10 @@ trait BlockMultipart extends Block override def addBlockHitEffects(world:World, hit:MovingObjectPosition, effectRenderer:EffectRenderer):Boolean = { val tile = getClientTile(world, hit.blockX, hit.blockY, hit.blockZ) - if(tile != null) - tile.partList(ExtendedMOP.getData[(Int, _)](hit)._1).addHitEffects(hit, effectRenderer) + if(tile != null) { + val (index, mop) = reduceMOP(hit) + tile.partList(index).addHitEffects(mop, effectRenderer) + } return true } @@ -197,8 +209,8 @@ trait BlockMultipart extends Block val tile = getTile(world, x, y, z) if(tile != null) { - val hitInfo:(Int, _) = ExtendedMOP.getData(hit) - return tile.partList(hitInfo._1).pickItem(hit) + val (index, mop) = reduceMOP(hit) + return tile.partList(index).pickItem(mop) } return null } @@ -207,8 +219,10 @@ trait BlockMultipart extends Block { val hit = RayTracer.retraceBlock(world, player, x, y, z) val tile = getTile(world, x, y, z) - if(hit != null && tile != null) - return tile.partList(ExtendedMOP.getData[(Int, _)](hit)._1).getStrength(hit, player)/30F; + if(hit != null && tile != null) { + val (index, mop) = reduceMOP(hit) + return tile.partList(index).getStrength(mop, player)/30F; + } return 1/100F } @@ -248,8 +262,8 @@ trait BlockMultipart extends Block if(tile == null) return false - val hitInfo:(Int, _) = ExtendedMOP.getData(hit) - return tile.partList(hitInfo._1).activate(player, hit, player.getHeldItem()) + val (index, mop) = reduceMOP(hit) + return tile.partList(index).activate(player, mop, player.getHeldItem) } override def onBlockClicked(world:World, x:Int, y:Int, z:Int, player:EntityPlayer) @@ -262,8 +276,8 @@ trait BlockMultipart extends Block if(tile == null) return - val hitInfo:(Int, _) = ExtendedMOP.getData(hit) - tile.partList(hitInfo._1).click(player, hit, player.getHeldItem()) + val (index, mop) = reduceMOP(hit) + tile.partList(index).click(player, mop, player.getHeldItem) } override def isProvidingStrongPower(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int):Int = @@ -308,9 +322,4 @@ trait BlockMultipart extends Block override def weakTileChanges() = true override def canProvidePower = true -} - -class BlockMultipartImpl(id:Int) extends Block(id, Material.rock) with BlockMultipart -{ - } \ No newline at end of file diff --git a/codechicken/multipart/ControlKeyModifier.scala b/codechicken/multipart/ControlKeyModifier.scala index 1ba4dcc..007087c 100644 --- a/codechicken/multipart/ControlKeyModifier.scala +++ b/codechicken/multipart/ControlKeyModifier.scala @@ -12,6 +12,9 @@ import codechicken.multipart.handler.MultipartCPH import scala.collection.mutable.HashMap import net.minecraft.entity.player.EntityPlayer +/** + * A class that maintains a map server<->client of which players are holding the control (or placement modifier key) much like sneaking. + */ object ControlKeyModifer { implicit def playerControlValue(p:EntityPlayer) = new ControlKeyValue(p) @@ -22,8 +25,16 @@ object ControlKeyModifer } val map = HashMap[EntityPlayer, Boolean]().withDefaultValue(false) + + /** + * Implicit static for Java users. + */ + def isControlDown(p:EntityPlayer) = p.isControlDown } +/** + * Key Handler implementation + */ object ControlKeyHandler extends KeyHandler ( Array(new KeyBinding("key.control", Keyboard.KEY_LCONTROL)), Array(false)) diff --git a/codechicken/multipart/IDWriter.scala b/codechicken/multipart/IDWriter.scala index ce184ca..9a240df 100644 --- a/codechicken/multipart/IDWriter.scala +++ b/codechicken/multipart/IDWriter.scala @@ -3,7 +3,10 @@ package codechicken.multipart import codechicken.lib.data.MCDataOutput import codechicken.lib.data.MCDataInput -trait IDWriter +/** + * Class for reading and writing ids, widening the carrier data type as necessary + */ +class IDWriter { var write:(MCDataOutput, Int)=>Unit = _ var read:(MCDataInput)=>Int = _ @@ -27,13 +30,4 @@ trait IDWriter read = (data) => data.readUByte() } } -} - -object IDWriter -{ - def apply():IDWriter = new IDWriterImpl; -} - -class IDWriterImpl extends IDWriter -{ } \ No newline at end of file diff --git a/codechicken/multipart/INeighborTileChange.scala b/codechicken/multipart/INeighborTileChange.scala index 5805cb7..6a8eb11 100644 --- a/codechicken/multipart/INeighborTileChange.scala +++ b/codechicken/multipart/INeighborTileChange.scala @@ -1,7 +1,15 @@ package codechicken.multipart +/** + * Mixin interface for parts that want to be notified of neighbor tile change events (comparators or inventory maintainers) + */ trait INeighborTileChange { + /** + * Returns whether this part needs calls for tile changes through one solid block + */ def weakTileChanges():Boolean - + /** + * Callback for neighbor tile changes, from same function in Block + */ def onNeighborTileChanged(side:Int, weak:Boolean) } \ No newline at end of file diff --git a/codechicken/multipart/IRandomDisplayTick.scala b/codechicken/multipart/IRandomDisplayTick.scala index 1382881..a51245d 100644 --- a/codechicken/multipart/IRandomDisplayTick.scala +++ b/codechicken/multipart/IRandomDisplayTick.scala @@ -2,7 +2,15 @@ package codechicken.multipart import java.util.Random +/** + * Interface for parts that need random display ticks (torches) + * + * Marker interface for TRandomDisplayTickTile + */ trait IRandomDisplayTick { + /** + * Called on a random display tick. + */ def randomDisplayTick(random:Random) } \ No newline at end of file diff --git a/codechicken/multipart/IRandomUpdateTick.scala b/codechicken/multipart/IRandomUpdateTick.scala index 5a28cd4..f689dce 100644 --- a/codechicken/multipart/IRandomUpdateTick.scala +++ b/codechicken/multipart/IRandomUpdateTick.scala @@ -1,6 +1,12 @@ package codechicken.multipart +/** + * Interface for parts with random update ticks. + */ trait IRandomUpdateTick { + /** + * Called on random update. Random ticks are between 800 and 1600 ticks from their last scheduled/random tick + */ def randomUpdate() } \ No newline at end of file diff --git a/codechicken/multipart/IRedstonePart.scala b/codechicken/multipart/IRedstonePart.scala index c346075..9bfb5c0 100644 --- a/codechicken/multipart/IRedstonePart.scala +++ b/codechicken/multipart/IRedstonePart.scala @@ -8,18 +8,36 @@ import net.minecraft.util.Direction import PartMap._ import codechicken.lib.vec.Rotation._ +/** + * Interface for parts with redstone interaction + * + * Marker interface for TRedstoneTile. This means that if a part is an instance of IRedstonePart, the container tile may be cast to TRedstoneTile + */ trait IRedstonePart { + /** + * Returns the strong (indirect, through blocks) signal being emitted by this part to the specified side + */ def strongPowerLevel(side:Int):Int + /** + * Returns the weak (direct) signal being emitted by this part to the specified side + */ def weakPowerLevel(side:Int):Int + /** + * Returns true if this part can connect to redstone on the specified side. Blocking parts like covers will be handled by RedstoneInteractions + */ def canConnectRedstone(side:Int):Boolean } /** - * For parts like wires that adhere to a specific face, reduces redstone connections to the specific edge between two faces + * For parts like wires that adhere to a specific face, reduces redstone connections to the specific edge between two faces. + * Should be implemented on parts implementing TFacePart */ trait IFaceRedstonePart extends IRedstonePart { + /** + * Return the face to which this redstone part is attached + */ def getFace():Int } @@ -28,27 +46,40 @@ trait IFaceRedstonePart extends IRedstonePart */ trait IMaskedRedstonePart extends IRedstonePart { + /** + * Returns the redstone connection mask for this part on side. See IRedstoneConnector for mask definition + */ def getConnectionMask(side:Int):Int } +/** + * Interface for tile entities which split their redstone connections into a mask for each side (edges and center) + * + * All connection masks are a 5 bit map. + * The lowest 4 bits correspond to the connection toward the face specified Rotation.rotateSide(side&6, b) where b is the bit index from lowest to highest. + * Bit 5 corresponds to a connection opposite side. + */ +trait IRedstoneConnector +{ + /** + * Returns the redstone connection mask for this tile on side. + */ + def getConnectionMask(side:Int):Int + /** + * Returns the weak power level provided by this tile on side through mask + */ + def weakPowerLevel(side:Int, mask:Int):Int +} + /** * Internal interface for TileMultipart instances hosting IRedstonePart */ trait IRedstoneTile extends IRedstoneConnector { + /** + * Returns a mask of spaces through which a wire could connect on side + */ def openConnections(side:Int):Int - def blocksRedstone(i:Int):Boolean -} - -/** - * All connection masks are a 5 bit map. - * The lowest 4 bits correspond to the connection toward the face specfied rotateSide(side&6, b) where b is the bit index from lowest to highest. - * Bit 5 corresponds to a connection opposite side. - */ -trait IRedstoneConnector -{ - def getConnectionMask(side:Int):Int - def weakPowerLevel(side:Int, mask:Int):Int } /** @@ -60,6 +91,11 @@ trait IRedstoneConnectorBlock def weakPowerLevel(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, mask:Int):Int } +/** + * static helper class for calculating various things about redstone. + * Indirect power (also known as strong power) is not handled here, just use world.getIndirectPowerTo + * Masks are defined in IRedstoneConnector + */ object RedstoneInteractions { import net.minecraft.util.Facing._ @@ -67,6 +103,9 @@ object RedstoneInteractions val vanillaSideMap = Array(-2, -1, 0, 2, 3, 1) val sideVanillaMap = Array(1, 2, 5, 3, 4) + /** + * Get the direct power to p on side + */ def getPowerTo(p:TMultiPart, side:Int):Int = { val tile = p.tile @@ -74,9 +113,15 @@ object RedstoneInteractions tile.asInstanceOf[IRedstoneTile].openConnections(side)&connectionMask(p, side)) } + /** + * Get the direct power level to space (x, y, z) on side with mask + */ def getPowerTo(world:World, x:Int, y:Int, z:Int, side:Int, mask:Int):Int = getPower(world, x+offsetsXForSide(side), y+offsetsYForSide(side), z+offsetsZForSide(side), side^1, mask) - + + /** + * Get the direct power level provided by space (x, y, z) on side with mask + */ def getPower(world:World, x:Int, y:Int, z:Int, side:Int, mask:Int):Int = { val tile = world.getBlockTileEntity(x, y, z) @@ -103,9 +148,16 @@ object RedstoneInteractions def vanillaToSide(vside:Int) = sideVanillaMap(vside+1) + /** + * Get the connection mask of the block on side of (x, y, z). + * @param power, whether the connection mask is for signal transfer or visual connection. (some blocks accept power without visual connection) + */ def otherConnectionMask(world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, power:Boolean):Int = getConnectionMask(world, x+offsetsXForSide(side), y+offsetsYForSide(side), z+offsetsZForSide(side), side^1, power) - + + /** + * Get the connection mask of part on side + */ def connectionMask(p:TMultiPart, side:Int):Int = { if(p.isInstanceOf[IRedstonePart] && p.asInstanceOf[IRedstonePart].canConnectRedstone(side)) @@ -146,6 +198,9 @@ object RedstoneInteractions return vanillaConnectionMask(block, world, x, y, z, side, power) } + /** + * Returns the connection mask for a vanilla block + */ def vanillaConnectionMask(block:Block, world:IBlockAccess, x:Int, y:Int, z:Int, side:Int, power:Boolean):Int = { if(block == Block.torchRedstoneActive || block == Block.torchRedstoneIdle || block == Block.lever || block == Block.stoneButton || block == Block.woodenButton) diff --git a/codechicken/multipart/ItemMultiPart.scala b/codechicken/multipart/ItemMultiPart.scala index 4f19fbd..aaf780d 100644 --- a/codechicken/multipart/ItemMultiPart.scala +++ b/codechicken/multipart/ItemMultiPart.scala @@ -8,8 +8,14 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.world.World import codechicken.lib.vec.BlockCoord +/** + * Java class implementation + */ abstract class JItemMultiPart(id:Int) extends Item(id) with TItemMultiPart +/** + * Simple multipart item class for easy placement. Simply override the newPart function and it the part will be added to the block space if it passes the occlusion tests. + */ trait TItemMultiPart extends Item { def getHitDepth(vhit:Vector3, side:Int):Double = @@ -41,5 +47,8 @@ trait TItemMultiPart extends Item return place() } + /** + * Create a new part based on the placement information parameters. + */ def newPart(item:ItemStack, player:EntityPlayer, world:World, pos:BlockCoord, side:Int, vhit:Vector3):TMultiPart } \ No newline at end of file diff --git a/codechicken/multipart/MultiPartRegistry.scala b/codechicken/multipart/MultiPartRegistry.scala index 3f225db..b1a84bc 100644 --- a/codechicken/multipart/MultiPartRegistry.scala +++ b/codechicken/multipart/MultiPartRegistry.scala @@ -8,32 +8,61 @@ import net.minecraft.world.World import codechicken.lib.vec.BlockCoord import scala.collection.mutable.ListBuffer +/** + * This class handles the registration and internal ID mapping of all multipart classes. + */ object MultiPartRegistry { + /** + * Interface to be registered for constructing parts. + * Every instance of every multipart is constructed from an implementor of this. + */ trait IPartFactory { + /** + * Create a new instance of the part with the specified type name identifier + * @param client If the part instance is for the client or the server + */ def createPart(name:String, client:Boolean):TMultiPart; } + /** + * An interface for converting existing blocks/tile entities to multipart versions. + */ trait IPartConverter { + /** + * Return true if this converter can handle the specific blockID (may or may not actually convert the block) + */ def canConvert(blockID:Int):Boolean + /** + * Return a multipart version of the block at pos in world. Return null if no conversion is possible. + */ def convert(world:World, pos:BlockCoord):TMultiPart } private val typeMap:HashMap[String, (Boolean)=>TMultiPart] = new HashMap private val nameMap:HashMap[String, Int] = new HashMap private var idMap:Array[(String, (Boolean)=>TMultiPart)] = _ - private val idWriter = IDWriter() + private val idWriter = new IDWriter private val converters:Array[Seq[IPartConverter]] = Array.fill(4096)(Seq()) + /** + * The state of the registry. 0 = no parts, 1 = registering, 2 = registered + */ private var state:Int = 0 + /** + * Register a part factory with an array of types it is capable of instantiating. Must be called before postInit + */ def registerParts(partFactory:IPartFactory, types:Array[String]) { registerParts(partFactory.createPart _, types:_*); } + /** + * Scala function version of registerParts + */ def registerParts(partFactory:(String, Boolean)=>TMultiPart, types:String*) { if(loaded) @@ -48,6 +77,9 @@ object MultiPartRegistry } } + /** + * Register a part converter instance + */ def registerConverter(c:IPartConverter) { for(i <- 0 until 4096) @@ -55,7 +87,7 @@ object MultiPartRegistry converters(i) = converters(i):+c } - def beforeServerStart() + private[multipart] def beforeServerStart() { idMap = typeMap.toList.sortBy(_._1).toArray idWriter.setMax(idMap.length) @@ -64,13 +96,13 @@ object MultiPartRegistry nameMap.put(idMap(i)._1, i) } - def writeIDMap(packet:PacketCustom) + private[multipart] def writeIDMap(packet:PacketCustom) { packet.writeInt(idMap.length) idMap.foreach(e => packet.writeString(e._1)) } - def readIDMap(packet:PacketCustom):Seq[String] = + private[multipart] def readIDMap(packet:PacketCustom):Seq[String] = { val k = packet.readInt() idWriter.setMax(k) @@ -88,19 +120,34 @@ object MultiPartRegistry return missing } - def required = state > 0 + /** + * Return true if any multiparts have been registered + */ + private[multipart] def required = state > 0 + /** + * Return true if no more parts can be registered + */ def loaded = state == 2 - def postInit(){state = 2} + private[multipart] def postInit(){state = 2} + /** + * Writes the id of part to data + */ def writePartID(data:MCDataOutput, part:TMultiPart) { idWriter.write(data, nameMap.get(part.getType).get) } + /** + * Uses instantiators to creat a new part from the id read from data + */ def readPart(data:MCDataInput) = idMap(idWriter.read(data))._2(true) + /** + * Uses instantiators to create a new part with specified identifier on side + */ def createPart(name:String, client:Boolean):TMultiPart = { val part = typeMap.get(name) @@ -113,6 +160,9 @@ object MultiPartRegistry } } + /** + * Calls converters to create a multipart version of the block at pos + */ def convertBlock(world:World, pos:BlockCoord, id:Int):TMultiPart = { converters(id).foreach{c => diff --git a/codechicken/multipart/MultipartGenerator.scala b/codechicken/multipart/MultipartGenerator.scala index cd994b6..26fb430 100644 --- a/codechicken/multipart/MultipartGenerator.scala +++ b/codechicken/multipart/MultipartGenerator.scala @@ -14,6 +14,16 @@ import scala.collection.mutable.ListBuffer import codechicken.multipart.asm.IMultipartFactory import codechicken.multipart.asm.ASMMixinFactory +/** + * This class manages the dynamic construction and allocation of container TileMultipart instances. + * + * Classes that extend TileMultipart, adding tile centric logic, optimisations or interfaces, can be registered to a marker interface on a part instance. + * When a part is added to the tile that implements the certain marker interface, the container tile will be replaced with a class that includes the functionality from the corresponding mixin class. + * + * Classes are generated in a similar fashion to the way scala traits are compiled. To see the output, simply enable the config option and look in the asm/multipart folder of you .minecraft directory. + * + * There are several mixin traits that come with the API included in the scalatraits package. TPartialOcclusionTile is defined as class instead of trait to give an example for Java programmers. + */ object MultipartGenerator { private var tileTraitMap:Map[Class[_], Set[String]] = Map() @@ -162,6 +172,15 @@ object MultipartGenerator def registerPassThroughInterface(s_interface:String):Unit = registerPassThroughInterface(s_interface, true, true) + /** + * A passthrough interface, is an interface to be implemented on the container tile instance, for which all calls are passed directly to the single implementing part. + * Registering a passthrough interface is equivalent to defining a mixin class as follows. + * 1. field 'impl' which contains the reference to the corresponding part + * 2. occlusionTest is overriden to prevent more than one part with s_interface existing in the block space + * 3. implementing s_interface and passing all calls directly to the part instance. + * + * This allows compatibility with APIs that expect interfaces on the tile entity. + */ def registerPassThroughInterface(s_interface:String, client:Boolean, server:Boolean) { val tType = factory.generatePassThroughTrait(s_interface) @@ -184,7 +203,7 @@ object MultipartGenerator } } - def registerTileClass(clazz:Class[_ <: TileEntity], traits:Set[String]) + private[multipart] def registerTileClass(clazz:Class[_ <: TileEntity], traits:Set[String]) { tileTraitMap=tileTraitMap+(clazz->traits) MultipartProxy.onTileClassBuilt(clazz) diff --git a/codechicken/multipart/MultipartRenderer.scala b/codechicken/multipart/MultipartRenderer.scala index 7e8f6cf..d086e35 100644 --- a/codechicken/multipart/MultipartRenderer.scala +++ b/codechicken/multipart/MultipartRenderer.scala @@ -20,6 +20,9 @@ import cpw.mods.fml.relauncher.Side import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.lighting.LazyLightMatrix +/** + * Internal class for rendering callbacks. Should be moved to the handler package + */ @SideOnly(Side.CLIENT) object MultipartRenderer extends TileEntitySpecialRenderer with ISimpleBlockRenderingHandler { diff --git a/codechicken/multipart/PartMap.java b/codechicken/multipart/PartMap.java index 06f49e0..9100ec9 100644 --- a/codechicken/multipart/PartMap.java +++ b/codechicken/multipart/PartMap.java @@ -1,5 +1,9 @@ package codechicken.multipart; +/** + * Defines what each slot in a multipart tile corresponds to and provides some utility functions. + * For performance reasons, it is recommended that integer constants be useds as opposed to this enum + */ public enum PartMap { BOTTOM(0), @@ -38,22 +42,36 @@ public enum PartMap this.i = i; mask = 1<>2) @@ -65,6 +83,11 @@ public enum PartMap throw new IllegalArgumentException("Switch Falloff"); } + /** + * Unpacks an edge index, to a mask where high values indicate positive positions in that axis. + * Note the parameter e is relative to the first edge slot and can range from 0-11 + * For example, edge 1 (slot 16), is EDGE_NYP so the mask returned would be 010 as z is positive. + */ public static int unpackEdgeBits(int e) { switch(e>>2) @@ -76,6 +99,10 @@ public enum PartMap throw new IllegalArgumentException("Switch Falloff"); } + /** + * Repacks a mask of axis bits indicating positive positions, into an edge in along the same axis as e. + * Note the parameter e is relative to the first edge slot and can range from 0-11 + */ public static int packEdgeBits(int e, int bits) { switch(e>>2) @@ -93,6 +120,9 @@ public enum PartMap -1, -1,-1, -1, 0, 2, -1, -1,-1, -1, 1, 3}; + /** + * Returns the slot of the edge between 2 sides. + */ public static int edgeBetween(int s1, int s2) { if(s2 < s1) diff --git a/codechicken/multipart/TCuboidPart.scala b/codechicken/multipart/TCuboidPart.scala index 222af84..38bbcde 100644 --- a/codechicken/multipart/TCuboidPart.scala +++ b/codechicken/multipart/TCuboidPart.scala @@ -11,10 +11,19 @@ import scala.collection.JavaConversions._ import java.lang.Iterable import codechicken.lib.vec.Translation +/** + * Java class implementation + */ abstract class JCuboidPart extends TCuboidPart +/** + * Trait for parts that are simply a cuboid, having one bounding box. Overrides multipart functions to this effect. + */ trait TCuboidPart extends TMultiPart { + /** + * Return the bounding Cuboid6 for this part. + */ def getBounds:Cuboid6 override def getSubParts:Iterable[IndexedCuboid6] = Seq(new IndexedCuboid6(0, getBounds)) diff --git a/codechicken/multipart/TEdgePart.scala b/codechicken/multipart/TEdgePart.scala index f514d1b..c8e8e88 100644 --- a/codechicken/multipart/TEdgePart.scala +++ b/codechicken/multipart/TEdgePart.scala @@ -1,6 +1,12 @@ package codechicken.multipart +/** + * Interface which must be implemented by parts that go in an edge slot. + */ trait TEdgePart extends TSlottedPart { + /** + * Return true if this part can conduct redstone signal or let redstone signal pass through it. + */ def conductsRedstone = false } \ No newline at end of file diff --git a/codechicken/multipart/TFacePart.scala b/codechicken/multipart/TFacePart.scala index 7f05633..bb97b1a 100644 --- a/codechicken/multipart/TFacePart.scala +++ b/codechicken/multipart/TFacePart.scala @@ -1,7 +1,16 @@ package codechicken.multipart +/** + * Inteface which must be implemented by parts that go in a face part. + */ trait TFacePart extends TSlottedPart { + /** + * Passed down from Block.isBlockSolidOnSide. Return true if this part is solid and opaque on the specified side + */ def solid(side:Int):Boolean = true + /** + * Return the redstone conduction map for which signal can pass through this part on the face. Eg, hollow covers return 0xF as signal can pass through the center hole. + */ def redstoneConductionMap = 0 } \ No newline at end of file diff --git a/codechicken/multipart/TIconHitEffects.scala b/codechicken/multipart/TIconHitEffects.scala index 7ae99a2..85a78ba 100644 --- a/codechicken/multipart/TIconHitEffects.scala +++ b/codechicken/multipart/TIconHitEffects.scala @@ -10,6 +10,16 @@ import codechicken.lib.vec.Vector3 import codechicken.lib.raytracer.ExtendedMOP import codechicken.lib.render.EntityDigIconFX +/** + * This suite of 3 classes provides simple functions for standard minecraft style hit and break particles. + * + * Scala|Java composition setup. + * Due to the lack of mixin inheritance in Java, the classes are structured to suit both languages as follows. + * IconHitEffects contains static implementations of the functions that would be overriden in TMultiPart + * JIconHitEffects is the interface that should be implemented by a Java class, + * which can then override the functions in TMultipart and call the static methods in IconHitEffects with 'this' as the first parameter + * TIconHitEffects is a trait for scala implementors that does includes the overrides/static calls that Java programmers need to include themselves. + */ object IconHitEffects { def addHitEffects(part:JIconHitEffects, hit:MovingObjectPosition, effectRenderer:EffectRenderer) @@ -37,17 +47,24 @@ object IconHitEffects } } +/** + * Java interface containing callbacks for particle rendering. + * Make sure to override addHitEffects and addDestroyEffects as in TIconHitEffects + */ trait JIconHitEffects extends TMultiPart { def getBounds:Cuboid6 @SideOnly(Side.CLIENT) - def getBreakingIcon(subPart:Any, side:Int) = getBrokenIcon(side) + def getBreakingIcon(subPart:Any, side:Int):Icon = getBrokenIcon(side) @SideOnly(Side.CLIENT) def getBrokenIcon(side:Int):Icon } +/** + * Trait for scala programmers + */ trait TIconHitEffects extends JIconHitEffects { @SideOnly(Side.CLIENT) diff --git a/codechicken/multipart/TMultiPart.scala b/codechicken/multipart/TMultiPart.scala index ad8b6d3..7f4d92e 100644 --- a/codechicken/multipart/TMultiPart.scala +++ b/codechicken/multipart/TMultiPart.scala @@ -30,81 +30,243 @@ import codechicken.lib.raytracer.RayTracer abstract class TMultiPart { + /** + * Reference to the container TileMultipart instance + */ var tile:TileMultipart = _ + /** + * Legacy helper function for getting the tile entity (from when TileMultipart was a trait). Use tile() now. + */ + @Deprecated def getTile():TileEntity = tile + /** + * Getter for tile.worldObj + */ def world() = if(tile == null) null else tile.worldObj + /** + * Short getter for xCoord + */ def x = tile.xCoord + /** + * Short getter for yCoord + */ def y = tile.yCoord + /** + * Short getter for zCoord + */ def z = tile.zCoord + /** + * The unique string identifier for this class of multipart. + */ def getType:String + /** + * Called when the container tile instance is changed to update reference + */ def bind(t:TileMultipart) { tile = t } + /** + * Perform an occlusion test to determine whether this and npart can 'fit' in this block space. + */ def occlusionTest(npart:TMultiPart):Boolean = true - def getSubParts:Iterable[IndexedCuboid6] = Seq() + /** + * Return a list of entity collision boxes. + * Note all Cuboid6's returned by methods in TMultiPart should be within (0,0,0)->(1,1,1) + */ def getCollisionBoxes:Iterable[Cuboid6] = Seq() + /** + * Perform a raytrace of this part. The default implementation does a Cuboid6 ray trace on bounding boxes returned from getSubParts. + * This should only be overridden if you need special ray-tracing capabilities such as triangular faces. + * The returned ExtendedMOP will be passed to methods such as 'activate' so it is recommended to use the data field to indicate information about the hit area. + */ def collisionRayTrace(start: Vec3, end: Vec3): ExtendedMOP = { val offset = new Vector3(x, y, z) val boxes = getSubParts.map(c => new IndexedCuboid6(c.data, c.copy.add(offset))) return RayTracer.instance.rayTraceCuboids(new Vector3(start), new Vector3(end), boxes.toList, new BlockCoord(x, y, z), tile.blockType).asInstanceOf[ExtendedMOP] } + /** + * For the default collisionRayTrace implementation, returns a list of indexed bounding boxes. The data field of ExtendedMOP will be set to the index of the cuboid the raytrace hit. + */ + def getSubParts:Iterable[IndexedCuboid6] = Seq() + /** + * Return a list of items that should be dropped when this part is destroyed. + */ def getDrops:Iterable[ItemStack] = Seq() + /** + * Return a value indicating how hard this part is to break + * @param hit An instance of ExtendedMOP from collisionRayTrace + */ def getStrength(hit:MovingObjectPosition, player:EntityPlayer):Float = 1 + /** + * The light level emitted by this part + */ def getLightValue = 0 + /** + * Add particles and other effects when a player is mining this part + * @param hit An instance of ExtendedMOP from collisionRayTrace + */ @SideOnly(Side.CLIENT) def addHitEffects(hit:MovingObjectPosition, effectRenderer:EffectRenderer){} + /** + * Add particles and other effects when a player broke this part + */ @SideOnly(Side.CLIENT) def addDestroyEffects(effectRenderer:EffectRenderer){} + /** + * Render the static, unmoving faces of this part into the world renderer. + * The Tessellator is already drawing. + * @param olm An optional light matrix to be used for rendering things with perfect MC blended lighting (eg microblocks). Only use this if you have to. + * @param pass The render pass, 1 or 0 + */ @SideOnly(Side.CLIENT) def renderStatic(pos:Vector3, olm:LazyLightMatrix, pass:Int){} + /** + * Render the dynamic, changing faces of this part and other gfx as in a TESR. + * The Tessellator will need to be started if it is to be used. + * @param pos The position of this block space relative to the renderer, same as x, y, z passed to TESR. + * @param frame The partial interpolation frame value for animations between ticks + * @param pass The render pass, 1 or 0 + */ @SideOnly(Side.CLIENT) def renderDynamic(pos:Vector3, frame:Float, pass:Int){} + /** + * Draw the breaking overlay for this part. The overrideIcon in RenderBlocks will be set to the fracture icon. + */ @SideOnly(Side.CLIENT) def drawBreaking(renderBlocks:RenderBlocks){} + /** + * Override the drawing of the selection box around this part. + * @param hit An instance of ExtendedMOP from collisionRayTrace + * @return true if highlight rendering was overridden. + */ @SideOnly(Side.CLIENT) def drawHighlight(hit:MovingObjectPosition, player:EntityPlayer, frame:Float) = false + /** + * Write all the data required to describe a client version of this part to the packet. + * Called serverside, when a client loads this part for the first time. + */ + def writeDesc(packet:MCDataOutput){} + /** + * Fill out this part with the description information contained in packet. Will be exactly as written from writeDesc. + * Called clientside when a client loads this part for the first time. + */ + def readDesc(packet:MCDataInput){} + /** + * Save part to NBT (only called serverside) + */ + def save(tag:NBTTagCompound){} + /** + * Load part from NBT (only called serverside) + */ + def load(tag:NBTTagCompound){} + /** + * Gets a MCDataOutput instance for writing update data to clients with this part loaded. + * The write stream functions as a buffer which is flushed in a compressed databurst packet at the end of the tick. + */ + def getWriteStream():MCDataOutput = tile.getWriteStream(this) + /** + * Read and operate on data written to getWriteStream. Ensure all data this part wrote is read even if it's not going to be used. + * The default implementation assumes a call to sendDescUpdate as the only use of getWriteStream. + */ def read(packet:MCDataInput) { readDesc(packet) tile.markRender() } - def readDesc(packet:MCDataInput){} - def writeDesc(packet:MCDataOutput){} - def save(tag:NBTTagCompound){} - def load(tag:NBTTagCompound){} + /** + * Quick and easy method to re-describe the whole part on the client. This will call read on the client which calls readDesc unless overriden. + * Incremental changes should be sent rather than the whole description packet if possible. + */ + def sendDescUpdate() = writeDesc(getWriteStream) /** + * Called when a part is added or removed from this block space. * The part parameter may be null if several things have changed. */ def onPartChanged(part:TMultiPart){} + /** + * Called when a neighbor block changed + */ def onNeighborChanged(){} + /** + * Called when this part is added to the block space + */ def onAdded() = onWorldJoin() + /** + * Called when this part is removed from the block space + */ def onRemoved() = onWorldSeparate() + /** + * Called when the containing chunk is loaded on the server. + */ def onChunkLoad() = onWorldJoin() + /** + * Called when the containing chunk is unloaded on the server. + */ def onChunkUnload() = onWorldSeparate() + /** + * Called when this part separates from the world (due to removal, chunk unload or other). Use this to sync with external data structures. + */ def onWorldSeparate(){} + /** + * Called when this part separates from the world (due to removal, chunk unload or other). Use this to sync with external data structures. + */ def onWorldJoin(){} + /** + * Called when this part is converted from a normal block/tile (only applicable if a converter has been registered) + */ def onConverted() = onAdded() + /** + * Called when this part has been moved without a save/load. + */ def onMoved() = onWorldJoin() + /** + * Called just before this part is actually removed from the container tile + */ def preRemove(){} + /** + * Return whether this part needs update ticks. This will only be called on addition/removal so it should be a constant for this instance. + */ def doesTick = true + /** + * Called once per world tick. This will be called even if doesTick returns false if another part in the space needs ticks. + */ def update(){} + /** + * Called when a scheduled tick is executed. + */ def scheduledTick(){} - - def pickItem(hit:MovingObjectPosition):ItemStack = null - def activate(player:EntityPlayer, part:MovingObjectPosition, item:ItemStack):Boolean = false - def click(player:EntityPlayer, part:MovingObjectPosition, item:ItemStack){} - def onEntityCollision(entity:Entity){} - - def sendDescUpdate() = writeDesc(tile.getWriteStream(this)) + /** + * Sets a scheduledTick callback for this part ticks in the future. This is a world time value, so if the chunk is unloaded and reloaded some time later, the tick may fire immediately. + */ def scheduleTick(ticks:Int) = TickScheduler.scheduleTick(this, ticks) + + /** + * Return the itemstack for the middle click pick-block function. + */ + def pickItem(hit:MovingObjectPosition):ItemStack = null + /** + * Called on block right click. item is the player's held item. + * This should not modify the part client side. If the client call returns false, the server will not call this function. + * @param hit An instance of ExtendedMOP from collisionRayTrace + */ + def activate(player:EntityPlayer, hit:MovingObjectPosition, item:ItemStack):Boolean = false + /** + * Called on block left click. item is the player's held item. + * @param hit An instance of ExtendedMOP from collisionRayTrace + */ + def click(player:EntityPlayer, hit:MovingObjectPosition, item:ItemStack){} + /** + * Called when an entity is within this block space. May not actually collide with this part. + */ + def onEntityCollision(entity:Entity){} } \ No newline at end of file diff --git a/codechicken/multipart/TNormalOcclusion.scala b/codechicken/multipart/TNormalOcclusion.scala index ef4dde0..bcf947e 100644 --- a/codechicken/multipart/TNormalOcclusion.scala +++ b/codechicken/multipart/TNormalOcclusion.scala @@ -4,11 +4,23 @@ import codechicken.lib.vec.Cuboid6 import scala.collection.JavaConversions._ import java.lang.Iterable +/** + * This suite of 3 classes provides simple functions for standard bounding box based occlusion testing. + * If any two parts have overlapping bounding boxes, the test fails + * + * See TIconHitEffects for notes on the Scala|Java composition setup. + */ object NormalOcclusionTest { + /** + * Performs the test, returns true if the test fails + */ def apply(boxes1:Traversable[Cuboid6], boxes2:Traversable[Cuboid6]):Boolean = boxes1.forall(v1 => boxes2.forall(v2 => !v1.intersects(v2))) + /** + * Performs the test, returns true if the test fails + */ def apply(part1:JNormalOcclusion, part2:TMultiPart):Boolean = { var boxes = Seq[Cuboid6]() @@ -22,11 +34,21 @@ object NormalOcclusionTest } } +/** + * Java interface containing callbacks for normal occlusion testing. + * Make sure to override occlusionTest as in TNormalOcclusion + */ trait JNormalOcclusion { + /** + * Return a list of normal occlusion boxes + */ def getOcclusionBoxes():Iterable[Cuboid6] } +/** + * Trait for scala programmers + */ trait TNormalOcclusion extends TMultiPart with JNormalOcclusion { override def occlusionTest(npart:TMultiPart):Boolean = diff --git a/codechicken/multipart/TPartialOcclusion.scala b/codechicken/multipart/TPartialOcclusion.scala index 8e75cb2..8f8c484 100644 --- a/codechicken/multipart/TPartialOcclusion.scala +++ b/codechicken/multipart/TPartialOcclusion.scala @@ -4,15 +4,18 @@ import codechicken.lib.vec.Cuboid6 import scala.collection.JavaConversions._ import java.lang.Iterable -trait JPartialOcclusion -{ - def getPartialOcclusionBoxes():Iterable[Cuboid6] - - def allowCompleteOcclusion = false -} - +/** + * This class provides a special type of occlusion model used by microblocks. + * The partial occlusion test defines bounding boxes that may intersect, so long as no part is completely obscured by a combination of the others. + * Partial bounding boxes may not intersect with normal bounding boxes from NormalOcclusionTest + * + * This test is actually managed by the mixin trait TPartialOcclusionTile which is generated when the marker interface JPartialOcclusion is found + */ class PartialOcclusionTest(size:Int) { + /** + * The resolution of the test, set to 1/8th of a block + */ val res = 8 val bits = new Array[Byte](res*res*res) val partial = new Array[Boolean](size) @@ -57,4 +60,17 @@ class PartialOcclusionTest(size:Int) return true } +} + +trait JPartialOcclusion +{ + /** + * Return a list of partial occlusion boxes + */ + def getPartialOcclusionBoxes():Iterable[Cuboid6] + + /** + * Return true if this part may be completely obscured + */ + def allowCompleteOcclusion = false } \ No newline at end of file diff --git a/codechicken/multipart/TSlottedPart.scala b/codechicken/multipart/TSlottedPart.scala index f9e16b2..c6e75a9 100644 --- a/codechicken/multipart/TSlottedPart.scala +++ b/codechicken/multipart/TSlottedPart.scala @@ -3,6 +3,8 @@ package codechicken.multipart /** * Interface for parts that fill a slot based configuration as defined in PartMap. * If this is implemented, calling partMap(slot) on the host tile will return this part if the corresponding bit in the slotMask is set + * + * Marker interface for TSlottedTile */ trait TSlottedPart extends TMultiPart { diff --git a/codechicken/multipart/TickScheduler.scala b/codechicken/multipart/TickScheduler.scala index 5eafb67..b829aa6 100644 --- a/codechicken/multipart/TickScheduler.scala +++ b/codechicken/multipart/TickScheduler.scala @@ -57,6 +57,8 @@ object TickScheduler extends WorldExtensionInstantiator .asInstanceOf[ChunkTickScheduler].scheduleTick(part, time, random) } + def loadRandom(part:TMultiPart) = scheduleTick(part, nextRandomTick, true) + override def preTick() { processing = true @@ -126,6 +128,8 @@ object TickScheduler extends WorldExtensionInstantiator CompressedStreamTools.writeCompressed(saveTag, dout); dout.close(); } + + def nextRandomTick = world.rand.nextInt(800)+800 } def createWorldExtension(world:World):WorldExtension = new WorldTickScheduler(world) @@ -146,7 +150,7 @@ object TickScheduler extends WorldExtensionInstantiator val e = it.next if(e.part == part) { - if(e.random && !random) + if(e.random && !random)//only override an existing tick if we're going from random->scheduled { e.time = time e.random = random @@ -159,7 +163,7 @@ object TickScheduler extends WorldExtensionInstantiator world.tickChunks+=this } - def nextRandomTick = world.world.rand.nextInt(800)+800 + def nextRandomTick = world.nextRandomTick def processTicks():Boolean = { @@ -255,10 +259,21 @@ object TickScheduler extends WorldExtensionInstantiator def createChunkExtension(chunk:Chunk, world:WorldExtension):ChunkExtension = new ChunkTickScheduler(chunk, world.asInstanceOf[WorldTickScheduler]) + private[multipart] def loadRandomTick(part:TMultiPart) + { + getExtension(part.tile.worldObj).asInstanceOf[WorldTickScheduler].loadRandom(part) + } + + /** + * Schedule a tick for part relative to the current time. + */ def scheduleTick(part:TMultiPart, ticks:Int) { getExtension(part.tile.worldObj).asInstanceOf[WorldTickScheduler].scheduleTick(part, ticks, false) } + /** + * Returns the current scheduler time. Like the world time, but unaffected by the time set command and other things changing time of day. + */ def getSchedulerTime(world:World):Long = getExtension(world).asInstanceOf[WorldTickScheduler].schedTime } \ No newline at end of file diff --git a/codechicken/multipart/TileMultipart.scala b/codechicken/multipart/TileMultipart.scala index 964e81b..56b7f7d 100644 --- a/codechicken/multipart/TileMultipart.scala +++ b/codechicken/multipart/TileMultipart.scala @@ -46,6 +46,9 @@ import codechicken.multipart.handler.MultipartSaveLoad class TileMultipart extends TileEntity { + /** + * List of parts in this tile space + */ var partList = ArrayBuffer[TMultiPart]() private var doesTick = false @@ -81,6 +84,9 @@ class TileMultipart extends TileEntity */ def partMap(slot:Int):TMultiPart = null + /** + * Implicit java conversion of part list + */ def jPartList():List[TMultiPart] = partList override def canUpdate() = doesTick @@ -191,11 +197,31 @@ class TileMultipart extends TileEntity def getLightValue() = partList.foldLeft(0)((l, p) => Math.max(l, p.getLightValue)) + /** + * Callback for parts to mark the chunk as needs saving + */ def markDirty() { worldObj.markTileEntityChunkModified(xCoord, yCoord, zCoord, this) } + /** + * Mark this block space for a render update. + */ + def markRender() + { + worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord) + } + + /** + * Helper function for calling a second level notify on a side (eg indirect power from a lever) + */ + def notifyNeighborChange(side:Int) + { + val pos = new BlockCoord(this).offset(side) + worldObj.notifyBlocksOfNeighborChange(pos.x, pos.y, pos.z, MultipartProxy.block.blockID) + } + def isSolid(side:Int):Boolean = { val part = partMap(side) @@ -220,6 +246,9 @@ class TileMultipart extends TileEntity } } + /** + * Returns true if part can be added to this space + */ def canAddPart(part:TMultiPart):Boolean = { if(partList.contains(part)) @@ -228,6 +257,15 @@ class TileMultipart extends TileEntity return occlusionTest(partList, part) } + /** + * Returns true if opart can be replaced with npart (note opart and npart may be the exact same object) + * + * This function should be used for testing if a part can change it's shape (eg. rotation, expansion, cable connection) + * For example, to test whether a cable part can connect to it's neighbor: + * 1. Set the cable part's bounding boxes as if the connection is established + * 2. Call canReplacePart(part, part) + * 3. If canReplacePart succeeds, perform connection, else, revert bounding box + */ def canReplacePart(opart:TMultiPart, npart:TMultiPart):Boolean = { val olist = partList.filterNot(_ == opart) @@ -237,11 +275,17 @@ class TileMultipart extends TileEntity return occlusionTest(olist, npart) } + /** + * Returns true if parts do not occlude npart + */ def occlusionTest(parts:Seq[TMultiPart], npart:TMultiPart):Boolean = { return parts.forall(part => part.occlusionTest(npart) && npart.occlusionTest(part)) } + /** + * Get the write stream for updates to part + */ def getWriteStream(part:TMultiPart):MCDataOutput = getWriteStream.writeByte(partList.indexOf(part)) private def getWriteStream = MultipartSPH.getTileStream(worldObj, new BlockCoord(this)) @@ -279,12 +323,24 @@ class TileMultipart extends TileEntity } /** - * Bind this part to an internal cache + * Bind this part to an internal cache. + * Provided for trait overrides, do not call externally. */ def bindPart(part:TMultiPart){} - def partAdded(part:TMultiPart){} + /** + * Called when a part is added (placement) + * Provided for trait overrides, do not call externally. + */ + def partAdded(part:TMultiPart) + { + if(part.isInstanceOf[IRandomUpdateTick]) + TickScheduler.loadRandomTick(part) + } + /** + * Removes part from this tile. Note that due to the operation sync, the part may not be removed until the call stack has been passed to all other parts in the space. + */ def remPart(part:TMultiPart):TileMultipart = { assert(!worldObj.isRemote, "Cannot remove multi parts from a client tile") @@ -343,6 +399,10 @@ class TileMultipart extends TileEntity return r } + /** + * Remove this part from internal cache. + * Provided for trait overrides, do not call externally. + */ def partRemoved(part:TMultiPart, p:Int){} private[multipart] def loadParts(parts:ListBuffer[TMultiPart]) @@ -353,11 +413,18 @@ class TileMultipart extends TileEntity notifyPartChange(null) } + /** + * Remove all parts from internal cache + * Provided for trait overrides, do not call externally. + */ def clearParts() { partList.clear() } + /** + * Writes the description of this tile, and all parts composing it, to packet + */ def writeDesc(packet:MCDataOutput) { packet.writeByte(partList.size) @@ -367,6 +434,9 @@ class TileMultipart extends TileEntity } } + /** + * Perform a raytrace returning all intersecting parts sorted nearest to farthest + */ def rayTraceAll(start:Vec3, end:Vec3):Iterable[ExtendedMOP] = { var list = ListBuffer[ExtendedMOP]() @@ -382,8 +452,14 @@ class TileMultipart extends TileEntity return list.sorted } + /** + * Perform a raytrace returning the nearest intersecting part + */ def collisionRayTrace(start:Vec3, end:Vec3):ExtendedMOP = rayTraceAll(start, end).headOption.getOrElse(null) + /** + * Drop and remove part at index (internal mining callback) + */ def harvestPart(index:Int, drop:Boolean):Boolean = { val part = partList(index) @@ -395,17 +471,15 @@ class TileMultipart extends TileEntity return partList.isEmpty } + /** + * Utility function for dropping items around the center of this space + */ def dropItems(items:Iterable[ItemStack]) { val pos = Vector3.fromTileEntityCenter(this) items.foreach(item => TileMultipart.dropItem(item, worldObj, pos)) } - def markRender() - { - worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord) - } - override def writeToNBT(tag:NBTTagCompound) { super.writeToNBT(tag) @@ -419,6 +493,9 @@ class TileMultipart extends TileEntity tag.setTag("parts", taglist) } + /** + * Internal callback + */ def onEntityCollision(entity:Entity) { TileMultipart.startOperation(this) @@ -426,17 +503,20 @@ class TileMultipart extends TileEntity TileMultipart.finishOperation(this) } + /** + * Internal callback, overriden in TRedstoneTile + */ def strongPowerLevel(side:Int) = 0 + /** + * Internal callback, overriden in TRedstoneTile + */ def weakPowerLevel(side:Int) = 0 + /** + * Internal callback, overriden in TRedstoneTile + */ def canConnectRedstone(side:Int) = false - - def notifyNeighborChange(side:Int) - { - val pos = new BlockCoord(this).offset(side) - worldObj.notifyBlocksOfNeighborChange(pos.x, pos.y, pos.z, MultipartProxy.block.blockID) - } } class TileMultipartClient extends TileMultipart @@ -460,6 +540,9 @@ class TileMultipartClient extends TileMultipart } } +/** + * Static class with multipart manipulation helper functions + */ object TileMultipart { var renderID:Int = -1 @@ -505,6 +588,11 @@ object TileMultipart } } + /** + * This class avoids concurrent modification exceptions when passing a call to all parts in the partList (such as onUpdate) + * Calls to add/remPart within an OperationSync start/finish pair will be delayed until the operation has completed. + * Extra complexity is required for recursive calls like notifyChange + */ class OperationSynchroniser { private val operations = ArrayBuffer[TileOperationSet]() @@ -588,16 +676,25 @@ object TileMultipart private val operationSync = new OperationSynchroniser - def startOperation(tile:TileMultipart) = if(!tile.worldObj.isRemote) operationSync.startOperation(tile) + private[multipart] def startOperation(tile:TileMultipart) = if(!tile.worldObj.isRemote) operationSync.startOperation(tile) - def finishOperation(tile:TileMultipart) = if(!tile.worldObj.isRemote) operationSync.finishOperation(tile) + private[multipart] def finishOperation(tile:TileMultipart) = if(!tile.worldObj.isRemote) operationSync.finishOperation(tile) - def queueRemoval(tile:TileMultipart, part:TMultiPart):Boolean = operationSync.queueRemoval(tile, part) + private[multipart] def queueRemoval(tile:TileMultipart, part:TMultiPart):Boolean = operationSync.queueRemoval(tile, part) - def queueAddition(world:World, pos:BlockCoord, part:TMultiPart):Boolean = operationSync.queueAddition(world, pos, part) + private[multipart] def queueAddition(world:World, pos:BlockCoord, part:TMultiPart):Boolean = operationSync.queueAddition(world, pos, part) + /** + * Gets a multipar ttile instance at pos, converting if necessary. + */ def getOrConvertTile(world:World, pos:BlockCoord) = getOrConvertTile2(world, pos)._1 + /** + * Gets a multipart tile instance at pos, converting if necessary. + * Note converted tiles are merely a structure formality, + * they do not actually exist in world until they are required to by the addition of another multipart to their space. + * @return (The tile or null if there was none, true if the tile is a result of a conversion) + */ def getOrConvertTile2(world:World, pos:BlockCoord):(TileMultipart, Boolean) = { val t = world.getBlockTileEntity(pos.x, pos.y, pos.z) @@ -619,6 +716,9 @@ object TileMultipart return (null, false) } + /** + * Gets the multipart tile instance at pos, or null if it doesn't exist or is not a multipart tile + */ def getTile(world:World, pos:BlockCoord):TileMultipart = { val t = world.getBlockTileEntity(pos.x, pos.y, pos.z) @@ -627,6 +727,10 @@ object TileMultipart return null } + /** + * Returns whether part can be added to the space at pos. Will do conversions as necessary. + * This function is the recommended way to add parts to the world. + */ def canPlacePart(world:World, pos:BlockCoord, part:TMultiPart):Boolean = { part.getCollisionBoxes.foreach{b => @@ -644,12 +748,19 @@ object TileMultipart return true } + /** + * Returns if the block at pos is replaceable (air, vines etc) + */ def replaceable(world:World, pos:BlockCoord):Boolean = { val block = Block.blocksList(world.getBlockId(pos.x, pos.y, pos.z)) return block == null || block.isAirBlock(world, pos.x, pos.y, pos.z) || block.isBlockReplaceable(world, pos.x, pos.y, pos.z) } + /** + * Adds a part to a block space. canPlacePart should always be called first. + * The addition of parts on the client is handled internally. + */ def addPart(world:World, pos:BlockCoord, part:TMultiPart):TileMultipart = { assert(!world.isRemote, "Cannot add multi parts to a client tile.") @@ -660,6 +771,9 @@ object TileMultipart return MultipartGenerator.addPart(world, pos, part) } + /** + * Constructs this tile and its parts from a desc packet + */ def handleDescPacket(world:World, pos:BlockCoord, packet:PacketCustom) { val nparts = packet.readUByte @@ -685,6 +799,9 @@ object TileMultipart tilemp.markRender() } + /** + * Handles an update packet, addition, removal and otherwise + */ def handlePacket(pos:BlockCoord, world:World, i:Int, packet:PacketCustom) { var tilemp = BlockMultipart.getTile(world, pos.x, pos.y, pos.z) @@ -705,6 +822,9 @@ object TileMultipart } } + /** + * Creates this tile from an NBT tag + */ def createFromNBT(tag:NBTTagCompound):TileMultipart = { val partList = tag.getTagList("parts") @@ -731,6 +851,9 @@ object TileMultipart return tmb } + /** + * Drops an item around pos + */ def dropItem(stack:ItemStack, world:World, pos:Vector3) { val item = new EntityItem(world, pos.x, pos.y, pos.z, stack) diff --git a/codechicken/multipart/asm/IMultipartFactory.scala b/codechicken/multipart/asm/IMultipartFactory.scala index e593d2a..11a0c3c 100644 --- a/codechicken/multipart/asm/IMultipartFactory.scala +++ b/codechicken/multipart/asm/IMultipartFactory.scala @@ -1,6 +1,5 @@ package codechicken.multipart.asm -import scala.reflect.runtime.universe._ import codechicken.multipart.TileMultipart trait IMultipartFactory diff --git a/codechicken/multipart/handler/Proxies.scala b/codechicken/multipart/handler/Proxies.scala index 7741e3e..154cce3 100644 --- a/codechicken/multipart/handler/Proxies.scala +++ b/codechicken/multipart/handler/Proxies.scala @@ -9,7 +9,6 @@ import codechicken.lib.config.ConfigFile import cpw.mods.fml.common.registry.GameRegistry import java.io.File import codechicken.multipart.handler.MultipartProxy._ -import codechicken.multipart.BlockMultipartImpl import codechicken.multipart.MultipartRenderer import java.util.HashMap import net.minecraftforge.common.MinecraftForge @@ -45,7 +44,7 @@ class MultipartProxy_serverImpl def postInit() { - block = new BlockMultipartImpl(config.getTag("block.id").getIntValue(getFreeBlockID(1281))) + block = new BlockMultipart(config.getTag("block.id").getIntValue(getFreeBlockID(1281))) block.setUnlocalizedName("ccmultipart") MinecraftForge.EVENT_BUS.register(MultipartEventHandler) diff --git a/codechicken/multipart/scalatraits/TFluidHandlerTile.scala b/codechicken/multipart/scalatraits/TFluidHandlerTile.scala index 4d39a11..ecacbf5 100644 --- a/codechicken/multipart/scalatraits/TFluidHandlerTile.scala +++ b/codechicken/multipart/scalatraits/TFluidHandlerTile.scala @@ -10,6 +10,10 @@ import net.minecraftforge.fluids.IFluidTank import net.minecraftforge.fluids.FluidTankInfo import net.minecraftforge.fluids.Fluid +/** + * Mixin trait implementation for parts implementing IFluidHandler. + * Distributes fluid manipulation amoung fluid handling parts. + */ trait TFluidHandlerTile extends TileMultipart with IFluidHandler { var tankList = ListBuffer[IFluidHandler]() diff --git a/codechicken/multipart/scalatraits/TPartialOcclusionTile.scala b/codechicken/multipart/scalatraits/TPartialOcclusionTile.scala index 367a992..7deb968 100644 --- a/codechicken/multipart/scalatraits/TPartialOcclusionTile.scala +++ b/codechicken/multipart/scalatraits/TPartialOcclusionTile.scala @@ -5,6 +5,9 @@ import codechicken.multipart.TMultiPart import codechicken.multipart.JPartialOcclusion import codechicken.multipart.PartialOcclusionTest +/** + * Implementation for the partial occlusion test. + */ class TPartialOcclusionTile extends TileMultipart { override def occlusionTest(parts:Seq[TMultiPart], npart:TMultiPart):Boolean = diff --git a/codechicken/multipart/scalatraits/TRedstoneTile.scala b/codechicken/multipart/scalatraits/TRedstoneTile.scala index bec4c97..21efa27 100644 --- a/codechicken/multipart/scalatraits/TRedstoneTile.scala +++ b/codechicken/multipart/scalatraits/TRedstoneTile.scala @@ -11,8 +11,15 @@ import codechicken.multipart.TFacePart import codechicken.multipart.TEdgePart import codechicken.multipart.TEdgePart +/** + * Mixin trait implementation for IRedstonePart + * Provides and overrides various redstone functions. + */ trait TRedstoneTile extends TileMultipart with IRedstoneTile { + /** + * Returns the strong (indirect) power being emitted fr + */ override def strongPowerLevel(side:Int):Int = { var max = 0 diff --git a/codechicken/multipart/scalatraits/TSlottedTile.scala b/codechicken/multipart/scalatraits/TSlottedTile.scala index b96032a..2c1ca63 100644 --- a/codechicken/multipart/scalatraits/TSlottedTile.scala +++ b/codechicken/multipart/scalatraits/TSlottedTile.scala @@ -4,6 +4,10 @@ import codechicken.multipart.TileMultipart import codechicken.multipart.TMultiPart import codechicken.multipart.TSlottedPart +/** + * Mixin implementation for TSlottedPart. + * Puts parts into a slot array for quick access at the cost of memory consumption + */ trait TSlottedTile extends TileMultipart { var v_partMap = new Array[TMultiPart](27) diff --git a/codechicken/multipart/scalatraits/TTileChangeTile.scala b/codechicken/multipart/scalatraits/TTileChangeTile.scala index 315b284..62fa1e5 100644 --- a/codechicken/multipart/scalatraits/TTileChangeTile.scala +++ b/codechicken/multipart/scalatraits/TTileChangeTile.scala @@ -5,6 +5,11 @@ import codechicken.multipart.INeighborTileChange import codechicken.multipart.TileMultipart import codechicken.lib.vec.BlockCoord +/** + * Mixin implementation for INeighborTileChange + * + * Reduces unnecessary computation + */ trait TTileChangeTile extends TileMultipart { var weakTileChanges = false