diff --git a/src/main/scala/net/bdew/lib/ApiReporter.scala b/src/main/scala/net/bdew/lib/ApiReporter.scala index 9b0a2aa..f1dd5c7 100644 --- a/src/main/scala/net/bdew/lib/ApiReporter.scala +++ b/src/main/scala/net/bdew/lib/ApiReporter.scala @@ -21,8 +21,10 @@ object ApiReporter extends ICrashCallable { val mods = new util.ArrayList[ModContainer] val nameLookup = new util.HashMap[String, ModContainer] ModAPIManager.INSTANCE.injectAPIModContainers(mods, nameLookup) - (for (mod <- mods.sortBy(_.getModId.toLowerCase(Locale.US))) yield - "\t\t* %s (%s) from %s".format(mod.getModId, mod.getVersion, + (for (mod <- mods.sortBy(_.getModId.toLowerCase(Locale.US))) + yield "\t\t* %s (%s) from %s".format( + mod.getModId, + mod.getVersion, if (mod.getSource.isDirectory) mod.getSource else diff --git a/src/main/scala/net/bdew/lib/BdLib.scala b/src/main/scala/net/bdew/lib/BdLib.scala index 13cac74..db9cfff 100644 --- a/src/main/scala/net/bdew/lib/BdLib.scala +++ b/src/main/scala/net/bdew/lib/BdLib.scala @@ -10,18 +10,35 @@ package net.bdew.lib import cpw.mods.fml.common.Mod.EventHandler -import cpw.mods.fml.common.event.{FMLPreInitializationEvent, FMLServerStartingEvent, FMLServerStoppingEvent} +import cpw.mods.fml.common.event.{ + FMLPreInitializationEvent, + FMLServerStartingEvent, + FMLServerStoppingEvent +} import cpw.mods.fml.common.{FMLCommonHandler, Mod} import net.bdew.lib.multiblock.data.MsgOutputCfgRSMode -import net.bdew.lib.multiblock.network.{MsgOutputCfg, MsgOutputCfgSlot, NetHandler} -import net.bdew.lib.network.{BaseMessage, NetworkSecurityLoader, SerializedMessageCodec} +import net.bdew.lib.multiblock.network.{ + MsgOutputCfg, + MsgOutputCfgSlot, + NetHandler +} +import net.bdew.lib.network.{ + BaseMessage, + NetworkSecurityLoader, + SerializedMessageCodec +} import net.bdew.lib.tooltip.TooltipHandler import net.minecraft.command.CommandHandler import org.apache.logging.log4j.Logger import java.io.File -@Mod(modid = "bdlib", name = "BD lib", version = "GRADLETOKEN_VERSION", modLanguage = "scala") +@Mod( + modid = "bdlib", + name = "BD lib", + version = "GRADLETOKEN_VERSION", + modLanguage = "scala" +) object BdLib { var log: Logger = null var configDir: File = null @@ -30,8 +47,10 @@ object BdLib { def logInfo(msg: String, args: Any*) = log.info(msg.format(args: _*)) def logWarn(msg: String, args: Any*) = log.warn(msg.format(args: _*)) def logError(msg: String, args: Any*) = log.error(msg.format(args: _*)) - def logWarnException(msg: String, t: Throwable, args: Any*) = log.warn(msg.format(args: _*), t) - def logErrorException(msg: String, t: Throwable, args: Any*) = log.error(msg.format(args: _*), t) + def logWarnException(msg: String, t: Throwable, args: Any*) = + log.warn(msg.format(args: _*), t) + def logErrorException(msg: String, t: Throwable, args: Any*) = + log.error(msg.format(args: _*), t) val onServerStarting = Event[FMLServerStartingEvent] val onServerStopping = Event[FMLServerStoppingEvent] @@ -56,7 +75,8 @@ object BdLib { @EventHandler def serverStarting(event: FMLServerStartingEvent) { - val commandHandler = event.getServer.getCommandManager.asInstanceOf[CommandHandler] + val commandHandler = + event.getServer.getCommandManager.asInstanceOf[CommandHandler] commandHandler.registerCommand(CommandDumpRegistry) commandHandler.registerCommand(CommandOreDistribution) onServerStarting.trigger(event) diff --git a/src/main/scala/net/bdew/lib/Client.scala b/src/main/scala/net/bdew/lib/Client.scala index 87f67c2..374a217 100644 --- a/src/main/scala/net/bdew/lib/Client.scala +++ b/src/main/scala/net/bdew/lib/Client.scala @@ -13,9 +13,8 @@ import net.minecraft.client.Minecraft import net.minecraft.client.renderer.texture.TextureMap import org.lwjgl.input.Keyboard -/** - * Misc functions and shortcuts for client-side code - */ +/** Misc functions and shortcuts for client-side code + */ object Client { def minecraft = Minecraft.getMinecraft def fontRenderer = Minecraft.getMinecraft.fontRenderer @@ -24,8 +23,14 @@ object Client { def player = Minecraft.getMinecraft.thePlayer def textureManager = Minecraft.getMinecraft.getTextureManager - def blockMissingIcon = textureManager.getTexture(TextureMap.locationBlocksTexture).asInstanceOf[TextureMap].getAtlasSprite("missingno") - def itemMissingIcon = textureManager.getTexture(TextureMap.locationItemsTexture).asInstanceOf[TextureMap].getAtlasSprite("missingno") + def blockMissingIcon = textureManager + .getTexture(TextureMap.locationBlocksTexture) + .asInstanceOf[TextureMap] + .getAtlasSprite("missingno") + def itemMissingIcon = textureManager + .getTexture(TextureMap.locationItemsTexture) + .asInstanceOf[TextureMap] + .getAtlasSprite("missingno") def shiftDown: Boolean = { return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54) diff --git a/src/main/scala/net/bdew/lib/CommandDumpRegistry.scala b/src/main/scala/net/bdew/lib/CommandDumpRegistry.scala index 8b50410..5a3c814 100644 --- a/src/main/scala/net/bdew/lib/CommandDumpRegistry.scala +++ b/src/main/scala/net/bdew/lib/CommandDumpRegistry.scala @@ -25,24 +25,47 @@ object CommandDumpRegistry extends CommandBase { def getCommandUsage(c: ICommandSender) = "dumpregistry" def processCommand(sender: ICommandSender, params: Array[String]) { - val mcHome = FMLInjectionData.data()(6).asInstanceOf[File] //is there a better way to get this? + val mcHome = + FMLInjectionData + .data()(6) + .asInstanceOf[File] // is there a better way to get this? val dumpFile = new File(mcHome, "registry.dump") val dumpWriter = new BufferedWriter(new FileWriter(dumpFile)) import scala.collection.JavaConversions._ try { dumpWriter.write("==== BLOCKS ====\n") - dumpWriter.write(GameData.getBlockRegistry.map(GameData.getBlockRegistry.getNameForObject).toList.sorted.mkString("\n")) + dumpWriter.write( + GameData.getBlockRegistry + .map(GameData.getBlockRegistry.getNameForObject) + .toList + .sorted + .mkString("\n") + ) dumpWriter.write("\n\n") dumpWriter.write("==== ITEMS ====\n") - dumpWriter.write(GameData.getItemRegistry.map(GameData.getItemRegistry.getNameForObject).toList.sorted.mkString("\n")) + dumpWriter.write( + GameData.getItemRegistry + .map(GameData.getItemRegistry.getNameForObject) + .toList + .sorted + .mkString("\n") + ) dumpWriter.write("\n\n") dumpWriter.write("==== CUSTOM STACKS ====\n") val stacksField = classOf[GameData].getDeclaredField("customItemStacks") stacksField.setAccessible(true) - val stacksData = stacksField.get(null).asInstanceOf[Table[String, String, ItemStack]] - dumpWriter.write(stacksData.cellSet().map(x => x.getRowKey + ":" + x.getColumnKey).toList.sorted.mkString("\n")) + val stacksData = + stacksField.get(null).asInstanceOf[Table[String, String, ItemStack]] + dumpWriter.write( + stacksData + .cellSet() + .map(x => x.getRowKey + ":" + x.getColumnKey) + .toList + .sorted + .mkString("\n") + ) dumpWriter.write("\n\n") dumpWriter.write("==== ORE DICT ====\n") @@ -55,16 +78,26 @@ object CommandDumpRegistry extends CommandBase { dumpWriter.write("\n\n") dumpWriter.write("==== FLUIDS ====\n") - dumpWriter.write(FluidRegistry.getRegisteredFluids.map(_._1).toList.sorted.mkString("\n")) + dumpWriter.write( + FluidRegistry.getRegisteredFluids.map(_._1).toList.sorted.mkString("\n") + ) dumpWriter.write("\n\n") - CommandBase.func_152373_a(sender, this, "Registry dumped to " + dumpFile.getCanonicalPath) + CommandBase.func_152373_a( + sender, + this, + "Registry dumped to " + dumpFile.getCanonicalPath + ) } catch { case e: Throwable => - CommandBase.func_152373_a(sender, this, "Failed to save registry dump: " + e) + CommandBase.func_152373_a( + sender, + this, + "Failed to save registry dump: " + e + ) BdLib.logErrorException("Failed to save registry dump", e) } finally { dumpWriter.close() } } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/CommandOreDistribution.scala b/src/main/scala/net/bdew/lib/CommandOreDistribution.scala index 688c1dc..dd91533 100644 --- a/src/main/scala/net/bdew/lib/CommandOreDistribution.scala +++ b/src/main/scala/net/bdew/lib/CommandOreDistribution.scala @@ -30,10 +30,12 @@ object CommandOreDistribution extends CommandBase { try { s.toInt } catch { - case e: NumberFormatException => throw new WrongUsageException("bdlib.oredistribution.usage") + case e: NumberFormatException => + throw new WrongUsageException("bdlib.oredistribution.usage") } - def wrapColor(s: String, c: EnumChatFormatting) = c + s + EnumChatFormatting.RESET + def wrapColor(s: String, c: EnumChatFormatting) = + c + s + EnumChatFormatting.RESET def processCommand(sender: ICommandSender, baseParams: Array[String]) { val (flags, params) = baseParams.partition(_.startsWith("--")) @@ -44,12 +46,13 @@ object CommandOreDistribution extends CommandBase { val (startX, startZ, world) = sender match { case p: EntityPlayerMP => (p.posX.toInt, p.posZ.toInt, p.worldObj) - case _ => (0, 0, sender.getEntityWorld) + case _ => (0, 0, sender.getEntityWorld) } val radius = safeInt(params.head) val minY = if (params.length >= 2) safeInt(params(1)) else 0 - val maxY = if (params.length >= 3) safeInt(params(2)) else world.getHeight - 1 + val maxY = + if (params.length >= 3) safeInt(params(2)) else world.getHeight - 1 if (minY < 0 || radius <= 0 || minY > maxY || maxY > world.getHeight - 1) throw new WrongUsageException(getCommandUsage(sender)) @@ -57,25 +60,41 @@ object CommandOreDistribution extends CommandBase { val toFile = flags.contains("--file") // why java, WHY? - CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.start1", - Array[Integer](startX - radius, minY, startZ - radius, startX + radius, maxY, startZ + radius, world.provider.dimensionId): _*) + CommandBase.func_152373_a( + sender, + this, + "bdlib.oredistribution.start1", + Array[Integer]( + startX - radius, + minY, + startZ - radius, + startX + radius, + maxY, + startZ + radius, + world.provider.dimensionId + ): _* + ) CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.start2") import scala.collection.JavaConversions._ - val ores = (OreDictionary.getOreNames.filter(x => x.startsWith("ore") || x.startsWith("denseore")) flatMap { name => + val ores = (OreDictionary.getOreNames.filter(x => + x.startsWith("ore") || x.startsWith("denseore") + ) flatMap { name => val fixedName = if (name.startsWith("ore")) name.substring(3) else if (name.startsWith("denseore")) "Dense " + name.substring(8) else name - for (s <- OreDictionary.getOres(name)) yield (s.getItem, s.getItemDamage) -> fixedName + for (s <- OreDictionary.getOres(name)) + yield (s.getItem, s.getItemDamage) -> fixedName }).toMap val distribution = mutable.Map.empty[String, Int].withDefaultValue(0) - val kinds = mutable.Map.empty[String, Set[(Item, Int)]].withDefaultValue(Set.empty) + val kinds = + mutable.Map.empty[String, Set[(Item, Int)]].withDefaultValue(Set.empty) for { x <- startX - radius to startX + radius @@ -83,7 +102,10 @@ object CommandOreDistribution extends CommandBase { z <- startZ - radius to startZ + radius if !world.isAirBlock(x, y, z) } { - val key = (Item.getItemFromBlock(world.getBlock(x, y, z)), world.getBlockMetadata(x, y, z)) + val key = ( + Item.getItemFromBlock(world.getBlock(x, y, z)), + world.getBlockMetadata(x, y, z) + ) for (ore <- ores.get(key)) { distribution(ore) += 1 kinds(ore) += key @@ -95,21 +117,39 @@ object CommandOreDistribution extends CommandBase { if (toFile) { // === OUTPUT TO FILE === - val mcHome = FMLInjectionData.data()(6).asInstanceOf[File] //is there a better way to get this? + val mcHome = + FMLInjectionData + .data()(6) + .asInstanceOf[File] // is there a better way to get this? val dumpFile = new File(mcHome, "ore_distribution.txt") val dumpWriter = new BufferedWriter(new FileWriter(dumpFile)) try { - dumpWriter.write("Ore distribution report - (%d,%d,%d) to (%d,%d,%d) dim %d".format( - startX - radius, minY, startZ - radius, startX + radius, maxY, startZ + radius, world.provider.dimensionId - )) + dumpWriter.write( + "Ore distribution report - (%d,%d,%d) to (%d,%d,%d) dim %d".format( + startX - radius, + minY, + startZ - radius, + startX + radius, + maxY, + startZ + radius, + world.provider.dimensionId + ) + ) dumpWriter.newLine() dumpWriter.newLine() if (warnings.nonEmpty) { for ((id, types) <- warnings.toList.sortBy(_._1)) { - dumpWriter.write("Warning: %s has multiple variants generated:".format(id)) + dumpWriter.write( + "Warning: %s has multiple variants generated:".format(id) + ) dumpWriter.newLine() for ((item, dmg) <- types) { - dumpWriter.write(" - %s@%s".format(GameData.getItemRegistry.getNameForObject(item), dmg)) + dumpWriter.write( + " - %s@%s".format( + GameData.getItemRegistry.getNameForObject(item), + dmg + ) + ) dumpWriter.newLine() } dumpWriter.newLine() @@ -119,13 +159,29 @@ object CommandOreDistribution extends CommandBase { dumpWriter.newLine() } for ((id, num) <- distribution.filter(_._2 > 0).toList.sortBy(-_._2)) { - dumpWriter.write("%s - %s (%s%%)".format(id, DecFormat.round(num), DecFormat.short(100F * num / total))) + dumpWriter.write( + "%s - %s (%s%%)".format( + id, + DecFormat.round(num), + DecFormat.short(100f * num / total) + ) + ) dumpWriter.newLine() } - CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.saved", dumpFile.getCanonicalPath) + CommandBase.func_152373_a( + sender, + this, + "bdlib.oredistribution.saved", + dumpFile.getCanonicalPath + ) } catch { case e: Throwable => - CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.error", e.toString) + CommandBase.func_152373_a( + sender, + this, + "bdlib.oredistribution.error", + e.toString + ) BdLib.logErrorException("Failed to save ore distribution dump", e) } finally { dumpWriter.close() @@ -133,16 +189,32 @@ object CommandOreDistribution extends CommandBase { } else { // === OUTPUT TO CHAT === for ((id, types) <- warnings.toList.sortBy(_._1)) { - CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.warn", - wrapColor(" !", EnumChatFormatting.RED), wrapColor(id, EnumChatFormatting.RED)) + CommandBase.func_152373_a( + sender, + this, + "bdlib.oredistribution.warn", + wrapColor(" !", EnumChatFormatting.RED), + wrapColor(id, EnumChatFormatting.RED) + ) for ((item, dmg) <- types) - CommandBase.func_152373_a(sender, this, wrapColor(" - ", EnumChatFormatting.RED) + GameData.getItemRegistry.getNameForObject(item) + "@" + dmg) + CommandBase.func_152373_a( + sender, + this, + wrapColor(" - ", EnumChatFormatting.RED) + GameData.getItemRegistry + .getNameForObject(item) + "@" + dmg + ) } for ((id, num) <- distribution.filter(_._2 > 0).toList.sortBy(-_._2)) { - CommandBase.func_152373_a(sender, this, "bdlib.oredistribution.entry", - " *", wrapColor(id, EnumChatFormatting.YELLOW), - DecFormat.round(num), DecFormat.short(100F * num / total)) + CommandBase.func_152373_a( + sender, + this, + "bdlib.oredistribution.entry", + " *", + wrapColor(id, EnumChatFormatting.YELLOW), + DecFormat.round(num), + DecFormat.short(100f * num / total) + ) } } } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/DecFormat.scala b/src/main/scala/net/bdew/lib/DecFormat.scala index b303201..76fed80 100644 --- a/src/main/scala/net/bdew/lib/DecFormat.scala +++ b/src/main/scala/net/bdew/lib/DecFormat.scala @@ -24,7 +24,13 @@ object DecFormat { def dec2(x: Float) = dec2Fmt.format(x).replace('\u00A0', ' ') def dec2(x: Int) = dec2Fmt.format(x).replace('\u00A0', ' ') - def short(x: Double) = (if (x > 10) thousandsFmt.format(x) else if (x > 1) dec1Fmt.format(x) else dec2Fmt.format(x)).replace('\u00A0', ' ') - def short(x: Float) = (if (x > 10) thousandsFmt.format(x) else if (x > 1) dec1Fmt.format(x) else dec2Fmt.format(x)).replace('\u00A0', ' ') - def short(x: Int) = (if (x > 10) thousandsFmt.format(x) else if (x > 1) dec1Fmt.format(x) else dec2Fmt.format(x)).replace('\u00A0', ' ') + def short(x: Double) = (if (x > 10) thousandsFmt.format(x) + else if (x > 1) dec1Fmt.format(x) + else dec2Fmt.format(x)).replace('\u00A0', ' ') + def short(x: Float) = (if (x > 10) thousandsFmt.format(x) + else if (x > 1) dec1Fmt.format(x) + else dec2Fmt.format(x)).replace('\u00A0', ' ') + def short(x: Int) = (if (x > 10) thousandsFmt.format(x) + else if (x > 1) dec1Fmt.format(x) + else dec2Fmt.format(x)).replace('\u00A0', ' ') } diff --git a/src/main/scala/net/bdew/lib/Event.scala b/src/main/scala/net/bdew/lib/Event.scala index 097ad04..f8e45fe 100644 --- a/src/main/scala/net/bdew/lib/Event.scala +++ b/src/main/scala/net/bdew/lib/Event.scala @@ -31,4 +31,4 @@ object Event { def apply() = new Event0 def apply[T] = new Event1[T] def apply[T, R] = new Event2[T, R] -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/Misc.scala b/src/main/scala/net/bdew/lib/Misc.scala index d133acf..25daef0 100644 --- a/src/main/scala/net/bdew/lib/Misc.scala +++ b/src/main/scala/net/bdew/lib/Misc.scala @@ -25,15 +25,18 @@ import net.minecraftforge.fluids.{Fluid, FluidStack} import net.minecraftforge.oredict.ShapedOreRecipe object Misc { - def getActiveModId = Option(Loader.instance().activeModContainer().getModId) getOrElse "" + def getActiveModId = Option( + Loader.instance().activeModContainer().getModId + ) getOrElse "" def toLocal(s: String) = StatCollector.translateToLocal(s) - def toLocalF(s: String, params: Any*) = StatCollector.translateToLocal(s).format(params: _*) + def toLocalF(s: String, params: Any*) = + StatCollector.translateToLocal(s).format(params: _*) def hasLocal(s: String) = StatCollector.canTranslate(s) def flattenRecipe(pattern: Seq[String], items: Map[Char, AnyRef]) = - pattern ++ items.flatMap { - case (k, v) => Seq(new Character(k), v) + pattern ++ items.flatMap { case (k, v) => + Seq(new Character(k), v) } def wrapTag(n: String, f: (NBTTagCompound) => Any)(t: NBTTagCompound) { @@ -42,23 +45,42 @@ object Misc { t.setTag(n, p) } - def addRecipe(result: ItemStack, pattern: Seq[String], items: Map[Char, AnyRef]) = + def addRecipe( + result: ItemStack, + pattern: Seq[String], + items: Map[Char, AnyRef] + ) = GameRegistry.addRecipe(result, flattenRecipe(pattern, items): _*) - def addRecipeOD(result: ItemStack, pattern: Seq[String], items: Map[Char, AnyRef]) = - GameRegistry.addRecipe(new ShapedOreRecipe(result, flattenRecipe(pattern, items): _*)) + def addRecipeOD( + result: ItemStack, + pattern: Seq[String], + items: Map[Char, AnyRef] + ) = + GameRegistry.addRecipe( + new ShapedOreRecipe(result, flattenRecipe(pattern, items): _*) + ) def min[T: Ordering](values: T*) = values.min def max[T: Ordering](values: T*) = values.max - def clamp[T](value: T, min: T, max: T)(implicit o: Ordering[T]): T = if (o.gt(value, max)) max else if (o.lt(value, min)) min else value + def clamp[T](value: T, min: T, max: T)(implicit o: Ordering[T]): T = + if (o.gt(value, max)) max else if (o.lt(value, min)) min else value - def iterSome[T](list: Seq[T], indexes: Iterable[Int]): Iterable[T] = for (i <- indexes) yield list(i) - def iterSomeEnum[T](list: Seq[T], indexes: Iterable[Int]): Iterable[(Int, T)] = for (i <- indexes) yield i -> list(i) + def iterSome[T](list: Seq[T], indexes: Iterable[Int]): Iterable[T] = for ( + i <- indexes + ) yield list(i) + def iterSomeEnum[T]( + list: Seq[T], + indexes: Iterable[Int] + ): Iterable[(Int, T)] = for (i <- indexes) yield i -> list(i) - def filterType[T](from: Iterable[_], cls: Class[T]) = from.filter(cls.isInstance).asInstanceOf[Iterable[T]] + def filterType[T](from: Iterable[_], cls: Class[T]) = + from.filter(cls.isInstance).asInstanceOf[Iterable[T]] - def getBiomeByName(name: String) = BiomeGenBase.getBiomeGenArray.find(x => x != null && x.biomeName == name).orNull + def getBiomeByName(name: String) = BiomeGenBase.getBiomeGenArray + .find(x => x != null && x.biomeName == name) + .orNull private lazy val modLookup = { val mods = new util.ArrayList[ModContainer] @@ -73,7 +95,9 @@ object Misc { def haveModVersion(modId: String) = { val spec = VersionParser.parseVersionReference(modId) - modLookup.contains(spec.getLabel) && spec.containsVersion(modLookup(spec.getLabel).getProcessedVersion) + modLookup.contains(spec.getLabel) && spec.containsVersion( + modLookup(spec.getLabel).getProcessedVersion + ) } def getModVersion(modId: String) = @@ -95,9 +119,18 @@ object Misc { def asInstanceOpt[T](cls: Class[T])(v: Any) = if (cls.isInstance(v)) Some(v.asInstanceOf[T]) else None - def getNeighbourTile[T](origin: TileEntity, dir: ForgeDirection, cls: Class[T]) = - Option(origin.getWorldObj.getTileEntity(origin.xCoord + dir.offsetX, - origin.yCoord + dir.offsetY, origin.zCoord + dir.offsetZ)) flatMap (asInstanceOpt(_, cls)) + def getNeighbourTile[T]( + origin: TileEntity, + dir: ForgeDirection, + cls: Class[T] + ) = + Option( + origin.getWorldObj.getTileEntity( + origin.xCoord + dir.offsetX, + origin.yCoord + dir.offsetY, + origin.zCoord + dir.offsetZ + ) + ) flatMap (asInstanceOpt(_, cls)) @inline def applyMutator[T](f: (T) => Unit, init: T): T = { f(init) @@ -132,34 +165,36 @@ object Misc { Client.blockMissingIcon def getFluidIcon(f: Fluid): IIcon = - if (f != null) getFluidIcon(new FluidStack(f, 1)) else Client.blockMissingIcon + if (f != null) getFluidIcon(new FluidStack(f, 1)) + else Client.blockMissingIcon def getFluidColor(fs: FluidStack): Int = - if (fs != null && fs.getFluid != null) fs.getFluid.getColor(fs) else 0xFFFFFF + if (fs != null && fs.getFluid != null) fs.getFluid.getColor(fs) + else 0xffffff def getFluidColor(f: Fluid): Int = - if (f != null) getFluidColor(new FluidStack(f, 1)) else 0xFFFFFF + if (f != null) getFluidColor(new FluidStack(f, 1)) else 0xffffff lazy val lineSeparator = System.getProperty("line.separator") - /** - * Provides something like java try-with-resources in scala - */ + /** Provides something like java try-with-resources in scala + */ def withAutoClose[T <: AutoCloseable, R](o: T)(f: T => R): R = { - val res = try { - f(o) - } catch { - case t1: Throwable => - if (o != null) { - try { - o.close() - } catch { - case t2: Throwable => - t1.addSuppressed(t2) + val res = + try { + f(o) + } catch { + case t1: Throwable => + if (o != null) { + try { + o.close() + } catch { + case t2: Throwable => + t1.addSuppressed(t2) + } } - } - throw t1 - } + throw t1 + } if (o != null) o.close() res @@ -172,4 +207,3 @@ object Misc { "%s:%s/%s".format(domain, name, path.mkString("/")).toLowerCase(Locale.US) } - diff --git a/src/main/scala/net/bdew/lib/block/BlockFace.scala b/src/main/scala/net/bdew/lib/block/BlockFace.scala index af1d9af..9b9e6a3 100644 --- a/src/main/scala/net/bdew/lib/block/BlockFace.scala +++ b/src/main/scala/net/bdew/lib/block/BlockFace.scala @@ -18,5 +18,6 @@ case class BlockFace(x: Int, y: Int, z: Int, face: ForgeDirection) { } object BlockFace { - def apply(bp: BlockRef, face: ForgeDirection) = new BlockFace(bp.x, bp.y, bp.z, face) + def apply(bp: BlockRef, face: ForgeDirection) = + new BlockFace(bp.x, bp.y, bp.z, face) } diff --git a/src/main/scala/net/bdew/lib/block/BlockRef.scala b/src/main/scala/net/bdew/lib/block/BlockRef.scala index 966d3c0..05c6224 100644 --- a/src/main/scala/net/bdew/lib/block/BlockRef.scala +++ b/src/main/scala/net/bdew/lib/block/BlockRef.scala @@ -18,16 +18,21 @@ import net.minecraftforge.common.util.ForgeDirection import scala.reflect.ClassTag case class BlockRef(x: Int, y: Int, z: Int) { - def isValid(w: IBlockAccess) = y >= 0 && y < 256 // hardcoded because getHeight is unavailable on servers :( + def isValid(w: IBlockAccess) = + y >= 0 && y < 256 // hardcoded because getHeight is unavailable on servers :( - def block(w: IBlockAccess) = if (isValid(w)) Option(w.getBlock(x, y, z)) else None - def tile(w: IBlockAccess) = if (isValid(w)) Option(w.getTileEntity(x, y, z)) else None + def block(w: IBlockAccess) = + if (isValid(w)) Option(w.getBlock(x, y, z)) else None + def tile(w: IBlockAccess) = + if (isValid(w)) Option(w.getTileEntity(x, y, z)) else None def meta(w: IBlockAccess) = if (isValid(w)) w.getBlockMetadata(x, y, z) else 0 def blockIs(w: IBlockAccess, other: Block) = block(w).contains(other) - def neighbour(side: ForgeDirection) = BlockRef(x + side.offsetX, y + side.offsetY, z + side.offsetZ) - def neighbours = ForgeDirection.VALID_DIRECTIONS.map(x => x -> neighbour(x)).toMap + def neighbour(side: ForgeDirection) = + BlockRef(x + side.offsetX, y + side.offsetY, z + side.offsetZ) + def neighbours = + ForgeDirection.VALID_DIRECTIONS.map(x => x -> neighbour(x)).toMap override def toString = "(x=%d y=%d z=%d)".format(x, y, z) @@ -58,4 +63,4 @@ object BlockRef { def fromTile(te: TileEntity) = BlockRef(te.xCoord, te.yCoord, te.zCoord) def fromNBT(tag: NBTTagCompound) = BlockRef(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z")) -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/block/HasItemBlock.scala b/src/main/scala/net/bdew/lib/block/HasItemBlock.scala index 06ddd1a..2aa32b0 100644 --- a/src/main/scala/net/bdew/lib/block/HasItemBlock.scala +++ b/src/main/scala/net/bdew/lib/block/HasItemBlock.scala @@ -12,10 +12,9 @@ package net.bdew.lib.block import net.minecraft.block.Block import net.minecraft.item.ItemBlock -/** - * If defined on a block - defines a custom ItemBlock class that will be used when registering - * Supported by BlockManager and Machine - */ +/** If defined on a block - defines a custom ItemBlock class that will be used + * when registering Supported by BlockManager and Machine + */ trait HasItemBlock extends Block { def ItemBlockClass: Class[_ <: ItemBlock] } diff --git a/src/main/scala/net/bdew/lib/block/HasTE.scala b/src/main/scala/net/bdew/lib/block/HasTE.scala index 750217e..3cb1418 100644 --- a/src/main/scala/net/bdew/lib/block/HasTE.scala +++ b/src/main/scala/net/bdew/lib/block/HasTE.scala @@ -17,14 +17,21 @@ import net.minecraft.world.{IBlockAccess, World} trait HasTE[T] extends Block with ITileEntityProvider { val TEClass: Class[_ <: TileEntity] - def createNewTileEntity(world: World, meta: Int): TileEntity = TEClass.newInstance() + def createNewTileEntity(world: World, meta: Int): TileEntity = + TEClass.newInstance() def getTE(w: IBlockAccess, ref: BlockRef): T = getTE(w, ref.x, ref.y, ref.z) def getTE(w: IBlockAccess, x: Int, y: Int, z: Int): T = { var t = w.getTileEntity(x, y, z) if ((t == null) || !TEClass.isInstance(t)) { - BdLib.logError("Tile entity for block %s at (%d,%d,%d) is corrupt or missing - recreating", this, x, y, z) + BdLib.logError( + "Tile entity for block %s at (%d,%d,%d) is corrupt or missing - recreating", + this, + x, + y, + z + ) w match { case ww: World => t = createNewTileEntity(ww, w.getBlockMetadata(x, y, z)) diff --git a/src/main/scala/net/bdew/lib/block/ItemBlockTooltip.scala b/src/main/scala/net/bdew/lib/block/ItemBlockTooltip.scala index e4e3fb7..c4bce9e 100644 --- a/src/main/scala/net/bdew/lib/block/ItemBlockTooltip.scala +++ b/src/main/scala/net/bdew/lib/block/ItemBlockTooltip.scala @@ -17,13 +17,26 @@ import net.minecraft.item.{ItemBlock, ItemStack} trait BlockTooltip extends Block with HasItemBlock { override val ItemBlockClass: Class[_ <: ItemBlock] = classOf[ItemBlockTooltip] - def getTooltip(stack: ItemStack, player: EntityPlayer, advanced: Boolean): List[String] + def getTooltip( + stack: ItemStack, + player: EntityPlayer, + advanced: Boolean + ): List[String] } class ItemBlockTooltip(b: Block) extends ItemBlock(b) { - override def addInformation(stack: ItemStack, player: EntityPlayer, list: util.List[_], advanced: Boolean): Unit = { + override def addInformation( + stack: ItemStack, + player: EntityPlayer, + list: util.List[_], + advanced: Boolean + ): Unit = { import scala.collection.JavaConversions._ if (b.isInstanceOf[BlockTooltip]) - list.asInstanceOf[util.List[String]].addAll(b.asInstanceOf[BlockTooltip].getTooltip(stack, player, advanced)) + list + .asInstanceOf[util.List[String]] + .addAll( + b.asInstanceOf[BlockTooltip].getTooltip(stack, player, advanced) + ) } } diff --git a/src/main/scala/net/bdew/lib/block/KeepData.scala b/src/main/scala/net/bdew/lib/block/KeepData.scala index a900f56..f6567bb 100644 --- a/src/main/scala/net/bdew/lib/block/KeepData.scala +++ b/src/main/scala/net/bdew/lib/block/KeepData.scala @@ -20,91 +20,162 @@ import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.MovingObjectPosition import net.minecraft.world.World -/** - * Mixin for blocks to keep their data when broken - * Must have a TileEntity that extends TileKeepData - */ +/** Mixin for blocks to keep their data when broken Must have a TileEntity that + * extends TileKeepData + */ trait BlockKeepData extends Block with HasItemBlock { this: HasTE[_ <: TileKeepData] => - override val ItemBlockClass: Class[_ <: ItemBlockKeepData] = classOf[ItemBlockKeepData] + override val ItemBlockClass: Class[_ <: ItemBlockKeepData] = + classOf[ItemBlockKeepData] def getSavedBlock(world: World, x: Int, y: Int, z: Int, metadata: Int) = { - val stack = new ItemStack(getItemDropped(metadata, world.rand, 0), 1, damageDropped(metadata)) + val stack = new ItemStack( + getItemDropped(metadata, world.rand, 0), + 1, + damageDropped(metadata) + ) getTE(world, x, y, z).saveToItem(stack) stack } - override def getDrops(world: World, x: Int, y: Int, z: Int, metadata: Int, fortune: Int): util.ArrayList[ItemStack] = { + override def getDrops( + world: World, + x: Int, + y: Int, + z: Int, + metadata: Int, + fortune: Int + ): util.ArrayList[ItemStack] = { val drops = new util.ArrayList[ItemStack]() drops.add(getSavedBlock(world, x, y, z, metadata)) drops } - override def removedByPlayer(world: World, player: EntityPlayer, x: Int, y: Int, z: Int, willHarvest: Boolean): Boolean = + override def removedByPlayer( + world: World, + player: EntityPlayer, + x: Int, + y: Int, + z: Int, + willHarvest: Boolean + ): Boolean = if (willHarvest) true else super.removedByPlayer(world, player, x, y, z, willHarvest) - override def harvestBlock(world: World, player: EntityPlayer, x: Int, y: Int, z: Int, meta: Int): Unit = { + override def harvestBlock( + world: World, + player: EntityPlayer, + x: Int, + y: Int, + z: Int, + meta: Int + ): Unit = { super.harvestBlock(world, player, x, y, z, meta) world.setBlockToAir(x, y, z) } - override def getPickBlock(target: MovingObjectPosition, world: World, x: Int, y: Int, z: Int, player: EntityPlayer): ItemStack = { + override def getPickBlock( + target: MovingObjectPosition, + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer + ): ItemStack = { getSavedBlock(world, x, y, z, world.getBlockMetadata(x, y, z)) } - /** - * Override for special actions on placing - * ItemStack might or might not contain actual data - * Called with the TE created and added to world, after onBlockPlacedBy & co - */ - def restoreTileEntity(world: World, x: Int, y: Int, z: Int, is: ItemStack, player: EntityPlayer) = getTE(world, x, y, z).loadFromItem(is) + /** Override for special actions on placing ItemStack might or might not + * contain actual data Called with the TE created and added to world, after + * onBlockPlacedBy & co + */ + def restoreTileEntity( + world: World, + x: Int, + y: Int, + z: Int, + is: ItemStack, + player: EntityPlayer + ) = getTE(world, x, y, z).loadFromItem(is) } -/** - * Mixin for tile entities to keep their data when broken - * Block class has to extend BlockKeepData - */ +/** Mixin for tile entities to keep their data when broken Block class has to + * extend BlockKeepData + */ trait TileKeepData extends TileExtended { - /** - * Override to modify data that will be stored in an item - * @param t Automatically serialized data - * @return Modified serialized data - */ + + /** Override to modify data that will be stored in an item + * @param t + * Automatically serialized data + * @return + * Modified serialized data + */ def afterTileBreakSave(t: NBTTagCompound) = t - /** - * Override to modify data that will be load from an item - * After the tile entity is fully constructed and added to world - * @param t Automatically serialized data - * @return Modified serialized data - */ + /** Override to modify data that will be load from an item After the tile + * entity is fully constructed and added to world + * @param t + * Automatically serialized data + * @return + * Modified serialized data + */ def beforeTileBreakLoad(t: NBTTagCompound) = t final def saveToItem(is: ItemStack): Unit = { if (!is.hasTagCompound) is.setTagCompound(new NBTTagCompound) - is.getTagCompound.setTag("data", afterTileBreakSave(NBT.from(persistSave.trigger))) + is.getTagCompound.setTag( + "data", + afterTileBreakSave(NBT.from(persistSave.trigger)) + ) } final def loadFromItem(is: ItemStack): Unit = { if (is.hasTagCompound && is.getTagCompound.hasKey("data")) { - persistLoad.trigger(beforeTileBreakLoad(is.getTagCompound.getCompoundTag("data"))) + persistLoad.trigger( + beforeTileBreakLoad(is.getTagCompound.getCompoundTag("data")) + ) } } } -/** - * Custom ItemBlock that handles loading data to the Tile Entity - */ +/** Custom ItemBlock that handles loading data to the Tile Entity + */ class ItemBlockKeepData(b: Block) extends ItemBlockTooltip(b) { - override def placeBlockAt(stack: ItemStack, player: EntityPlayer, world: World, x: Int, y: Int, z: Int, side: Int, hitX: Float, hitY: Float, hitZ: Float, metadata: Int): Boolean = { - if (super.placeBlockAt(stack, player, world, x, y, z, side, hitX, hitY, hitZ, metadata)) { + override def placeBlockAt( + stack: ItemStack, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int, + side: Int, + hitX: Float, + hitY: Float, + hitZ: Float, + metadata: Int + ): Boolean = { + if ( + super.placeBlockAt( + stack, + player, + world, + x, + y, + z, + side, + hitX, + hitY, + hitZ, + metadata + ) + ) { if (!world.isRemote && b.isInstanceOf[BlockKeepData]) - b.asInstanceOf[BlockKeepData].restoreTileEntity(world, x, y, z, stack, player) + b.asInstanceOf[BlockKeepData] + .restoreTileEntity(world, x, y, z, stack, player) true } else false } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/block/SimpleBlock.scala b/src/main/scala/net/bdew/lib/block/SimpleBlock.scala index 0e22cc6..6bc0c78 100644 --- a/src/main/scala/net/bdew/lib/block/SimpleBlock.scala +++ b/src/main/scala/net/bdew/lib/block/SimpleBlock.scala @@ -21,7 +21,9 @@ trait NamedBlock extends Block { def name: String } -class SimpleBlock(val name: String, material: Material) extends Block(material) with NamedBlock { +class SimpleBlock(val name: String, material: Material) + extends Block(material) + with NamedBlock { val modId = Misc.getActiveModId setBlockName(modId + "." + name) diff --git a/src/main/scala/net/bdew/lib/config/BlockManager.scala b/src/main/scala/net/bdew/lib/config/BlockManager.scala index 3d392fd..e68db13 100644 --- a/src/main/scala/net/bdew/lib/config/BlockManager.scala +++ b/src/main/scala/net/bdew/lib/config/BlockManager.scala @@ -21,14 +21,24 @@ import net.minecraft.tileentity.TileEntity class BlockManager(creativeTab: CreativeTabs) { def regBlock[T <: NamedBlock](block: T): T = regBlock(block, block.name) - def regSpecial[T <: NamedBlock](block: T, addStack: Boolean = false, skipTileEntityReg: Boolean = false): T = + def regSpecial[T <: NamedBlock]( + block: T, + addStack: Boolean = false, + skipTileEntityReg: Boolean = false + ): T = regBlock(block, block.name, addStack, skipTileEntityReg) - def regBlock[T <: Block](block: T, name: String, addStack: Boolean = false, skipTileEntityReg: Boolean = false): T = { - val itemClass: Class[_ <: ItemBlock] = if (block.isInstanceOf[HasItemBlock]) - block.asInstanceOf[HasItemBlock].ItemBlockClass - else - classOf[ItemBlock] + def regBlock[T <: Block]( + block: T, + name: String, + addStack: Boolean = false, + skipTileEntityReg: Boolean = false + ): T = { + val itemClass: Class[_ <: ItemBlock] = + if (block.isInstanceOf[HasItemBlock]) + block.asInstanceOf[HasItemBlock].ItemBlockClass + else + classOf[ItemBlock] GameRegistry.registerBlock(block, itemClass, name) @@ -38,17 +48,28 @@ class BlockManager(creativeTab: CreativeTabs) { GameRegistry.registerCustomItemStack(name, new ItemStack(block)) if (block.isInstanceOf[HasTE[_]] && !skipTileEntityReg) - GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass, - "%s.%s".format(Misc.getActiveModId, name)) + GameRegistry.registerTileEntity( + block.asInstanceOf[HasTE[_]].TEClass, + "%s.%s".format(Misc.getActiveModId, name) + ) return block } - /** - * Registers a legacy TE name->class mapping. Stolen from GameRegistry.registerTileEntityWithAlternatives - */ - def registerLegacyTileEntity(name: String, cls: Class[_ <: TileEntity]): Unit = { - val teMappings: java.util.Map[String, Class[_]] = ObfuscationReflectionHelper.getPrivateValue(classOf[TileEntity], null, "field_" + "145855_i", "nameToClassMap") + /** Registers a legacy TE name->class mapping. Stolen from + * GameRegistry.registerTileEntityWithAlternatives + */ + def registerLegacyTileEntity( + name: String, + cls: Class[_ <: TileEntity] + ): Unit = { + val teMappings: java.util.Map[String, Class[_]] = + ObfuscationReflectionHelper.getPrivateValue( + classOf[TileEntity], + null, + "field_" + "145855_i", + "nameToClassMap" + ) if (!teMappings.containsKey(name)) teMappings.put(name, cls) } diff --git a/src/main/scala/net/bdew/lib/config/ItemManager.scala b/src/main/scala/net/bdew/lib/config/ItemManager.scala index 00a0b03..d28233b 100644 --- a/src/main/scala/net/bdew/lib/config/ItemManager.scala +++ b/src/main/scala/net/bdew/lib/config/ItemManager.scala @@ -15,11 +15,16 @@ import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.{Item, ItemStack} class ItemManager(creativeTab: CreativeTabs) { - def regSimpleItem(name: String): SimpleItem = regItem(new SimpleItem(name), name) + def regSimpleItem(name: String): SimpleItem = + regItem(new SimpleItem(name), name) def regItem[T <: NamedItem](item: T): T = regItem[T](item, item.name) - def regItem[T <: Item](item: T, name: String, addStack: Boolean = false): T = { + def regItem[T <: Item]( + item: T, + name: String, + addStack: Boolean = false + ): T = { GameRegistry.registerItem(item, name) item.setCreativeTab(creativeTab) if (addStack) diff --git a/src/main/scala/net/bdew/lib/config/MachineManager.scala b/src/main/scala/net/bdew/lib/config/MachineManager.scala index 30c417d..b768ebf 100644 --- a/src/main/scala/net/bdew/lib/config/MachineManager.scala +++ b/src/main/scala/net/bdew/lib/config/MachineManager.scala @@ -17,7 +17,11 @@ import net.bdew.lib.multiblock.block.BlockModule import net.bdew.lib.recipes.gencfg.ConfigSection import net.minecraft.creativetab.CreativeTabs -class MachineManager(val tuning: ConfigSection, guiHandler: GuiHandler, creativeTab: CreativeTabs) { +class MachineManager( + val tuning: ConfigSection, + guiHandler: GuiHandler, + creativeTab: CreativeTabs +) { def registerMachine[R <: Machine[_]](machine: R): R = { machine.tuning = tuning.getSection(machine.name) if (machine.tuning.getBoolean("Enabled")) { @@ -38,9 +42,10 @@ trait MachineManagerMultiblock extends MachineManager { override def registerMachine[R <: Machine[_]](machine: R): R = { super.registerMachine(machine) if (machine.enabled) { - Misc.asInstanceOpt(machine, classOf[MachineCore]) foreach { controllerMachine => - controllers += controllerMachine - controllerMachine.getController.machine = controllerMachine + Misc.asInstanceOpt(machine, classOf[MachineCore]) foreach { + controllerMachine => + controllers += controllerMachine + controllerMachine.getController.machine = controllerMachine } } machine @@ -48,7 +53,7 @@ trait MachineManagerMultiblock extends MachineManager { def getMachinesForBlock(b: BlockModule[_]): Map[MachineCore, (Int, Int)] = { (for (machine <- controllers; max <- machine.modules.get(b.kind)) yield { - machine ->(machine.required.getOrElse(b.kind, 0), max) + machine -> (machine.required.getOrElse(b.kind, 0), max) }).toMap } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/covers/BlockCoverable.scala b/src/main/scala/net/bdew/lib/covers/BlockCoverable.scala index be105a7..eb86c96 100644 --- a/src/main/scala/net/bdew/lib/covers/BlockCoverable.scala +++ b/src/main/scala/net/bdew/lib/covers/BlockCoverable.scala @@ -24,7 +24,13 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { @SideOnly(Side.CLIENT) override def getRenderType = CoverRenderer.id - private def getCoverItem(w: IBlockAccess, x: Int, y: Int, z: Int, side: ForgeDirection): Option[(ItemCover, ItemStack, TileCoverable)] = { + private def getCoverItem( + w: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: ForgeDirection + ): Option[(ItemCover, ItemStack, TileCoverable)] = { val te = getTE(w, x, y, z) for { coverStack <- Option(te.covers(side).value) @@ -33,7 +39,17 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { } yield (coverItem, coverStack, te) } - override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, face: Int, xOffs: Float, yOffs: Float, zOffs: Float): Boolean = { + override def onBlockActivated( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer, + face: Int, + xOffs: Float, + yOffs: Float, + zOffs: Float + ): Boolean = { val te = getTE(world, x, y, z) val side = Misc.forgeDirection(face) @@ -58,20 +74,37 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { activeStack <- Option(player.getCurrentEquippedItem) activeItem <- Option(activeStack.getItem) coverItem <- Misc.asInstanceOpt(activeItem, classOf[ItemCover]) - if te.isValidCover(side, activeStack) && coverItem.isValidTile(te, activeStack) + if te.isValidCover(side, activeStack) && coverItem.isValidTile( + te, + activeStack + ) } { if (!world.isRemote && player.isInstanceOf[EntityPlayerMP]) { for { oldCover <- Option(te.covers(side).value) oldItem <- Misc.asInstanceOpt(oldCover.getItem, classOf[ItemCover]) } { - ItemUtils.throwItemAt(world, te.xCoord + side.offsetX, te.yCoord + side.offsetY, te.zCoord + side.offsetZ, oldItem.onRemove(oldCover)) + ItemUtils.throwItemAt( + world, + te.xCoord + side.offsetX, + te.yCoord + side.offsetY, + te.zCoord + side.offsetZ, + oldItem.onRemove(oldCover) + ) } - te.covers(side) := coverItem.onInstall(te, side, activeStack.splitStack(1), player.asInstanceOf[EntityPlayerMP]) + te.covers(side) := coverItem.onInstall( + te, + side, + activeStack.splitStack(1), + player.asInstanceOf[EntityPlayerMP] + ) if (activeStack.stackSize <= 0) - player.inventory.setInventorySlotContents(player.inventory.currentItem, null) + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + null + ) te.onCoversChanged() coverChanged(world, x, y, z, side) @@ -89,7 +122,13 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { override def canProvidePower = true - override def isProvidingWeakPower(w: IBlockAccess, x: Int, y: Int, z: Int, side: Int): Int = { + override def isProvidingWeakPower( + w: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: Int + ): Int = { val direction = Misc.forgeDirection(side).getOpposite for ((item, stack, te) <- getCoverItem(w, x, y, z, direction)) { if (item.isEmittingSignal(te, direction, stack)) return 15 @@ -97,16 +136,35 @@ trait BlockCoverable[T <: TileCoverable] extends HasTE[T] { 0 } - def coverChanged(w: World, x: Int, y: Int, z: Int, side: ForgeDirection): Unit = { + def coverChanged( + w: World, + x: Int, + y: Int, + z: Int, + side: ForgeDirection + ): Unit = { val pos = BlockRef(x, y, z).neighbour(side) w.notifyBlockOfNeighborChange(pos.x, pos.y, pos.z, pos.block(w).orNull) } - def getCoverIcon(w: IBlockAccess, x: Int, y: Int, z: Int, side: ForgeDirection): Option[IIcon] = + def getCoverIcon( + w: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: ForgeDirection + ): Option[IIcon] = for ((item, stack, te) <- getCoverItem(w, x, y, z, side)) yield item.getCoverIcon(te, side, stack) - override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) { + override def breakBlock( + world: World, + x: Int, + y: Int, + z: Int, + block: Block, + meta: Int + ) { if (!world.isRemote) { val te = getTE(world, x, y, z) for { diff --git a/src/main/scala/net/bdew/lib/covers/CoverRenderer.scala b/src/main/scala/net/bdew/lib/covers/CoverRenderer.scala index e6b9850..c5e233a 100644 --- a/src/main/scala/net/bdew/lib/covers/CoverRenderer.scala +++ b/src/main/scala/net/bdew/lib/covers/CoverRenderer.scala @@ -18,18 +18,39 @@ import net.minecraft.world.IBlockAccess import net.minecraftforge.common.util.ForgeDirection object CoverRenderer extends BaseBlockRenderHandler { - override def renderInventoryBlock(block: Block, metadata: Int, modelId: Int, renderer: RenderBlocks) = + override def renderInventoryBlock( + block: Block, + metadata: Int, + modelId: Int, + renderer: RenderBlocks + ) = RenderUtils.renderSimpleBlockItem(block, metadata, renderer) - override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks) = { + override def renderWorldBlock( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + block: Block, + modelId: Int, + renderer: RenderBlocks + ) = { renderer.renderStandardBlock(block, x, y, z) if (!renderer.hasOverrideBlockTexture) for { blockCov <- Misc.asInstanceOpt(block, classOf[BlockCoverable[_]]) face <- ForgeDirection.VALID_DIRECTIONS icon <- blockCov.getCoverIcon(world, x, y, z, face) - if block.shouldSideBeRendered(world, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal()) - } ConnectedHelper.draw(face, 8).doDraw(ConnectedHelper.Vec3F(x, y, z), icon) + if block.shouldSideBeRendered( + world, + x + face.offsetX, + y + face.offsetY, + z + face.offsetZ, + face.ordinal() + ) + } ConnectedHelper + .draw(face, 8) + .doDraw(ConnectedHelper.Vec3F(x, y, z), icon) true } } diff --git a/src/main/scala/net/bdew/lib/covers/ItemCover.scala b/src/main/scala/net/bdew/lib/covers/ItemCover.scala index 111d468..72f9b30 100644 --- a/src/main/scala/net/bdew/lib/covers/ItemCover.scala +++ b/src/main/scala/net/bdew/lib/covers/ItemCover.scala @@ -15,68 +15,111 @@ import net.minecraft.util.IIcon import net.minecraftforge.common.util.ForgeDirection trait ItemCover extends Item { - /** - * @return true if tickCover should be called - */ + + /** @return + * true if tickCover should be called + */ def isCoverTicking: Boolean - /** - * @param te Host TileEntity - * @param side Side the cover is installed on - * @param cover Cover ItemStack - * @return Icon to render, MUST be on terrain sprite sheet (0), not item! - */ - def getCoverIcon(te: TileCoverable, side: ForgeDirection, cover: ItemStack): IIcon + /** @param te + * Host TileEntity + * @param side + * Side the cover is installed on + * @param cover + * Cover ItemStack + * @return + * Icon to render, MUST be on terrain sprite sheet (0), not item! + */ + def getCoverIcon( + te: TileCoverable, + side: ForgeDirection, + cover: ItemStack + ): IIcon - /** - * Perform tick, called on server only - * @param te Host TileEntity - * @param side Side the cover is installed on - * @param cover Cover ItemStack - */ - def tickCover(te: TileCoverable, side: ForgeDirection, cover: ItemStack): Unit = {} + /** Perform tick, called on server only + * @param te + * Host TileEntity + * @param side + * Side the cover is installed on + * @param cover + * Cover ItemStack + */ + def tickCover( + te: TileCoverable, + side: ForgeDirection, + cover: ItemStack + ): Unit = {} - /** - * Checks if this cover can be installed on a specific TE - * @param te Potential host TileEntity - * @param cover Cover ItemStack - * @return true if can be installed - */ + /** Checks if this cover can be installed on a specific TE + * @param te + * Potential host TileEntity + * @param cover + * Cover ItemStack + * @return + * true if can be installed + */ def isValidTile(te: TileCoverable, cover: ItemStack): Boolean - /** - * Handle click on covered side - called on both client and server - * @param te Host TileEntity - * @param side Side the cover is installed on - * @param cover Cover ItemStack - * @param player Player clicking the cover - * @return true if click was handled by cover - */ - def clickCover(te: TileCoverable, side: ForgeDirection, cover: ItemStack, player: EntityPlayer): Boolean = false + /** Handle click on covered side - called on both client and server + * @param te + * Host TileEntity + * @param side + * Side the cover is installed on + * @param cover + * Cover ItemStack + * @param player + * Player clicking the cover + * @return + * true if click was handled by cover + */ + def clickCover( + te: TileCoverable, + side: ForgeDirection, + cover: ItemStack, + player: EntityPlayer + ): Boolean = false - /** - * Check if cover is emitting RS signal - * @param te Host TileEntity - * @param side Side the cover is installed on - * @param cover Cover ItemStack - * @return true if cover is emitting RS signal - */ - def isEmittingSignal(te: TileCoverable, side: ForgeDirection, cover: ItemStack): Boolean = false + /** Check if cover is emitting RS signal + * @param te + * Host TileEntity + * @param side + * Side the cover is installed on + * @param cover + * Cover ItemStack + * @return + * true if cover is emitting RS signal + */ + def isEmittingSignal( + te: TileCoverable, + side: ForgeDirection, + cover: ItemStack + ): Boolean = false - /** - * Called when cover is installed on a block - called only on server - * @param te Host TileEntity - * @param side Side the cover is installed on - * @param cover Cover ItemStack - do not modify! - * @param player Player entity doing the installation - * @return cover ItemStack - copy if modified - */ - def onInstall(te:TileCoverable, side: ForgeDirection, cover: ItemStack, player: EntityPlayerMP): ItemStack = cover + /** Called when cover is installed on a block - called only on server + * @param te + * Host TileEntity + * @param side + * Side the cover is installed on + * @param cover + * Cover ItemStack - do not modify! + * @param player + * Player entity doing the installation + * @return + * cover ItemStack - copy if modified + */ + def onInstall( + te: TileCoverable, + side: ForgeDirection, + cover: ItemStack, + player: EntityPlayerMP + ): ItemStack = cover - /** - * Called when cover is removed from block or block is destroyed - called only on server - * @param cover Cover ItemStack - do not modify! - * @return cover ItemStack - copy if modified - */ + /** Called when cover is removed from block or block is destroyed - called + * only on server + * @param cover + * Cover ItemStack - do not modify! + * @return + * cover ItemStack - copy if modified + */ def onRemove(cover: ItemStack): ItemStack = cover } diff --git a/src/main/scala/net/bdew/lib/covers/TileCoverable.scala b/src/main/scala/net/bdew/lib/covers/TileCoverable.scala index b85a7d4..5263561 100644 --- a/src/main/scala/net/bdew/lib/covers/TileCoverable.scala +++ b/src/main/scala/net/bdew/lib/covers/TileCoverable.scala @@ -19,24 +19,26 @@ import net.minecraftforge.common.util.ForgeDirection trait TileCoverable extends TileDataSlots { val covers = (ForgeDirection.VALID_DIRECTIONS map { x => - x -> DataSlotItemStack("cover_" + x.toString.toLowerCase(Locale.US), this).setUpdate(UpdateKind.SAVE, UpdateKind.WORLD, UpdateKind.RENDER) + x -> DataSlotItemStack("cover_" + x.toString.toLowerCase(Locale.US), this) + .setUpdate(UpdateKind.SAVE, UpdateKind.WORLD, UpdateKind.RENDER) }).toMap - /** - * Checks if a specific cover can be installed here - */ + /** Checks if a specific cover can be installed here + */ def isValidCover(side: ForgeDirection, cover: ItemStack): Boolean - /** - * Called when new covers are installed - */ + /** Called when new covers are installed + */ def onCoversChanged() {} def tickCovers() = for { (dir, coverSlot) <- covers coverStack <- Option(coverSlot.value) - coverItem <- Option(coverStack.getItem) flatMap (Misc.asInstanceOpt(_, classOf[ItemCover])) + coverItem <- Option(coverStack.getItem) flatMap (Misc.asInstanceOpt( + _, + classOf[ItemCover] + )) } { coverItem.tickCover(this, dir, coverStack) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotBoolean.scala b/src/main/scala/net/bdew/lib/data/DataSlotBoolean.scala index e14823b..7da8931 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotBoolean.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotBoolean.scala @@ -12,8 +12,14 @@ package net.bdew.lib.data import net.bdew.lib.data.base.{DataSlotContainer, DataSlotVal, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotBoolean(name: String, parent: DataSlotContainer, default: Boolean = false) extends DataSlotVal[Boolean] { +case class DataSlotBoolean( + name: String, + parent: DataSlotContainer, + default: Boolean = false +) extends DataSlotVal[Boolean] { var value = default - def save(t: NBTTagCompound, kind: UpdateKind.Value) = t.setBoolean(name, value) - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = t.getBoolean(name) + def save(t: NBTTagCompound, kind: UpdateKind.Value) = + t.setBoolean(name, value) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + t.getBoolean(name) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotDirection.scala b/src/main/scala/net/bdew/lib/data/DataSlotDirection.scala index 48b7863..0e42a98 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotDirection.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotDirection.scala @@ -13,8 +13,11 @@ import net.bdew.lib.data.base.{DataSlotContainer, DataSlotVal, UpdateKind} import net.minecraft.nbt.NBTTagCompound import net.minecraftforge.common.util.ForgeDirection -case class DataSlotDirection(name: String, parent: DataSlotContainer) extends DataSlotVal[ForgeDirection] { +case class DataSlotDirection(name: String, parent: DataSlotContainer) + extends DataSlotVal[ForgeDirection] { var value = ForgeDirection.UP - def save(t: NBTTagCompound, kind: UpdateKind.Value) = t.setByte(name, value.ordinal().toByte) - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = ForgeDirection.getOrientation(t.getByte(name)) + def save(t: NBTTagCompound, kind: UpdateKind.Value) = + t.setByte(name, value.ordinal().toByte) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + ForgeDirection.getOrientation(t.getByte(name)) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotDouble.scala b/src/main/scala/net/bdew/lib/data/DataSlotDouble.scala index e86026b..a7d0adc 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotDouble.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotDouble.scala @@ -12,7 +12,12 @@ package net.bdew.lib.data import net.bdew.lib.data.base.{DataSlotContainer, DataSlotNumeric, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotDouble(name: String, parent: DataSlotContainer, default: Double = 0) extends DataSlotNumeric[Double](default) { +case class DataSlotDouble( + name: String, + parent: DataSlotContainer, + default: Double = 0 +) extends DataSlotNumeric[Double](default) { def save(t: NBTTagCompound, kind: UpdateKind.Value) = t.setDouble(name, value) - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = t.getDouble(name) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + t.getDouble(name) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotFloat.scala b/src/main/scala/net/bdew/lib/data/DataSlotFloat.scala index 0ec2a14..c25c36d 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotFloat.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotFloat.scala @@ -12,7 +12,11 @@ package net.bdew.lib.data import net.bdew.lib.data.base.{DataSlotContainer, DataSlotNumeric, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotFloat(name: String, parent: DataSlotContainer, default: Float = 0) extends DataSlotNumeric[Float](default) { +case class DataSlotFloat( + name: String, + parent: DataSlotContainer, + default: Float = 0 +) extends DataSlotNumeric[Float](default) { def save(t: NBTTagCompound, kind: UpdateKind.Value) = t.setFloat(name, value) def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = t.getFloat(name) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotFluidOption.scala b/src/main/scala/net/bdew/lib/data/DataSlotFluidOption.scala index f6d91c8..f3b9b04 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotFluidOption.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotFluidOption.scala @@ -13,7 +13,8 @@ import net.bdew.lib.data.base.{DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound import net.minecraftforge.fluids.{Fluid, FluidRegistry} -case class DataSlotFluidOption(name: String, parent: DataSlotContainer) extends DataSlotOption[Fluid] { +case class DataSlotFluidOption(name: String, parent: DataSlotContainer) + extends DataSlotOption[Fluid] { setUpdate(UpdateKind.SAVE, UpdateKind.GUI) override def save(t: NBTTagCompound, kind: UpdateKind.Value) { diff --git a/src/main/scala/net/bdew/lib/data/DataSlotGameProfile.scala b/src/main/scala/net/bdew/lib/data/DataSlotGameProfile.scala index a22b0cd..c84be64 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotGameProfile.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotGameProfile.scala @@ -16,21 +16,29 @@ import net.bdew.lib.data.base.{DataSlotContainer, DataSlotVal, UpdateKind} import net.minecraft.nbt.NBTTagCompound import org.apache.commons.lang3.StringUtils -case class DataSlotGameProfile(name: String, parent: DataSlotContainer) extends DataSlotVal[GameProfile] { +case class DataSlotGameProfile(name: String, parent: DataSlotContainer) + extends DataSlotVal[GameProfile] { override var value: GameProfile = null override def load(t: NBTTagCompound, kind: UpdateKind.Value) = { value = if (t.hasKey(name + "_uid") || t.hasKey(name + "_name")) { - val uId = if (t.hasKey(name + "_uid")) UUID.fromString(t.getString(name + "_uid")) else null - val uName = if (t.hasKey(name + "_name")) t.getString(name + "_name") else null + val uId = + if (t.hasKey(name + "_uid")) UUID.fromString(t.getString(name + "_uid")) + else null + val uName = + if (t.hasKey(name + "_name")) t.getString(name + "_name") else null new GameProfile(uId, uName) } else null } override def save(t: NBTTagCompound, kind: UpdateKind.Value) = { if (value != null) { - Option(value.getId) foreach (id => t.setString(name + "_uid", id.toString)) - Option(value.getName) filterNot (name => StringUtils.isBlank(name)) foreach (name => t.setString(name + "_name", name)) + Option(value.getId) foreach (id => + t.setString(name + "_uid", id.toString) + ) + Option(value.getName) filterNot (name => + StringUtils.isBlank(name) + ) foreach (name => t.setString(name + "_name", name)) } } } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotInt.scala b/src/main/scala/net/bdew/lib/data/DataSlotInt.scala index ee36ad9..36205b9 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotInt.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotInt.scala @@ -12,7 +12,13 @@ package net.bdew.lib.data import net.bdew.lib.data.base.{DataSlotContainer, DataSlotNumeric, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotInt(name: String, parent: DataSlotContainer, default: Int = 0) extends DataSlotNumeric[Int](default) { - def save(t: NBTTagCompound, kind: UpdateKind.Value) = t.setInteger(name, value) - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = t.getInteger(name) +case class DataSlotInt( + name: String, + parent: DataSlotContainer, + default: Int = 0 +) extends DataSlotNumeric[Int](default) { + def save(t: NBTTagCompound, kind: UpdateKind.Value) = + t.setInteger(name, value) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + t.getInteger(name) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotInventory.scala b/src/main/scala/net/bdew/lib/data/DataSlotInventory.scala index df6e952..a2849f4 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotInventory.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotInventory.scala @@ -14,7 +14,9 @@ import net.bdew.lib.tile.inventory.BaseInventory import net.minecraft.item.ItemStack import net.minecraft.nbt.{NBTTagCompound, NBTTagList} -case class DataSlotInventory(name: String, parent: DataSlotContainer, size: Int) extends DataSlot with BaseInventory { +case class DataSlotInventory(name: String, parent: DataSlotContainer, size: Int) + extends DataSlot + with BaseInventory { setUpdate(UpdateKind.SAVE) override def getSizeInventory = size @@ -42,5 +44,3 @@ case class DataSlotInventory(name: String, parent: DataSlotContainer, size: Int) t.setTag(name, itemList) } } - - diff --git a/src/main/scala/net/bdew/lib/data/DataSlotItemStack.scala b/src/main/scala/net/bdew/lib/data/DataSlotItemStack.scala index 6e11a40..3a4993e 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotItemStack.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotItemStack.scala @@ -13,7 +13,8 @@ import net.bdew.lib.data.base.{DataSlotContainer, DataSlotVal, UpdateKind} import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound -case class DataSlotItemStack(name: String, parent: DataSlotContainer) extends DataSlotVal[ItemStack] { +case class DataSlotItemStack(name: String, parent: DataSlotContainer) + extends DataSlotVal[ItemStack] { var value: ItemStack = null override def update(v: ItemStack) = { @@ -28,5 +29,6 @@ case class DataSlotItemStack(name: String, parent: DataSlotContainer) extends Da if (value != null) value.writeToNBT(tag) t.setTag(name, tag) } - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = ItemStack.loadItemStackFromNBT(t.getCompoundTag(name)) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + ItemStack.loadItemStackFromNBT(t.getCompoundTag(name)) } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotMovingAverage.scala b/src/main/scala/net/bdew/lib/data/DataSlotMovingAverage.scala index ef41db9..d60e22c 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotMovingAverage.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotMovingAverage.scala @@ -9,14 +9,23 @@ package net.bdew.lib.data -import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream} +import java.io.{ + ByteArrayInputStream, + ByteArrayOutputStream, + DataInputStream, + DataOutputStream +} import net.bdew.lib.data.base.{DataSlot, DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound import scala.collection.mutable -case class DataSlotMovingAverage(name: String, parent: DataSlotContainer, size: Int) extends DataSlot { +case class DataSlotMovingAverage( + name: String, + parent: DataSlotContainer, + size: Int +) extends DataSlot { val values = mutable.Queue.empty[Double] var average: Double = 0 @@ -53,7 +62,9 @@ case class DataSlotMovingAverage(name: String, parent: DataSlotContainer, size: } else { values.clear() if (t.hasKey(name)) { - val i = new DataInputStream(new ByteArrayInputStream(t.getByteArray(name))) + val i = new DataInputStream( + new ByteArrayInputStream(t.getByteArray(name)) + ) val len = i.readByte() values ++= (for (x <- 0 until Math.min(len, size)) yield i.readDouble()) i.close() diff --git a/src/main/scala/net/bdew/lib/data/DataSlotString.scala b/src/main/scala/net/bdew/lib/data/DataSlotString.scala index cd372d4..7403400 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotString.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotString.scala @@ -12,8 +12,14 @@ package net.bdew.lib.data import net.bdew.lib.data.base.{DataSlotContainer, DataSlotVal, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotString(name: String, parent: DataSlotContainer, default: String = null) extends DataSlotVal[String] { +case class DataSlotString( + name: String, + parent: DataSlotContainer, + default: String = null +) extends DataSlotVal[String] { var value: String = default - def save(t: NBTTagCompound, kind: UpdateKind.Value) = if (value != null) t.setString(name, value) - def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = if (t.hasKey(name)) t.getString(name) else null + def save(t: NBTTagCompound, kind: UpdateKind.Value) = + if (value != null) t.setString(name, value) + def load(t: NBTTagCompound, kind: UpdateKind.Value) = value = + if (t.hasKey(name)) t.getString(name) else null } diff --git a/src/main/scala/net/bdew/lib/data/DataSlotTank.scala b/src/main/scala/net/bdew/lib/data/DataSlotTank.scala index ff1c358..18ac61b 100644 --- a/src/main/scala/net/bdew/lib/data/DataSlotTank.scala +++ b/src/main/scala/net/bdew/lib/data/DataSlotTank.scala @@ -13,7 +13,10 @@ import net.bdew.lib.data.base.{DataSlot, DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound import net.minecraftforge.fluids._ -abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank with DataSlot { +abstract class DataSlotTankBase(sz: Int) + extends FluidTank(sz) + with IFluidTank + with DataSlot { var oldStack: FluidStack = null parent.onServerTick(checkUpdate) @@ -51,12 +54,19 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w setCapacity(tag.getInteger("size")) } - override def setFluid(fluid: FluidStack) = execWithChangeNotify(super.setFluid(fluid)) - override def setCapacity(capacity: Int) = execWithChangeNotify(super.setCapacity(capacity)) + override def setFluid(fluid: FluidStack) = execWithChangeNotify( + super.setFluid(fluid) + ) + override def setCapacity(capacity: Int) = execWithChangeNotify( + super.setCapacity(capacity) + ) override def drain(maxDrain: Int, doDrain: Boolean) = if (doDrain) - execWithChangeNotifyConditional[FluidStack](super.drain(maxDrain, true), _ != null) + execWithChangeNotifyConditional[FluidStack]( + super.drain(maxDrain, true), + _ != null + ) else super.drain(maxDrain, false) @@ -67,10 +77,17 @@ abstract class DataSlotTankBase(sz: Int) extends FluidTank(sz) with IFluidTank w super.fill(resource, false) } -case class DataSlotTank(name: String, parent: DataSlotContainer, size: Int) extends DataSlotTankBase(size) +case class DataSlotTank(name: String, parent: DataSlotContainer, size: Int) + extends DataSlotTankBase(size) -case class DataSlotTankRestricted(name: String, parent: DataSlotContainer, var size: Int, filterFluid: Fluid) extends DataSlotTankBase(size) { - def fill(amount: Int, doFill: Boolean) = super.fill(new FluidStack(filterFluid, amount), doFill) +case class DataSlotTankRestricted( + name: String, + parent: DataSlotContainer, + var size: Int, + filterFluid: Fluid +) extends DataSlotTankBase(size) { + def fill(amount: Int, doFill: Boolean) = + super.fill(new FluidStack(filterFluid, amount), doFill) override def fill(resource: FluidStack, doFill: Boolean): Int = { if ((resource != null) && (resource.getFluid != filterFluid)) return 0 diff --git a/src/main/scala/net/bdew/lib/data/base/ContainerDataSlots.scala b/src/main/scala/net/bdew/lib/data/base/ContainerDataSlots.scala index 9038924..2e7eee0 100644 --- a/src/main/scala/net/bdew/lib/data/base/ContainerDataSlots.scala +++ b/src/main/scala/net/bdew/lib/data/base/ContainerDataSlots.scala @@ -21,14 +21,19 @@ trait ContainerDataSlots extends NoInvContainer { super.addCraftingToCrafters(crafter) if (crafter.isInstanceOf[EntityPlayerMP]) { val pkt = dataSource.getDataSlotPacket - crafter.asInstanceOf[EntityPlayerMP].playerNetServerHandler.sendPacket(pkt) + crafter + .asInstanceOf[EntityPlayerMP] + .playerNetServerHandler + .sendPacket(pkt) } } override def detectAndSendChanges() { super.detectAndSendChanges() // only send updates every 10 ticks - if (dataSource.lastChange >= lastSentChange + 10 || (dataSource.lastChange > lastSentChange && lastSentChange + 10 < dataSource.getWorldObj.getTotalWorldTime)) { + if ( + dataSource.lastChange >= lastSentChange + 10 || (dataSource.lastChange > lastSentChange && lastSentChange + 10 < dataSource.getWorldObj.getTotalWorldTime) + ) { lastSentChange = dataSource.lastChange val pkt = dataSource.getDataSlotPacket diff --git a/src/main/scala/net/bdew/lib/data/base/DataSlot.scala b/src/main/scala/net/bdew/lib/data/base/DataSlot.scala index e03f220..39dfb50 100644 --- a/src/main/scala/net/bdew/lib/data/base/DataSlot.scala +++ b/src/main/scala/net/bdew/lib/data/base/DataSlot.scala @@ -11,20 +11,18 @@ package net.bdew.lib.data.base import net.minecraft.nbt.NBTTagCompound -/** - * Base trait for all data slots - */ +/** Base trait for all data slots + */ trait DataSlot { - /** - * Tile Entity that owns this slot - * Accessed in constructor, so should be in parameters or a lazy val, otherwise will crash - */ + + /** Tile Entity that owns this slot Accessed in constructor, so should be in + * parameters or a lazy val, otherwise will crash + */ val parent: DataSlotContainer - /** - * Unique name - * Accessed in constructor, so should be in parameters or a lazy val, otherwise will crash - */ + /** Unique name Accessed in constructor, so should be in parameters or a lazy + * val, otherwise will crash + */ val name: String parent.dataSlots += (name -> this) @@ -41,7 +39,10 @@ trait DataSlot { v } - def execWithChangeNotifyConditional[T](f: => T, condition: T => Boolean): T = { + def execWithChangeNotifyConditional[T]( + f: => T, + condition: T => Boolean + ): T = { val v = f if (condition(v)) parent.dataSlotChanged(this) diff --git a/src/main/scala/net/bdew/lib/data/base/DataSlotContainer.scala b/src/main/scala/net/bdew/lib/data/base/DataSlotContainer.scala index b139613..65e7b94 100644 --- a/src/main/scala/net/bdew/lib/data/base/DataSlotContainer.scala +++ b/src/main/scala/net/bdew/lib/data/base/DataSlotContainer.scala @@ -14,37 +14,32 @@ import net.minecraft.world.World import scala.collection.mutable -/** - * Base Trait for objects that can contain Data Slots, this allows implementing them on things that aren't TEs - */ +/** Base Trait for objects that can contain Data Slots, this allows implementing + * them on things that aren't TEs + */ trait DataSlotContainer { // Can't use getWorldObj - it fails to get remapped and stuff breaks in obfuscated environment def getWorldObject: World - /** - * Called when a dataslot value changes - */ + /** Called when a dataslot value changes + */ def dataSlotChanged(slot: DataSlot): Unit - /** - * Register a function to run on every server tick - */ + /** Register a function to run on every server tick + */ def onServerTick(f: () => Unit): Unit - /** - * List of dataslots in this container - */ + /** List of dataslots in this container + */ val dataSlots = mutable.HashMap.empty[String, DataSlot] - /** - * The value of getTotalWorldTime when the last change happened - */ + /** The value of getTotalWorldTime when the last change happened + */ var lastChange = 0L - /** - * The value of getTotalWorldTime when the last GUI packet was sent happened - */ + /** The value of getTotalWorldTime when the last GUI packet was sent happened + */ var lastGuiPacket = 0L final val TRACE = false @@ -73,5 +68,3 @@ trait DataSlotContainer { } } } - - diff --git a/src/main/scala/net/bdew/lib/data/base/DataSlotNumeric.scala b/src/main/scala/net/bdew/lib/data/base/DataSlotNumeric.scala index 9175343..dc83e81 100644 --- a/src/main/scala/net/bdew/lib/data/base/DataSlotNumeric.scala +++ b/src/main/scala/net/bdew/lib/data/base/DataSlotNumeric.scala @@ -9,12 +9,12 @@ package net.bdew.lib.data.base -/** - * Base class for data slots that hold numeric values - * adds convenience operators to modify the value - */ +/** Base class for data slots that hold numeric values adds convenience + * operators to modify the value + */ -abstract class DataSlotNumeric[T](default: T)(implicit n: Numeric[T]) extends DataSlotVal[T] { +abstract class DataSlotNumeric[T](default: T)(implicit n: Numeric[T]) + extends DataSlotVal[T] { var value = default def +=(that: T) = update(n.plus(value, that)) def -=(that: T) = update(n.minus(value, that)) diff --git a/src/main/scala/net/bdew/lib/data/base/DataSlotOrdered.scala b/src/main/scala/net/bdew/lib/data/base/DataSlotOrdered.scala index 6531c7f..930e70c 100644 --- a/src/main/scala/net/bdew/lib/data/base/DataSlotOrdered.scala +++ b/src/main/scala/net/bdew/lib/data/base/DataSlotOrdered.scala @@ -9,11 +9,12 @@ package net.bdew.lib.data.base -/** - * Base class for data slots that hold values with ordering operators, adds more convenience operators - * TODO: Do i need this? normal operators can be used with the implicit conversion - */ -abstract class DataSlotOrdered[T](implicit n: Ordering[T]) extends DataSlotVal[T] { +/** Base class for data slots that hold values with ordering operators, adds + * more convenience operators TODO: Do i need this? normal operators can be + * used with the implicit conversion + */ +abstract class DataSlotOrdered[T](implicit n: Ordering[T]) + extends DataSlotVal[T] { def :>(that: T) = n.compare(value, that) > 0 def :<(that: T) = n.compare(value, that) < 0 def :>=(that: T) = n.compare(value, that) >= 0 diff --git a/src/main/scala/net/bdew/lib/data/base/DataSlotVal.scala b/src/main/scala/net/bdew/lib/data/base/DataSlotVal.scala index e78c7de..8435221 100644 --- a/src/main/scala/net/bdew/lib/data/base/DataSlotVal.scala +++ b/src/main/scala/net/bdew/lib/data/base/DataSlotVal.scala @@ -11,10 +11,10 @@ package net.bdew.lib.data.base import scala.language.implicitConversions -/** - * Base trait for data slots that hold primitive values - * Defines some convenience operators to access the value and an implicit conversion to the value - */ +/** Base trait for data slots that hold primitive values Defines some + * convenience operators to access the value and an implicit conversion to the + * value + */ trait DataSlotVal[T] extends DataSlot { var value: T @@ -36,4 +36,4 @@ trait DataSlotVal[T] extends DataSlot { object DataSlotVal { implicit def slot2val[T](slot: DataSlotVal[T]): T = slot.value -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/data/base/TileDataSlots.scala b/src/main/scala/net/bdew/lib/data/base/TileDataSlots.scala index 35b382f..7fd21e6 100644 --- a/src/main/scala/net/bdew/lib/data/base/TileDataSlots.scala +++ b/src/main/scala/net/bdew/lib/data/base/TileDataSlots.scala @@ -21,7 +21,14 @@ trait TileDataSlots extends TileExtended with DataSlotContainer { handleClientUpdate.listen { tag => doLoad(UpdateKind.WORLD, tag) if (dataSlots.values.exists(_.updateKind.contains(UpdateKind.RENDER))) - getWorldObj.markBlockRangeForRenderUpdate(xCoord, yCoord, zCoord, xCoord, yCoord, zCoord) + getWorldObj.markBlockRangeForRenderUpdate( + xCoord, + yCoord, + zCoord, + xCoord, + yCoord, + zCoord + ) } override def getWorldObject = getWorldObj diff --git a/src/main/scala/net/bdew/lib/data/base/UpdateKind.scala b/src/main/scala/net/bdew/lib/data/base/UpdateKind.scala index 915cdae..196f344 100644 --- a/src/main/scala/net/bdew/lib/data/base/UpdateKind.scala +++ b/src/main/scala/net/bdew/lib/data/base/UpdateKind.scala @@ -14,4 +14,4 @@ object UpdateKind extends Enumeration { val GUI = Value("GUI") val SAVE = Value("SAVE") val RENDER = Value("RENDER") -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/gui/BaseContainer.scala b/src/main/scala/net/bdew/lib/gui/BaseContainer.scala index 94b767d..1cfbed3 100644 --- a/src/main/scala/net/bdew/lib/gui/BaseContainer.scala +++ b/src/main/scala/net/bdew/lib/gui/BaseContainer.scala @@ -15,20 +15,30 @@ import net.minecraft.inventory.IInventory import net.minecraft.item.ItemStack abstract class BaseContainer(te: IInventory) extends NoInvContainer { - override def transferStackInSlot(player: EntityPlayer, slot: Int): ItemStack = { + override def transferStackInSlot( + player: EntityPlayer, + slot: Int + ): ItemStack = { var stack = getSlot(slot).getStack if (getSlot(slot).inventory == player.inventory) { - stack = ItemUtils.addStackToSlots(stack, te, 0 until te.getSizeInventory, true) + stack = + ItemUtils.addStackToSlots(stack, te, 0 until te.getSizeInventory, true) } else { - stack = ItemUtils.addStackToSlots(stack, player.inventory, 9 until player.inventory.mainInventory.length, true) + stack = ItemUtils.addStackToSlots( + stack, + player.inventory, + 9 until player.inventory.mainInventory.length, + true + ) // Only put in hotbar if the rest is full if (stack != null) - stack = ItemUtils.addStackToSlots(stack, player.inventory, 0 until 9, true) + stack = + ItemUtils.addStackToSlots(stack, player.inventory, 0 until 9, true) } getSlot(slot).putStack(stack) return null } - override def canInteractWith(player: EntityPlayer) = te.isUseableByPlayer(player) + override def canInteractWith(player: EntityPlayer) = + te.isUseableByPlayer(player) } - diff --git a/src/main/scala/net/bdew/lib/gui/BaseRect.scala b/src/main/scala/net/bdew/lib/gui/BaseRect.scala index 7cfceaa..5ad78fa 100644 --- a/src/main/scala/net/bdew/lib/gui/BaseRect.scala +++ b/src/main/scala/net/bdew/lib/gui/BaseRect.scala @@ -16,7 +16,8 @@ case class BaseRect[T: Numeric](x: T, y: T, w: T, h: T) { def this(p: BasePoint[T], w: T, h: T) = this(p.x, p.y, w, h) - def contains(p: BasePoint[T]) = n.gteq(p.x, x) && n.gteq(p.y, y) && n.lt(p.x, x2) && n.lt(p.y, y2) + def contains(p: BasePoint[T]) = + n.gteq(p.x, x) && n.gteq(p.y, y) && n.lt(p.x, x2) && n.lt(p.y, y2) def origin = BasePoint(x, y) diff --git a/src/main/scala/net/bdew/lib/gui/BaseScreen.scala b/src/main/scala/net/bdew/lib/gui/BaseScreen.scala index ff4f49b..28b34e5 100644 --- a/src/main/scala/net/bdew/lib/gui/BaseScreen.scala +++ b/src/main/scala/net/bdew/lib/gui/BaseScreen.scala @@ -16,7 +16,8 @@ import org.lwjgl.opengl.GL11 import scala.collection.mutable -abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) extends GuiContainer(cont) { +abstract class BaseScreen(cont: Container, xSz: Int, ySz: Int) + extends GuiContainer(cont) { xSize = xSz ySize = ySz diff --git a/src/main/scala/net/bdew/lib/gui/BaseSlot.scala b/src/main/scala/net/bdew/lib/gui/BaseSlot.scala index 6775c75..0b8dc8c 100644 --- a/src/main/scala/net/bdew/lib/gui/BaseSlot.scala +++ b/src/main/scala/net/bdew/lib/gui/BaseSlot.scala @@ -12,7 +12,8 @@ package net.bdew.lib.gui import net.minecraft.inventory.{IInventory, Slot} import org.lwjgl.opengl.GL11 -class BaseSlot(inv: IInventory, slot: Int, x: Int, y: Int) extends Slot(inv, slot, x, y) { +class BaseSlot(inv: IInventory, slot: Int, x: Int, y: Int) + extends Slot(inv, slot, x, y) { override def getBackgroundIconIndex = { // Workaround for bug in GuiContainer, color isn't reset if previous slot had an item with color. GL11.glColor4d(1, 1, 1, 1) diff --git a/src/main/scala/net/bdew/lib/gui/Color.scala b/src/main/scala/net/bdew/lib/gui/Color.scala index a4f36b6..f5bcdba 100644 --- a/src/main/scala/net/bdew/lib/gui/Color.scala +++ b/src/main/scala/net/bdew/lib/gui/Color.scala @@ -28,11 +28,12 @@ case class Color(r: Float, g: Float, b: Float, a: Float = 1) { } object Color { - def fromRGB(r: Int, g: Int, b: Int, a: Int = 255) = Color(r / 255F, g / 255F, b / 255F, a / 255F) + def fromRGB(r: Int, g: Int, b: Int, a: Int = 255) = + Color(r / 255f, g / 255f, b / 255f, a / 255f) def fromInt(v: Int) = Color( - ((v >> 16) & 0xFF) / 255F, - ((v >> 8) & 0xFF) / 255F, - (v & 0xFF) / 255F + ((v >> 16) & 0xff) / 255f, + ((v >> 8) & 0xff) / 255f, + (v & 0xff) / 255f ) final val white = Color(1, 1, 1) final val black = Color(0, 0, 0) @@ -43,7 +44,7 @@ object Color { final val cyan = Color(0, 1, 1) final val magenta = Color(1, 0, 1) - final val gray = Color(0.5F, 0.5F, 0.5F) - final val lightGray = Color(0.75F, 0.75F, 0.75F) - final val darkGray = Color(0.25F, 0.25F, 0.25F) + final val gray = Color(0.5f, 0.5f, 0.5f) + final val lightGray = Color(0.75f, 0.75f, 0.75f) + final val darkGray = Color(0.25f, 0.25f, 0.25f) } diff --git a/src/main/scala/net/bdew/lib/gui/DrawTarget.scala b/src/main/scala/net/bdew/lib/gui/DrawTarget.scala index 3da771f..af55a87 100644 --- a/src/main/scala/net/bdew/lib/gui/DrawTarget.scala +++ b/src/main/scala/net/bdew/lib/gui/DrawTarget.scala @@ -19,8 +19,20 @@ trait DrawTarget { def drawText(text: String, p: Point, color: Color, shadow: Boolean) def drawTextMultiline(text: String, r: Rect, color: Color) - def drawTextureInterpolate(r: Rect, t: Texture, x1: Float, y1: Float, x2: Float, y2: Float, color: Color = Color.white) = - drawTexture(r.interpolate(x1, y1, x2, y2), Texture.interpolate(t, x1, y1, x2, y2), color) + def drawTextureInterpolate( + r: Rect, + t: Texture, + x1: Float, + y1: Float, + x2: Float, + y2: Float, + color: Color = Color.white + ) = + drawTexture( + r.interpolate(x1, y1, x2, y2), + Texture.interpolate(t, x1, y1, x2, y2), + color + ) } trait SimpleDrawTarget extends DrawTarget { @@ -42,5 +54,11 @@ trait SimpleDrawTarget extends DrawTarget { getFontRenderer.drawString(text, p.x.round, p.y.round, color.asARGB, shadow) def drawTextMultiline(text: String, r: Rect, color: Color) = - getFontRenderer.drawSplitString(text, r.x.round, r.y.round, r.w.round, color.asARGB) + getFontRenderer.drawSplitString( + text, + r.x.round, + r.y.round, + r.w.round, + color.asARGB + ) } diff --git a/src/main/scala/net/bdew/lib/gui/GuiHandler.scala b/src/main/scala/net/bdew/lib/gui/GuiHandler.scala index 2a7ae79..a2d2423 100644 --- a/src/main/scala/net/bdew/lib/gui/GuiHandler.scala +++ b/src/main/scala/net/bdew/lib/gui/GuiHandler.scala @@ -20,13 +20,30 @@ class GuiHandler extends IGuiHandler { def register(p: GuiProvider) = { if (GUIs.isDefinedAt(p.guiId)) - sys.error("GUI ID Collision - %d was registered for %s and attempted to register by %s".format(p.guiId, GUIs(p.guiId), p)) + sys.error( + "GUI ID Collision - %d was registered for %s and attempted to register by %s" + .format(p.guiId, GUIs(p.guiId), p) + ) GUIs += (p.guiId -> p) } - def getServerGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef = + def getServerGuiElement( + ID: Int, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): AnyRef = GUIs(ID).getContainer(world.getTileEntity(x, y, z), player) - def getClientGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int): AnyRef = + def getClientGuiElement( + ID: Int, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): AnyRef = GUIs(ID).getGui(world.getTileEntity(x, y, z), player) } diff --git a/src/main/scala/net/bdew/lib/gui/NoInvContainer.scala b/src/main/scala/net/bdew/lib/gui/NoInvContainer.scala index 1af59e8..29bf428 100644 --- a/src/main/scala/net/bdew/lib/gui/NoInvContainer.scala +++ b/src/main/scala/net/bdew/lib/gui/NoInvContainer.scala @@ -10,7 +10,11 @@ package net.bdew.lib.gui import net.bdew.lib.Misc -import net.minecraft.entity.player.{EntityPlayer, EntityPlayerMP, InventoryPlayer} +import net.minecraft.entity.player.{ + EntityPlayer, + EntityPlayerMP, + InventoryPlayer +} import net.minecraft.inventory.{Container, Slot} import net.minecraft.item.ItemStack @@ -20,22 +24,37 @@ abstract class NoInvContainer extends Container { def players = Misc.filterType(crafters, classOf[EntityPlayerMP]) - protected def bindPlayerInventory(inv: InventoryPlayer, xOffs: Int, yOffsInv: Int, yOffsHotbar: Int) { + protected def bindPlayerInventory( + inv: InventoryPlayer, + xOffs: Int, + yOffsInv: Int, + yOffsHotbar: Int + ) { for (i <- 0 until 3; j <- 0 until 9) - addSlotToContainer(new Slot(inv, j + i * 9 + 9, xOffs + j * 18, yOffsInv + i * 18)) + addSlotToContainer( + new Slot(inv, j + i * 9 + 9, xOffs + j * 18, yOffsInv + i * 18) + ) for (i <- 0 until 9) addSlotToContainer(new Slot(inv, i, xOffs + i * 18, yOffsHotbar)) } - override def slotClick(slotNum: Int, button: Int, modifiers: Int, player: EntityPlayer): ItemStack = { + override def slotClick( + slotNum: Int, + button: Int, + modifiers: Int, + player: EntityPlayer + ): ItemStack = { if (inventorySlots.isDefinedAt(slotNum)) { val slot = getSlot(slotNum) if (slot != null && slot.isInstanceOf[SlotClickable]) - return slot.asInstanceOf[SlotClickable].onClick(button, modifiers, player) + return slot + .asInstanceOf[SlotClickable] + .onClick(button, modifiers, player) } return super.slotClick(slotNum, button, modifiers, player) } - override def transferStackInSlot(player: EntityPlayer, slot: Int): ItemStack = null + override def transferStackInSlot(player: EntityPlayer, slot: Int): ItemStack = + null } diff --git a/src/main/scala/net/bdew/lib/gui/SlotValidating.scala b/src/main/scala/net/bdew/lib/gui/SlotValidating.scala index 2cedfe8..dbdf9ea 100644 --- a/src/main/scala/net/bdew/lib/gui/SlotValidating.scala +++ b/src/main/scala/net/bdew/lib/gui/SlotValidating.scala @@ -12,6 +12,8 @@ package net.bdew.lib.gui import net.minecraft.inventory.IInventory import net.minecraft.item.ItemStack -class SlotValidating(inv: IInventory, slot: Int, x: Int, y: Int) extends BaseSlot(inv, slot, x, y) { - override def isItemValid(stack: ItemStack) = inventory.isItemValidForSlot(getSlotIndex, stack) -} \ No newline at end of file +class SlotValidating(inv: IInventory, slot: Int, x: Int, y: Int) + extends BaseSlot(inv, slot, x, y) { + override def isItemValid(stack: ItemStack) = + inventory.isItemValidForSlot(getSlotIndex, stack) +} diff --git a/src/main/scala/net/bdew/lib/gui/Texture.scala b/src/main/scala/net/bdew/lib/gui/Texture.scala index 5ea3ec1..0c38c10 100644 --- a/src/main/scala/net/bdew/lib/gui/Texture.scala +++ b/src/main/scala/net/bdew/lib/gui/Texture.scala @@ -30,7 +30,8 @@ class InterpolatedTexture(val texture: Texture, rect: Rect) extends Texture { def v2 = rect.y2 * (texture.v2 - texture.v1) + texture.v1 } -class IconWrapper(val resource: ResourceLocation, aIcon: IIcon) extends Texture { +class IconWrapper(val resource: ResourceLocation, aIcon: IIcon) + extends Texture { val icon = if (aIcon == null) { if (resource == Texture.ITEMS) Client.itemMissingIcon else if (resource == Texture.BLOCKS) Client.blockMissingIcon @@ -44,7 +45,8 @@ class IconWrapper(val resource: ResourceLocation, aIcon: IIcon) extends Texture def bind() = Minecraft.getMinecraft.renderEngine.bindTexture(resource) } -class Sprite(val resource: ResourceLocation, r: Rect, scale: Int = 256) extends Texture { +class Sprite(val resource: ResourceLocation, r: Rect, scale: Int = 256) + extends Texture { val rect = Rect(r.x / scale, r.y / scale, r.w / scale, r.h / scale) def u1 = rect.x1 def u2 = rect.x2 @@ -53,8 +55,10 @@ class Sprite(val resource: ResourceLocation, r: Rect, scale: Int = 256) extends def bind() = Minecraft.getMinecraft.renderEngine.bindTexture(resource) } -class ScaledResourceLocation(path: String, val scale: Int = 256) extends ResourceLocation(path) { - def this(domain: String, path: String, scale: Int) = this(domain + ":" + path, scale) +class ScaledResourceLocation(path: String, val scale: Int = 256) + extends ResourceLocation(path) { + def this(domain: String, path: String, scale: Int) = + this(domain + ":" + path, scale) def this(domain: String, path: String) = this(domain + ":" + path, 256) } @@ -67,27 +71,76 @@ object Texture { // From a ResourceLocation and position, scale optional def apply(res: ResourceLocation, r: Rect) = new Sprite(res, r) - def apply(res: ResourceLocation, r: Rect, scale: Int) = new Sprite(res, r, scale) - def apply(res: ResourceLocation, u1: Float, v1: Float, w: Float, h: Float) = new Sprite(res, Rect(u1, v1, w, h)) - def apply(res: ResourceLocation, u1: Float, v1: Float, w: Float, h: Float, scale: Int) = new Sprite(res, Rect(u1, v1, w, h), scale) + def apply(res: ResourceLocation, r: Rect, scale: Int) = + new Sprite(res, r, scale) + def apply(res: ResourceLocation, u1: Float, v1: Float, w: Float, h: Float) = + new Sprite(res, Rect(u1, v1, w, h)) + def apply( + res: ResourceLocation, + u1: Float, + v1: Float, + w: Float, + h: Float, + scale: Int + ) = new Sprite(res, Rect(u1, v1, w, h), scale) // From a path (with optional domain) and position, no scale def apply(path: String, r: Rect) = new Sprite(new ResourceLocation(path), r) - def apply(path: String, u1: Float, v1: Float, w: Float, h: Float) = new Sprite(new ResourceLocation(path), Rect(u1, v1, w, h)) - def apply(domain: String, path: String, r: Rect) = new Sprite(new ResourceLocation(domain, path), r) - def apply(domain: String, path: String, u1: Float, v1: Float, w: Float, h: Float) = new Sprite(new ResourceLocation(domain, path), Rect(u1, v1, w, h)) + def apply(path: String, u1: Float, v1: Float, w: Float, h: Float) = + new Sprite(new ResourceLocation(path), Rect(u1, v1, w, h)) + def apply(domain: String, path: String, r: Rect) = + new Sprite(new ResourceLocation(domain, path), r) + def apply( + domain: String, + path: String, + u1: Float, + v1: Float, + w: Float, + h: Float + ) = new Sprite(new ResourceLocation(domain, path), Rect(u1, v1, w, h)) // From a path (with optional domain), position and scale - def apply(path: String, r: Rect, scale: Int) = new Sprite(new ResourceLocation(path), r, scale) - def apply(path: String, u1: Float, v1: Float, w: Float, h: Float, scale: Int) = new Sprite(new ResourceLocation(path), Rect(u1, v1, w, h), scale) - def apply(domain: String, path: String, r: Rect, scale: Int) = new Sprite(new ResourceLocation(domain, path), r, scale) - def apply(domain: String, path: String, u1: Float, v1: Float, w: Float, h: Float, scale: Int) = new Sprite(new ResourceLocation(domain, path), Rect(u1, v1, w, h), scale) + def apply(path: String, r: Rect, scale: Int) = + new Sprite(new ResourceLocation(path), r, scale) + def apply( + path: String, + u1: Float, + v1: Float, + w: Float, + h: Float, + scale: Int + ) = new Sprite(new ResourceLocation(path), Rect(u1, v1, w, h), scale) + def apply(domain: String, path: String, r: Rect, scale: Int) = + new Sprite(new ResourceLocation(domain, path), r, scale) + def apply( + domain: String, + path: String, + u1: Float, + v1: Float, + w: Float, + h: Float, + scale: Int + ) = new Sprite(new ResourceLocation(domain, path), Rect(u1, v1, w, h), scale) // From a ScaledResourceLocation and position - def apply(res: ScaledResourceLocation, r: Rect) = new Sprite(res, r, res.scale) - def apply(res: ScaledResourceLocation, u1: Float, v1: Float, w: Float, h: Float) = new Sprite(res, Rect(u1, v1, w, h), res.scale) + def apply(res: ScaledResourceLocation, r: Rect) = + new Sprite(res, r, res.scale) + def apply( + res: ScaledResourceLocation, + u1: Float, + v1: Float, + w: Float, + h: Float + ) = new Sprite(res, Rect(u1, v1, w, h), res.scale) // A fraction of another Texture, parameters should be between 0 and 1 - def interpolate(texture: Texture, rect: Rect) = new InterpolatedTexture(texture, rect) - def interpolate(texture: Texture, u1: Float, v1: Float, u2: Float, v2: Float) = new InterpolatedTexture(texture, Rect(u1, v1, u2 - u1, v2 - v1)) + def interpolate(texture: Texture, rect: Rect) = + new InterpolatedTexture(texture, rect) + def interpolate( + texture: Texture, + u1: Float, + v1: Float, + u2: Float, + v2: Float + ) = new InterpolatedTexture(texture, Rect(u1, v1, u2 - u1, v2 - v1)) } diff --git a/src/main/scala/net/bdew/lib/gui/WidgetContainer.scala b/src/main/scala/net/bdew/lib/gui/WidgetContainer.scala index eea7f89..d400d23 100644 --- a/src/main/scala/net/bdew/lib/gui/WidgetContainer.scala +++ b/src/main/scala/net/bdew/lib/gui/WidgetContainer.scala @@ -78,7 +78,9 @@ trait WidgetContainer extends DrawTarget { def getOffsetFromWindow: Point } -class WidgetContainerWindow(val parent: BaseScreen, xSz: Int, ySz: Int) extends WidgetContainer with SimpleDrawTarget { +class WidgetContainerWindow(val parent: BaseScreen, xSz: Int, ySz: Int) + extends WidgetContainer + with SimpleDrawTarget { def getZLevel = parent.getZLevel def getFontRenderer = parent.getFontRenderer def getOffsetFromWindow = Point(0, 0) diff --git a/src/main/scala/net/bdew/lib/gui/package.scala b/src/main/scala/net/bdew/lib/gui/package.scala index ec12876..4e7bd22 100644 --- a/src/main/scala/net/bdew/lib/gui/package.scala +++ b/src/main/scala/net/bdew/lib/gui/package.scala @@ -15,19 +15,25 @@ package object gui { import scala.language.implicitConversions - implicit def awt2point(p: java.awt.Point): BasePoint[Int] = BasePoint(p.x, p.y) - implicit def point2awt(p: BasePoint[Int]): java.awt.Point = new java.awt.Point(p.x, p.y) - implicit def tuple2point[T: Numeric](p: (T, T)): BasePoint[T] = BasePoint(p._1, p._2) + implicit def awt2point(p: java.awt.Point): BasePoint[Int] = + BasePoint(p.x, p.y) + implicit def point2awt(p: BasePoint[Int]): java.awt.Point = + new java.awt.Point(p.x, p.y) + implicit def tuple2point[T: Numeric](p: (T, T)): BasePoint[T] = + BasePoint(p._1, p._2) // Converts different kinds of Point/Rect as long as there's an implicit for the underlying type - implicit def pointConvert[T, R](a: BasePoint[R])(implicit f: R => T, n: Numeric[T]): BasePoint[T] = + implicit def pointConvert[T, R]( + a: BasePoint[R] + )(implicit f: R => T, n: Numeric[T]): BasePoint[T] = BasePoint[T](f(a.x), f(a.y)) - implicit def rectConvert[T, R](a: BaseRect[R])(implicit f: R => T, n: Numeric[T]): BaseRect[T] = + implicit def rectConvert[T, R]( + a: BaseRect[R] + )(implicit f: R => T, n: Numeric[T]): BaseRect[T] = BaseRect[T](f(a.x), f(a.y), f(a.w), f(a.h)) def Rect(x: Float, y: Float, w: Float, h: Float) = BaseRect(x, y, w, h) def Point(x: Float, y: Float) = BasePoint(x, y) } - diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetButton.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetButton.scala index 5e452ae..5533db1 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetButton.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetButton.scala @@ -16,12 +16,26 @@ import net.minecraft.client.gui.GuiButton import net.minecraft.util.ResourceLocation class WidgetButton(val rect: Rect, text: String, clicked: WidgetButton => Unit) - extends GuiButton(0, rect.x.round, rect.y.round, rect.w.round, rect.h.round, text) with Widget { + extends GuiButton( + 0, + rect.x.round, + rect.y.round, + rect.w.round, + rect.h.round, + text + ) + with Widget { override def mouseClicked(p: Point, button: Int) { - Minecraft.getMinecraft.getSoundHandler.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)) + Minecraft.getMinecraft.getSoundHandler.playSound( + PositionedSoundRecord.func_147674_a( + new ResourceLocation("gui.button.press"), + 1.0f + ) + ) clicked(this) } - override def draw(mouse: Point) = drawButton(Minecraft.getMinecraft, mouse.x.round, mouse.y.round) + override def draw(mouse: Point) = + drawButton(Minecraft.getMinecraft, mouse.x.round, mouse.y.round) } diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetButtonIcon.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetButtonIcon.scala index c707c79..1dc060f 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetButtonIcon.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetButtonIcon.scala @@ -16,9 +16,14 @@ import net.minecraft.util.ResourceLocation import scala.collection.mutable -class WidgetButtonIcon(p: Point, clicked: WidgetButtonIcon => Unit, baseTex: Texture, hoverTex: Texture) extends Widget { +class WidgetButtonIcon( + p: Point, + clicked: WidgetButtonIcon => Unit, + baseTex: Texture, + hoverTex: Texture +) extends Widget { val rect = new Rect(p, 16, 16) - val iconRect = new Rect(p +(1, 1), 14, 14) + val iconRect = new Rect(p + (1, 1), 14, 14) var icon: Texture = null var hover: String = null @@ -39,7 +44,12 @@ class WidgetButtonIcon(p: Point, clicked: WidgetButtonIcon => Unit, baseTex: Tex } override def mouseClicked(p: Point, button: Int) { - Minecraft.getMinecraft.getSoundHandler.playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)) + Minecraft.getMinecraft.getSoundHandler.playSound( + PositionedSoundRecord.func_147674_a( + new ResourceLocation("gui.button.press"), + 1.0f + ) + ) clicked(this) } } diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetDynLabel.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetDynLabel.scala index 3f0cced..16d7f54 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetDynLabel.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetDynLabel.scala @@ -11,7 +11,8 @@ package net.bdew.lib.gui.widgets import net.bdew.lib.gui.{Color, Point, Rect} -class WidgetDynLabel(text: => String, x: Int, y: Int, color: Color) extends Widget { +class WidgetDynLabel(text: => String, x: Int, y: Int, color: Color) + extends Widget { val rect = new Rect(x, y, 0, 0) override def draw(mouse: Point) { parent.drawText(text, rect.origin, color, false) diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetFillDataslot.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetFillDataslot.scala index f17da1f..fd76577 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetFillDataslot.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetFillDataslot.scala @@ -12,7 +12,14 @@ package net.bdew.lib.gui.widgets import net.bdew.lib.data.base.DataSlotNumeric import net.bdew.lib.gui._ -class WidgetFillDataSlot[T](val rect: Rect, val texture: Texture, dir: Direction.Direction, dSlot: DataSlotNumeric[T], maxVal: T)(implicit num: Numeric[T]) extends Widget { +class WidgetFillDataSlot[T]( + val rect: Rect, + val texture: Texture, + dir: Direction.Direction, + dSlot: DataSlotNumeric[T], + maxVal: T +)(implicit num: Numeric[T]) + extends Widget { import num.mkNumericOps @@ -30,5 +37,3 @@ class WidgetFillDataSlot[T](val rect: Rect, val texture: Texture, dir: Direction } } } - - diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetFluidGauge.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetFluidGauge.scala index 6ddae21..f9fc25f 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetFluidGauge.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetFluidGauge.scala @@ -16,11 +16,18 @@ import org.lwjgl.opengl.GL11 import scala.collection.mutable -class WidgetFluidGauge(val rect: Rect, overlay: Texture, dSlot: DataSlotTankBase) extends Widget { +class WidgetFluidGauge( + val rect: Rect, + overlay: Texture, + dSlot: DataSlotTankBase +) extends Widget { override def handleTooltip(p: Point, tip: mutable.MutableList[String]) { if (dSlot.getFluid != null) { tip += dSlot.getFluid.getFluid.getLocalizedName(dSlot.getFluid) - tip += "%s/%s mB".format(DecFormat.round(dSlot.getFluidAmount), DecFormat.round(dSlot.getCapacity)) + tip += "%s/%s mB".format( + DecFormat.round(dSlot.getFluidAmount), + DecFormat.round(dSlot.getCapacity) + ) } else { tip += Misc.toLocal("bdlib.label.empty") } @@ -34,15 +41,29 @@ class WidgetFluidGauge(val rect: Rect, overlay: Texture, dSlot: DataSlotTankBase if (fStack != null) { val color = Color.fromInt(Misc.getFluidColor(fStack)) val icon = Texture(Texture.BLOCKS, Misc.getFluidIcon(fStack)) - var fillHeight = if (dSlot.getCapacity > 0) rect.h * fStack.amount / dSlot.getCapacity else 0 + var fillHeight = + if (dSlot.getCapacity > 0) rect.h * fStack.amount / dSlot.getCapacity + else 0 var yStart: Int = 0 while (fillHeight > 0) { if (fillHeight > 16) { - parent.drawTexture(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon, color) + parent.drawTexture( + new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), + icon, + color + ) fillHeight -= 16 } else { - parent.drawTextureInterpolate(new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), icon, 0, 1 - fillHeight / 16, 1, 1, color) + parent.drawTextureInterpolate( + new Rect(rect.x, rect.y2 - 16 - yStart, rect.w, 16), + icon, + 0, + 1 - fillHeight / 16, + 1, + 1, + color + ) fillHeight = 0 } yStart = yStart + 16 diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetProgressBar.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetProgressBar.scala index 83acb40..ac8eb19 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetProgressBar.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetProgressBar.scala @@ -14,6 +14,14 @@ import net.bdew.lib.gui._ import scala.collection.mutable -class WidgetProgressBar(rect: Rect, texture: Texture, dSlot: DataSlotFloat) extends WidgetFillDataSlot[Float](rect, texture, Direction.RIGHT, dSlot, 1) { - override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = tip += "%.0f".format(dSlot.value * 100) + "%" +class WidgetProgressBar(rect: Rect, texture: Texture, dSlot: DataSlotFloat) + extends WidgetFillDataSlot[Float]( + rect, + texture, + Direction.RIGHT, + dSlot, + 1 + ) { + override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = + tip += "%.0f".format(dSlot.value * 100) + "%" } diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetSubcontainer.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetSubcontainer.scala index 32a0ef3..9ae9020 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetSubcontainer.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetSubcontainer.scala @@ -11,7 +11,10 @@ package net.bdew.lib.gui.widgets import net.bdew.lib.gui._ -class WidgetSubContainer(val rect: Rect) extends BaseWidget with WidgetContainer with SimpleDrawTarget { +class WidgetSubContainer(val rect: Rect) + extends BaseWidget + with WidgetContainer + with SimpleDrawTarget { def getZLevel = parent.getZLevel def getFontRenderer = parent.getFontRenderer def getOffsetFromWindow = parent.getOffsetFromWindow + rect.origin diff --git a/src/main/scala/net/bdew/lib/gui/widgets/WidgetTextEdit.scala b/src/main/scala/net/bdew/lib/gui/widgets/WidgetTextEdit.scala index 8ad9528..f68e0e6 100644 --- a/src/main/scala/net/bdew/lib/gui/widgets/WidgetTextEdit.scala +++ b/src/main/scala/net/bdew/lib/gui/widgets/WidgetTextEdit.scala @@ -12,7 +12,15 @@ package net.bdew.lib.gui.widgets import net.bdew.lib.gui.{Point, Rect} import net.minecraft.client.gui.{FontRenderer, GuiTextField} -class WidgetTextEdit(val rect: Rect, fr: FontRenderer) extends GuiTextField(fr, rect.x.round, rect.y.round, rect.w.round, rect.h.round) with Widget { +class WidgetTextEdit(val rect: Rect, fr: FontRenderer) + extends GuiTextField( + fr, + rect.x.round, + rect.y.round, + rect.w.round, + rect.h.round + ) + with Widget { override def mouseClicked(p: Point, button: Int) = { val pp = p + rect.origin diff --git a/src/main/scala/net/bdew/lib/helpers/ChatHelper.scala b/src/main/scala/net/bdew/lib/helpers/ChatHelper.scala index 0afae0a..ec8fc70 100644 --- a/src/main/scala/net/bdew/lib/helpers/ChatHelper.scala +++ b/src/main/scala/net/bdew/lib/helpers/ChatHelper.scala @@ -52,9 +52,13 @@ object ChatHelper { } implicit def str2chat(s: String): ChatComponentText = new ChatComponentText(s) - implicit def str2rich(s: String): RichChatComponent = new RichChatComponent(new ChatComponentText(s)) - implicit def pimpIChatComponent(v: IChatComponent): RichChatComponent = new RichChatComponent(v) + implicit def str2rich(s: String): RichChatComponent = new RichChatComponent( + new ChatComponentText(s) + ) + implicit def pimpIChatComponent(v: IChatComponent): RichChatComponent = + new RichChatComponent(v) def C(s: String) = new ChatComponentText(s) - def L(s: String, params: IChatComponent*) = new ChatComponentTranslation(s, params: _*) + def L(s: String, params: IChatComponent*) = + new ChatComponentTranslation(s, params: _*) } diff --git a/src/main/scala/net/bdew/lib/items/IStack.scala b/src/main/scala/net/bdew/lib/items/IStack.scala index cbc42b1..1ce770b 100644 --- a/src/main/scala/net/bdew/lib/items/IStack.scala +++ b/src/main/scala/net/bdew/lib/items/IStack.scala @@ -12,9 +12,8 @@ package net.bdew.lib.items import net.minecraft.block.Block import net.minecraft.item.{Item, ItemBlock, ItemStack} -/** - * Allows matching Items in ItemStacks in scala pattern matches - */ +/** Allows matching Items in ItemStacks in scala pattern matches + */ object IStack { def unapply(x: ItemStack): Option[Item] = if (x == null || x.getItem == null) @@ -23,9 +22,8 @@ object IStack { Some(x.getItem) } -/** - * Allows matching Blocks in ItemStacks in scala pattern matches - */ +/** Allows matching Blocks in ItemStacks in scala pattern matches + */ object IStackBlock { def unapply(x: ItemStack): Option[Block] = if (x == null || x.getItem == null || !x.getItem.isInstanceOf[ItemBlock]) diff --git a/src/main/scala/net/bdew/lib/items/ItemUtils.scala b/src/main/scala/net/bdew/lib/items/ItemUtils.scala index 0904484..3f8a167 100644 --- a/src/main/scala/net/bdew/lib/items/ItemUtils.scala +++ b/src/main/scala/net/bdew/lib/items/ItemUtils.scala @@ -34,7 +34,9 @@ object ItemUtils { def dropItemToPlayer(world: World, player: EntityPlayer, stack: ItemStack) { if ((stack == null) || world.isRemote) return - world.spawnEntityInWorld(new EntityItem(world, player.posX, player.posY, player.posZ, stack)) + world.spawnEntityInWorld( + new EntityItem(world, player.posX, player.posY, player.posZ, stack) + ) } def isSameItem(stack1: ItemStack, stack2: ItemStack): Boolean = { @@ -47,13 +49,28 @@ object ItemUtils { return ItemStack.areItemStackTagsEqual(stack2, stack1) } - def addStackToSlots(stack: ItemStack, inv: IInventory, slots: Iterable[Int], checkValid: Boolean): ItemStack = { + def addStackToSlots( + stack: ItemStack, + inv: IInventory, + slots: Iterable[Int], + checkValid: Boolean + ): ItemStack = { if (stack == null) return null // Try merging into existing slots - for (slot <- slots if (!checkValid || inv.isItemValidForSlot(slot, stack)) && isSameItem(stack, inv.getStackInSlot(slot))) { + for ( + slot <- slots + if (!checkValid || inv.isItemValidForSlot(slot, stack)) && isSameItem( + stack, + inv.getStackInSlot(slot) + ) + ) { val target = inv.getStackInSlot(slot) - val toAdd = Misc.min(target.getMaxStackSize - target.stackSize, inv.getInventoryStackLimit - target.stackSize, stack.stackSize) + val toAdd = Misc.min( + target.getMaxStackSize - target.stackSize, + inv.getInventoryStackLimit - target.stackSize, + stack.stackSize + ) if (toAdd >= stack.stackSize) { target.stackSize += stack.stackSize stack.stackSize = 0 @@ -67,9 +84,16 @@ object ItemUtils { } // Now find empty slots and stick any leftovers there - for (slot <- slots if (!checkValid || inv.isItemValidForSlot(slot, stack)) && inv.getStackInSlot(slot) == null) { + for ( + slot <- slots + if (!checkValid || inv.isItemValidForSlot(slot, stack)) && inv + .getStackInSlot(slot) == null + ) { if (inv.getInventoryStackLimit < stack.stackSize) { - inv.setInventorySlotContents(slot, stack.splitStack(inv.getInventoryStackLimit)) + inv.setInventorySlotContents( + slot, + stack.splitStack(inv.getInventoryStackLimit) + ) } else { inv.setInventorySlotContents(slot, stack.copy()) stack.stackSize = 0 @@ -86,7 +110,8 @@ object ItemUtils { getOrElse (0 until inv.getSizeInventory)) def findItemInInventory(inv: IInventory, item: Item) = - Range(0, inv.getSizeInventory).map(x => x -> inv.getStackInSlot(x)) + Range(0, inv.getSizeInventory) + .map(x => x -> inv.getStackInSlot(x)) .find({ case (slot, stack) => stack != null && stack.getItem == item }) .map({ case (slot, stack) => slot }) @@ -102,4 +127,4 @@ object ItemUtils { newSize newStack } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/items/inventory/ContainerItemInventory.scala b/src/main/scala/net/bdew/lib/items/inventory/ContainerItemInventory.scala index ccab35f..42f39e6 100644 --- a/src/main/scala/net/bdew/lib/items/inventory/ContainerItemInventory.scala +++ b/src/main/scala/net/bdew/lib/items/inventory/ContainerItemInventory.scala @@ -14,8 +14,14 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.Slot import net.minecraft.item.ItemStack -class ContainerItemInventory(inv: InventoryItemAdapter, player: EntityPlayer) extends BaseContainer(inv) { - override def slotClick(slotNum: Int, button: Int, modifiers: Int, player: EntityPlayer): ItemStack = { +class ContainerItemInventory(inv: InventoryItemAdapter, player: EntityPlayer) + extends BaseContainer(inv) { + override def slotClick( + slotNum: Int, + button: Int, + modifiers: Int, + player: EntityPlayer + ): ItemStack = { if (slotNum > 0 && slotNum < inventorySlots.size()) { val slot = inventorySlots.asInstanceOf[java.util.List[Slot]].get(slotNum) if (slot.isSlotInInventory(inv.player.inventory, inv.slot)) diff --git a/src/main/scala/net/bdew/lib/items/inventory/InventoryItemAdapter.scala b/src/main/scala/net/bdew/lib/items/inventory/InventoryItemAdapter.scala index 0519118..b3f8484 100644 --- a/src/main/scala/net/bdew/lib/items/inventory/InventoryItemAdapter.scala +++ b/src/main/scala/net/bdew/lib/items/inventory/InventoryItemAdapter.scala @@ -14,7 +14,12 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.{NBTTagCompound, NBTTagList} -class InventoryItemAdapter(val player: EntityPlayer, val slot: Int, val size: Int, val tagName: String) extends BaseInventory { +class InventoryItemAdapter( + val player: EntityPlayer, + val slot: Int, + val size: Int, + val tagName: String +) extends BaseInventory { def getSizeInventory = size def getStack = player.inventory.getStackInSlot(slot) diff --git a/src/main/scala/net/bdew/lib/items/inventory/ItemInventory.scala b/src/main/scala/net/bdew/lib/items/inventory/ItemInventory.scala index 01f0b9f..94b7553 100644 --- a/src/main/scala/net/bdew/lib/items/inventory/ItemInventory.scala +++ b/src/main/scala/net/bdew/lib/items/inventory/ItemInventory.scala @@ -17,10 +17,9 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.Item import net.minecraft.world.World -/** - * Mixin for items that have an internal inventory - * Subclasses are responsible for registering themselves with the GuiHandler of their mod - */ +/** Mixin for items that have an internal inventory Subclasses are responsible + * for registering themselves with the GuiHandler of their mod + */ trait ItemInventory extends Item with GuiProvider { type TEClass = Any def guiId: Int @@ -30,9 +29,17 @@ trait ItemInventory extends Item with GuiProvider { @SideOnly(Side.CLIENT) def makeGui(inv: InventoryItemAdapter, player: EntityPlayer): AnyRef - def makeContainer(inv: InventoryItemAdapter, player: EntityPlayer): ContainerItemInventory + def makeContainer( + inv: InventoryItemAdapter, + player: EntityPlayer + ): ContainerItemInventory - def makeAdaptor(player: EntityPlayer) = new InventoryItemAdapter(player, player.inventory.currentItem, invSize, invTagName) + def makeAdaptor(player: EntityPlayer) = new InventoryItemAdapter( + player, + player.inventory.currentItem, + invSize, + invTagName + ) @SideOnly(Side.CLIENT) def getGui(te: TEClass, player: EntityPlayer) = { @@ -40,7 +47,10 @@ trait ItemInventory extends Item with GuiProvider { if (stack.getItem == this) { makeGui(makeAdaptor(player), player) } else { - BdLib.logWarn("Attempt to open item container GUI without active item (%s)", this) + BdLib.logWarn( + "Attempt to open item container GUI without active item (%s)", + this + ) null } } @@ -50,12 +60,23 @@ trait ItemInventory extends Item with GuiProvider { if (stack.getItem == this) { makeContainer(makeAdaptor(player), player) } else { - BdLib.logWarn("Attempt to open item container GUI without active item by '%s' (%s)", player.getCommandSenderName, this) + BdLib.logWarn( + "Attempt to open item container GUI without active item by '%s' (%s)", + player.getCommandSenderName, + this + ) null } } def doOpenGui(player: EntityPlayer, world: World) { - player.openGui(modObj, guiId, world, player.posX.toInt, player.posY.toInt, player.posZ.toInt) + player.openGui( + modObj, + guiId, + world, + player.posX.toInt, + player.posY.toInt, + player.posZ.toInt + ) } } diff --git a/src/main/scala/net/bdew/lib/machine/Machine.scala b/src/main/scala/net/bdew/lib/machine/Machine.scala index e7146ff..dbd64dd 100644 --- a/src/main/scala/net/bdew/lib/machine/Machine.scala +++ b/src/main/scala/net/bdew/lib/machine/Machine.scala @@ -26,16 +26,20 @@ abstract class Machine[T <: Block](val name: String, blockConstruct: => T) { def regBlock(creativeTab: CreativeTabs) { block = blockConstruct - val itemClass: Class[_ <: ItemBlock] = if (block.isInstanceOf[HasItemBlock]) - block.asInstanceOf[HasItemBlock].ItemBlockClass - else - classOf[ItemBlock] + val itemClass: Class[_ <: ItemBlock] = + if (block.isInstanceOf[HasItemBlock]) + block.asInstanceOf[HasItemBlock].ItemBlockClass + else + classOf[ItemBlock] GameRegistry.registerBlock(block, itemClass, name) block.setCreativeTab(creativeTab) if (block.isInstanceOf[HasTE[_]]) { - GameRegistry.registerTileEntity(block.asInstanceOf[HasTE[_]].TEClass, "%s.%s".format(modId, name)) + GameRegistry.registerTileEntity( + block.asInstanceOf[HasTE[_]].TEClass, + "%s.%s".format(modId, name) + ) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/MachineCore.scala b/src/main/scala/net/bdew/lib/multiblock/MachineCore.scala index 36e7f96..58689a3 100644 --- a/src/main/scala/net/bdew/lib/multiblock/MachineCore.scala +++ b/src/main/scala/net/bdew/lib/multiblock/MachineCore.scala @@ -19,10 +19,17 @@ trait MachineCore extends { def getController: BlockController[_] = block - def cfgSectionToMap(name: String) = tuning.getSection(name).map({ - case (n, EntryDouble(v)) => n -> v.toInt - case (n, x) => sys.error("Invalid config value in section %s%s.%s = %s".format(tuning.pfx, name, n, x)) - }).toMap + def cfgSectionToMap(name: String) = tuning + .getSection(name) + .map({ + case (n, EntryDouble(v)) => n -> v.toInt + case (n, x) => + sys.error( + "Invalid config value in section %s%s.%s = %s" + .format(tuning.pfx, name, n, x) + ) + }) + .toMap lazy val modules = cfgSectionToMap("Modules") lazy val required = cfgSectionToMap("Required") diff --git a/src/main/scala/net/bdew/lib/multiblock/Tools.scala b/src/main/scala/net/bdew/lib/multiblock/Tools.scala index 0034b44..973b764 100644 --- a/src/main/scala/net/bdew/lib/multiblock/Tools.scala +++ b/src/main/scala/net/bdew/lib/multiblock/Tools.scala @@ -24,13 +24,18 @@ object Tools { def findConnections(world: World, start: BlockRef, kind: String) = (start.neighbours.values flatMap { case pos => (pos.tile(world) flatMap { - case t: TileModule => t.connected.value + case t: TileModule => t.connected.value case t: TileController => Some(pos) - case _ => None + case _ => None }) filter (x => canConnect(world, x, kind)) }).toList.distinct - def getConnectedNeighbours(w: World, core: BlockRef, pos: BlockRef, seen: mutable.Set[BlockRef]) = + def getConnectedNeighbours( + w: World, + core: BlockRef, + pos: BlockRef, + seen: mutable.Set[BlockRef] + ) = pos.neighbours.values .filterNot(seen.contains) .flatMap(_.getTile[TileModule](w)) diff --git a/src/main/scala/net/bdew/lib/multiblock/block/BlockController.scala b/src/main/scala/net/bdew/lib/multiblock/block/BlockController.scala index 2a8e5e7..832ece3 100644 --- a/src/main/scala/net/bdew/lib/multiblock/block/BlockController.scala +++ b/src/main/scala/net/bdew/lib/multiblock/block/BlockController.scala @@ -21,8 +21,14 @@ import net.minecraft.item.ItemStack import net.minecraft.util.EnumChatFormatting import net.minecraft.world.{IBlockAccess, World} -abstract class BlockController[T <: TileController](val name: String, material: Material, val TEClass: Class[T]) - extends Block(material) with HasTE[T] with ConnectedTextureBlock with BlockTooltip { +abstract class BlockController[T <: TileController]( + val name: String, + material: Material, + val TEClass: Class[T] +) extends Block(material) + with HasTE[T] + with ConnectedTextureBlock + with BlockTooltip { var machine: MachineCore = null @@ -30,37 +36,67 @@ abstract class BlockController[T <: TileController](val name: String, material: override def edgeIcon = resources.edge - override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) { + override def breakBlock( + world: World, + x: Int, + y: Int, + z: Int, + block: Block, + meta: Int + ) { getTE(world, x, y, z).onBreak() super.breakBlock(world, x, y, z, block, meta) } - override def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef) = + override def canConnect( + world: IBlockAccess, + origin: BlockRef, + target: BlockRef + ) = getTE(world, origin).modules.contains(target) - override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, meta: Int, xOffs: Float, yOffs: Float, zOffs: Float): Boolean = { + override def onBlockActivated( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer, + meta: Int, + xOffs: Float, + yOffs: Float, + zOffs: Float + ): Boolean = { if (player.isSneaking) return false if (world.isRemote) return true getTE(world, x, y, z).onClick(player) return true } - override def getTooltip(stack: ItemStack, player: EntityPlayer, advanced: Boolean): List[String] = { - List(Misc.toLocal("bdlib.multiblock.tip.controller")) ++ ( - for ((kind, max) <- machine.modules) yield { - val name = Misc.toLocalF(resources.getModuleName(kind)) - if (machine.required.getOrElse(kind, 0) > 0) { - Misc.toLocalF("bdlib.multiblock.tip.module.range", - EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + machine.required(kind).toString + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET) - } else { - Misc.toLocalF("bdlib.multiblock.tip.module.max", - EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET) - } - }) + override def getTooltip( + stack: ItemStack, + player: EntityPlayer, + advanced: Boolean + ): List[String] = { + List(Misc.toLocal("bdlib.multiblock.tip.controller")) ++ (for ( + (kind, max) <- machine.modules + ) yield { + val name = Misc.toLocalF(resources.getModuleName(kind)) + if (machine.required.getOrElse(kind, 0) > 0) { + Misc.toLocalF( + "bdlib.multiblock.tip.module.range", + EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + machine + .required(kind) + .toString + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET + ) + } else { + Misc.toLocalF( + "bdlib.multiblock.tip.module.max", + EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET + ) + } + }) } } - - diff --git a/src/main/scala/net/bdew/lib/multiblock/block/BlockModule.scala b/src/main/scala/net/bdew/lib/multiblock/block/BlockModule.scala index bb09ece..30adbfb 100644 --- a/src/main/scala/net/bdew/lib/multiblock/block/BlockModule.scala +++ b/src/main/scala/net/bdew/lib/multiblock/block/BlockModule.scala @@ -23,8 +23,16 @@ import net.minecraft.item.ItemStack import net.minecraft.util.{ChatComponentTranslation, EnumChatFormatting} import net.minecraft.world.{IBlockAccess, World} -abstract class BlockModule[T <: TileModule](val name: String, val kind: String, material: Material, val TEClass: Class[T], val machines: MachineManagerMultiblock) - extends Block(material) with HasTE[T] with ConnectedTextureBlock with BlockTooltip { +abstract class BlockModule[T <: TileModule]( + val name: String, + val kind: String, + material: Material, + val TEClass: Class[T], + val machines: MachineManagerMultiblock +) extends Block(material) + with HasTE[T] + with ConnectedTextureBlock + with BlockTooltip { def resources: ResourceProvider @@ -33,28 +41,62 @@ abstract class BlockModule[T <: TileModule](val name: String, val kind: String, override def canPlaceBlockAt(world: World, x: Int, y: Int, z: Int): Boolean = Tools.findConnections(world, BlockRef(x, y, z), kind).size <= 1 - override def onBlockPlacedBy(world: World, x: Int, y: Int, z: Int, player: EntityLivingBase, stack: ItemStack) { + override def onBlockPlacedBy( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityLivingBase, + stack: ItemStack + ) { getTE(world, x, y, z).tryConnect() } - override def onNeighborBlockChange(world: World, x: Int, y: Int, z: Int, block: Block) { + override def onNeighborBlockChange( + world: World, + x: Int, + y: Int, + z: Int, + block: Block + ) { getTE(world, x, y, z).tryConnect() } - override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) { + override def breakBlock( + world: World, + x: Int, + y: Int, + z: Int, + block: Block, + meta: Int + ) { getTE(world, x, y, z).onBreak() super.breakBlock(world, x, y, z, block, meta) } - override def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef) = { + override def canConnect( + world: IBlockAccess, + origin: BlockRef, + target: BlockRef + ) = { val me = getTE(world, origin) me.connected.contains(target) || - (target.getTile[TileModule](world) exists { other => - me.getCore.isDefined && other.getCore == me.getCore - }) + (target.getTile[TileModule](world) exists { other => + me.getCore.isDefined && other.getCore == me.getCore + }) } - override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, meta: Int, xOffs: Float, yOffs: Float, zOffs: Float): Boolean = { + override def onBlockActivated( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer, + meta: Int, + xOffs: Float, + yOffs: Float, + zOffs: Float + ): Boolean = { if (player.isSneaking) return false if (world.isRemote) return true val te = getTE(world, x, y, z) @@ -62,27 +104,38 @@ abstract class BlockModule[T <: TileModule](val name: String, val kind: String, p <- te.connected.value bl <- p.block(world) } yield { - bl.onBlockActivated(world, p.x, p.y, p.z, player, meta, 0, 0, 0) - }) getOrElse { - player.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.notconnected")) + bl.onBlockActivated(world, p.x, p.y, p.z, player, meta, 0, 0, 0) + }) getOrElse { + player.addChatMessage( + new ChatComponentTranslation("bdlib.multiblock.notconnected") + ) } true } - override def getTooltip(stack: ItemStack, player: EntityPlayer, advanced: Boolean): List[String] = { - List(Misc.toLocal("bdlib.multiblock.tip.module")) ++ ( - for ((machine, (min, max)) <- machines.getMachinesForBlock(this)) yield { - val name = machine.getController.getLocalizedName - if (min > 0) { - Misc.toLocalF("bdlib.multiblock.tip.module.range", - EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + min.toString + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET) - } else { - Misc.toLocalF("bdlib.multiblock.tip.module.max", - EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, - EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET) - } - }) + override def getTooltip( + stack: ItemStack, + player: EntityPlayer, + advanced: Boolean + ): List[String] = { + List(Misc.toLocal("bdlib.multiblock.tip.module")) ++ (for ( + (machine, (min, max)) <- machines.getMachinesForBlock(this) + ) yield { + val name = machine.getController.getLocalizedName + if (min > 0) { + Misc.toLocalF( + "bdlib.multiblock.tip.module.range", + EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + min.toString + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET + ) + } else { + Misc.toLocalF( + "bdlib.multiblock.tip.module.max", + EnumChatFormatting.YELLOW + name + EnumChatFormatting.RESET, + EnumChatFormatting.YELLOW + max.toString + EnumChatFormatting.RESET + ) + } + }) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/block/BlockOutput.scala b/src/main/scala/net/bdew/lib/multiblock/block/BlockOutput.scala index a643075..bc2a2be 100644 --- a/src/main/scala/net/bdew/lib/multiblock/block/BlockOutput.scala +++ b/src/main/scala/net/bdew/lib/multiblock/block/BlockOutput.scala @@ -11,11 +11,17 @@ package net.bdew.lib.multiblock.block import net.bdew.lib.block.{BlockFace, BlockRef} import net.bdew.lib.multiblock.tile.TileOutput -import net.bdew.lib.render.connected.{BlockAdditionalRender, ConnectedHelper, FaceOverlay} +import net.bdew.lib.render.connected.{ + BlockAdditionalRender, + ConnectedHelper, + FaceOverlay +} import net.minecraft.world.IBlockAccess import net.minecraftforge.common.util.ForgeDirection -trait BlockOutput[T <: TileOutput[_]] extends BlockModule[T] with BlockAdditionalRender { +trait BlockOutput[T <: TileOutput[_]] + extends BlockModule[T] + with BlockAdditionalRender { def getNeighbourFaces(face: ForgeDirection, bp: BlockRef) = { val sides = ConnectedHelper.neighbourFaces(face) Seq( @@ -26,15 +32,27 @@ trait BlockOutput[T <: TileOutput[_]] extends BlockModule[T] with BlockAdditiona ) } - def getFaceOverlays(world: IBlockAccess, x: Int, y: Int, z: Int, face: ForgeDirection): List[FaceOverlay] = { + def getFaceOverlays( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + face: ForgeDirection + ): List[FaceOverlay] = { var result = List.empty[FaceOverlay] Option(getTE(world, x, y, z)) flatMap (_.getCore) foreach { core => val bf = BlockFace(x, y, z, face) if (core.outputFaces.contains(bf)) - result :+= FaceOverlay(resources.output, resources.outputColors(core.outputFaces(bf))) + result :+= FaceOverlay( + resources.output, + resources.outputColors(core.outputFaces(bf)) + ) for ((bf, icon) <- getNeighbourFaces(face, bf.origin)) { if (core.outputFaces.contains(bf)) - result :+= FaceOverlay(icon, resources.outputColors(core.outputFaces(bf))) + result :+= FaceOverlay( + icon, + resources.outputColors(core.outputFaces(bf)) + ) } } return result diff --git a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotBlockFaceMap.scala b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotBlockFaceMap.scala index 36b735d..9b74f61 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotBlockFaceMap.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotBlockFaceMap.scala @@ -16,15 +16,18 @@ import net.minecraftforge.common.util.ForgeDirection import scala.collection.mutable -case class DataSlotBlockFaceMap(name: String, parent: DataSlotContainer) extends DataSlot { +case class DataSlotBlockFaceMap(name: String, parent: DataSlotContainer) + extends DataSlot { val map = collection.mutable.Map.empty[BlockFace, Int] setUpdate(UpdateKind.SAVE, UpdateKind.WORLD) def inverted = map.map(_.swap) - def ent2arr(x: (BlockFace, Int)) = Array(x._2, x._1.x, x._1.y, x._1.z, x._1.face.ordinal()) - def arr2ent(x: Array[Int]) = BlockFace(x(1), x(2), x(3), ForgeDirection.values()(x(4))) -> x(0) + def ent2arr(x: (BlockFace, Int)) = + Array(x._2, x._1.x, x._1.y, x._1.z, x._1.face.ordinal()) + def arr2ent(x: Array[Int]) = + BlockFace(x(1), x(2), x(3), ForgeDirection.values()(x(4))) -> x(0) import net.bdew.lib.nbt._ @@ -44,5 +47,7 @@ object DataSlotBlockFaceMap { import scala.language.implicitConversions - implicit def dataSlotBlockFaceMap2map(v: DataSlotBlockFaceMap): mutable.Map[BlockFace, Int] = v.map + implicit def dataSlotBlockFaceMap2map( + v: DataSlotBlockFaceMap + ): mutable.Map[BlockFace, Int] = v.map } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotOutputConfig.scala b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotOutputConfig.scala index 9ce67bf..4e920a1 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotOutputConfig.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotOutputConfig.scala @@ -14,7 +14,11 @@ import net.minecraft.nbt.NBTTagCompound import scala.collection.mutable -case class DataSlotOutputConfig(name: String, parent: DataSlotContainer, slots: Int) extends DataSlot { +case class DataSlotOutputConfig( + name: String, + parent: DataSlotContainer, + slots: Int +) extends DataSlot { val map = collection.mutable.Map.empty[Int, OutputConfig] setUpdate(UpdateKind.SAVE, UpdateKind.GUI) @@ -49,5 +53,7 @@ object DataSlotOutputConfig { import scala.language.implicitConversions - implicit def dataSlotOutputConfig2map(v: DataSlotOutputConfig): mutable.Map[Int, OutputConfig] = v.map + implicit def dataSlotOutputConfig2map( + v: DataSlotOutputConfig + ): mutable.Map[Int, OutputConfig] = v.map } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPos.scala b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPos.scala index 419db39..2e43ed3 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPos.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPos.scala @@ -15,17 +15,21 @@ import net.bdew.lib.data.DataSlotOption import net.bdew.lib.data.base.{DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotPos(name: String, parent: DataSlotContainer) extends DataSlotOption[BlockRef] { +case class DataSlotPos(name: String, parent: DataSlotContainer) + extends DataSlotOption[BlockRef] { setUpdate(UpdateKind.SAVE, UpdateKind.WORLD) def save(t: NBTTagCompound, kind: UpdateKind.Value) { - value foreach (x => t.setTag(name, Misc.applyMutator(x.writeToNBT, new NBTTagCompound))) + value foreach (x => + t.setTag(name, Misc.applyMutator(x.writeToNBT, new NBTTagCompound)) + ) } def load(t: NBTTagCompound, kind: UpdateKind.Value) { - value = if (t.hasKey(name)) - Some(BlockRef.fromNBT(t.getCompoundTag(name))) - else - None + value = + if (t.hasKey(name)) + Some(BlockRef.fromNBT(t.getCompoundTag(name))) + else + None } } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPosSet.scala b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPosSet.scala index c16a083..3d5705f 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPosSet.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/DataSlotPosSet.scala @@ -16,7 +16,8 @@ import net.minecraft.nbt.NBTTagCompound import scala.collection.mutable -case class DataSlotPosSet(name: String, parent: DataSlotContainer) extends DataSlot { +case class DataSlotPosSet(name: String, parent: DataSlotContainer) + extends DataSlot { val set = collection.mutable.Set.empty[BlockRef] setUpdate(UpdateKind.SAVE, UpdateKind.WORLD) @@ -24,7 +25,10 @@ case class DataSlotPosSet(name: String, parent: DataSlotContainer) extends DataS import net.bdew.lib.nbt._ def save(t: NBTTagCompound, kind: UpdateKind.Value) { - t.setList(name, set.map(x => Misc.applyMutator(x.writeToNBT, new NBTTagCompound))) + t.setList( + name, + set.map(x => Misc.applyMutator(x.writeToNBT, new NBTTagCompound)) + ) } def load(t: NBTTagCompound, kind: UpdateKind.Value) { @@ -39,5 +43,6 @@ object DataSlotPosSet { import scala.language.implicitConversions - implicit def dataSlotPosSet2set(v: DataSlotPosSet): mutable.Set[BlockRef] = v.set + implicit def dataSlotPosSet2set(v: DataSlotPosSet): mutable.Set[BlockRef] = + v.set } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfig.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfig.scala index c74d422..ff51c8d 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfig.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfig.scala @@ -30,8 +30,9 @@ class OutputConfigInvalid extends OutputConfig { object OutputConfigManager { var loaders = Map.empty[String, () => OutputConfig] def register(id: String, loader: () => OutputConfig) = loaders += id -> loader - def create(id: String) = loaders.get(id).map(_.apply()).getOrElse(new OutputConfigInvalid) + def create(id: String) = + loaders.get(id).map(_.apply()).getOrElse(new OutputConfigInvalid) register("fluid", () => new OutputConfigFluid) register("power", () => new OutputConfigPower) -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluid.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluid.scala index 15642b0..44e4d39 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluid.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluid.scala @@ -45,6 +45,7 @@ class OutputConfigFluid extends OutputConfig with OutputConfigRSControllable { def handleConfigPacket(m: MsgOutputCfg) = m match { case MsgOutputCfgRSMode(_, r) => rsMode = r - case _ => sys.error("Invalid output config packet %s to config %s".format(m, this)) + case _ => + sys.error("Invalid output config packet %s to config %s".format(m, this)) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluidSlots.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluidSlots.scala index e3fde3b..07b5ec7 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluidSlots.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigFluidSlots.scala @@ -17,7 +17,9 @@ trait OutputConfigSlots { var slot = slotsDef.default } -class OutputConfigFluidSlots(val slotsDef: SlotSet) extends OutputConfigFluid with OutputConfigSlots { +class OutputConfigFluidSlots(val slotsDef: SlotSet) + extends OutputConfigFluid + with OutputConfigSlots { override def id = slotsDef.outputConfigId override def read(t: NBTTagCompound) { super.read(t) @@ -29,6 +31,6 @@ class OutputConfigFluidSlots(val slotsDef: SlotSet) extends OutputConfigFluid wi } override def handleConfigPacket(m: MsgOutputCfg) = m match { case MsgOutputCfgSlot(n, id) => slot = slotsDef.get(id) - case _ => super.handleConfigPacket(m) + case _ => super.handleConfigPacket(m) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigItems.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigItems.scala index 3e604f7..c413f78 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigItems.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigItems.scala @@ -26,7 +26,8 @@ class OutputConfigItems extends OutputConfig with OutputConfigRSControllable { def handleConfigPacket(m: MsgOutputCfg) = m match { case MsgOutputCfgRSMode(_, r) => rsMode = r - case _ => sys.error("Invalid output config packet %s to config %s".format(m, this)) + case _ => + sys.error("Invalid output config packet %s to config %s".format(m, this)) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigPower.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigPower.scala index 505b872..8d9cd48 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigPower.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigPower.scala @@ -12,7 +12,9 @@ package net.bdew.lib.multiblock.data import net.bdew.lib.multiblock.network.MsgOutputCfg import net.minecraft.nbt.NBTTagCompound -class OutputConfigPower(var unit: String = "MJ") extends OutputConfig with OutputConfigRSControllable { +class OutputConfigPower(var unit: String = "MJ") + extends OutputConfig + with OutputConfigRSControllable { override val id = "power" var avg = 0.0 var rsMode = RSMode.ALWAYS @@ -37,6 +39,7 @@ class OutputConfigPower(var unit: String = "MJ") extends OutputConfig with Outpu def handleConfigPacket(m: MsgOutputCfg) = m match { case MsgOutputCfgRSMode(_, r) => rsMode = r - case _ => sys.error("Invalid output config packet %s to config %s".format(m, this)) + case _ => + sys.error("Invalid output config packet %s to config %s".format(m, this)) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigRSMode.scala b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigRSMode.scala index 9a6a3f0..4ee8ba5 100644 --- a/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigRSMode.scala +++ b/src/main/scala/net/bdew/lib/multiblock/data/OutputConfigRSMode.scala @@ -11,8 +11,9 @@ package net.bdew.lib.multiblock.data import net.bdew.lib.multiblock.network.MsgOutputCfg -case class MsgOutputCfgRSMode(output: Int, rsMode: RSMode.Value) extends MsgOutputCfg +case class MsgOutputCfgRSMode(output: Int, rsMode: RSMode.Value) + extends MsgOutputCfg trait OutputConfigRSControllable extends OutputConfig { var rsMode: RSMode.Value -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetInfo.scala b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetInfo.scala index 01b8aba..8a4e417 100644 --- a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetInfo.scala +++ b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetInfo.scala @@ -14,7 +14,12 @@ import net.bdew.lib.gui.{Color, Point, Rect, Texture} import scala.collection.mutable -class WidgetInfoMulti(val rect: Rect, icon: Texture, text: => String, tooltip: => List[String]) extends Widget { +class WidgetInfoMulti( + val rect: Rect, + icon: Texture, + text: => String, + tooltip: => List[String] +) extends Widget { final val iconRect = Rect(1, 1, 8, 8) override def handleTooltip(p: Point, tip: mutable.MutableList[String]) { @@ -23,8 +28,9 @@ class WidgetInfoMulti(val rect: Rect, icon: Texture, text: => String, tooltip: = override def draw(mouse: Point) { parent.drawTexture(iconRect + rect.origin, icon) - parent.drawText(text, rect.origin +(12, 1), Color.darkGray, false) + parent.drawText(text, rect.origin + (12, 1), Color.darkGray, false) } } -class WidgetInfo(rect: Rect, icon: Texture, text: => String, tooltip: => String) extends WidgetInfoMulti(rect, icon, text, List(tooltip)) +class WidgetInfo(rect: Rect, icon: Texture, text: => String, tooltip: => String) + extends WidgetInfoMulti(rect, icon, text, List(tooltip)) diff --git a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetOutputIcon.scala b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetOutputIcon.scala index a44c156..a632717 100644 --- a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetOutputIcon.scala +++ b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetOutputIcon.scala @@ -19,7 +19,8 @@ import net.bdew.lib.render.connected.BlockAdditionalRender import scala.collection.mutable -class WidgetOutputIcon(p: Point, te: CIOutputFaces, output: Int) extends Widget { +class WidgetOutputIcon(p: Point, te: CIOutputFaces, output: Int) + extends Widget { val rect = new Rect(p, 16, 16) override def draw(mouse: Point) { @@ -27,14 +28,44 @@ class WidgetOutputIcon(p: Point, te: CIOutputFaces, output: Int) extends Widget if (faces.isDefinedAt(output)) { val bf = faces(output) bf.origin.block(te.getWorldObj) foreach { block => - parent.drawTexture(rect, Texture(Texture.BLOCKS, block.getIcon(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face.ordinal()))) + parent.drawTexture( + rect, + Texture( + Texture.BLOCKS, + block.getIcon( + te.getWorldObj, + bf.origin.x, + bf.origin.y, + bf.origin.z, + bf.face.ordinal() + ) + ) + ) if (block.isInstanceOf[BlockAdditionalRender]) { - for (over <- block.asInstanceOf[BlockAdditionalRender].getFaceOverlays(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face)) - parent.drawTexture(rect, Texture(Texture.BLOCKS, over.icon), over.color) + for ( + over <- block + .asInstanceOf[BlockAdditionalRender] + .getFaceOverlays( + te.getWorldObj, + bf.origin.x, + bf.origin.y, + bf.origin.z, + bf.face + ) + ) + parent.drawTexture( + rect, + Texture(Texture.BLOCKS, over.icon), + over.color + ) } } } else { - parent.drawTexture(rect, Texture(Texture.BLOCKS, te.resources.disabled), te.resources.outputColors(output)) + parent.drawTexture( + rect, + Texture(Texture.BLOCKS, te.resources.disabled), + te.resources.outputColors(output) + ) } } @@ -45,7 +76,14 @@ class WidgetOutputIcon(p: Point, te: CIOutputFaces, output: Int) extends Widget val bf = faces(output) bf.origin.block(te.getWorldObj) map { block => tip += block.getLocalizedName - tip += "%d, %d, %d - %s".format(bf.x, bf.y, bf.z, Misc.toLocal("bdlib.multiblock.face." + bf.face.toString.toLowerCase(Locale.US))) + tip += "%d, %d, %d - %s".format( + bf.x, + bf.y, + bf.z, + Misc.toLocal( + "bdlib.multiblock.face." + bf.face.toString.toLowerCase(Locale.US) + ) + ) } } else { tip += Misc.toLocal("bdlib.multiblock.disabled") diff --git a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetRSConfig.scala b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetRSConfig.scala index cab66b2..0a9c05f 100644 --- a/src/main/scala/net/bdew/lib/multiblock/gui/WidgetRSConfig.scala +++ b/src/main/scala/net/bdew/lib/multiblock/gui/WidgetRSConfig.scala @@ -14,14 +14,26 @@ import java.util.Locale import net.bdew.lib.Misc import net.bdew.lib.gui.widgets.{WidgetButtonIcon, WidgetSubContainer} import net.bdew.lib.gui.{Point, Rect} -import net.bdew.lib.multiblock.data.{MsgOutputCfgRSMode, OutputConfigRSControllable, RSMode} +import net.bdew.lib.multiblock.data.{ + MsgOutputCfgRSMode, + OutputConfigRSControllable, + RSMode +} import net.bdew.lib.multiblock.interact.CIOutputFaces import net.bdew.lib.multiblock.network.NetHandler -class WidgetRSConfig(te: CIOutputFaces, output: Int, p: Point) extends WidgetSubContainer(new Rect(p, 16, 16)) { +class WidgetRSConfig(te: CIOutputFaces, output: Int, p: Point) + extends WidgetSubContainer(new Rect(p, 16, 16)) { def cfg = te.outputConfig(output).asInstanceOf[OutputConfigRSControllable] - val bt = add(new WidgetButtonIcon(Point(0, 0), clicked, te.resources.btBase, te.resources.btHover)) + val bt = add( + new WidgetButtonIcon( + Point(0, 0), + clicked, + te.resources.btBase, + te.resources.btHover + ) + ) val icons = Map( RSMode.ALWAYS -> te.resources.btEnabled, @@ -39,7 +51,8 @@ class WidgetRSConfig(te: CIOutputFaces, output: Int, p: Point) extends WidgetSub override def draw(mouse: Point) { bt.icon = icons(cfg.rsMode) - bt.hover = Misc.toLocal("bdlib.rsmode." + cfg.rsMode.toString.toLowerCase(Locale.US)) + bt.hover = + Misc.toLocal("bdlib.rsmode." + cfg.rsMode.toString.toLowerCase(Locale.US)) super.draw(mouse) } diff --git a/src/main/scala/net/bdew/lib/multiblock/interact/CIFluidOutputSelect.scala b/src/main/scala/net/bdew/lib/multiblock/interact/CIFluidOutputSelect.scala index 5e992ba..1c69334 100644 --- a/src/main/scala/net/bdew/lib/multiblock/interact/CIFluidOutputSelect.scala +++ b/src/main/scala/net/bdew/lib/multiblock/interact/CIFluidOutputSelect.scala @@ -14,9 +14,16 @@ import net.minecraftforge.fluids.{Fluid, FluidStack, FluidTankInfo} trait CIFluidOutputSelect extends CIOutputFaces { val outputSlotsDef: SlotSet - def outputFluid(slot: outputSlotsDef.Slot, resource: FluidStack, doDrain: Boolean): FluidStack - def outputFluid(slot: outputSlotsDef.Slot, amount: Int, doDrain: Boolean): FluidStack + def outputFluid( + slot: outputSlotsDef.Slot, + resource: FluidStack, + doDrain: Boolean + ): FluidStack + def outputFluid( + slot: outputSlotsDef.Slot, + amount: Int, + doDrain: Boolean + ): FluidStack def canOutputFluid(slot: outputSlotsDef.Slot, fluid: Fluid): Boolean def getTankInfo: Array[FluidTankInfo] } - diff --git a/src/main/scala/net/bdew/lib/multiblock/interact/CIOutputFaces.scala b/src/main/scala/net/bdew/lib/multiblock/interact/CIOutputFaces.scala index b818ac3..a426692 100644 --- a/src/main/scala/net/bdew/lib/multiblock/interact/CIOutputFaces.scala +++ b/src/main/scala/net/bdew/lib/multiblock/interact/CIOutputFaces.scala @@ -35,7 +35,10 @@ trait CIOutputFaces extends TileController { return i } val pl = getWorldObj.getClosestPlayer(bf.x, bf.y, bf.z, 10) - if (pl != null) pl.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.toomanyoutputs")) + if (pl != null) + pl.addChatMessage( + new ChatComponentTranslation("bdlib.multiblock.toomanyoutputs") + ) return -1 } @@ -56,7 +59,10 @@ trait CIOutputFaces extends TileController { (x, n) <- outputFaces t <- x.origin.getTile[MIOutput[_]](getWorldObj) } { - if (!outputConfig.isDefinedAt(n) || !t.outputConfigType.isInstance(outputConfig(n))) + if ( + !outputConfig + .isDefinedAt(n) || !t.outputConfigType.isInstance(outputConfig(n)) + ) outputConfig(n) = t.makeCfgObject(x.face) t.doOutput(x.face, outputConfig(n).asInstanceOf[t.OCType]) } diff --git a/src/main/scala/net/bdew/lib/multiblock/network/NetHandler.scala b/src/main/scala/net/bdew/lib/multiblock/network/NetHandler.scala index a507db5..f05c5f7 100644 --- a/src/main/scala/net/bdew/lib/multiblock/network/NetHandler.scala +++ b/src/main/scala/net/bdew/lib/multiblock/network/NetHandler.scala @@ -14,10 +14,9 @@ import net.bdew.lib.network.NetChannel import net.minecraft.entity.player.EntityPlayerMP object NetHandler extends NetChannel("bdew.multiblock") { - regServerHandler { - case (msg: MsgOutputCfg, p: EntityPlayerMP) => - val te = p.openContainer.asInstanceOf[ContainerOutputFaces].te - te.outputConfig(msg.output).handleConfigPacket(msg) - te.outputConfig.updated() + regServerHandler { case (msg: MsgOutputCfg, p: EntityPlayerMP) => + val te = p.openContainer.asInstanceOf[ContainerOutputFaces].te + te.outputConfig(msg.output).handleConfigPacket(msg) + te.outputConfig.updated() } } diff --git a/src/main/scala/net/bdew/lib/multiblock/tile/RSControllableOutput.scala b/src/main/scala/net/bdew/lib/multiblock/tile/RSControllableOutput.scala index 8417291..406dd0d 100644 --- a/src/main/scala/net/bdew/lib/multiblock/tile/RSControllableOutput.scala +++ b/src/main/scala/net/bdew/lib/multiblock/tile/RSControllableOutput.scala @@ -16,6 +16,10 @@ trait RSControllableOutput extends TileEntity { def checkCanOutput(cfg: OutputConfigRSControllable): Boolean = { if (cfg.rsMode == RSMode.ALWAYS) return true if (cfg.rsMode == RSMode.NEVER) return false - return getWorldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord) ^ (cfg.rsMode == RSMode.RS_OFF) + return getWorldObj.isBlockIndirectlyGettingPowered( + xCoord, + yCoord, + zCoord + ) ^ (cfg.rsMode == RSMode.RS_OFF) } } diff --git a/src/main/scala/net/bdew/lib/multiblock/tile/TileController.scala b/src/main/scala/net/bdew/lib/multiblock/tile/TileController.scala index 729e663..2f1f340 100644 --- a/src/main/scala/net/bdew/lib/multiblock/tile/TileController.scala +++ b/src/main/scala/net/bdew/lib/multiblock/tile/TileController.scala @@ -18,7 +18,8 @@ import net.bdew.lib.multiblock.{MachineCore, ResourceProvider, Tools} import net.minecraft.entity.player.EntityPlayer trait TileController extends TileDataSlots { - val modules = new DataSlotPosSet("modules", this).setUpdate(UpdateKind.WORLD, UpdateKind.SAVE) + val modules = new DataSlotPosSet("modules", this) + .setUpdate(UpdateKind.WORLD, UpdateKind.SAVE) def resources: ResourceProvider def cfg: MachineCore @@ -29,7 +30,8 @@ trait TileController extends TileDataSlots { lazy val myPos = BlockRef(xCoord, yCoord, zCoord) - def getNumOfModules(kind: String) = modules.flatMap(_.getTile[TileModule](getWorldObj)).count(_.kind == kind) + def getNumOfModules(kind: String) = + modules.flatMap(_.getTile[TileModule](getWorldObj)).count(_.kind == kind) def onModulesChanged() def onClick(player: EntityPlayer) @@ -58,22 +60,45 @@ trait TileController extends TileDataSlots { } def validateModules() { - modules.filter(x => { - x.getTile[TileModule](getWorldObj).isEmpty || x.getBlock[BlockModule[TileModule]](getWorldObj).isEmpty - }).foreach(x => { - BdLib.logWarn("Block at %s is not a valid module, removing from machine %s at %d,%d,%d", x, this.getClass.getSimpleName, xCoord, yCoord, zCoord) - modules.remove(x) - }) + modules + .filter(x => { + x.getTile[TileModule](getWorldObj) + .isEmpty || x.getBlock[BlockModule[TileModule]](getWorldObj).isEmpty + }) + .foreach(x => { + BdLib.logWarn( + "Block at %s is not a valid module, removing from machine %s at %d,%d,%d", + x, + this.getClass.getSimpleName, + xCoord, + yCoord, + zCoord + ) + modules.remove(x) + }) val reachable = Tools.findReachableModules(getWorldObj, myPos) - val toRemove = modules.filterNot(reachable.contains).flatMap(_.getTile[TileModule](getWorldObj)) + val toRemove = modules + .filterNot(reachable.contains) + .flatMap(_.getTile[TileModule](getWorldObj)) acceptNewModules = false toRemove.foreach(moduleRemoved) toRemove.foreach(_.coreRemoved()) acceptNewModules = true modulesChanged = true - modules.map(x => - (x.getBlock[BlockModule[TileModule]](getWorldObj).orNull, x.getTile[TileModule](getWorldObj).orNull) - ).filter({ case (a, b) => a.kind != b.kind }).foreach({ case (a, b) => sys.error("Type mismatch between Block/Tile Block=%s(%s) Tile=%s(%s)".format(a.kind, a, b.kind, b)) }) + modules + .map(x => + ( + x.getBlock[BlockModule[TileModule]](getWorldObj).orNull, + x.getTile[TileModule](getWorldObj).orNull + ) + ) + .filter({ case (a, b) => a.kind != b.kind }) + .foreach({ case (a, b) => + sys.error( + "Type mismatch between Block/Tile Block=%s(%s) Tile=%s(%s)" + .format(a.kind, a, b.kind, b) + ) + }) } serverTick.listen(() => { diff --git a/src/main/scala/net/bdew/lib/multiblock/tile/TileControllerGui.scala b/src/main/scala/net/bdew/lib/multiblock/tile/TileControllerGui.scala index bc4af81..3dcf19b 100644 --- a/src/main/scala/net/bdew/lib/multiblock/tile/TileControllerGui.scala +++ b/src/main/scala/net/bdew/lib/multiblock/tile/TileControllerGui.scala @@ -16,11 +16,18 @@ abstract class TileControllerGui extends TileController { def onClick(player: EntityPlayer) = { import net.bdew.lib.helpers.ChatHelper._ - val missing = cfg.required.filter({ case (mod, cnt) => getNumOfModules(mod) < cnt }) + val missing = cfg.required.filter({ case (mod, cnt) => + getNumOfModules(mod) < cnt + }) if (missing.nonEmpty) { - player.addChatMessage(L("bdlib.multiblock.incomplete").setColor(Color.RED)) + player.addChatMessage( + L("bdlib.multiblock.incomplete").setColor(Color.RED) + ) for ((mod, cnt) <- missing) - player.addChatMessage(L("- %s %s", cnt.toString, L(resources.getModuleName(mod))).setColor(Color.RED)) + player.addChatMessage( + L("- %s %s", cnt.toString, L(resources.getModuleName(mod))) + .setColor(Color.RED) + ) } else openGui(player) } diff --git a/src/main/scala/net/bdew/lib/multiblock/tile/TileModule.scala b/src/main/scala/net/bdew/lib/multiblock/tile/TileModule.scala index 73b6f5a..0b2daf2 100644 --- a/src/main/scala/net/bdew/lib/multiblock/tile/TileModule.scala +++ b/src/main/scala/net/bdew/lib/multiblock/tile/TileModule.scala @@ -18,9 +18,11 @@ import scala.reflect.ClassTag trait TileModule extends TileDataSlots { val kind: String - val connected = new DataSlotPos("connected", this).setUpdate(UpdateKind.WORLD, UpdateKind.SAVE, UpdateKind.RENDER) + val connected = new DataSlotPos("connected", this) + .setUpdate(UpdateKind.WORLD, UpdateKind.SAVE, UpdateKind.RENDER) - def getCoreAs[T <: TileController : ClassTag] = connected flatMap (_.getTile[T](getWorldObj)) + def getCoreAs[T <: TileController: ClassTag] = + connected flatMap (_.getTile[T](getWorldObj)) def getCore = getCoreAs[TileController] @@ -30,14 +32,24 @@ trait TileModule extends TileDataSlots { if (target.moduleConnected(this)) { connected.set(target.myPos) getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord) - getWorldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType) + getWorldObj.notifyBlocksOfNeighborChange( + xCoord, + yCoord, + zCoord, + getBlockType + ) } } def coreRemoved() { connected.unset() getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord) - getWorldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, getBlockType) + getWorldObj.notifyBlocksOfNeighborChange( + xCoord, + yCoord, + zCoord, + getBlockType + ) } def onBreak() { @@ -49,7 +61,8 @@ trait TileModule extends TileDataSlots { def tryConnect() { if (getCore.isEmpty) { for { - conn <- Tools.findConnections(getWorldObj, myPos, kind).headOption if canConnectToCore(conn) + conn <- Tools.findConnections(getWorldObj, myPos, kind).headOption + if canConnectToCore(conn) core <- conn.getTile[TileController](getWorldObj) } { connect(core) diff --git a/src/main/scala/net/bdew/lib/multiblock/tile/TileOutput.scala b/src/main/scala/net/bdew/lib/multiblock/tile/TileOutput.scala index de4d96e..0d880bf 100644 --- a/src/main/scala/net/bdew/lib/multiblock/tile/TileOutput.scala +++ b/src/main/scala/net/bdew/lib/multiblock/tile/TileOutput.scala @@ -15,7 +15,9 @@ import net.bdew.lib.multiblock.data.OutputConfig import net.bdew.lib.multiblock.interact.{CIOutputFaces, MIOutput} import net.minecraftforge.common.util.ForgeDirection -abstract class TileOutput[T <: OutputConfig] extends TileModule with MIOutput[T] { +abstract class TileOutput[T <: OutputConfig] + extends TileModule + with MIOutput[T] { override def getCore = getCoreAs[CIOutputFaces] def makeCfgObject(face: ForgeDirection): T @@ -44,7 +46,10 @@ abstract class TileOutput[T <: OutputConfig] extends TileModule with MIOutput[T] def canConnectToFace(d: ForgeDirection): Boolean - def onConnectionsChanged(added: Set[ForgeDirection], removed: Set[ForgeDirection]) {} + def onConnectionsChanged( + added: Set[ForgeDirection], + removed: Set[ForgeDirection] + ) {} def doRescanFaces() { getCore foreach { core => @@ -52,8 +57,9 @@ abstract class TileOutput[T <: OutputConfig] extends TileModule with MIOutput[T] ForgeDirection.VALID_DIRECTIONS filterNot { dir => core.modules.contains(myPos.neighbour(dir)) } filter canConnectToFace - ).toSet - val known = core.outputFaces.filter(_._1.origin == myPos).map(_._1.face).toSet + ).toSet + val known = + core.outputFaces.filter(_._1.origin == myPos).map(_._1.face).toSet val toAdd = connections -- known val toRemove = known -- connections toRemove.foreach(x => core.removeOutput(myPos, x)) diff --git a/src/main/scala/net/bdew/lib/nbt/ListElement.scala b/src/main/scala/net/bdew/lib/nbt/ListElement.scala index 7da4ccd..f3a0586 100644 --- a/src/main/scala/net/bdew/lib/nbt/ListElement.scala +++ b/src/main/scala/net/bdew/lib/nbt/ListElement.scala @@ -26,4 +26,4 @@ object ListElement { implicit val intArrayInList = ListElement(TIntArray, _.func_150306_c(_)) implicit val doubleInList = ListElement(TDouble, _.func_150309_d(_)) implicit val floatInList = ListElement(TFloat, _.func_150308_e(_)) -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/nbt/NBT.scala b/src/main/scala/net/bdew/lib/nbt/NBT.scala index 71dd1eb..fcd78ed 100644 --- a/src/main/scala/net/bdew/lib/nbt/NBT.scala +++ b/src/main/scala/net/bdew/lib/nbt/NBT.scala @@ -19,7 +19,8 @@ object NBT { class NBTSerialized(val value: NBTBase) extends AnyVal object NBTSerialized { - implicit def serializeNbtPrimitive[T: Type](v: T): NBTSerialized = new NBTSerialized(Type[T].toNBT(v)) + implicit def serializeNbtPrimitive[T: Type](v: T): NBTSerialized = + new NBTSerialized(Type[T].toNBT(v)) implicit def serializeNbtList[T: Type](v: Traversable[T]): NBTSerialized = { val list = new NBTTagList @@ -28,11 +29,15 @@ object NBT { } // Boolean is special because it's represented as a byte in NBT - implicit def serializeBoolean(v: Boolean): NBTSerialized = new NBTSerialized(new NBTTagByte(if (v) 1 else 0)) + implicit def serializeBoolean(v: Boolean): NBTSerialized = + new NBTSerialized(new NBTTagByte(if (v) 1 else 0)) // Itemstack serialization helpers - implicit def serializeItemStack(v: ItemStack): NBTSerialized = new NBTSerialized(NBT.from(v.writeToNBT _)) - implicit def serializeItemStackList(v: Traversable[ItemStack]): NBTSerialized = serializeNbtList(v map (x => NBT.from(x.writeToNBT _))) + implicit def serializeItemStack(v: ItemStack): NBTSerialized = + new NBTSerialized(NBT.from(v.writeToNBT _)) + implicit def serializeItemStackList( + v: Traversable[ItemStack] + ): NBTSerialized = serializeNbtList(v map (x => NBT.from(x.writeToNBT _))) } def apply(pairs: (String, NBTSerialized)*): NBTTagCompound = { diff --git a/src/main/scala/net/bdew/lib/nbt/RichNBTTagCompound.scala b/src/main/scala/net/bdew/lib/nbt/RichNBTTagCompound.scala index bd22ddb..9b924a8 100644 --- a/src/main/scala/net/bdew/lib/nbt/RichNBTTagCompound.scala +++ b/src/main/scala/net/bdew/lib/nbt/RichNBTTagCompound.scala @@ -29,4 +29,4 @@ class RichNBTTagCompound(tag: NBTTagCompound) { } def toItemStack = Option(ItemStack.loadItemStackFromNBT(tag)) -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/nbt/Type.scala b/src/main/scala/net/bdew/lib/nbt/Type.scala index bf21e90..3bdb342 100644 --- a/src/main/scala/net/bdew/lib/nbt/Type.scala +++ b/src/main/scala/net/bdew/lib/nbt/Type.scala @@ -28,7 +28,8 @@ object Type { override def toNBT(p: Byte): NBTTagByte = new NBTTagByte(p) } - implicit object TShort extends TypeDef(2, classOf[NBTTagShort], classOf[Short]) { + implicit object TShort + extends TypeDef(2, classOf[NBTTagShort], classOf[Short]) { override def toVal(p: NBTTagShort): Short = p.func_150289_e() override def toNBT(p: Short): NBTTagShort = new NBTTagShort(p) } @@ -43,22 +44,26 @@ object Type { override def toNBT(p: Long): NBTTagLong = new NBTTagLong(p) } - implicit object TFloat extends TypeDef(5, classOf[NBTTagFloat], classOf[Float]) { + implicit object TFloat + extends TypeDef(5, classOf[NBTTagFloat], classOf[Float]) { override def toVal(p: NBTTagFloat): Float = p.func_150288_h() override def toNBT(p: Float): NBTTagFloat = new NBTTagFloat(p) } - implicit object TDouble extends TypeDef(6, classOf[NBTTagDouble], classOf[Double]) { + implicit object TDouble + extends TypeDef(6, classOf[NBTTagDouble], classOf[Double]) { override def toVal(p: NBTTagDouble): Double = p.func_150286_g() override def toNBT(p: Double): NBTTagDouble = new NBTTagDouble(p) } - implicit object TByteArray extends TypeDef(7, classOf[NBTTagByteArray], classOf[Array[Byte]]) { + implicit object TByteArray + extends TypeDef(7, classOf[NBTTagByteArray], classOf[Array[Byte]]) { override def toVal(p: NBTTagByteArray): Array[Byte] = p.func_150292_c() override def toNBT(p: Array[Byte]): NBTTagByteArray = new NBTTagByteArray(p) } - implicit object TString extends TypeDef(8, classOf[NBTTagString], classOf[String]) { + implicit object TString + extends TypeDef(8, classOf[NBTTagString], classOf[String]) { override def toVal(p: NBTTagString): String = p.func_150285_a_() override def toNBT(p: String): NBTTagString = new NBTTagString(p) } @@ -67,11 +72,10 @@ object Type { implicit object TCompound extends TypeDefSimple(10, classOf[NBTTagCompound]) - implicit object TIntArray extends TypeDef(11, classOf[NBTTagIntArray], classOf[Array[Int]]) { + implicit object TIntArray + extends TypeDef(11, classOf[NBTTagIntArray], classOf[Array[Int]]) { override def toVal(p: NBTTagIntArray): Array[Int] = p.func_150302_c() override def toNBT(p: Array[Int]): NBTTagIntArray = new NBTTagIntArray(p) } } - - diff --git a/src/main/scala/net/bdew/lib/nbt/TypeDef.scala b/src/main/scala/net/bdew/lib/nbt/TypeDef.scala index b1909c3..5c37f5c 100644 --- a/src/main/scala/net/bdew/lib/nbt/TypeDef.scala +++ b/src/main/scala/net/bdew/lib/nbt/TypeDef.scala @@ -14,7 +14,11 @@ import net.minecraft.nbt.{NBTBase, NBTTagCompound} import scala.annotation.implicitNotFound @implicitNotFound("Type ${R} is not supported by NBT") -abstract class TypeDef[T <: NBTBase, R](val id: Int, val cls: Class[T], val valueClass: Class[R]) extends Type[R] { +abstract class TypeDef[T <: NBTBase, R]( + val id: Int, + val cls: Class[T], + val valueClass: Class[R] +) extends Type[R] { TypeDef.map += id -> this def toVal(p: T): R def toNBT(p: R): T @@ -26,7 +30,8 @@ object TypeDef { var map = Map.empty[Int, TypeDef[_, _]] } -class TypeDefSimple[T <: NBTBase](id: Int, cls: Class[T]) extends TypeDef[T, T](id, cls, cls) { +class TypeDefSimple[T <: NBTBase](id: Int, cls: Class[T]) + extends TypeDef[T, T](id, cls, cls) { override def toVal(p: T): T = p override def toNBT(p: T): T = p } diff --git a/src/main/scala/net/bdew/lib/nbt/package.scala b/src/main/scala/net/bdew/lib/nbt/package.scala index 9685a03..efdfe2a 100644 --- a/src/main/scala/net/bdew/lib/nbt/package.scala +++ b/src/main/scala/net/bdew/lib/nbt/package.scala @@ -14,5 +14,6 @@ import net.minecraft.nbt.NBTTagCompound import scala.language.implicitConversions package object nbt { - implicit def compound2rich(p: NBTTagCompound): RichNBTTagCompound = new RichNBTTagCompound(p) + implicit def compound2rich(p: NBTTagCompound): RichNBTTagCompound = + new RichNBTTagCompound(p) } diff --git a/src/main/scala/net/bdew/lib/network/ItemStackSerialize.scala b/src/main/scala/net/bdew/lib/network/ItemStackSerialize.scala index 21a1be2..c6441e7 100644 --- a/src/main/scala/net/bdew/lib/network/ItemStackSerialize.scala +++ b/src/main/scala/net/bdew/lib/network/ItemStackSerialize.scala @@ -40,6 +40,6 @@ object ItemStackSerialize { import scala.language.implicitConversions implicit def ser2content(v: ItemStackSerialize): ItemStack = v.stack - implicit def content2ser(v: ItemStack): ItemStackSerialize = new ItemStackSerialize(v) + implicit def content2ser(v: ItemStack): ItemStackSerialize = + new ItemStackSerialize(v) } - diff --git a/src/main/scala/net/bdew/lib/network/NBTTagCompoundSerialize.scala b/src/main/scala/net/bdew/lib/network/NBTTagCompoundSerialize.scala index 35f9f54..2d67d3d 100644 --- a/src/main/scala/net/bdew/lib/network/NBTTagCompoundSerialize.scala +++ b/src/main/scala/net/bdew/lib/network/NBTTagCompoundSerialize.scala @@ -13,7 +13,8 @@ import java.io.{ObjectInputStream, ObjectOutputStream} import net.minecraft.nbt.NBTTagCompound -class NBTTagCompoundSerialize(var tag: NBTTagCompound = new NBTTagCompound) extends Serializable { +class NBTTagCompoundSerialize(var tag: NBTTagCompound = new NBTTagCompound) + extends Serializable { private def writeObject(out: ObjectOutputStream) { out.writeObject(NBTHelper.toBytes(tag)) @@ -29,5 +30,6 @@ object NBTTagCompoundSerialize { import scala.language.implicitConversions implicit def ser2content(v: NBTTagCompoundSerialize): NBTTagCompound = v.tag - implicit def content2ser(v: NBTTagCompound): NBTTagCompoundSerialize = new NBTTagCompoundSerialize(v) + implicit def content2ser(v: NBTTagCompound): NBTTagCompoundSerialize = + new NBTTagCompoundSerialize(v) } diff --git a/src/main/scala/net/bdew/lib/network/NetChannel.scala b/src/main/scala/net/bdew/lib/network/NetChannel.scala index 4279094..f869b4d 100644 --- a/src/main/scala/net/bdew/lib/network/NetChannel.scala +++ b/src/main/scala/net/bdew/lib/network/NetChannel.scala @@ -11,9 +11,18 @@ package net.bdew.lib.network import java.util -import cpw.mods.fml.common.network.{FMLEmbeddedChannel, FMLOutboundHandler, NetworkRegistry} +import cpw.mods.fml.common.network.{ + FMLEmbeddedChannel, + FMLOutboundHandler, + NetworkRegistry +} import cpw.mods.fml.relauncher.Side -import io.netty.channel.{ChannelFutureListener, ChannelHandler, ChannelHandlerContext, SimpleChannelInboundHandler} +import io.netty.channel.{ + ChannelFutureListener, + ChannelHandler, + ChannelHandlerContext, + SimpleChannelInboundHandler +} import net.bdew.lib.{BdLib, Misc} import net.minecraft.entity.player.EntityPlayerMP import net.minecraft.network.NetHandlerPlayServer @@ -26,11 +35,20 @@ class NetChannel(val name: String) { object ServerHandler extends SimpleChannelInboundHandler[Message] { def channelRead0(ctx: ChannelHandlerContext, msg: Message) { try { - val player = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get.asInstanceOf[NetHandlerPlayServer].playerEntity + val player = ctx + .channel() + .attr(NetworkRegistry.NET_HANDLER) + .get + .asInstanceOf[NetHandlerPlayServer] + .playerEntity if (serverChain.isDefinedAt(msg, player)) serverChain(msg, player) else - BdLib.logWarn("Unable to handle message from user %s: %s", player.getDisplayName, msg) + BdLib.logWarn( + "Unable to handle message from user %s: %s", + player.getDisplayName, + msg + ) } catch { case e: Throwable => BdLib.logErrorException("Error handling packet", e) } @@ -51,9 +69,15 @@ class NetChannel(val name: String) { } def init() { - if (channels != null) sys.error("Attempted to initialize a channel twice (%s)".format(name)) - channels = NetworkRegistry.INSTANCE.newChannel(name, new SerializedMessageCodec) - BdLib.logInfo("Initialized network channel '%s' for mod '%s'", name, Misc.getActiveModId) + if (channels != null) + sys.error("Attempted to initialize a channel twice (%s)".format(name)) + channels = + NetworkRegistry.INSTANCE.newChannel(name, new SerializedMessageCodec) + BdLib.logInfo( + "Initialized network channel '%s' for mod '%s'", + name, + Misc.getActiveModId + ) addHandler(Side.SERVER, ServerHandler) addHandler(Side.CLIENT, ClientHandler) } @@ -69,36 +93,77 @@ class NetChannel(val name: String) { private def addHandler(side: Side, handler: ChannelHandler) { val ch = channels.get(side) - val name = ch.findChannelHandlerNameForType(classOf[SerializedMessageCodec[this.type]]) + val name = ch.findChannelHandlerNameForType( + classOf[SerializedMessageCodec[this.type]] + ) ch.pipeline().addAfter(name, side + "Handler", handler) } def sendToAll(message: Message) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL) - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.ALL) + channels + .get(Side.SERVER) + .writeAndFlush(message) + .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) } def sendTo(message: Message, player: EntityPlayerMP) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER) - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player) - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.PLAYER) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGETARGS) + .set(player) + channels + .get(Side.SERVER) + .writeAndFlush(message) + .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) } def sendToAllAround(message: Message, point: NetworkRegistry.TargetPoint) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT) - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point) - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGETARGS) + .set(point) + channels + .get(Side.SERVER) + .writeAndFlush(message) + .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) } def sendToDimension(message: Message, dimensionId: Int) { - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION) - channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(new Integer(dimensionId)) - channels.get(Side.SERVER).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.DIMENSION) + channels + .get(Side.SERVER) + .attr(FMLOutboundHandler.FML_MESSAGETARGETARGS) + .set(new Integer(dimensionId)) + channels + .get(Side.SERVER) + .writeAndFlush(message) + .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) } def sendToServer(message: Message) { - channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER) - channels.get(Side.CLIENT).writeAndFlush(message).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) + channels + .get(Side.CLIENT) + .attr(FMLOutboundHandler.FML_MESSAGETARGET) + .set(FMLOutboundHandler.OutboundTarget.TOSERVER) + channels + .get(Side.CLIENT) + .writeAndFlush(message) + .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE) } } diff --git a/src/main/scala/net/bdew/lib/network/NetworkSecurityConfig.scala b/src/main/scala/net/bdew/lib/network/NetworkSecurityConfig.scala index 36dc94c..ede2e59 100644 --- a/src/main/scala/net/bdew/lib/network/NetworkSecurityConfig.scala +++ b/src/main/scala/net/bdew/lib/network/NetworkSecurityConfig.scala @@ -2,7 +2,11 @@ package net.bdew.lib.network import net.bdew.lib.BdLib import net.bdew.lib.recipes.{RecipeLoader, RecipeParser, RecipesHelper} -import net.bdew.lib.recipes.gencfg.{ConfigSection, GenericConfigLoader, GenericConfigParser} +import net.bdew.lib.recipes.gencfg.{ + ConfigSection, + GenericConfigLoader, + GenericConfigParser +} import java.io.{File, FileWriter} @@ -12,7 +16,8 @@ object NetworkSecurityLoader { val loader = new RecipeLoader with GenericConfigLoader { override val cfgStore: ConfigSection = NetworkSecurity - override def newParser(): RecipeParser = new RecipeParser with GenericConfigParser + override def newParser(): RecipeParser = new RecipeParser + with GenericConfigParser } def loadConfigFiles(): Unit = { @@ -20,8 +25,12 @@ object NetworkSecurityLoader { BdLib.configDir.mkdir() val nl = System.getProperty("line.separator") val f = new FileWriter(new File(BdLib.configDir, "readme.txt")) - f.write("Any .cfg files in this directory will be loaded after the internal configuration, in alphabetic order" + nl) - f.write("Files in 'overrides' directory with matching names cab be used to override internal configuration" + nl) + f.write( + "Any .cfg files in this directory will be loaded after the internal configuration, in alphabetic order" + nl + ) + f.write( + "Files in 'overrides' directory with matching names cab be used to override internal configuration" + nl + ) f.close() } @@ -30,12 +39,15 @@ object NetworkSecurityLoader { listResource = "/assets/bdlib/config/files.lst", configDir = BdLib.configDir, resBaseName = "/assets/bdlib/config/", - loader = loader) + loader = loader + ) val section = NetworkSecurity.getSection("messageWhitelist") - SerializedMessageCodec.validClassPrefixes ++= section.getStringList("prefix") + SerializedMessageCodec.validClassPrefixes ++= section.getStringList( + "prefix" + ) SerializedMessageCodec.validClasses ++= section.getStringList("exact") SerializedMessageCodec.enforceFilter = section.getBoolean("enforce") SerializedMessageCodec.validClassCache.clear() } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/network/SerializedMessageCodec.scala b/src/main/scala/net/bdew/lib/network/SerializedMessageCodec.scala index 86f3fa6..e4b45d0 100644 --- a/src/main/scala/net/bdew/lib/network/SerializedMessageCodec.scala +++ b/src/main/scala/net/bdew/lib/network/SerializedMessageCodec.scala @@ -9,7 +9,12 @@ package net.bdew.lib.network -import java.io.{ObjectInputStream, ObjectOutputStream, ObjectStreamClass, Serializable} +import java.io.{ + ObjectInputStream, + ObjectOutputStream, + ObjectStreamClass, + Serializable +} import java.lang.{Boolean => BoxedBoolean} import java.util import java.util.concurrent.ConcurrentHashMap @@ -26,25 +31,48 @@ import net.bdew.lib.BdLib import net.bdew.lib.network.SerializedMessageCodec._ @Sharable -class SerializedMessageCodec[T <: NetChannel] extends MessageToMessageCodec[FMLProxyPacket, BaseMessage[T]] { - def encode(ctx: ChannelHandlerContext, msg: BaseMessage[T], out: util.List[AnyRef]) { +class SerializedMessageCodec[T <: NetChannel] + extends MessageToMessageCodec[FMLProxyPacket, BaseMessage[T]] { + def encode( + ctx: ChannelHandlerContext, + msg: BaseMessage[T], + out: util.List[AnyRef] + ) { val buff = Unpooled.buffer() val writer = new ObjectOutputStream(new ByteBufOutputStream(buff)) writer.writeObject(msg) - val pkt = new FMLProxyPacket(buff, ctx.channel.attr(NetworkRegistry.FML_CHANNEL).get) + val pkt = new FMLProxyPacket( + buff, + ctx.channel.attr(NetworkRegistry.FML_CHANNEL).get + ) out.add(pkt) } - def decode(ctx: ChannelHandlerContext, msg: FMLProxyPacket, out: util.List[AnyRef]) { + def decode( + ctx: ChannelHandlerContext, + msg: FMLProxyPacket, + out: util.List[AnyRef] + ) { try { - val reader = new ObjectInputStream(new ByteBufInputStream(msg.payload())) { + val reader = new ObjectInputStream( + new ByteBufInputStream(msg.payload()) + ) { override def resolveClass(desc: ObjectStreamClass): Class[_] = { val name = desc.getName - if (!validClassCache.computeIfAbsent(name, new JavaFunction[String, BoxedBoolean]() { - override def apply(v1: String): BoxedBoolean = - validClasses.contains(v1) || validClassPrefixes.exists(v1.startsWith) - })) { - BdLib.log.warn("Received disallowed message component class: {}", name) + if ( + !validClassCache.computeIfAbsent( + name, + new JavaFunction[String, BoxedBoolean]() { + override def apply(v1: String): BoxedBoolean = + validClasses.contains(v1) || validClassPrefixes + .exists(v1.startsWith) + } + ) + ) { + BdLib.log.warn( + "Received disallowed message component class: {}", + name + ) if (enforceFilter) { throw new InvalidClassException(name) } @@ -60,11 +88,11 @@ class SerializedMessageCodec[T <: NetChannel] extends MessageToMessageCodec[FMLP } object SerializedMessageCodec { - /** - * A hardcoded list of possible loaded - and probably safe - classes - * - * Can be extended via configurations - */ + + /** A hardcoded list of possible loaded - and probably safe - classes + * + * Can be extended via configurations + */ val validClasses: mutable.Set[String] = mutable.Set( "scala.Enumeration", "scala.Enumeration$Val", @@ -74,18 +102,14 @@ object SerializedMessageCodec { "scala.Enumeration$ValueSet$", "scala.collection.immutable.BitSet", "scala.collection.immutable.BitSet$BitSet1", - "java.lang.Float", "java.lang.Double", "java.lang.Integer", "java.lang.Number", - "net.bdew.lib.multiblock.data.RSMode$", - "[B", "net.bdew.lib.network.NBTTagCompoundSerialize", "net.bdew.lib.network.ItemStackSerialize", - "net.bdew.lib.network.BaseMessage", "net.bdew.lib.multiblock.data.MsgOutputCfgRSMode", "net.bdew.lib.multiblock.network.MsgOutputCfg", @@ -94,7 +118,6 @@ object SerializedMessageCodec { // ae2stuff stuff "net.bdew.ae2stuff.items.visualiser.VisualisationData", "net.bdew.ae2stuff.items.visualiser.VisualisationModes$", - "net.bdew.ae2stuff.network.MsgSetLock", "net.bdew.ae2stuff.network.MsgSetRecipe", "net.bdew.ae2stuff.network.MsgSetRecipe2", @@ -126,7 +149,8 @@ object SerializedMessageCodec { // add other bdew mods in configurations if you need. this is as far as I'd like to support - glee8e ) val validClassPrefixes: mutable.Set[String] = mutable.Set() - val validClassCache: ConcurrentHashMap[String, BoxedBoolean] = new ConcurrentHashMap[String, BoxedBoolean]() + val validClassCache: ConcurrentHashMap[String, BoxedBoolean] = + new ConcurrentHashMap[String, BoxedBoolean]() var enforceFilter: Boolean = true def addValidClass(clazz: Class[_]): Unit = { @@ -138,7 +162,9 @@ object SerializedMessageCodec { // recursively add all serialized fields val desc = ObjectStreamClass.lookup(clazz) if (desc != null) - desc.getFields.map { it => it.getType }.foreach(SerializedMessageCodec.addValidClass) + desc.getFields + .map { it => it.getType } + .foreach(SerializedMessageCodec.addValidClass) } } } diff --git a/src/main/scala/net/bdew/lib/player/PlayerCache.scala b/src/main/scala/net/bdew/lib/player/PlayerCache.scala index 824d95b..d0878fd 100644 --- a/src/main/scala/net/bdew/lib/player/PlayerCache.scala +++ b/src/main/scala/net/bdew/lib/player/PlayerCache.scala @@ -54,7 +54,9 @@ class PlayerCache[T] extends mutable.Map[EntityPlayer, T] { def handlePlayerLogout(ev: PlayerLoggedOutEvent) = reset(ev.player) @SubscribeEvent - def handlePlayerChangedDimension(ev: PlayerChangedDimensionEvent) = reset(ev.player) + def handlePlayerChangedDimension(ev: PlayerChangedDimensionEvent) = reset( + ev.player + ) @SubscribeEvent def handlePlayerRespawn(ev: PlayerRespawnEvent) = reset(ev.player) diff --git a/src/main/scala/net/bdew/lib/power/DataSlotPower.scala b/src/main/scala/net/bdew/lib/power/DataSlotPower.scala index a05f563..1a196de 100644 --- a/src/main/scala/net/bdew/lib/power/DataSlotPower.scala +++ b/src/main/scala/net/bdew/lib/power/DataSlotPower.scala @@ -14,15 +14,16 @@ import net.bdew.lib.data.base.{DataSlot, DataSlotContainer, UpdateKind} import net.bdew.lib.machine.PoweredMachine import net.minecraft.nbt.NBTTagCompound -case class DataSlotPower(name: String, parent: DataSlotContainer) extends DataSlot { +case class DataSlotPower(name: String, parent: DataSlotContainer) + extends DataSlot { updateKind = Set(UpdateKind.GUI, UpdateKind.SAVE) - var stored = 0F - var capacity = 0F - var maxReceive = 0F + var stored = 0f + var capacity = 0f + var maxReceive = 0f def inject(v: Float, simulate: Boolean): Float = { - val canAdd = Misc.clamp(v, 0F, Misc.min(capacity - stored, maxReceive)) + val canAdd = Misc.clamp(v, 0f, Misc.min(capacity - stored, maxReceive)) if ((canAdd > 0) && !simulate) { stored += canAdd parent.dataSlotChanged(this) @@ -31,7 +32,7 @@ case class DataSlotPower(name: String, parent: DataSlotContainer) extends DataSl } def extract(v: Float, simulate: Boolean): Float = { - val canExtract = Misc.clamp(v, 0F, stored) + val canExtract = Misc.clamp(v, 0f, stored) if ((canExtract > 0) && !simulate) { stored -= canExtract if (stored < 1) stored = 0 @@ -62,5 +63,3 @@ case class DataSlotPower(name: String, parent: DataSlotContainer) extends DataSl } } } - - diff --git a/src/main/scala/net/bdew/lib/power/ItemPoweredBase.scala b/src/main/scala/net/bdew/lib/power/ItemPoweredBase.scala index fc040c4..17140df 100644 --- a/src/main/scala/net/bdew/lib/power/ItemPoweredBase.scala +++ b/src/main/scala/net/bdew/lib/power/ItemPoweredBase.scala @@ -24,7 +24,10 @@ trait ItemPoweredBase extends Item { } def useCharge(stack: ItemStack, uses: Int = 1, player: EntityLivingBase) { - setCharge(stack, Misc.clamp(getCharge(stack) - uses * mjPerCharge, 0, maxCharge)) + setCharge( + stack, + Misc.clamp(getCharge(stack) - uses * mjPerCharge, 0, maxCharge) + ) } def hasCharges(stack: ItemStack) = getCharge(stack) >= mjPerCharge @@ -36,7 +39,14 @@ trait ItemPoweredBase extends Item { } def updateDamage(stack: ItemStack) { - setDamage(stack, Misc.clamp((100 * (1 - getCharge(stack).toFloat / maxCharge)).round, 1, 100)) + setDamage( + stack, + Misc.clamp( + (100 * (1 - getCharge(stack).toFloat / maxCharge)).round, + 1, + 100 + ) + ) } def stackWithCharge(charge: Int): ItemStack = { @@ -45,5 +55,6 @@ trait ItemPoweredBase extends Item { return n } - override def setDamage(stack: ItemStack, damage: Int) = super.setDamage(stack, Misc.clamp(damage, 1, 100)) + override def setDamage(stack: ItemStack, damage: Int) = + super.setDamage(stack, Misc.clamp(damage, 1, 100)) } diff --git a/src/main/scala/net/bdew/lib/power/TileBaseProcessor.scala b/src/main/scala/net/bdew/lib/power/TileBaseProcessor.scala index 85c2219..32f47f6 100644 --- a/src/main/scala/net/bdew/lib/power/TileBaseProcessor.scala +++ b/src/main/scala/net/bdew/lib/power/TileBaseProcessor.scala @@ -15,14 +15,16 @@ import net.bdew.lib.machine.ProcessorMachine import net.bdew.lib.tile.TileExtended import net.bdew.lib.tile.inventory.{PersistentInventoryTile, SidedInventory} -abstract class TileBaseProcessor extends TileExtended -with TileDataSlots -with PersistentInventoryTile -with SidedInventory -with TilePoweredBase { +abstract class TileBaseProcessor + extends TileExtended + with TileDataSlots + with PersistentInventoryTile + with SidedInventory + with TilePoweredBase { def cfg: ProcessorMachine val power = DataSlotPower("power", this) - val progress = DataSlotFloat("progress", this).setUpdate(UpdateKind.SAVE, UpdateKind.GUI) + val progress = + DataSlotFloat("progress", this).setUpdate(UpdateKind.SAVE, UpdateKind.GUI) configurePower(cfg) @@ -36,7 +38,10 @@ with TilePoweredBase { if (isWorking) { if ((progress < 1) && (power.stored > cfg.activationEnergy)) { - val maxConsume = Math.min(Math.max(cfg.powerUseRate * power.stored, cfg.activationEnergy), cfg.mjPerItem * (1 - progress)) + val maxConsume = Math.min( + Math.max(cfg.powerUseRate * power.stored, cfg.activationEnergy), + cfg.mjPerItem * (1 - progress) + ) val consumed = power.extract(maxConsume, false) progress += consumed / cfg.mjPerItem } @@ -49,18 +54,15 @@ with TilePoweredBase { } } - /** - * Return true when an operation is in progress - */ + /** Return true when an operation is in progress + */ def isWorking: Boolean - /** - * Try starting a new operation, return true if successful - */ + /** Try starting a new operation, return true if successful + */ def tryStart(): Boolean - /** - * Perform output when operation is done, return true if successful - */ + /** Perform output when operation is done, return true if successful + */ def tryFinish(): Boolean } diff --git a/src/main/scala/net/bdew/lib/power/WidgetPowerGauge.scala b/src/main/scala/net/bdew/lib/power/WidgetPowerGauge.scala index 10e209a..7964e50 100644 --- a/src/main/scala/net/bdew/lib/power/WidgetPowerGauge.scala +++ b/src/main/scala/net/bdew/lib/power/WidgetPowerGauge.scala @@ -15,7 +15,8 @@ import net.bdew.lib.gui.{Point, Rect, Texture} import scala.collection.mutable -class WidgetPowerGauge(val rect: Rect, texture: Texture, dSlot: DataSlotPower) extends Widget { +class WidgetPowerGauge(val rect: Rect, texture: Texture, dSlot: DataSlotPower) + extends Widget { val a = rect.map(_.round) override def draw(mouse: Point) { @@ -23,5 +24,8 @@ class WidgetPowerGauge(val rect: Rect, texture: Texture, dSlot: DataSlotPower) e parent.drawTextureInterpolate(rect, texture, 0, 1 - fill, 1, 1) } - override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = tip += DecFormat.round(dSlot.stored) + "/" + DecFormat.round(dSlot.capacity) + " MJ" + override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = + tip += DecFormat.round(dSlot.stored) + "/" + DecFormat.round( + dSlot.capacity + ) + " MJ" } diff --git a/src/main/scala/net/bdew/lib/recipes/RecipeLoader.scala b/src/main/scala/net/bdew/lib/recipes/RecipeLoader.scala index dc46907..fd86cb0 100644 --- a/src/main/scala/net/bdew/lib/recipes/RecipeLoader.scala +++ b/src/main/scala/net/bdew/lib/recipes/RecipeLoader.scala @@ -18,74 +18,90 @@ import net.minecraft.block.Block import net.minecraft.item.{Item, ItemStack} import net.minecraftforge.oredict.{OreDictionary, ShapelessOreRecipe} -/** - * Main recipe loader class - * The input file is parsed by [[net.bdew.lib.recipes.RecipeParser]] - * Into a list of [[net.bdew.lib.recipes.ConfigStatement]] subclasses - * That are then executed here - */ +/** Main recipe loader class The input file is parsed by + * [[net.bdew.lib.recipes.RecipeParser]] Into a list of + * [[net.bdew.lib.recipes.ConfigStatement]] subclasses That are then executed + * here + */ class RecipeLoader { - /** - * Create a new parser, override in subclasses to use an extended parser - * @return New ConfigParser (or subclass) instance - */ + /** Create a new parser, override in subclasses to use an extended parser + * @return + * New ConfigParser (or subclass) instance + */ def newParser() = new RecipeParser() - /** - * Current map of recipe characters to parser item references - */ - var currCharMap = Map.empty[Char, StackRef].withDefault(x => error("Undefined recipe character '%s'", x)) + /** Current map of recipe characters to parser item references + */ + var currCharMap = Map + .empty[Char, StackRef] + .withDefault(x => error("Undefined recipe character '%s'", x)) - /** - * Current map of class macros - */ - var currClassMacros = Map.empty[String, String].withDefault(x => error("Undefined class macro '%s'", x)) + /** Current map of class macros + */ + var currClassMacros = Map + .empty[String, String] + .withDefault(x => error("Undefined class macro '%s'", x)) - /** - * Triggers an error with formatted string - */ - def error(msg: String, params: Any*) = throw new StatementError(msg.format(params: _*)) + /** Triggers an error with formatted string + */ + def error(msg: String, params: Any*) = throw new StatementError( + msg.format(params: _*) + ) - /** - * List of unprocessed recipe statements - */ + /** List of unprocessed recipe statements + */ var recipeStatements = List.empty[RecipeStatement] - /** - * Looks up a recipe component - * @param s Parser ItemStack reference - * @return ItemStack or String that can be used as recipe components in MC functions - */ + /** Looks up a recipe component + * @param s + * Parser ItemStack reference + * @return + * ItemStack or String that can be used as recipe components in MC + * functions + */ def getRecipeComponent(s: StackRef): AnyRef = s match { case StackOreDict(id) => id - case StackMacro(ch) => getRecipeComponent(currCharMap(ch)) - case _ => getConcreteStack(s) + case StackMacro(ch) => getRecipeComponent(currCharMap(ch)) + case _ => getConcreteStack(s) } - /** - * Resolve class name if it's a macro - */ + /** Resolve class name if it's a macro + */ def getRealClassName(s: String) = { if (s.startsWith("$")) currClassMacros(s.stripPrefix("$")) else s } - /** - * Sanitize items from reflection - * @param x The item - * @param source Human readable source (used in errors and warnings) - * @param meta Metadata or damage - * @param cnt Stack size - * @return - */ - def sanitizeReflectedItem(x: AnyRef, source: String, meta: Int, cnt: Int): ItemStack = x match { + + /** Sanitize items from reflection + * @param x + * The item + * @param source + * Human readable source (used in errors and warnings) + * @param meta + * Metadata or damage + * @param cnt + * Stack size + * @return + */ + def sanitizeReflectedItem( + x: AnyRef, + source: String, + meta: Int, + cnt: Int + ): ItemStack = x match { case x: ItemStack => val l = x.copy() l.stackSize = cnt if (meta != OreDictionary.WILDCARD_VALUE && meta != l.getItemDamage) { - BdLib.logWarn("%s requested with meta %d but specifies %d", source, meta, l.getItemDamage) + BdLib.logWarn( + "%s requested with meta %d but specifies %d", + source, + meta, + l.getItemDamage + ) l.setItemDamage(meta) } return l @@ -94,39 +110,68 @@ class RecipeLoader { case x: Block => return new ItemStack(x, cnt, meta) case _ => - error("%s is %s which cannot be translated to an ItemStack", source, x.getClass.getName) + error( + "%s is %s which cannot be translated to an ItemStack", + source, + x.getClass.getName + ) } - /** - * Fetches an ItemStack using reflection from static fields - * Item and Block instances are converted to ItemStacks - * @param clsName Name of class to fetch from (can be a class macro) - * @param fldName Field name - * @param meta Metadata or damage - * @param cnt Stack size - * @return Matching item stack - */ - def reflectStack(clsName: String, fldName: String, meta: Int, cnt: Int): ItemStack = { + /** Fetches an ItemStack using reflection from static fields Item and Block + * instances are converted to ItemStacks + * @param clsName + * Name of class to fetch from (can be a class macro) + * @param fldName + * Field name + * @param meta + * Metadata or damage + * @param cnt + * Stack size + * @return + * Matching item stack + */ + def reflectStack( + clsName: String, + fldName: String, + meta: Int, + cnt: Int + ): ItemStack = { val realName = getRealClassName(clsName) val fld = Class.forName(realName).getField(fldName).get(null) - return sanitizeReflectedItem(fld, "%s.%s".format(realName, fldName), meta, cnt) + return sanitizeReflectedItem( + fld, + "%s.%s".format(realName, fldName), + meta, + cnt + ) } - /** - * Fetches an ItemStack using reflection from static getters - * Item and Block instances are converted to ItemStacks - * @param clsName Name of class to fetch from (can be a class macro) - * @param method Method name - * @param param Parameter to method - * @param meta Metadata or damage - * @param cnt Stack size - * @return Matching item stack - */ - def reflectStackGetter(clsName: String, method: String, param: String, meta: Int, cnt: Int): ItemStack = { + /** Fetches an ItemStack using reflection from static getters Item and Block + * instances are converted to ItemStacks + * @param clsName + * Name of class to fetch from (can be a class macro) + * @param method + * Method name + * @param param + * Parameter to method + * @param meta + * Metadata or damage + * @param cnt + * Stack size + * @return + * Matching item stack + */ + def reflectStackGetter( + clsName: String, + method: String, + param: String, + meta: Int, + cnt: Int + ): ItemStack = { var realName: String = clsName var realMethod: String = method - //Some acrobatics to allow use with macros, even bare ones like $foo(bar) + // Some acrobatics to allow use with macros, even bare ones like $foo(bar) if ((realName.length == 0) && realMethod.startsWith("$")) { val v = getRealClassName(realMethod).split('.').reverse @@ -137,63 +182,102 @@ class RecipeLoader { realName = getRealClassName(clsName) } - val res = Class.forName(realName).getMethod(realMethod, classOf[String]).invoke(null, param) - return sanitizeReflectedItem(res, "%s.%s(%s)".format(realName, realMethod, param), meta, cnt) + val res = Class + .forName(realName) + .getMethod(realMethod, classOf[String]) + .invoke(null, param) + return sanitizeReflectedItem( + res, + "%s.%s(%s)".format(realName, realMethod, param), + meta, + cnt + ) } - /** - * Returns all possible ItemStacks that match a reference - * Currently everything except OreDictionary references just returns one item - * @param s Parser ItemStack reference - * @param cnt Stack size - * @return List of matching ItemStacks - */ - def getAllConcreteStacks(s: StackRef, cnt: Int = 1): Iterable[ItemStack] = s match { - case StackOreDict(id) => - import scala.collection.JavaConversions._ - val c = OreDictionary.getOres(id).map(_.copy()) - c.foreach(_.stackSize = cnt) - return c - case _ => Seq(getConcreteStack(s)) - } + /** Returns all possible ItemStacks that match a reference Currently + * everything except OreDictionary references just returns one item + * @param s + * Parser ItemStack reference + * @param cnt + * Stack size + * @return + * List of matching ItemStacks + */ + def getAllConcreteStacks(s: StackRef, cnt: Int = 1): Iterable[ItemStack] = + s match { + case StackOreDict(id) => + import scala.collection.JavaConversions._ + val c = OreDictionary.getOres(id).map(_.copy()) + c.foreach(_.stackSize = cnt) + return c + case _ => Seq(getConcreteStack(s)) + } def notNull[T](v: T, err: => String) = if (v == null) error(err) else v - /** - * Returns an ItemStack that match a reference - * This is the main StackRef resolution method - * @param s Parser ItemStack reference - * @param cnt Stack size - * @return A matching ItemStack - */ + /** Returns an ItemStack that match a reference This is the main StackRef + * resolution method + * @param s + * Parser ItemStack reference + * @param cnt + * Stack size + * @return + * A matching ItemStack + */ def getConcreteStack(s: StackRef, cnt: Int = 1): ItemStack = s match { case StackOreDict(id) => val l = OreDictionary.getOres(id) - if (l.size == 0) error("Concrete ItemStack requested for OD entry '%s' that is empty", id) + if (l.size == 0) + error( + "Concrete ItemStack requested for OD entry '%s' that is empty", + id + ) val s = l.get(0).copy() s.stackSize = cnt BdLib.logDebug("Concrete ItemStack for OD entry '%s' -> %s", id, s) return s case StackMacro(ch) => getConcreteStack(currCharMap(ch), cnt) case StackGeneric(mod, id) => - notNull(GameRegistry.findItemStack(mod, id, cnt), "Stack not found %s:%s".format(mod, id)) + notNull( + GameRegistry.findItemStack(mod, id, cnt), + "Stack not found %s:%s".format(mod, id) + ) case StackBlock(mod, id, meta) => - val block = notNull(GameRegistry.findBlock(mod, id), "Block not found %s:%s".format(mod, id)) + val block = notNull( + GameRegistry.findBlock(mod, id), + "Block not found %s:%s".format(mod, id) + ) if (Item.getItemFromBlock(block) == null) - error("The block '%s:%s' does not have a valid matching item registered and thus can't be used in recipes", mod, id) + error( + "The block '%s:%s' does not have a valid matching item registered and thus can't be used in recipes", + mod, + id + ) new ItemStack(block, cnt, meta) case StackItem(mod, id, meta) => - new ItemStack(notNull(GameRegistry.findItem(mod, id), "Item not found %s:%s".format(mod, id)), cnt, meta) + new ItemStack( + notNull( + GameRegistry.findItem(mod, id), + "Item not found %s:%s".format(mod, id) + ), + cnt, + meta + ) case StackReflect(cls, field, meta) => reflectStack(cls, field, meta, cnt) - case StackGetter(cls, method, param, meta) => reflectStackGetter(cls, method, param, meta, cnt) + case StackGetter(cls, method, param, meta) => + reflectStackGetter(cls, method, param, meta, cnt) } - /** - * Looks up all characters used in the recipe - * @param s The pattern - * @return Map from character to recipe components and a boolean that means OD-aware methods should be used - */ - def resolveRecipeComponents(s: Iterable[Char]): (Map[Char, AnyRef], Boolean) = { + /** Looks up all characters used in the recipe + * @param s + * The pattern + * @return + * Map from character to recipe components and a boolean that means + * OD-aware methods should be used + */ + def resolveRecipeComponents( + s: Iterable[Char] + ): (Map[Char, AnyRef], Boolean) = { var comp = Map.empty[Char, AnyRef] var needOd = false for (x <- s if !comp.contains(x) && x != '_') { @@ -206,13 +290,18 @@ class RecipeLoader { return (comp, needOd) } - /** - * Helper to remove recipes from lists - * @param list list to check - * @param res crafting result to remove - * @return cleaned list - */ - def clearStatements(list: List[RecipeStatement], res: StackRef): List[RecipeStatement] = { + /** Helper to remove recipes from lists + * @param list + * list to check + * @param res + * crafting result to remove + * @return + * cleaned list + */ + def clearStatements( + list: List[RecipeStatement], + res: StackRef + ): List[RecipeStatement] = { list flatMap { case x: CraftingStatement => if (res == x.result) { @@ -222,14 +311,19 @@ class RecipeLoader { case RsRecipes(inner) => Some(RsRecipes(clearStatements(inner, res))) case RsConditional(cnd, thn, els) => - Some(RsConditional(cnd, clearStatements(thn, res), clearStatements(els, res))) + Some( + RsConditional( + cnd, + clearStatements(thn, res), + clearStatements(els, res) + ) + ) case x => Some(x) } } - /** - * Checks a condition and returns the result - */ + /** Checks a condition and returns the result + */ def resolveCondition(cond: Condition): Boolean = cond match { case CndHaveMod(mod) => Misc.haveModVersion(mod) @@ -237,17 +331,17 @@ class RecipeLoader { ModAPIManager.INSTANCE.hasAPI(api) case CndHaveOD(od) => OreDictionary.getOres(od).size() > 0 - case CndNOT(cnd) => !resolveCondition(cnd) + case CndNOT(cnd) => !resolveCondition(cnd) case CndAND(c1, c2) => resolveCondition(c1) && resolveCondition(c2) - case CndOR(c1, c2) => resolveCondition(c1) || resolveCondition(c2) + case CndOR(c1, c2) => resolveCondition(c1) || resolveCondition(c2) case x => error("Can't process %s - this is a programing bug!", x) } - /** - * Process a single statement, override this to add more statements - * @param s The statement - */ + /** Process a single statement, override this to add more statements + * @param s + * The statement + */ def processConfigStatement(s: ConfigStatement): Unit = s match { case CsConditionalConfig(cnd, thn, els) => if (resolveCondition(cnd)) { @@ -269,10 +363,10 @@ class RecipeLoader { BdLib.logError("Can't process %s - this is a programing bug!", x) } - /** - * Process a single recipe statement - * @param st The statement - */ + /** Process a single recipe statement + * @param st + * The statement + */ def processRecipeStatement(st: RecipeStatement) = st match { case RsCharAssign(c, r) => currCharMap += (c -> r) @@ -318,7 +412,13 @@ class RecipeLoader { BdLib.logDebug("Done... result=%s, od=%s", resStack, needOd) case RsRecipeSmelting(in, out, cnt, xp) => - BdLib.logDebug("Adding smelting recipe %s => %s * %d (%f xp)", in, out, cnt, xp) + BdLib.logDebug( + "Adding smelting recipe %s => %s * %d (%f xp)", + in, + out, + cnt, + xp + ) val outStack = getConcreteStack(out, cnt) if (outStack.getItemDamage == OreDictionary.WILDCARD_VALUE) { BdLib.logDebug("Result meta is unset, defaulting to 0") @@ -355,10 +455,9 @@ class RecipeLoader { BdLib.logError("Can't process %s - this is a programing bug!", x) } - /** - * Processes recipe statements in a new context - * Any changes to mutable state will not persist when this method returns - */ + /** Processes recipe statements in a new context Any changes to mutable state + * will not persist when this method returns + */ def processRecipeStatementsInSubcontext(list: List[RecipeStatement]) = { val oldCharMap = currCharMap val oldClassMacros = currClassMacros @@ -370,19 +469,18 @@ class RecipeLoader { } } - /** - * Process main recipe statements list, clear the list afterwards - */ + /** Process main recipe statements list, clear the list afterwards + */ def processRecipeStatements() { BdLib.logDebug("Processing %d recipe statements", recipeStatements.size) processRecipeStatementsSafe(recipeStatements) recipeStatements = List.empty } - /** - * Process a list of recipe statements and catch all exceptions - * @param list The list to process - */ + /** Process a list of recipe statements and catch all exceptions + * @param list + * The list to process + */ def processRecipeStatementsSafe(list: List[RecipeStatement]) { for (s <- list) { try { @@ -396,10 +494,10 @@ class RecipeLoader { } } - /** - * Process a list of config statements and catch all exceptions - * @param r The list to process - */ + /** Process a list of config statements and catch all exceptions + * @param r + * The list to process + */ def processConfigStatementsSafe(r: List[ConfigStatement]): Unit = { for (s <- r) { try { diff --git a/src/main/scala/net/bdew/lib/recipes/RecipeParser.scala b/src/main/scala/net/bdew/lib/recipes/RecipeParser.scala index a8d1daa..b6eae9f 100644 --- a/src/main/scala/net/bdew/lib/recipes/RecipeParser.scala +++ b/src/main/scala/net/bdew/lib/recipes/RecipeParser.scala @@ -18,7 +18,8 @@ import scala.util.parsing.combinator._ class RecipeParser extends JavaTokenParsers { // Allows C-style comments - protected override val whiteSpace = """(\s|//.*|(?m)/\*(\*(?!/)|[^*])*\*/)+""".r + protected override val whiteSpace = + """(\s|//.*|(?m)/\*(\*(?!/)|[^*])*\*/)+""".r // Simple integer without signs def int = "\\d+".r ^^ (_.toInt) @@ -42,7 +43,9 @@ class RecipeParser extends JavaTokenParsers { def recipeDuplet = repN(2, recipeChar | "_") ^^ (_.mkString("")) // Quoted string with escape characters - def unescapeStr = stringLiteral ^^ { case x => StringEscapeUtils.unescapeJava(x.substring(1, x.length - 1)) } + def unescapeStr = stringLiteral ^^ { case x => + StringEscapeUtils.unescapeJava(x.substring(1, x.length - 1)) + } // Identifier or quoted string def str = ident | unescapeStr @@ -50,9 +53,15 @@ class RecipeParser extends JavaTokenParsers { // === Item references === def specOD = "OD" ~> ":" ~> ident ^^ StackOreDict - def specBlock = "B" ~> ":" ~> maybeModId ~ str ~ maybeMeta ^^ { case m ~ n ~ i => StackBlock(m, n, i) } - def specItem = "I" ~> ":" ~> maybeModId ~ str ~ maybeMeta ^^ { case m ~ n ~ i => StackItem(m, n, i) } - def specGenericStack = "S" ~> ":" ~> str ~ ":" ~ str ^^ { case m ~ c ~ n => StackGeneric(m, n) } + def specBlock = "B" ~> ":" ~> maybeModId ~ str ~ maybeMeta ^^ { + case m ~ n ~ i => StackBlock(m, n, i) + } + def specItem = "I" ~> ":" ~> maybeModId ~ str ~ maybeMeta ^^ { + case m ~ n ~ i => StackItem(m, n, i) + } + def specGenericStack = "S" ~> ":" ~> str ~ ":" ~ str ^^ { case m ~ c ~ n => + StackGeneric(m, n) + } def specMacro = "$" ~> recipeChar ^^ StackMacro def specReflect = clsPath ~ ("[" ~> ident <~ "]") ~ maybeMeta ^^ { @@ -63,7 +72,8 @@ class RecipeParser extends JavaTokenParsers { case (p ~ cl) ~ n ~ m => StackGetter(p.mkString("."), cl, n, m) } - def spec = specBlock | specItem | specOD | specGenericStack | specGetter | specReflect | specMacro + def spec = + specBlock | specItem | specOD | specGenericStack | specGetter | specReflect | specMacro // Spec with possible number of items def specWithCount = spec ~ ("*" ~> int).? @@ -75,61 +85,87 @@ class RecipeParser extends JavaTokenParsers { def cndHaveOD = "HaveOD" ~> str ^^ CndHaveOD def cndNOT = "!" ~> condition ^^ CndNOT - def cndOR = "(" ~> condition ~ "||" ~ condition <~ ")" ^^ { case c1 ~ or ~ c2 => CndOR(c1, c2) } - def cndAND = "(" ~> condition ~ "&&" ~ condition <~ ")" ^^ { case c1 ~ and ~ c2 => CndAND(c1, c2) } + def cndOR = "(" ~> condition ~ "||" ~ condition <~ ")" ^^ { + case c1 ~ or ~ c2 => CndOR(c1, c2) + } + def cndAND = "(" ~> condition ~ "&&" ~ condition <~ ")" ^^ { + case c1 ~ and ~ c2 => CndAND(c1, c2) + } - def condition: Parser[Condition] = cndHaveAPI | cndHaveMod | cndHaveOD | cndNOT | cndOR | cndAND + def condition: Parser[Condition] = + cndHaveAPI | cndHaveMod | cndHaveOD | cndNOT | cndOR | cndAND // === Blocks === - def recipesSubBlock = "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ RsRecipes - def recipesTopBlock = "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ CsRecipeBlock + def recipesSubBlock = + "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ RsRecipes + def recipesTopBlock = + "recipes" ~> ("{" ~> recipeStatements <~ "}") ^^ CsRecipeBlock - def conditionRecipes = "if" ~> condition ~ ("{" ~> recipeStatements <~ "}") ~ ("else" ~> "{" ~> recipeStatements <~ "}").? ^^ { - case cond ~ thn ~ els => new RsConditional(cond, thn, els.getOrElse(List.empty)) + def conditionRecipes = + "if" ~> condition ~ ("{" ~> recipeStatements <~ "}") ~ ("else" ~> "{" ~> recipeStatements <~ "}").? ^^ { + case cond ~ thn ~ els => + new RsConditional(cond, thn, els.getOrElse(List.empty)) + } + + def conditionConfig = + "if" ~> condition ~ ("<<" ~> configStatements <~ ">>") ~ ("else" ~> "<<" ~> configStatements <~ ">>").? ^^ { + case cond ~ thn ~ els => + new CsConditionalConfig(cond, thn, els.getOrElse(List.empty)) + } + + def conditionBridge = conditionRecipes ^^ { case cond => + CsRecipeBlock(List(cond)) } - def conditionConfig = "if" ~> condition ~ ("<<" ~> configStatements <~ ">>") ~ ("else" ~> "<<" ~> configStatements <~ ">>").? ^^ { - case cond ~ thn ~ els => new CsConditionalConfig(cond, thn, els.getOrElse(List.empty)) - } - - def conditionBridge = conditionRecipes ^^ { case cond => CsRecipeBlock(List(cond)) } - // === Statements === - def charSpec = recipeChar ~ "=" ~ spec ^^ { - case ch ~ eq ~ spec => new RsCharAssign(ch, spec) + def charSpec = recipeChar ~ "=" ~ spec ^^ { case ch ~ eq ~ spec => + new RsCharAssign(ch, spec) } - def classMacro = ("def" ~> ident <~ "=") ~ clsPath ^^ { - case id ~ (p ~ cl) => RsClassMacro(id, (p :+ cl).mkString(".")) + def classMacro = ("def" ~> ident <~ "=") ~ clsPath ^^ { case id ~ (p ~ cl) => + RsClassMacro(id, (p :+ cl).mkString(".")) } - def recipeShaped3x3 = recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ~ recipeTriplet ^^ { - case r1 ~ r2 ~ (res ~ n) ~ r3 => RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1)) - } + def recipeShaped3x3 = + recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ~ recipeTriplet ^^ { + case r1 ~ r2 ~ (res ~ n) ~ r3 => + RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1)) + } - def recipeShaped2x2 = recipeDuplet ~ recipeDuplet ~ ("=>" ~> specWithCount) ^^ { - case r1 ~ r2 ~ (res ~ n) => RsRecipeShaped(Seq(r1, r2), res, n.getOrElse(1)) - } + def recipeShaped2x2 = + recipeDuplet ~ recipeDuplet ~ ("=>" ~> specWithCount) ^^ { + case r1 ~ r2 ~ (res ~ n) => + RsRecipeShaped(Seq(r1, r2), res, n.getOrElse(1)) + } - def recipeShaped9 = recipeTriplet ~ recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ^^ { - case r1 ~ r2 ~ r3 ~ (res ~ n) => RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1)) - } + def recipeShaped9 = + recipeTriplet ~ recipeTriplet ~ recipeTriplet ~ ("=>" ~> specWithCount) ^^ { + case r1 ~ r2 ~ r3 ~ (res ~ n) => + RsRecipeShaped(Seq(r1, r2, r3), res, n.getOrElse(1)) + } - def recipeShapeless = "shapeless" ~> ":" ~> recipeChar.+ ~ ("=>" ~> specWithCount) ^^ { - case r ~ (res ~ n) => RsRecipeShapeless(r.mkString(""), res, n.getOrElse(1)) - } + def recipeShapeless = + "shapeless" ~> ":" ~> recipeChar.+ ~ ("=>" ~> specWithCount) ^^ { + case r ~ (res ~ n) => + RsRecipeShapeless(r.mkString(""), res, n.getOrElse(1)) + } - def recipeSmelting = "smelt" ~> ":" ~> spec ~ ("=>" ~> specWithCount) ~ ("+" ~> decimalNumber <~ "xp").? ^^ { - case in ~ (out ~ n) ~ xp => RsRecipeSmelting(in, out, n.getOrElse(1), xp.getOrElse("0").toFloat) - } + def recipeSmelting = + "smelt" ~> ":" ~> spec ~ ("=>" ~> specWithCount) ~ ("+" ~> decimalNumber <~ "xp").? ^^ { + case in ~ (out ~ n) ~ xp => + RsRecipeSmelting(in, out, n.getOrElse(1), xp.getOrElse("0").toFloat) + } - def regOreDict = "regOreDict" ~> ":" ~> spec ~ "@WILDCARD".? ~ ("=>" ~> str) ^^ { - case spec ~ wildcard ~ id => RsRegOredict(id, spec, wildcard.isDefined) - } + def regOreDict = + "regOreDict" ~> ":" ~> spec ~ "@WILDCARD".? ~ ("=>" ~> str) ^^ { + case spec ~ wildcard ~ id => RsRegOredict(id, spec, wildcard.isDefined) + } - def clearRecipes = "clearRecipes" ~> ":" ~> spec ^^ { case sp => CsClearRecipes(sp) } + def clearRecipes = "clearRecipes" ~> ":" ~> spec ^^ { case sp => + CsClearRecipes(sp) + } def recipeStatement: Parser[RecipeStatement] = ( charSpec @@ -143,14 +179,14 @@ class RecipeParser extends JavaTokenParsers { | recipeShapeless | recipeSmelting | regOreDict - ) + ) def configStatement: Parser[ConfigStatement] = ( recipesTopBlock | clearRecipes | conditionBridge | conditionConfig - ) + ) def configStatements = configStatement.* def recipeStatements = recipeStatement.* @@ -158,7 +194,8 @@ class RecipeParser extends JavaTokenParsers { def doParse(r: Reader): List[ConfigStatement] = { parseAll(configStatements, r) match { case Success(res, next) => return res - case NoSuccess(msg, next) => sys.error("Config parsing failed at %s: %s".format(next.pos, msg)) + case NoSuccess(msg, next) => + sys.error("Config parsing failed at %s: %s".format(next.pos, msg)) } } } diff --git a/src/main/scala/net/bdew/lib/recipes/RecipesHelper.scala b/src/main/scala/net/bdew/lib/recipes/RecipesHelper.scala index 94403e5..786db77 100644 --- a/src/main/scala/net/bdew/lib/recipes/RecipesHelper.scala +++ b/src/main/scala/net/bdew/lib/recipes/RecipesHelper.scala @@ -15,19 +15,35 @@ import cpw.mods.fml.common.FMLCommonHandler import net.bdew.lib.{BdLib, Misc} object RecipesHelper { - /** - * Perform full loading of a set of config - * @param modName Name of the mod, used in logging and errors - * @param listResource Resource Name of the internal config list file - * @param configDir Base path to user config giles - * @param resBaseName Base resource name for internal config files - * @param loader Loader instance - */ - def loadConfigs(modName: String, listResource: String, configDir: File, resBaseName: String, loader: RecipeLoader) { + + /** Perform full loading of a set of config + * @param modName + * Name of the mod, used in logging and errors + * @param listResource + * Resource Name of the internal config list file + * @param configDir + * Base path to user config giles + * @param resBaseName + * Base resource name for internal config files + * @param loader + * Loader instance + */ + def loadConfigs( + modName: String, + listResource: String, + configDir: File, + resBaseName: String, + loader: RecipeLoader + ) { BdLib.logInfo("Loading internal config files for mod %s", modName) - val internals = Misc.withAutoClose(new BufferedReader(new InputStreamReader(getClass.getResourceAsStream(listResource)))) { listReader => - Iterator.continually(listReader.readLine) + val internals = Misc.withAutoClose( + new BufferedReader( + new InputStreamReader(getClass.getResourceAsStream(listResource)) + ) + ) { listReader => + Iterator + .continually(listReader.readLine) .takeWhile(_ != null) .map(_.trim) .filterNot(_.startsWith("#")) @@ -41,11 +57,21 @@ object RecipesHelper { for (fileName <- internals) { val overrideFile = new File(overrideDir, fileName) if (overrideFile.exists()) { - tryLoadConfig(new FileReader(overrideFile), overrideFile.getCanonicalPath, modName, loader) + tryLoadConfig( + new FileReader(overrideFile), + overrideFile.getCanonicalPath, + modName, + loader + ) } else { val url = getClass.getResource(resBaseName + fileName) Misc.withAutoClose(url.openStream()) { stream => - tryLoadConfig(new InputStreamReader(stream), url.toString, modName, loader) + tryLoadConfig( + new InputStreamReader(stream), + url.toString, + modName, + loader + ) } } } @@ -55,19 +81,36 @@ object RecipesHelper { for (fileName <- configDir.list().sorted if fileName.endsWith(".cfg")) { val file = new File(configDir, fileName) if (file.canRead) - tryLoadConfig(new FileReader(file), file.getCanonicalPath, modName, loader) + tryLoadConfig( + new FileReader(file), + file.getCanonicalPath, + modName, + loader + ) } BdLib.logInfo("Config loading for mod %s finished", modName) } - def tryLoadConfig(reader: Reader, path: String, modName: String, loader: RecipeLoader) { + def tryLoadConfig( + reader: Reader, + path: String, + modName: String, + loader: RecipeLoader + ) { BdLib.logInfo("Loading config: %s", path) try { loader.load(reader) } catch { case e: Throwable => - FMLCommonHandler.instance().raiseException(e, "%s config loading failed in file %s: %s".format(modName, path, e.getMessage), true) + FMLCommonHandler + .instance() + .raiseException( + e, + "%s config loading failed in file %s: %s" + .format(modName, path, e.getMessage), + true + ) } finally { reader.close() } diff --git a/src/main/scala/net/bdew/lib/recipes/StatementError.scala b/src/main/scala/net/bdew/lib/recipes/StatementError.scala index 71a0eb3..ea8d61d 100644 --- a/src/main/scala/net/bdew/lib/recipes/StatementError.scala +++ b/src/main/scala/net/bdew/lib/recipes/StatementError.scala @@ -9,8 +9,7 @@ package net.bdew.lib.recipes -/** - * Used in statement processing to abort the current statement and show an error without a stack trace - */ +/** Used in statement processing to abort the current statement and show an + * error without a stack trace + */ class StatementError(msg: String) extends Exception(msg) - diff --git a/src/main/scala/net/bdew/lib/recipes/ast-conditions.scala b/src/main/scala/net/bdew/lib/recipes/ast-conditions.scala index 85b6311..3a8c8a9 100644 --- a/src/main/scala/net/bdew/lib/recipes/ast-conditions.scala +++ b/src/main/scala/net/bdew/lib/recipes/ast-conditions.scala @@ -9,54 +9,40 @@ package net.bdew.lib.recipes -/** - * Represents a condition, something that can be resolved to a boolean - * Actual processing is in [[RecipeLoader.resolveCondition]] - * - * Naming convention: All subclasses are named CndFoo - */ +/** Represents a condition, something that can be resolved to a boolean Actual + * processing is in [[RecipeLoader.resolveCondition]] + * + * Naming convention: All subclasses are named CndFoo + */ abstract class Condition -/** - * True if mod is present - * Syntax: HaveMod {string} - * Parser: [[RecipeParser.cndHaveMod]] - * @param mod mod id - */ +/** True if mod is present Syntax: HaveMod {string} Parser: + * [[RecipeParser.cndHaveMod]] + * @param mod + * mod id + */ case class CndHaveMod(mod: String) extends Condition -/** - * True if API is present - * Syntax: HaveAPI {string} - * Parser: [[RecipeParser.cndHaveAPI]] - */ +/** True if API is present Syntax: HaveAPI {string} Parser: + * [[RecipeParser.cndHaveAPI]] + */ case class CndHaveAPI(api: String) extends Condition -/** - * True if oredict entry is present - * Syntax: HaveOD {string} - * Parser: [[RecipeParser.cndHaveOD]] - */ +/** True if oredict entry is present Syntax: HaveOD {string} Parser: + * [[RecipeParser.cndHaveOD]] + */ case class CndHaveOD(od: String) extends Condition -/** - * Boolean NOT - * Syntax: ! {condition} - * Parser: [[RecipeParser.cndNOT]] - */ +/** Boolean NOT Syntax: ! {condition} Parser: [[RecipeParser.cndNOT]] + */ case class CndNOT(cnd: Condition) extends Condition -/** - * Boolean AND - * Syntax: ( {condition} && {condition} ) - * Parser: [[RecipeParser.cndAND]] - */ +/** Boolean AND Syntax: ( {condition} && {condition} ) Parser: + * [[RecipeParser.cndAND]] + */ case class CndAND(c1: Condition, c2: Condition) extends Condition -/** - * Boolean OR - * Syntax: ( {condition} || {condition} ) - * Parser: [[RecipeParser.cndOR]] - */ +/** Boolean OR Syntax: ( {condition} || {condition} ) Parser: + * [[RecipeParser.cndOR]] + */ case class CndOR(c1: Condition, c2: Condition) extends Condition - diff --git a/src/main/scala/net/bdew/lib/recipes/ast-stackref.scala b/src/main/scala/net/bdew/lib/recipes/ast-stackref.scala index 2d7eb59..7080557 100644 --- a/src/main/scala/net/bdew/lib/recipes/ast-stackref.scala +++ b/src/main/scala/net/bdew/lib/recipes/ast-stackref.scala @@ -9,79 +9,84 @@ package net.bdew.lib.recipes -/** - * Represents something that can be resolved to ItemStack or recipe component - * Actual processing is in: - * * [[net.bdew.lib.recipes.RecipeLoader.getRecipeComponent]] - * * [[net.bdew.lib.recipes.RecipeLoader.getConcreteStack]] - * * [[net.bdew.lib.recipes.RecipeLoader.getAllConcreteStacks]] - * - * Naming convention: All subclasses are named StackFoo - */ +/** Represents something that can be resolved to ItemStack or recipe component + * Actual processing is in: * + * [[net.bdew.lib.recipes.RecipeLoader.getRecipeComponent]] * + * [[net.bdew.lib.recipes.RecipeLoader.getConcreteStack]] * + * [[net.bdew.lib.recipes.RecipeLoader.getAllConcreteStacks]] + * + * Naming convention: All subclasses are named StackFoo + */ abstract class StackRef -/** - * Ore Dictionary reference - * Syntax: OD:{identifier} - * Parser: [[net.bdew.lib.recipes.RecipeParser.specOD]] - * @param id OD entry name - */ +/** Ore Dictionary reference Syntax: OD:{identifier} Parser: + * [[net.bdew.lib.recipes.RecipeParser.specOD]] + * @param id + * OD entry name + */ case class StackOreDict(id: String) extends StackRef -/** - * Generic Reference - * Syntax: S:{modId}:{name} - * Parser: [[net.bdew.lib.recipes.RecipeParser.specGenericStack]] - * @param mod modId of owner mod - * @param name name of the stack - */ +/** Generic Reference Syntax: S:{modId}:{name} Parser: + * [[net.bdew.lib.recipes.RecipeParser.specGenericStack]] + * @param mod + * modId of owner mod + * @param name + * name of the stack + */ case class StackGeneric(mod: String, name: String) extends StackRef -/** - * Block reference - * Syntax: B:[{modId}:]{name} [@ {meta}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.specBlock]] - * @param mod modId of owner mod, default is "minecraft" - * @param name Registered name - * @param meta Metadata / Damage - */ +/** Block reference Syntax: B:[{modId}:]{name} [@ {meta}] Parser: + * [[net.bdew.lib.recipes.RecipeParser.specBlock]] + * @param mod + * modId of owner mod, default is "minecraft" + * @param name + * Registered name + * @param meta + * Metadata / Damage + */ case class StackBlock(mod: String, name: String, meta: Int) extends StackRef -/** - * Item reference - * Syntax: I:[{modId}:]{name} [@ {meta}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.specItem]] - * @param mod modId of owner mod, default is "minecraft" - * @param name Registered name - * @param meta Metadata / Damage - */ +/** Item reference Syntax: I:[{modId}:]{name} [@ {meta}] Parser: + * [[net.bdew.lib.recipes.RecipeParser.specItem]] + * @param mod + * modId of owner mod, default is "minecraft" + * @param name + * Registered name + * @param meta + * Metadata / Damage + */ case class StackItem(mod: String, name: String, meta: Int) extends StackRef -/** - * Reference to an Item/Block/ItemStack public static field - * Syntax: {path}.{to}.{class}[{field}] [@ {meta}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.specReflect]] - * @param cls Class name - * @param field Field name - * @param meta Metadata / Damage (Ignored for ItemStacks) - */ +/** Reference to an Item/Block/ItemStack public static field Syntax: + * {path}.{to}.{class}[{field}] [@ {meta}] Parser: + * [[net.bdew.lib.recipes.RecipeParser.specReflect]] + * @param cls + * Class name + * @param field + * Field name + * @param meta + * Metadata / Damage (Ignored for ItemStacks) + */ case class StackReflect(cls: String, field: String, meta: Int) extends StackRef -/** - * Reference to an Item/Block/ItemStack public static getter - * Syntax: {path}.{to}.{class}.{method}({string}) [@ {meta}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.specGetter]] - * @param cls Class name - * @param method Method name - * @param name Parameter to getter - * @param meta Metadata / Damage (Ignored for ItemStacks) - */ -case class StackGetter(cls: String, method: String, name: String, meta: Int) extends StackRef +/** Reference to an Item/Block/ItemStack public static getter Syntax: + * {path}.{to}.{class}.{method}({string}) [@ {meta}] Parser: + * [[net.bdew.lib.recipes.RecipeParser.specGetter]] + * @param cls + * Class name + * @param method + * Method name + * @param name + * Parameter to getter + * @param meta + * Metadata / Damage (Ignored for ItemStacks) + */ +case class StackGetter(cls: String, method: String, name: String, meta: Int) + extends StackRef -/** - * Macro reference to a previous definition - * Syntax: ${char} - * Parser: [[net.bdew.lib.recipes.RecipeParser.specMacro]] - * @param id The underlying character - */ +/** Macro reference to a previous definition Syntax: ${char} Parser: + * [[net.bdew.lib.recipes.RecipeParser.specMacro]] + * @param id + * The underlying character + */ case class StackMacro(id: Char) extends StackRef diff --git a/src/main/scala/net/bdew/lib/recipes/ast-statements-cfg.scala b/src/main/scala/net/bdew/lib/recipes/ast-statements-cfg.scala index 819ba26..dea2244 100644 --- a/src/main/scala/net/bdew/lib/recipes/ast-statements-cfg.scala +++ b/src/main/scala/net/bdew/lib/recipes/ast-statements-cfg.scala @@ -9,35 +9,38 @@ package net.bdew.lib.recipes -/** - * Base class for config statements - * Actual processing is in [[RecipeLoader.processConfigStatement]] - */ +/** Base class for config statements Actual processing is in + * [[RecipeLoader.processConfigStatement]] + */ abstract class ConfigStatement -/** - * Block of delayed statements, used to include recipe statements in config scope (which is always top level) - * Syntax: recipes { {statements} } - * Parser: [[RecipeParser.recipesTopBlock]] - * Also used internally by the parser to bridge [[RsConditional]] to config scope in [[RecipeParser.conditionBridge]] - * @param list Statements to run - */ +/** Block of delayed statements, used to include recipe statements in config + * scope (which is always top level) Syntax: recipes { {statements} } Parser: + * [[RecipeParser.recipesTopBlock]] Also used internally by the parser to + * bridge [[RsConditional]] to config scope in [[RecipeParser.conditionBridge]] + * @param list + * Statements to run + */ case class CsRecipeBlock(list: List[RecipeStatement]) extends ConfigStatement -/** - * Conditional config block - * Syntax: if {condition} << {statements} >> [else << {statements} >>] - * Parser: [[RecipeParser.conditionConfig]] - * @param cond Condition - * @param thn Statements to run if true - * @param els Statements to run otherwise - */ -case class CsConditionalConfig(cond: Condition, thn: List[ConfigStatement], els: List[ConfigStatement]) extends ConfigStatement +/** Conditional config block Syntax: if {condition} << {statements} >> [else << + * {statements} >>] Parser: [[RecipeParser.conditionConfig]] + * @param cond + * Condition + * @param thn + * Statements to run if true + * @param els + * Statements to run otherwise + */ +case class CsConditionalConfig( + cond: Condition, + thn: List[ConfigStatement], + els: List[ConfigStatement] +) extends ConfigStatement -/** - * Removes previously defined recipes for a specific result - * Syntax: clearRecipes: {spec} - * Parser: [[RecipeParser.clearRecipes]] - * @param res Recipes that produce this result will be cleared - */ +/** Removes previously defined recipes for a specific result Syntax: + * clearRecipes: {spec} Parser: [[RecipeParser.clearRecipes]] + * @param res + * Recipes that produce this result will be cleared + */ case class CsClearRecipes(res: StackRef) extends ConfigStatement diff --git a/src/main/scala/net/bdew/lib/recipes/ast-statements-recipe.scala b/src/main/scala/net/bdew/lib/recipes/ast-statements-recipe.scala index 0b24c4f..3aa03bb 100644 --- a/src/main/scala/net/bdew/lib/recipes/ast-statements-recipe.scala +++ b/src/main/scala/net/bdew/lib/recipes/ast-statements-recipe.scala @@ -9,109 +9,115 @@ package net.bdew.lib.recipes -/** - * Base class for recipe statements - * Actual processing is in [[net.bdew.lib.recipes.RecipeLoader.processRecipeStatements]] - * - * Naming convention: All subclasses are named RsFoo - */ +/** Base class for recipe statements Actual processing is in + * [[net.bdew.lib.recipes.RecipeLoader.processRecipeStatements]] + * + * Naming convention: All subclasses are named RsFoo + */ abstract class RecipeStatement -/** - * Character assignment - * Syntax: {char} = {ref} - * Parser: [[net.bdew.lib.recipes.RecipeParser.charSpec]] - * @param char Character to assign - * @param spec ItemStack Reference - */ +/** Character assignment Syntax: {char} = {ref} Parser: + * [[net.bdew.lib.recipes.RecipeParser.charSpec]] + * @param char + * Character to assign + * @param spec + * ItemStack Reference + */ case class RsCharAssign(char: Char, spec: StackRef) extends RecipeStatement -/** - * Define class macro - * Syntax: def {id} = {name} - * Parser: [[net.bdew.lib.recipes.RecipeParser.classMacro]] - * @param id Macro identifier - * @param cls Class name - */ +/** Define class macro Syntax: def {id} = {name} Parser: + * [[net.bdew.lib.recipes.RecipeParser.classMacro]] + * @param id + * Macro identifier + * @param cls + * Class name + */ case class RsClassMacro(id: String, cls: String) extends RecipeStatement -/** - * Unconditional block - allows grouping and isolation of statements - * Syntax: recipes { {statements} } - * Parser: [[net.bdew.lib.recipes.RecipeParser.recipesSubBlock]] - * @param list Statements to run - */ +/** Unconditional block - allows grouping and isolation of statements Syntax: + * recipes { {statements} } Parser: + * [[net.bdew.lib.recipes.RecipeParser.recipesSubBlock]] + * @param list + * Statements to run + */ case class RsRecipes(list: List[RecipeStatement]) extends RecipeStatement -/** - * Conditional recipes block - * Syntax: if {condition} recipes { {statements} } [else { {statements} }] - * Parser: [[net.bdew.lib.recipes.RecipeParser.conditionRecipes]] - * @param cond Condition - * @param thn Statements to run if true - * @param els Statements to run otherwise - */ -case class RsConditional(cond: Condition, thn: List[RecipeStatement], els: List[RecipeStatement]) extends RecipeStatement +/** Conditional recipes block Syntax: if {condition} recipes { {statements} } + * [else { {statements} }] Parser: + * [[net.bdew.lib.recipes.RecipeParser.conditionRecipes]] + * @param cond + * Condition + * @param thn + * Statements to run if true + * @param els + * Statements to run otherwise + */ +case class RsConditional( + cond: Condition, + thn: List[RecipeStatement], + els: List[RecipeStatement] +) extends RecipeStatement -/** - * Base class for statements that represent a crafting recipe, that has a result - */ +/** Base class for statements that represent a crafting recipe, that has a + * result + */ abstract class CraftingStatement extends RecipeStatement { def result: StackRef } -/** - * Shaped recipe definition - * - * Syntax: - * XXX - * XXX => {result} [* {count}] - * XXX - * - * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped3x3]] - * - * Syntax: - * XX - * XX => {result} [* {count}] - * - * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped2x2]] - * - * Syntax: XXX XXX XXX => {result} [* {count}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped9]] - * - * @param rec Recipe pattern - * @param result Result reference - * @param cnt Number of output items - */ -case class RsRecipeShaped(rec: Seq[String], result: StackRef, cnt: Int) extends CraftingStatement +/** Shaped recipe definition + * + * Syntax: XXX XXX => {result} [* {count}] XXX + * + * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped3x3]] + * + * Syntax: XX XX => {result} [* {count}] + * + * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShaped2x2]] + * + * Syntax: XXX XXX XXX => {result} [* {count}] Parser: + * [[net.bdew.lib.recipes.RecipeParser.recipeShaped9]] + * + * @param rec + * Recipe pattern + * @param result + * Result reference + * @param cnt + * Number of output items + */ +case class RsRecipeShaped(rec: Seq[String], result: StackRef, cnt: Int) + extends CraftingStatement -/** - * Shapeless recipe definition - * Syntax: shapeless: {characters} => {result} [* {count}] - * Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShapeless]] - * - * @param rec Recipe pattern - * @param result Result reference - * @param cnt Number of output items - */ -case class RsRecipeShapeless(rec: String, result: StackRef, cnt: Int) extends CraftingStatement +/** Shapeless recipe definition Syntax: shapeless: {characters} => {result} [* + * {count}] Parser: [[net.bdew.lib.recipes.RecipeParser.recipeShapeless]] + * + * @param rec + * Recipe pattern + * @param result + * Result reference + * @param cnt + * Number of output items + */ +case class RsRecipeShapeless(rec: String, result: StackRef, cnt: Int) + extends CraftingStatement -/** - * Smelting recipe definition - * Syntax: smelt: {input} => {output}, {XP} - * Parser [[net.bdew.lib.recipes.RecipeParser.recipeSmelting]] - * - * @param in Input Stack - * @param result Output Stack - * @param cnt Output Count - * @param xp XP for smelting - */ -case class RsRecipeSmelting(in: StackRef, result: StackRef, cnt: Int, xp: Float) extends CraftingStatement - -/** - * Smelting recipe definition - * Syntax: regOreDict: {reference} -> {name} - * Parser [[net.bdew.lib.recipes.RecipeParser.regOreDict]] - */ -case class RsRegOredict(id: String, spec: StackRef, wildcard: Boolean) extends RecipeStatement +/** Smelting recipe definition Syntax: smelt: {input} => {output}, {XP} Parser + * [[net.bdew.lib.recipes.RecipeParser.recipeSmelting]] + * + * @param in + * Input Stack + * @param result + * Output Stack + * @param cnt + * Output Count + * @param xp + * XP for smelting + */ +case class RsRecipeSmelting(in: StackRef, result: StackRef, cnt: Int, xp: Float) + extends CraftingStatement +/** Smelting recipe definition Syntax: regOreDict: {reference} -> {name} Parser + * [[net.bdew.lib.recipes.RecipeParser.regOreDict]] + */ +case class RsRegOredict(id: String, spec: StackRef, wildcard: Boolean) + extends RecipeStatement diff --git a/src/main/scala/net/bdew/lib/recipes/gencfg/ConfigSection.scala b/src/main/scala/net/bdew/lib/recipes/gencfg/ConfigSection.scala index f7f5b64..c9668f4 100644 --- a/src/main/scala/net/bdew/lib/recipes/gencfg/ConfigSection.scala +++ b/src/main/scala/net/bdew/lib/recipes/gencfg/ConfigSection.scala @@ -23,11 +23,18 @@ case class EntryNumList(v: List[Double]) extends ConfigEntry case class EntryStrList(v: List[String]) extends ConfigEntry -case class ConfigSection(pfx: String = "") extends ConfigEntry with Iterable[(String, ConfigEntry)] { - var raw = Map.empty[String, ConfigEntry].withDefault(x => sys.error("Config value '%s%s' is missing".format(pfx, x))) +case class ConfigSection(pfx: String = "") + extends ConfigEntry + with Iterable[(String, ConfigEntry)] { + var raw = Map + .empty[String, ConfigEntry] + .withDefault(x => + sys.error("Config value '%s%s' is missing".format(pfx, x)) + ) def iterator: Iterator[(String, ConfigEntry)] = raw.iterator - def filterType[T <: ConfigEntry](cls: Class[T]): Iterable[(String, T)] = raw.filter(x => cls.isInstance(x._2)).map(x => x.asInstanceOf[(String, T)]) + def filterType[T <: ConfigEntry](cls: Class[T]): Iterable[(String, T)] = + raw.filter(x => cls.isInstance(x._2)).map(x => x.asInstanceOf[(String, T)]) def keys = raw.keys @@ -36,7 +43,14 @@ case class ConfigSection(pfx: String = "") extends ConfigEntry with Iterable[(St if (t.isInstance(v)) return v.asInstanceOf[T] else - sys.error("Config value '%s%s' is of the wrong type, expected %s, got %s".format(pfx, id, t.getName, v.getClass.getName)) + sys.error( + "Config value '%s%s' is of the wrong type, expected %s, got %s".format( + pfx, + id, + t.getName, + v.getClass.getName + ) + ) } def set(id: String, v: ConfigEntry) = raw += id -> v @@ -48,7 +62,8 @@ case class ConfigSection(pfx: String = "") extends ConfigEntry with Iterable[(St def getSection(id: String) = getRaw(id, classOf[ConfigSection]) final val trueVals = Set("y", "true", "yes", "on") - def getBoolean(id: String) = trueVals.contains(getString(id).toLowerCase(Locale.US)) + def getBoolean(id: String) = + trueVals.contains(getString(id).toLowerCase(Locale.US)) def hasValue(id: String) = raw.isDefinedAt(id) @@ -70,9 +85,8 @@ case class ConfigSection(pfx: String = "") extends ConfigEntry with Iterable[(St def getColor(id: String) = raw(id) match { case EntryDouble(c) => Color.fromInt(c.toInt) - case EntryNumList(r :: g :: b :: Nil) => Color(r.toFloat, g.toFloat, b.toFloat) + case EntryNumList(r :: g :: b :: Nil) => + Color(r.toFloat, g.toFloat, b.toFloat) case x => sys.error("Invalid color definition: %s".format(x)) } } - - diff --git a/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigLoader.scala b/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigLoader.scala index 27e13ea..5a3d55f 100644 --- a/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigLoader.scala +++ b/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigLoader.scala @@ -15,21 +15,23 @@ import net.bdew.lib.recipes.{ConfigStatement, RecipeLoader} trait GenericConfigLoader extends RecipeLoader { val cfgStore: ConfigSection - def processConfigStatement(section: ConfigSection, s: CfgEntry): Unit = s match { - case CfgVal(id, v) => - BdLib.logDebug("Config: %s%s = %s", section.pfx, id, v) - section.set(id, v) - case CfgSection(id, st) => processConfigBlock(section.getOrAddSection(id), st) - case x => - BdLib.logError("Can't process %s - this is a programing bug!", x) - } + def processConfigStatement(section: ConfigSection, s: CfgEntry): Unit = + s match { + case CfgVal(id, v) => + BdLib.logDebug("Config: %s%s = %s", section.pfx, id, v) + section.set(id, v) + case CfgSection(id, st) => + processConfigBlock(section.getOrAddSection(id), st) + case x => + BdLib.logError("Can't process %s - this is a programing bug!", x) + } def processConfigBlock(view: ConfigSection, block: List[CfgEntry]): Unit = for (s <- block) processConfigStatement(view, s) override def processConfigStatement(s: ConfigStatement) = s match { - case CsCfgSection(id, st) => processConfigBlock(cfgStore.getOrAddSection(id), st) + case CsCfgSection(id, st) => + processConfigBlock(cfgStore.getOrAddSection(id), st) case _ => super.processConfigStatement(s) } } - diff --git a/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigParser.scala b/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigParser.scala index 3f9ac79..c413e35 100644 --- a/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigParser.scala +++ b/src/main/scala/net/bdew/lib/recipes/gencfg/GenericConfigParser.scala @@ -19,7 +19,7 @@ trait GenericConfigParser extends RecipeParser { ("0x" ~> "[0-9A-Fa-f]+".r) ^^ { case x => Integer.parseInt(x, 16).toDouble } | decimalNumber ^^ { case x => x.toDouble } | ("-" ~> decimalNumber) ^^ { case x => -x.toDouble } - ) + ) def cvNum = signedNumber ^^ EntryDouble def cvStr = str ^^ EntryStr diff --git a/src/main/scala/net/bdew/lib/recipes/gencfg/ast.scala b/src/main/scala/net/bdew/lib/recipes/gencfg/ast.scala index 805ef87..60ebd2e 100644 --- a/src/main/scala/net/bdew/lib/recipes/gencfg/ast.scala +++ b/src/main/scala/net/bdew/lib/recipes/gencfg/ast.scala @@ -17,8 +17,5 @@ case class CfgVal(id: String, value: ConfigEntry) extends CfgEntry case class CfgSection(id: String, vals: List[CfgEntry]) extends CfgEntry -case class CsCfgSection(id: String, vals: List[CfgEntry]) extends ConfigStatement - - - - +case class CsCfgSection(id: String, vals: List[CfgEntry]) + extends ConfigStatement diff --git a/src/main/scala/net/bdew/lib/recipes/lootlist/EntryLootList.scala b/src/main/scala/net/bdew/lib/recipes/lootlist/EntryLootList.scala index b519b3c..e75e7f4 100644 --- a/src/main/scala/net/bdew/lib/recipes/lootlist/EntryLootList.scala +++ b/src/main/scala/net/bdew/lib/recipes/lootlist/EntryLootList.scala @@ -12,13 +12,9 @@ package net.bdew.lib.recipes.lootlist import net.bdew.lib.recipes.StackRef import net.bdew.lib.recipes.gencfg.ConfigEntry -/** - * Allows definition of random-weighted loot/drop lists in config sections - * @param list List of (chance percent, stack reference) pairs, resolve to - * real ItemStacks with LootListLoader.resolveLootList - */ +/** Allows definition of random-weighted loot/drop lists in config sections + * @param list + * List of (chance percent, stack reference) pairs, resolve to real + * ItemStacks with LootListLoader.resolveLootList + */ case class EntryLootList(list: List[(Double, StackRef)]) extends ConfigEntry - - - - diff --git a/src/main/scala/net/bdew/lib/recipes/lootlist/LootListLoader.scala b/src/main/scala/net/bdew/lib/recipes/lootlist/LootListLoader.scala index 0971bd8..bf0eac2 100644 --- a/src/main/scala/net/bdew/lib/recipes/lootlist/LootListLoader.scala +++ b/src/main/scala/net/bdew/lib/recipes/lootlist/LootListLoader.scala @@ -15,11 +15,11 @@ import net.bdew.lib.recipes.gencfg.GenericConfigLoader import net.minecraft.item.ItemStack import net.minecraftforge.oredict.OreDictionary -/** - * Loader mixin for loot lists - */ +/** Loader mixin for loot lists + */ trait LootListLoader extends GenericConfigLoader { - def resolveLootList(entry: EntryLootList): List[(Double, ItemStack)] = resolveLootList(entry.list) + def resolveLootList(entry: EntryLootList): List[(Double, ItemStack)] = + resolveLootList(entry.list) def resolveLootList(list: List[(Double, StackRef)]) = (for ((chance, ref) <- list) yield { try { diff --git a/src/main/scala/net/bdew/lib/recipes/lootlist/LootListParser.scala b/src/main/scala/net/bdew/lib/recipes/lootlist/LootListParser.scala index cd12359..b390ede 100644 --- a/src/main/scala/net/bdew/lib/recipes/lootlist/LootListParser.scala +++ b/src/main/scala/net/bdew/lib/recipes/lootlist/LootListParser.scala @@ -11,16 +11,12 @@ package net.bdew.lib.recipes.lootlist import net.bdew.lib.recipes.gencfg.GenericConfigParser -/** - * Parser mixin for loot lists - * ident = DropsList( - * {chance}% {stackRef} - * ... - * ) - */ +/** Parser mixin for loot lists ident = DropsList( {chance}% {stackRef} ... ) + */ trait LootListParser extends GenericConfigParser { - def dropsEntry = (decimalNumber <~ "%") ~ spec ^^ { case n ~ s => (n.toDouble, s) } + def dropsEntry = (decimalNumber <~ "%") ~ spec ^^ { case n ~ s => + (n.toDouble, s) + } def ceDrops = "DropsList" ~> "(" ~> dropsEntry.* <~ ")" ^^ EntryLootList override def cfgValue = ceDrops | super.cfgValue } - diff --git a/src/main/scala/net/bdew/lib/render/BaseBlockRenderHandler.scala b/src/main/scala/net/bdew/lib/render/BaseBlockRenderHandler.scala index 776a362..b416198 100644 --- a/src/main/scala/net/bdew/lib/render/BaseBlockRenderHandler.scala +++ b/src/main/scala/net/bdew/lib/render/BaseBlockRenderHandler.scala @@ -9,7 +9,10 @@ package net.bdew.lib.render -import cpw.mods.fml.client.registry.{ISimpleBlockRenderingHandler, RenderingRegistry} +import cpw.mods.fml.client.registry.{ + ISimpleBlockRenderingHandler, + RenderingRegistry +} abstract class BaseBlockRenderHandler extends ISimpleBlockRenderingHandler { val id = RenderingRegistry.getNextAvailableRenderId diff --git a/src/main/scala/net/bdew/lib/render/IconPreloader.scala b/src/main/scala/net/bdew/lib/render/IconPreloader.scala index 90829d9..d1ca5b6 100644 --- a/src/main/scala/net/bdew/lib/render/IconPreloader.scala +++ b/src/main/scala/net/bdew/lib/render/IconPreloader.scala @@ -17,14 +17,17 @@ import net.minecraft.util.IIcon import net.minecraftforge.client.event.TextureStitchEvent import net.minecraftforge.common.MinecraftForge -/** - * Allows loading of texture that don't belong to specific block or item into vanilla block/item atlas - * @param kind 0=Blocks / 1=Items - */ +/** Allows loading of texture that don't belong to specific block or item into + * vanilla block/item atlas + * @param kind + * 0=Blocks / 1=Items + */ class IconPreloader(kind: Int) { lazy val map = { (for { - method <- getClass.getMethods if method.getParameterTypes.isEmpty && classOf[TextureLoc].isAssignableFrom(method.getReturnType) + method <- getClass.getMethods + if method.getParameterTypes.isEmpty && classOf[TextureLoc] + .isAssignableFrom(method.getReturnType) value <- Misc.asInstanceOpt(method.invoke(this), classOf[TextureLoc]) } yield method.getName -> value).toMap } diff --git a/src/main/scala/net/bdew/lib/render/RenderUtils.scala b/src/main/scala/net/bdew/lib/render/RenderUtils.scala index 0e7eff0..d1f98b5 100644 --- a/src/main/scala/net/bdew/lib/render/RenderUtils.scala +++ b/src/main/scala/net/bdew/lib/render/RenderUtils.scala @@ -15,36 +15,49 @@ import net.minecraftforge.common.util.ForgeDirection import org.lwjgl.opengl.GL11 object RenderUtils { - /** - * Render a single item side - */ - def doRenderItemSide(d: ForgeDirection, r: RenderBlocks, block: Block, meta: Int) = { + + /** Render a single item side + */ + def doRenderItemSide( + d: ForgeDirection, + r: RenderBlocks, + block: Block, + meta: Int + ) = { val icon = r.getBlockIconFromSideAndMetadata(block, d.ordinal(), meta) Tessellator.instance.setNormal(d.offsetX, d.offsetY, d.offsetZ) d match { - case ForgeDirection.DOWN => r.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, icon) - case ForgeDirection.UP => r.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, icon) - case ForgeDirection.NORTH => r.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, icon) - case ForgeDirection.SOUTH => r.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, icon) - case ForgeDirection.WEST => r.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, icon) - case ForgeDirection.EAST => r.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, icon) + case ForgeDirection.DOWN => + r.renderFaceYNeg(block, 0.0d, 0.0d, 0.0d, icon) + case ForgeDirection.UP => r.renderFaceYPos(block, 0.0d, 0.0d, 0.0d, icon) + case ForgeDirection.NORTH => + r.renderFaceZNeg(block, 0.0d, 0.0d, 0.0d, icon) + case ForgeDirection.SOUTH => + r.renderFaceZPos(block, 0.0d, 0.0d, 0.0d, icon) + case ForgeDirection.WEST => + r.renderFaceXNeg(block, 0.0d, 0.0d, 0.0d, icon) + case ForgeDirection.EAST => + r.renderFaceXPos(block, 0.0d, 0.0d, 0.0d, icon) case _ => sys.error("Invalid side") } } - /** - * Render a simple block as an item (for gui, item entities etc.) - */ - def renderSimpleBlockItem(block: Block, metadata: Int, renderer: RenderBlocks) { + /** Render a simple block as an item (for gui, item entities etc.) + */ + def renderSimpleBlockItem( + block: Block, + metadata: Int, + renderer: RenderBlocks + ) { block.setBlockBoundsForItemRender() renderer.setRenderBoundsFromBlock(block) val T = Tessellator.instance - GL11.glTranslatef(-0.5F, -0.5F, -0.5F) + GL11.glTranslatef(-0.5f, -0.5f, -0.5f) for (side <- ForgeDirection.VALID_DIRECTIONS) { T.startDrawingQuads() doRenderItemSide(side, renderer, block, metadata) T.draw() } - GL11.glTranslatef(0.5F, 0.5F, 0.5F) + GL11.glTranslatef(0.5f, 0.5f, 0.5f) } } diff --git a/src/main/scala/net/bdew/lib/render/RotatedBlockRenderer.scala b/src/main/scala/net/bdew/lib/render/RotatedBlockRenderer.scala index 315b538..10c8aaa 100644 --- a/src/main/scala/net/bdew/lib/render/RotatedBlockRenderer.scala +++ b/src/main/scala/net/bdew/lib/render/RotatedBlockRenderer.scala @@ -19,7 +19,7 @@ import net.minecraftforge.common.util.ForgeDirection object RotatedBlockRenderer extends BaseBlockRenderHandler { val filterIconDraw = (for (dir <- ForgeDirection.VALID_DIRECTIONS) - yield (dir, new EdgeDraw(RectF(0.35F, 0.35F, 0.65F, 0.65F), dir))).toMap + yield (dir, new EdgeDraw(RectF(0.35f, 0.35f, 0.65f, 0.65f), dir))).toMap def setRenderRotation(renderer: RenderBlocks, side: ForgeDirection): Unit = { side.ordinal() match { @@ -59,16 +59,35 @@ object RotatedBlockRenderer extends BaseBlockRenderHandler { renderer.uvRotateBottom = 0 } - override def renderInventoryBlock(block: Block, metadata: Int, modelID: Int, renderer: RenderBlocks) { - setRenderRotation(renderer, block.asInstanceOf[BaseRotatableBlock].getDefaultFacing) + override def renderInventoryBlock( + block: Block, + metadata: Int, + modelID: Int, + renderer: RenderBlocks + ) { + setRenderRotation( + renderer, + block.asInstanceOf[BaseRotatableBlock].getDefaultFacing + ) RenderUtils.renderSimpleBlockItem(block, metadata, renderer) clearRenderRotation(renderer) } - override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks): Boolean = { - setRenderRotation(renderer, block.asInstanceOf[BaseRotatableBlock].getFacing(world, x, y, z)) + override def renderWorldBlock( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + block: Block, + modelId: Int, + renderer: RenderBlocks + ): Boolean = { + setRenderRotation( + renderer, + block.asInstanceOf[BaseRotatableBlock].getFacing(world, x, y, z) + ) renderer.renderStandardBlock(block, x, y, z) clearRenderRotation(renderer) true } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/render/connected/BlockAdditionalRender.scala b/src/main/scala/net/bdew/lib/render/connected/BlockAdditionalRender.scala index 21c8872..e1a9041 100644 --- a/src/main/scala/net/bdew/lib/render/connected/BlockAdditionalRender.scala +++ b/src/main/scala/net/bdew/lib/render/connected/BlockAdditionalRender.scala @@ -15,9 +15,16 @@ import net.minecraft.world.IBlockAccess import net.minecraftforge.common.util.ForgeDirection case class FaceOverlay(icon: IIcon, color: Color) { - def this(icon: IIcon, color: (Float, Float, Float)) = this(icon, new Color(color._1, color._2, color._3)) + def this(icon: IIcon, color: (Float, Float, Float)) = + this(icon, new Color(color._1, color._2, color._3)) } trait BlockAdditionalRender { - def getFaceOverlays(world: IBlockAccess, x: Int, y: Int, z: Int, face: ForgeDirection): List[FaceOverlay] + def getFaceOverlays( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + face: ForgeDirection + ): List[FaceOverlay] } diff --git a/src/main/scala/net/bdew/lib/render/connected/ConnectedHelper.scala b/src/main/scala/net/bdew/lib/render/connected/ConnectedHelper.scala index 3dc51c5..22ac478 100644 --- a/src/main/scala/net/bdew/lib/render/connected/ConnectedHelper.scala +++ b/src/main/scala/net/bdew/lib/render/connected/ConnectedHelper.scala @@ -15,7 +15,7 @@ import net.minecraft.util.IIcon import net.minecraftforge.common.util.ForgeDirection object ConnectedHelper { - val edgeWidth = 1 / 16F + val edgeWidth = 1 / 16f // Represents the rectangles of all edges/corners on a 2d pane // 701 @@ -34,33 +34,39 @@ object ConnectedHelper { RectF(0, 0, 1, 1) ) - val neighbourFaces = (for (x <- ForgeDirection.VALID_DIRECTIONS) yield x -> new neighbourFaces(x)).toMap + val neighbourFaces = (for (x <- ForgeDirection.VALID_DIRECTIONS) + yield x -> new neighbourFaces(x)).toMap // Maps edge number + face to 3d vertices val draw = - (for ((rect, n) <- faceEdges.zipWithIndex; face <- ForgeDirection.VALID_DIRECTIONS) - yield (face, n) -> new EdgeDraw(rect, face)).toMap + (for ( + (rect, n) <- faceEdges.zipWithIndex; + face <- ForgeDirection.VALID_DIRECTIONS + ) + yield (face, n) -> new EdgeDraw(rect, face)).toMap val brightnessMultiplier = Map( - ForgeDirection.UP -> 1F, - ForgeDirection.DOWN -> 0.5F, - ForgeDirection.NORTH -> 0.8F, - ForgeDirection.SOUTH -> 0.8F, - ForgeDirection.WEST -> 0.6F, - ForgeDirection.EAST -> 0.6F + ForgeDirection.UP -> 1f, + ForgeDirection.DOWN -> 0.5f, + ForgeDirection.NORTH -> 0.8f, + ForgeDirection.SOUTH -> 0.8f, + ForgeDirection.WEST -> 0.6f, + ForgeDirection.EAST -> 0.6f ) case class Vec3F(x: Float, y: Float, z: Float) { def *(m: Float) = Vec3F(x * m, y * m, z * m) def +(m: Vec3F) = Vec3F(x + m.x, y + m.y, z + m.z) def -(m: Vec3F) = Vec3F(x - m.x, y - m.y, z - m.z) - def +(d: ForgeDirection) = Vec3F(x + d.offsetX, y + d.offsetY, z + d.offsetZ) + def +(d: ForgeDirection) = + Vec3F(x + d.offsetX, y + d.offsetY, z + d.offsetZ) def toInts = (x.toInt, y.toInt, z.toInt) def asBlockRef = BlockRef(x.toInt, y.toInt, z.toInt) } case class RectF(x1: Float, y1: Float, x2: Float, y2: Float) { - def corners = Seq(Vec2F(x1, y1), Vec2F(x2, y1), Vec2F(x2, y2), Vec2F(x1, y2)) + def corners = + Seq(Vec2F(x1, y1), Vec2F(x2, y1), Vec2F(x2, y2), Vec2F(x1, y2)) } case class Vec2F(u: Float, v: Float) @@ -70,15 +76,15 @@ object ConnectedHelper { class EdgeDraw(rect: RectF, face: ForgeDirection) { val vertices = rect.corners map { d => val v = face match { - case ForgeDirection.UP => Vec3F(d.u, 1, 1 - d.v) - case ForgeDirection.DOWN => Vec3F(d.u, 0, d.v) + case ForgeDirection.UP => Vec3F(d.u, 1, 1 - d.v) + case ForgeDirection.DOWN => Vec3F(d.u, 0, d.v) case ForgeDirection.NORTH => Vec3F(1 - d.u, d.v, 0) case ForgeDirection.SOUTH => Vec3F(d.u, d.v, 1) - case ForgeDirection.EAST => Vec3F(1, d.v, 1 - d.u) - case ForgeDirection.WEST => Vec3F(0, d.v, d.u) - case _ => sys.error("Invalid face") + case ForgeDirection.EAST => Vec3F(1, d.v, 1 - d.u) + case ForgeDirection.WEST => Vec3F(0, d.v, d.u) + case _ => sys.error("Invalid face") } - VecPair(extend(v, 0.001F), d) + VecPair(extend(v, 0.001f), d) } def doDraw(pos: Vec3F, icon: IIcon) { @@ -88,31 +94,32 @@ object ConnectedHelper { } def extend(v: Vec3F, o: Float) = Vec3F( - if (v.x == 0F) -o else if (v.x == 1F) 1 + o else v.x, - if (v.y == 0F) -o else if (v.y == 1F) 1 + o else v.y, - if (v.z == 0F) -o else if (v.z == 1F) 1 + o else v.z + if (v.x == 0f) -o else if (v.x == 1f) 1 + o else v.x, + if (v.y == 0f) -o else if (v.y == 1f) 1 + o else v.y, + if (v.z == 0f) -o else if (v.z == 1f) 1 + o else v.z ) - def mapToIcon(v: Vec2F, i: IIcon) = Vec2F(i.getInterpolatedU(v.u * 16), i.getInterpolatedV((1 - v.v) * 16)) + def mapToIcon(v: Vec2F, i: IIcon) = + Vec2F(i.getInterpolatedU(v.u * 16), i.getInterpolatedV((1 - v.v) * 16)) def addVertexWithUV(p: Vec3F, t: Vec2F) = Tessellator.instance.addVertexWithUV(p.x, p.y, p.z, t.u, t.v) class neighbourFaces(d: ForgeDirection) { val top = d match { - case ForgeDirection.UP => ForgeDirection.NORTH + case ForgeDirection.UP => ForgeDirection.NORTH case ForgeDirection.DOWN => ForgeDirection.SOUTH - case _ => ForgeDirection.UP + case _ => ForgeDirection.UP } val right = d match { - case ForgeDirection.UP => ForgeDirection.EAST - case ForgeDirection.DOWN => ForgeDirection.EAST + case ForgeDirection.UP => ForgeDirection.EAST + case ForgeDirection.DOWN => ForgeDirection.EAST case ForgeDirection.NORTH => ForgeDirection.WEST - case ForgeDirection.WEST => ForgeDirection.SOUTH + case ForgeDirection.WEST => ForgeDirection.SOUTH case ForgeDirection.SOUTH => ForgeDirection.EAST - case ForgeDirection.EAST => ForgeDirection.NORTH - case _ => ForgeDirection.UNKNOWN + case ForgeDirection.EAST => ForgeDirection.NORTH + case _ => ForgeDirection.UNKNOWN } val bottom = top.getOpposite val left = right.getOpposite diff --git a/src/main/scala/net/bdew/lib/render/connected/ConnectedRenderer.scala b/src/main/scala/net/bdew/lib/render/connected/ConnectedRenderer.scala index 6193fb7..18a1e3e 100644 --- a/src/main/scala/net/bdew/lib/render/connected/ConnectedRenderer.scala +++ b/src/main/scala/net/bdew/lib/render/connected/ConnectedRenderer.scala @@ -10,7 +10,11 @@ package net.bdew.lib.render.connected import net.bdew.lib.block.BlockRef -import net.bdew.lib.render.{BaseBlockRenderHandler, RenderUtils, RotatedBlockRenderer} +import net.bdew.lib.render.{ + BaseBlockRenderHandler, + RenderUtils, + RotatedBlockRenderer +} import net.bdew.lib.rotate.BaseRotatableBlock import net.minecraft.block.Block import net.minecraft.client.renderer.{RenderBlocks, Tessellator} @@ -19,9 +23,14 @@ import net.minecraftforge.common.util.ForgeDirection import org.lwjgl.opengl.GL11 object ConnectedRenderer extends BaseBlockRenderHandler { - override def renderInventoryBlock(block: Block, metadata: Int, modelID: Int, renderer: RenderBlocks) { + override def renderInventoryBlock( + block: Block, + metadata: Int, + modelID: Int, + renderer: RenderBlocks + ) { val tessellator = Tessellator.instance - GL11.glTranslatef(-0.5F, -0.5F, -0.5F) + GL11.glTranslatef(-0.5f, -0.5f, -0.5f) val edge = block.asInstanceOf[ConnectedTextureBlock].edgeIcon @@ -32,24 +41,58 @@ object ConnectedRenderer extends BaseBlockRenderHandler { tessellator.draw() } - GL11.glTranslatef(0.5F, 0.5F, 0.5F) + GL11.glTranslatef(0.5f, 0.5f, 0.5f) } - override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks): Boolean = { + override def renderWorldBlock( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + block: Block, + modelId: Int, + renderer: RenderBlocks + ): Boolean = { if (block.isInstanceOf[BaseRotatableBlock]) - RotatedBlockRenderer.renderWorldBlock(world, x, y, z, block, modelId, renderer) + RotatedBlockRenderer.renderWorldBlock( + world, + x, + y, + z, + block, + modelId, + renderer + ) else renderer.renderStandardBlock(block, x, y, z) val pos = ConnectedHelper.Vec3F(x, y, z) for (face <- ForgeDirection.VALID_DIRECTIONS) - if (block.shouldSideBeRendered(world, x + face.offsetX, y + face.offsetY, z + face.offsetZ, face.ordinal())) - drawFaceEdges(world, pos, face, block.asInstanceOf[ConnectedTextureBlock]) + if ( + block.shouldSideBeRendered( + world, + x + face.offsetX, + y + face.offsetY, + z + face.offsetZ, + face.ordinal() + ) + ) + drawFaceEdges( + world, + pos, + face, + block.asInstanceOf[ConnectedTextureBlock] + ) return true } - def drawFaceEdges(world: IBlockAccess, pos: ConnectedHelper.Vec3F, face: ForgeDirection, block: ConnectedTextureBlock) { + def drawFaceEdges( + world: IBlockAccess, + pos: ConnectedHelper.Vec3F, + face: ForgeDirection, + block: ConnectedTextureBlock + ) { val edge = block.edgeIcon val canConnect = block.canConnect(world, pos.asBlockRef, _: BlockRef) val sides = ConnectedHelper.neighbourFaces(face) @@ -58,7 +101,12 @@ object ConnectedRenderer extends BaseBlockRenderHandler { Tessellator.instance.setColorOpaque_F(m, m, m) val fo = pos + face - val b = block.getMixedBrightnessForBlock(world, fo.x.toInt, fo.y.toInt, fo.z.toInt) + val b = block.getMixedBrightnessForBlock( + world, + fo.x.toInt, + fo.y.toInt, + fo.z.toInt + ) Tessellator.instance.setBrightness(b) val U = !canConnect((pos + sides.top).asBlockRef) @@ -84,13 +132,17 @@ object ConnectedRenderer extends BaseBlockRenderHandler { if (L) ConnectedHelper.draw(face, 6).doDraw(pos, edge) if (block.isInstanceOf[BlockAdditionalRender]) { - val overlays = block.asInstanceOf[BlockAdditionalRender].getFaceOverlays(world, pos.x.toInt, pos.y.toInt, pos.z.toInt, face) + val overlays = block + .asInstanceOf[BlockAdditionalRender] + .getFaceOverlays(world, pos.x.toInt, pos.y.toInt, pos.z.toInt, face) for (overlay <- overlays) { - Tessellator.instance.setColorOpaque_F(overlay.color.r, overlay.color.g, overlay.color.b) + Tessellator.instance.setColorOpaque_F( + overlay.color.r, + overlay.color.g, + overlay.color.b + ) ConnectedHelper.draw(face, 8).doDraw(pos, overlay.icon) } } } } - - diff --git a/src/main/scala/net/bdew/lib/render/connected/ConnectedTextureBlock.scala b/src/main/scala/net/bdew/lib/render/connected/ConnectedTextureBlock.scala index a1e9e63..34487bc 100644 --- a/src/main/scala/net/bdew/lib/render/connected/ConnectedTextureBlock.scala +++ b/src/main/scala/net/bdew/lib/render/connected/ConnectedTextureBlock.scala @@ -16,7 +16,11 @@ import net.minecraft.world.IBlockAccess trait ConnectedTextureBlock extends Block { def edgeIcon: IIcon - def canConnect(world: IBlockAccess, origin: BlockRef, target: BlockRef): Boolean + def canConnect( + world: IBlockAccess, + origin: BlockRef, + target: BlockRef + ): Boolean override def getRenderType = ConnectedRenderer.id } diff --git a/src/main/scala/net/bdew/lib/resource/DataSlotResource.scala b/src/main/scala/net/bdew/lib/resource/DataSlotResource.scala index 1e0e7dc..447beec 100644 --- a/src/main/scala/net/bdew/lib/resource/DataSlotResource.scala +++ b/src/main/scala/net/bdew/lib/resource/DataSlotResource.scala @@ -14,44 +14,63 @@ import net.bdew.lib.data.base.{DataSlot, DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound import net.minecraftforge.fluids.{FluidStack, FluidTankInfo} -class DataSlotResource(val name: String, val parent: DataSlotContainer, initCapacity: Int) extends DataSlot { +class DataSlotResource( + val name: String, + val parent: DataSlotContainer, + initCapacity: Int +) extends DataSlot { var resource: Option[Resource] = None var capacity = initCapacity val sendCapacityOnUpdateKind = Set(UpdateKind.GUI) setUpdate(UpdateKind.SAVE, UpdateKind.GUI) - def getEffectiveCapacity = resource.map(_.kind.capacityMultiplier).getOrElse(0D) * capacity + def getEffectiveCapacity = + resource.map(_.kind.capacityMultiplier).getOrElse(0d) * capacity - /** - * Low level fill method that operates on Resource's - * @param res Resource to fill - * @param onlyRound Only fill integer amounts - * @param doFill If false, fill will only be simulated - * @return how much was or would be filled - */ + /** Low level fill method that operates on Resource's + * @param res + * Resource to fill + * @param onlyRound + * Only fill integer amounts + * @param doFill + * If false, fill will only be simulated + * @return + * how much was or would be filled + */ def rawFill(res: Resource, onlyRound: Boolean, doFill: Boolean) = { if (resource.isEmpty || resource.get.kind == res.kind) { - val current = if (resource.isEmpty) 0D else resource.get.amount - var canFill = Misc.clamp(res.amount, 0D, capacity * res.kind.capacityMultiplier - current) + val current = if (resource.isEmpty) 0d else resource.get.amount + var canFill = Misc.clamp( + res.amount, + 0d, + capacity * res.kind.capacityMultiplier - current + ) if (onlyRound) canFill = canFill.floor if (doFill && canFill > 0) execWithChangeNotify { resource = Some(Resource(res.kind, current + canFill)) } canFill - } else 0D + } else 0d } - /** - * Low level drain method that operates on Resource's - * @param maxDrain maximum amount to drain - * @param onlyRound Only fill integer amounts - * @param doDrain If false, drain will only be simulated - * @return how much was or would be drained - */ - def rawDrain(maxDrain: Double, onlyRound: Boolean, doDrain: Boolean): Option[Resource] = { + /** Low level drain method that operates on Resource's + * @param maxDrain + * maximum amount to drain + * @param onlyRound + * Only fill integer amounts + * @param doDrain + * If false, drain will only be simulated + * @return + * how much was or would be drained + */ + def rawDrain( + maxDrain: Double, + onlyRound: Boolean, + doDrain: Boolean + ): Option[Resource] = { resource map { res => - var canDrain = Misc.clamp(res.amount, 0D, maxDrain) + var canDrain = Misc.clamp(res.amount, 0d, maxDrain) if (onlyRound) canDrain = canDrain.floor if (doDrain && canDrain > 0) execWithChangeNotify { resource = @@ -64,7 +83,8 @@ class DataSlotResource(val name: String, val parent: DataSlotContainer, initCapa } } - def fillFluid(resource: FluidStack, doFill: Boolean): Int = rawFill(Resource.from(resource), onlyRound = true, doFill).toInt + def fillFluid(resource: FluidStack, doFill: Boolean): Int = + rawFill(Resource.from(resource), onlyRound = true, doFill).toInt def drainFluid(maxDrain: Int, doDrain: Boolean): FluidStack = { (for { res <- rawDrain(maxDrain, true, false) @@ -80,18 +100,21 @@ class DataSlotResource(val name: String, val parent: DataSlotContainer, initCapa res <- resource rKind <- Misc.asInstanceOpt(res.kind, classOf[FluidResource]) } yield { - new FluidTankInfo(new FluidStack(rKind.fluid, res.amount.toInt), getEffectiveCapacity.toInt) + new FluidTankInfo( + new FluidStack(rKind.fluid, res.amount.toInt), + getEffectiveCapacity.toInt + ) }).getOrElse(new FluidTankInfo(null, capacity)) } override def load(t: NBTTagCompound, kind: UpdateKind.Value) { val tag = t.getCompoundTag(name) - resource = if (tag.hasKey("resource")) - ResourceManager.loadFromNBT(tag.getCompoundTag("resource")) - else - None - + resource = + if (tag.hasKey("resource")) + ResourceManager.loadFromNBT(tag.getCompoundTag("resource")) + else + None if (sendCapacityOnUpdateKind.contains(kind)) tag.getInteger("capacity") @@ -100,7 +123,9 @@ class DataSlotResource(val name: String, val parent: DataSlotContainer, initCapa override def save(t: NBTTagCompound, kind: UpdateKind.Value) { val tag = new NBTTagCompound() - resource foreach { res => tag.setTag("resource", ResourceManager.saveToNBT(res)) } + resource foreach { res => + tag.setTag("resource", ResourceManager.saveToNBT(res)) + } if (sendCapacityOnUpdateKind.contains(kind)) tag.setInteger("capacity", capacity) @@ -108,4 +133,3 @@ class DataSlotResource(val name: String, val parent: DataSlotContainer, initCapa t.setTag(name, tag) } } - diff --git a/src/main/scala/net/bdew/lib/resource/DataSlotResourceKindOption.scala b/src/main/scala/net/bdew/lib/resource/DataSlotResourceKindOption.scala index cc90631..de2e144 100644 --- a/src/main/scala/net/bdew/lib/resource/DataSlotResourceKindOption.scala +++ b/src/main/scala/net/bdew/lib/resource/DataSlotResourceKindOption.scala @@ -14,12 +14,14 @@ import net.bdew.lib.data.DataSlotOption import net.bdew.lib.data.base.{DataSlotContainer, UpdateKind} import net.minecraft.nbt.NBTTagCompound -case class DataSlotResourceKindOption(name: String, parent: DataSlotContainer) extends DataSlotOption[ResourceKind] { +case class DataSlotResourceKindOption(name: String, parent: DataSlotContainer) + extends DataSlotOption[ResourceKind] { setUpdate(UpdateKind.SAVE, UpdateKind.GUI) override def save(t: NBTTagCompound, kind: UpdateKind.Value) { value foreach { r => - t.setTag(name, + t.setTag( + name, Misc.applyMutator(new NBTTagCompound) { tag => r.helperObject.saveToNBT(tag, r) tag.setString("kind", r.helperObject.id) @@ -32,7 +34,9 @@ case class DataSlotResourceKindOption(name: String, parent: DataSlotContainer) e if (t.hasKey(name)) { val tag = t.getCompoundTag(name) value = if (tag.hasKey("kind")) { - ResourceManager.resourceHelpers.get(tag.getString("kind")).flatMap(_.loadFromNBT(tag)) + ResourceManager.resourceHelpers + .get(tag.getString("kind")) + .flatMap(_.loadFromNBT(tag)) } else None } else unset() } diff --git a/src/main/scala/net/bdew/lib/resource/FluidResource.scala b/src/main/scala/net/bdew/lib/resource/FluidResource.scala index 7534433..6ea3904 100644 --- a/src/main/scala/net/bdew/lib/resource/FluidResource.scala +++ b/src/main/scala/net/bdew/lib/resource/FluidResource.scala @@ -17,10 +17,15 @@ import net.minecraftforge.fluids.{Fluid, FluidRegistry, FluidStack} case class FluidResource(fluid: Fluid) extends ResourceKind { override def getTexture = new IconWrapper(Texture.BLOCKS, fluid.getIcon) override def getColor = Color.fromInt(fluid.getColor) - override def getLocalizedName = fluid.getLocalizedName(new FluidStack(fluid, 1)) + override def getLocalizedName = + fluid.getLocalizedName(new FluidStack(fluid, 1)) override def getUnlocalizedName = fluid.getUnlocalizedName override def getFormattedString(amount: Double, capacity: Double) = - Misc.toLocalF("resource.fluid.format", DecFormat.round(amount), DecFormat.round(capacity)) + Misc.toLocalF( + "resource.fluid.format", + DecFormat.round(amount), + DecFormat.round(capacity) + ) override def capacityMultiplier = 1 override def toString = "FluidResource(%s)".format(getUnlocalizedName) override def helperObject = FluidResourceHelper diff --git a/src/main/scala/net/bdew/lib/resource/ItemResource.scala b/src/main/scala/net/bdew/lib/resource/ItemResource.scala index 459412e..4f0a9d8 100644 --- a/src/main/scala/net/bdew/lib/resource/ItemResource.scala +++ b/src/main/scala/net/bdew/lib/resource/ItemResource.scala @@ -17,17 +17,23 @@ import net.minecraft.nbt.NBTTagCompound case class ItemResource(item: Item, meta: Int) extends ResourceKind { override def getTexture = new IconWrapper( if (item.getSpriteNumber == 0) Texture.BLOCKS else Texture.ITEMS, - item.getIconFromDamageForRenderPass(meta, 0)) + item.getIconFromDamageForRenderPass(meta, 0) + ) - override def getColor = Color.fromInt(item.getColorFromItemStack(makeStack(1), 0)) + override def getColor = + Color.fromInt(item.getColorFromItemStack(makeStack(1), 0)) override def getLocalizedName = item.getItemStackDisplayName(makeStack(1)) override def getUnlocalizedName = item.getUnlocalizedName(makeStack(1)) override def getFormattedString(amount: Double, capacity: Double) = - Misc.toLocalF("resource.item.format", DecFormat.dec2(amount), DecFormat.round(capacity)) + Misc.toLocalF( + "resource.item.format", + DecFormat.dec2(amount), + DecFormat.round(capacity) + ) - override def capacityMultiplier = 1 / 250D + override def capacityMultiplier = 1 / 250d def makeStack(n: Int) = new ItemStack(item, n, meta) @@ -46,4 +52,3 @@ object ItemResourceHelper extends ResourceHelper[ItemResource]("item") { tag.setInteger("meta", r.meta) } } - diff --git a/src/main/scala/net/bdew/lib/resource/Resource.scala b/src/main/scala/net/bdew/lib/resource/Resource.scala index 4dc1d89..bc076c1 100644 --- a/src/main/scala/net/bdew/lib/resource/Resource.scala +++ b/src/main/scala/net/bdew/lib/resource/Resource.scala @@ -33,7 +33,8 @@ abstract class ResourceHelper[T <: ResourceKind](val id: String) { object ResourceManager { var resourceHelpers = Map.empty[String, ResourceHelper[_ <: ResourceKind]] - def register[T <: ResourceKind](helper: ResourceHelper[T]) = resourceHelpers += helper.id -> helper + def register[T <: ResourceKind](helper: ResourceHelper[T]) = + resourceHelpers += helper.id -> helper register(FluidResourceHelper) register(ItemResourceHelper) @@ -58,5 +59,6 @@ case class Resource(kind: ResourceKind, amount: Double) object Resource { def from(fs: FluidStack) = Resource(FluidResource(fs.getFluid), fs.amount) - def from(is: ItemStack) = Resource(ItemResource(is.getItem, is.getItemDamage), is.stackSize) -} \ No newline at end of file + def from(is: ItemStack) = + Resource(ItemResource(is.getItem, is.getItemDamage), is.stackSize) +} diff --git a/src/main/scala/net/bdew/lib/resource/ResourceInventoryOutput.scala b/src/main/scala/net/bdew/lib/resource/ResourceInventoryOutput.scala index 2af97ab..635b4a6 100644 --- a/src/main/scala/net/bdew/lib/resource/ResourceInventoryOutput.scala +++ b/src/main/scala/net/bdew/lib/resource/ResourceInventoryOutput.scala @@ -21,13 +21,14 @@ case class ResourceInventoryOutput(res: DataSlotResource) extends IInventory { def getResource = res.resource match { case Some(Resource(kind: ItemResource, amount)) => Some((kind, amount)) - case _ => None + case _ => None } override def getStackInSlot(slot: Int) = if (slot == 0) { (getResource map { case (kind, amount) => - val amt = Misc.clamp(amount.floor.toInt, 0, kind.makeStack(1).getMaxStackSize) + val amt = + Misc.clamp(amount.floor.toInt, 0, kind.makeStack(1).getMaxStackSize) if (amt > 0) kind.makeStack(amt) else @@ -43,7 +44,11 @@ case class ResourceInventoryOutput(res: DataSlotResource) extends IInventory { (kind, stored) <- getResource drained <- res.rawDrain(amt, true, false) } yield { - val stackSize = Misc.clamp(drained.amount.floor.toInt, 0, kind.makeStack(1).getMaxStackSize) + val stackSize = Misc.clamp( + drained.amount.floor.toInt, + 0, + kind.makeStack(1).getMaxStackSize + ) if (stackSize > 0) { res.rawDrain(stackSize, true, true) kind.makeStack(stackSize) @@ -58,7 +63,10 @@ case class ResourceInventoryOutput(res: DataSlotResource) extends IInventory { decrStackSize(0, Int.MaxValue) } else { val stackRes = Resource.from(stack) - for ((kind, stored) <- getResource if kind == stackRes.kind && stackRes.amount < stored) { + for ( + (kind, stored) <- getResource + if kind == stackRes.kind && stackRes.amount < stored + ) { res.rawDrain(stored - stackRes.amount, true, true) } } diff --git a/src/main/scala/net/bdew/lib/rotate/BaseRotatableBlock.scala b/src/main/scala/net/bdew/lib/rotate/BaseRotatableBlock.scala index dfa4dde..c74b25d 100644 --- a/src/main/scala/net/bdew/lib/rotate/BaseRotatableBlock.scala +++ b/src/main/scala/net/bdew/lib/rotate/BaseRotatableBlock.scala @@ -19,40 +19,48 @@ import net.minecraft.util.{IIcon, MathHelper} import net.minecraft.world.{IBlockAccess, World} import net.minecraftforge.common.util.ForgeDirection -/** - * Basic logic for block rotation - */ +/** Basic logic for block rotation + */ trait BaseRotatableBlock extends Block { - /** - * Override this method to provide your textures, also called when rendering as item - */ + /** Override this method to provide your textures, also called when rendering + * as item + */ def getIcon(meta: Int, kind: IconType.Value): IIcon - /** - * Override this method to provide your textures, if you need to check other state - */ - def getIcon(world: IBlockAccess, x: Int, y: Int, z: Int, kind: IconType.Value): IIcon = getIcon(world.getBlockMetadata(x, y, z), kind) + /** Override this method to provide your textures, if you need to check other + * state + */ + def getIcon( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + kind: IconType.Value + ): IIcon = getIcon(world.getBlockMetadata(x, y, z), kind) - /** - * Set of valid rotations, default is all of them - */ + /** Set of valid rotations, default is all of them + */ def getValidFacings: util.EnumSet[ForgeDirection] = { return util.EnumSet.allOf(classOf[ForgeDirection]) } - /** - * Rotation to show when it's unavailable (like rendering item in inventory) - */ + /** Rotation to show when it's unavailable (like rendering item in inventory) + */ def getDefaultFacing: ForgeDirection = ForgeDirection.UP - /** - * Those will be overridden to provide concrete storage - */ + /** Those will be overridden to provide concrete storage + */ def setFacing(world: World, x: Int, y: Int, z: Int, facing: ForgeDirection) def getFacing(world: IBlockAccess, x: Int, y: Int, z: Int): ForgeDirection - override def rotateBlock(worldObj: World, x: Int, y: Int, z: Int, axis: ForgeDirection): Boolean = { + override def rotateBlock( + worldObj: World, + x: Int, + y: Int, + z: Int, + axis: ForgeDirection + ): Boolean = { if (getValidFacings.contains(axis)) { setFacing(worldObj, x, y, z, axis) return true @@ -61,16 +69,43 @@ trait BaseRotatableBlock extends Block { } @SideOnly(Side.CLIENT) - override def getIcon(side: Int, meta: Int): IIcon = getIcon(meta, IconType.fromSideAndDir(side, getDefaultFacing)) + override def getIcon(side: Int, meta: Int): IIcon = + getIcon(meta, IconType.fromSideAndDir(side, getDefaultFacing)) @SideOnly(Side.CLIENT) - override def getIcon(world: IBlockAccess, x: Int, y: Int, z: Int, side: Int): IIcon = getIcon(world, x, y, z, IconType.fromSideAndDir(side, getFacing(world, x, y, z))) + override def getIcon( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: Int + ): IIcon = getIcon( + world, + x, + y, + z, + IconType.fromSideAndDir(side, getFacing(world, x, y, z)) + ) - override def getValidRotations(worldObj: World, x: Int, y: Int, z: Int): Array[ForgeDirection] = getValidFacings.toArray(Array.empty[ForgeDirection]) + override def getValidRotations( + worldObj: World, + x: Int, + y: Int, + z: Int + ): Array[ForgeDirection] = + getValidFacings.toArray(Array.empty[ForgeDirection]) - override def onBlockPlacedBy(world: World, x: Int, y: Int, z: Int, ent: EntityLivingBase, stack: ItemStack) { - val dir = RotatedHelper.getFacingFromEntity(ent, getValidFacings, getDefaultFacing) + override def onBlockPlacedBy( + world: World, + x: Int, + y: Int, + z: Int, + ent: EntityLivingBase, + stack: ItemStack + ) { + val dir = + RotatedHelper.getFacingFromEntity(ent, getValidFacings, getDefaultFacing) setFacing(world, x, y, z, dir) super.onBlockPlacedBy(world, x, y, z, ent, stack) } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/rotate/IconType.scala b/src/main/scala/net/bdew/lib/rotate/IconType.scala index 89c76d8..f20837b 100644 --- a/src/main/scala/net/bdew/lib/rotate/IconType.scala +++ b/src/main/scala/net/bdew/lib/rotate/IconType.scala @@ -16,7 +16,8 @@ object IconType extends Enumeration { val FRONT = Value(1, "FRONT") val SIDE = Value(2, "SIDE") - def fromSideAndDir(side: Int, facing: ForgeDirection) = this(metaSideMap(side)(facing.ordinal)) + def fromSideAndDir(side: Int, facing: ForgeDirection) = + this(metaSideMap(side)(facing.ordinal)) val metaSideMap = Array( Array(1, 0, 2, 2, 2, 2), @@ -24,5 +25,6 @@ object IconType extends Enumeration { Array(2, 2, 1, 0, 2, 2), Array(2, 2, 0, 1, 2, 2), Array(2, 2, 2, 2, 1, 0), - Array(2, 2, 2, 2, 0, 1)) -} \ No newline at end of file + Array(2, 2, 2, 2, 0, 1) + ) +} diff --git a/src/main/scala/net/bdew/lib/rotate/RotatableTile.scala b/src/main/scala/net/bdew/lib/rotate/RotatableTile.scala index 8c9c4ef..2890306 100644 --- a/src/main/scala/net/bdew/lib/rotate/RotatableTile.scala +++ b/src/main/scala/net/bdew/lib/rotate/RotatableTile.scala @@ -13,5 +13,9 @@ import net.bdew.lib.data.DataSlotDirection import net.bdew.lib.data.base.{TileDataSlots, UpdateKind} trait RotatableTile extends TileDataSlots { - var rotation = DataSlotDirection("rotation", this).setUpdate(UpdateKind.SAVE, UpdateKind.WORLD, UpdateKind.RENDER) + var rotation = DataSlotDirection("rotation", this).setUpdate( + UpdateKind.SAVE, + UpdateKind.WORLD, + UpdateKind.RENDER + ) } diff --git a/src/main/scala/net/bdew/lib/rotate/RotatableTileBlock.scala b/src/main/scala/net/bdew/lib/rotate/RotatableTileBlock.scala index 1594f41..1c2e530 100644 --- a/src/main/scala/net/bdew/lib/rotate/RotatableTileBlock.scala +++ b/src/main/scala/net/bdew/lib/rotate/RotatableTileBlock.scala @@ -14,20 +14,24 @@ import net.minecraft.block.ITileEntityProvider import net.minecraft.world.{IBlockAccess, World} import net.minecraftforge.common.util.ForgeDirection -/** - * Stores rotation data in tile entity. The TE should implement [[RotatableTile]] - */ +/** Stores rotation data in tile entity. The TE should implement + * [[RotatableTile]] + */ trait RotatableTileBlock extends BaseRotatableBlock with ITileEntityProvider { def setFacing(world: World, x: Int, y: Int, z: Int, facing: ForgeDirection) { world.getTileEntity(x, y, z).asInstanceOf[RotatableTile].rotation := facing } def getFacing(world: IBlockAccess, x: Int, y: Int, z: Int): ForgeDirection = { - val te: RotatableTile = world.getTileEntity(x, y, z).asInstanceOf[RotatableTile] + val te: RotatableTile = + world.getTileEntity(x, y, z).asInstanceOf[RotatableTile] if (te == null || te.rotation == null) { - FMLCommonHandler.instance().getFMLLogger.warn("Failed getting rotation for block at %d, %d, %d".format(x, y, z)) + FMLCommonHandler + .instance() + .getFMLLogger + .warn("Failed getting rotation for block at %d, %d, %d".format(x, y, z)) return getDefaultFacing } return te.rotation } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/lib/rotate/RotatedHelper.scala b/src/main/scala/net/bdew/lib/rotate/RotatedHelper.scala index eb8ad55..f2b11ef 100644 --- a/src/main/scala/net/bdew/lib/rotate/RotatedHelper.scala +++ b/src/main/scala/net/bdew/lib/rotate/RotatedHelper.scala @@ -16,16 +16,27 @@ import net.minecraft.util.MathHelper import net.minecraftforge.common.util.ForgeDirection object RotatedHelper { - def getFacingFromEntity(ent: EntityLivingBase, validRotations: util.EnumSet[ForgeDirection], default: ForgeDirection): ForgeDirection = { + def getFacingFromEntity( + ent: EntityLivingBase, + validRotations: util.EnumSet[ForgeDirection], + default: ForgeDirection + ): ForgeDirection = { val pitch = Math.round(ent.rotationPitch) - val yaw = MathHelper.floor_double(ent.rotationYaw * 4.0F / 360.0F + 0.5D) & 3 + val yaw = + MathHelper.floor_double(ent.rotationYaw * 4.0f / 360.0f + 0.5d) & 3 yaw match { - case _ if pitch >= 50 && validRotations.contains(ForgeDirection.UP) => ForgeDirection.UP - case _ if pitch <= -50 && validRotations.contains(ForgeDirection.DOWN) => ForgeDirection.DOWN - case 0 if validRotations.contains(ForgeDirection.NORTH) => ForgeDirection.NORTH - case 1 if validRotations.contains(ForgeDirection.EAST) => ForgeDirection.EAST - case 2 if validRotations.contains(ForgeDirection.SOUTH) => ForgeDirection.SOUTH - case 3 if validRotations.contains(ForgeDirection.WEST) => ForgeDirection.WEST + case _ if pitch >= 50 && validRotations.contains(ForgeDirection.UP) => + ForgeDirection.UP + case _ if pitch <= -50 && validRotations.contains(ForgeDirection.DOWN) => + ForgeDirection.DOWN + case 0 if validRotations.contains(ForgeDirection.NORTH) => + ForgeDirection.NORTH + case 1 if validRotations.contains(ForgeDirection.EAST) => + ForgeDirection.EAST + case 2 if validRotations.contains(ForgeDirection.SOUTH) => + ForgeDirection.SOUTH + case 3 if validRotations.contains(ForgeDirection.WEST) => + ForgeDirection.WEST case _ => default } } diff --git a/src/main/scala/net/bdew/lib/sensors/DataSlotSensor.scala b/src/main/scala/net/bdew/lib/sensors/DataSlotSensor.scala index 241ee09..74cdf0a 100644 --- a/src/main/scala/net/bdew/lib/sensors/DataSlotSensor.scala +++ b/src/main/scala/net/bdew/lib/sensors/DataSlotSensor.scala @@ -14,20 +14,29 @@ import net.bdew.lib.data.base.{DataSlotVal, UpdateKind} import net.bdew.lib.sensors.multiblock.TileRedstoneSensorModule import net.minecraft.nbt.NBTTagCompound -case class DataSlotSensor[T, R](registry: SensorSystem[T, R], name: String, parent: TileRedstoneSensorModule, default: GenericSensorType[T, R]) extends DataSlotVal[SensorPair[T, R]] { +case class DataSlotSensor[T, R]( + registry: SensorSystem[T, R], + name: String, + parent: TileRedstoneSensorModule, + default: GenericSensorType[T, R] +) extends DataSlotVal[SensorPair[T, R]] { override var value = SensorPair(default, default.defaultParameter) setUpdate(UpdateKind.SAVE, UpdateKind.GUI) override def save(t: NBTTagCompound, kind: UpdateKind.Value) = { - t.setTag(name, Misc.applyMutator(new NBTTagCompound) { tag => - tag.setString("uid", value.sensor.uid) - value.sensor.saveParameter(value.param, tag) - }) + t.setTag( + name, + Misc.applyMutator(new NBTTagCompound) { tag => + tag.setString("uid", value.sensor.uid) + value.sensor.saveParameter(value.param, tag) + } + ) } override def load(t: NBTTagCompound, kind: UpdateKind.Value) = { - value = registry.get(t.getCompoundTag(name).getString("uid")) + value = registry + .get(t.getCompoundTag(name).getString("uid")) .map(x => SensorPair(x, x.loadParameter(t.getCompoundTag(name)))) .getOrElse(SensorPair(default, default.defaultParameter)) } diff --git a/src/main/scala/net/bdew/lib/sensors/GenericSensorType.scala b/src/main/scala/net/bdew/lib/sensors/GenericSensorType.scala index f8eb646..8f07a56 100644 --- a/src/main/scala/net/bdew/lib/sensors/GenericSensorType.scala +++ b/src/main/scala/net/bdew/lib/sensors/GenericSensorType.scala @@ -21,13 +21,20 @@ abstract class GenericSensorType[-T, +R](system: SensorSystem[T, R]) { system.register(this) def getTooltip(obj: T): List[String] = List(localizedName) - def getParamTooltip(obj: T, param: GenericSensorParameter): List[String] = List(param.localizedName) + def getParamTooltip(obj: T, param: GenericSensorParameter): List[String] = + List(param.localizedName) def localizedName = Misc.toLocal(system.localizationPrefix + "." + uid) def defaultParameter: GenericSensorParameter - def paramClicked(current: GenericSensorParameter, item: ItemStack, button: Int, mod: Int, obj: T): GenericSensorParameter + def paramClicked( + current: GenericSensorParameter, + item: ItemStack, + button: Int, + mod: Int, + obj: T + ): GenericSensorParameter def saveParameter(p: GenericSensorParameter, tag: NBTTagCompound) def loadParameter(tag: NBTTagCompound): GenericSensorParameter @@ -39,5 +46,10 @@ abstract class GenericSensorType[-T, +R](system: SensorSystem[T, R]) { def drawSensor(rect: Rect, target: DrawTarget, obj: T): Unit @SideOnly(Side.CLIENT) - def drawParameter(rect: Rect, target: DrawTarget, obj: T, param: GenericSensorParameter): Unit + def drawParameter( + rect: Rect, + target: DrawTarget, + obj: T, + param: GenericSensorParameter + ): Unit } diff --git a/src/main/scala/net/bdew/lib/sensors/RedstoneSensors.scala b/src/main/scala/net/bdew/lib/sensors/RedstoneSensors.scala index a7f003c..33b86fc 100644 --- a/src/main/scala/net/bdew/lib/sensors/RedstoneSensors.scala +++ b/src/main/scala/net/bdew/lib/sensors/RedstoneSensors.scala @@ -15,11 +15,17 @@ import net.bdew.lib.gui.{DrawTarget, IconWrapper, Rect, Texture} import net.minecraft.init.Blocks abstract class RedstoneSensors[T] extends SensorSystem[T, Boolean](false) { - lazy val rsOn = new IconWrapper(Texture.BLOCKS, Blocks.redstone_torch.getIcon(0, 0)) - lazy val rsOff = new IconWrapper(Texture.BLOCKS, Blocks.unlit_redstone_torch.getIcon(0, 0)) + lazy val rsOn = + new IconWrapper(Texture.BLOCKS, Blocks.redstone_torch.getIcon(0, 0)) + lazy val rsOff = + new IconWrapper(Texture.BLOCKS, Blocks.unlit_redstone_torch.getIcon(0, 0)) @SideOnly(Side.CLIENT) - override def drawResult(result: Boolean, rect: Rect, target: DrawTarget): Unit = { + override def drawResult( + result: Boolean, + rect: Rect, + target: DrawTarget + ): Unit = { if (result) target.drawTexture(rect, rsOn) else diff --git a/src/main/scala/net/bdew/lib/sensors/SensorPair.scala b/src/main/scala/net/bdew/lib/sensors/SensorPair.scala index 56edf20..6f2b483 100644 --- a/src/main/scala/net/bdew/lib/sensors/SensorPair.scala +++ b/src/main/scala/net/bdew/lib/sensors/SensorPair.scala @@ -9,6 +9,9 @@ package net.bdew.lib.sensors -case class SensorPair[-T, +R](sensor: GenericSensorType[T, R], param: GenericSensorParameter) { +case class SensorPair[-T, +R]( + sensor: GenericSensorType[T, R], + param: GenericSensorParameter +) { def getResult(obj: T) = sensor.getResult(param, obj) } diff --git a/src/main/scala/net/bdew/lib/sensors/SensorSystem.scala b/src/main/scala/net/bdew/lib/sensors/SensorSystem.scala index 944978b..7d1488a 100644 --- a/src/main/scala/net/bdew/lib/sensors/SensorSystem.scala +++ b/src/main/scala/net/bdew/lib/sensors/SensorSystem.scala @@ -20,7 +20,9 @@ abstract class SensorSystem[T, R](defaultResult: R) { def register[Z <: GenericSensorType[T, R]](s: Z): Z = { if (map.isDefinedAt(s.uid)) - sys.error("Duplicate sensor ID: %s (%s / %s)".format(s.uid, map(s.uid), s)) + sys.error( + "Duplicate sensor ID: %s (%s / %s)".format(s.uid, map(s.uid), s) + ) map += s.uid -> s s } @@ -55,22 +57,28 @@ abstract class SensorSystem[T, R](defaultResult: R) { override def parameters = Vector(DisabledParameter) override def uid = "disabled" - override def paramClicked(current: GenericSensorParameter, item: ItemStack, button: Int, mod: Int, obj: T): GenericSensorParameter = DisabledParameter - override def getResult(param: GenericSensorParameter, obj: T): R = defaultResult + override def paramClicked( + current: GenericSensorParameter, + item: ItemStack, + button: Int, + mod: Int, + obj: T + ): GenericSensorParameter = DisabledParameter + override def getResult(param: GenericSensorParameter, obj: T): R = + defaultResult @SideOnly(Side.CLIENT) override def texture = disabledTexture } - object DisabledSensorPair extends SensorPair(DisabledSensor, DisabledParameter) + object DisabledSensorPair + extends SensorPair(DisabledSensor, DisabledParameter) def init(): Unit = { - BdLib.logDebug("Initialized sensor system %s for mod %s", this.getClass.getName, Misc.getActiveModId) + BdLib.logDebug( + "Initialized sensor system %s for mod %s", + this.getClass.getName, + Misc.getActiveModId + ) } } - - - - - - diff --git a/src/main/scala/net/bdew/lib/sensors/SimpleGenericSensor.scala b/src/main/scala/net/bdew/lib/sensors/SimpleGenericSensor.scala index e62a32b..3d63134 100644 --- a/src/main/scala/net/bdew/lib/sensors/SimpleGenericSensor.scala +++ b/src/main/scala/net/bdew/lib/sensors/SimpleGenericSensor.scala @@ -15,7 +15,8 @@ import net.bdew.lib.gui._ import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound -abstract class SimpleGenericParameter(system: SensorSystem[_, _]) extends GenericSensorParameter(system) { +abstract class SimpleGenericParameter(system: SensorSystem[_, _]) + extends GenericSensorParameter(system) { @SideOnly(Side.CLIENT) def texture: Texture @@ -23,14 +24,22 @@ abstract class SimpleGenericParameter(system: SensorSystem[_, _]) extends Generi def textureColor = Color.white } -abstract class SimpleGenericSensor[-T, +R](system: SensorSystem[T, R]) extends GenericSensorType[T, R](system) { +abstract class SimpleGenericSensor[-T, +R](system: SensorSystem[T, R]) + extends GenericSensorType[T, R](system) { def parameters: IndexedSeq[GenericSensorParameter] - override lazy val defaultParameter = parameters.headOption.getOrElse(system.DisabledParameter) + override lazy val defaultParameter = + parameters.headOption.getOrElse(system.DisabledParameter) lazy val parameterMap = (parameters map (x => x.uid -> x)).toMap - override def paramClicked(current: GenericSensorParameter, item: ItemStack, button: Int, mod: Int, obj: T) = + override def paramClicked( + current: GenericSensorParameter, + item: ItemStack, + button: Int, + mod: Int, + obj: T + ) = if (item == null && button == 0 && mod == 0) Misc.nextInSeq(parameters, current) else if (item == null && button == 1 && mod == 0) @@ -38,9 +47,12 @@ abstract class SimpleGenericSensor[-T, +R](system: SensorSystem[T, R]) extends G else current - override def saveParameter(p: GenericSensorParameter, tag: NBTTagCompound) = tag.setString("param", p.uid) - override def loadParameter(tag: NBTTagCompound) = parameterMap.getOrElse(tag.getString("param"), system.DisabledParameter) - override def isValidParameter(p: GenericSensorParameter, obj: T) = parameters.contains(p) + override def saveParameter(p: GenericSensorParameter, tag: NBTTagCompound) = + tag.setString("param", p.uid) + override def loadParameter(tag: NBTTagCompound) = + parameterMap.getOrElse(tag.getString("param"), system.DisabledParameter) + override def isValidParameter(p: GenericSensorParameter, obj: T) = + parameters.contains(p) @SideOnly(Side.CLIENT) def texture: Texture @@ -54,12 +66,22 @@ abstract class SimpleGenericSensor[-T, +R](system: SensorSystem[T, R]) extends G } @SideOnly(Side.CLIENT) - override def drawParameter(rect: Rect, target: DrawTarget, obj: T, param: GenericSensorParameter): Unit = { + override def drawParameter( + rect: Rect, + target: DrawTarget, + obj: T, + param: GenericSensorParameter + ): Unit = { param match { - case x: SimpleGenericParameter => target.drawTexture(rect, x.texture, x.textureColor) - case _ => target.drawTexture(rect, system.DisabledParameter.texture, system.DisabledParameter.textureColor) + case x: SimpleGenericParameter => + target.drawTexture(rect, x.texture, x.textureColor) + case _ => + target.drawTexture( + rect, + system.DisabledParameter.texture, + system.DisabledParameter.textureColor + ) } } } - diff --git a/src/main/scala/net/bdew/lib/sensors/SlotSensorParameter.scala b/src/main/scala/net/bdew/lib/sensors/SlotSensorParameter.scala index 264ad3c..9ca28bd 100644 --- a/src/main/scala/net/bdew/lib/sensors/SlotSensorParameter.scala +++ b/src/main/scala/net/bdew/lib/sensors/SlotSensorParameter.scala @@ -13,10 +13,24 @@ import net.bdew.lib.gui.SlotClickable import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.{IInventory, Slot} -class SlotSensorParameter[T, R](inv: IInventory, index: Int, x: Int, y: Int, ds: DataSlotSensor[T, R], obj: => Option[T]) extends Slot(inv, index, x, y) with SlotClickable { +class SlotSensorParameter[T, R]( + inv: IInventory, + index: Int, + x: Int, + y: Int, + ds: DataSlotSensor[T, R], + obj: => Option[T] +) extends Slot(inv, index, x, y) + with SlotClickable { override def onClick(button: Int, mods: Int, player: EntityPlayer) = { obj foreach { x => - val newParam = ds.sensor.paramClicked(ds.param, player.inventory.getItemStack, button, mods, x) + val newParam = ds.sensor.paramClicked( + ds.param, + player.inventory.getItemStack, + button, + mods, + x + ) ds := ds.value.copy(param = newParam) } player.inventory.getItemStack diff --git a/src/main/scala/net/bdew/lib/sensors/SlotSensorType.scala b/src/main/scala/net/bdew/lib/sensors/SlotSensorType.scala index 5cc714f..c8943f3 100644 --- a/src/main/scala/net/bdew/lib/sensors/SlotSensorType.scala +++ b/src/main/scala/net/bdew/lib/sensors/SlotSensorType.scala @@ -14,9 +14,19 @@ import net.bdew.lib.gui.SlotClickable import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.{IInventory, Slot} -class SlotSensorType[T, R](inv: IInventory, index: Int, x: Int, y: Int, ds: DataSlotSensor[T, R], types: => Seq[GenericSensorType[T, R]]) extends Slot(inv, index, x, y) with SlotClickable { +class SlotSensorType[T, R]( + inv: IInventory, + index: Int, + x: Int, + y: Int, + ds: DataSlotSensor[T, R], + types: => Seq[GenericSensorType[T, R]] +) extends Slot(inv, index, x, y) + with SlotClickable { override def onClick(button: Int, mods: Int, player: EntityPlayer) = { - if (mods == 0 && (button == 0 || button == 1) && types.nonEmpty && player.inventory.getItemStack == null) { + if ( + mods == 0 && (button == 0 || button == 1) && types.nonEmpty && player.inventory.getItemStack == null + ) { val newSensor = if (button == 0) Misc.nextInSeq(types, ds.sensor) diff --git a/src/main/scala/net/bdew/lib/sensors/multiblock/BlockRedstoneSensorModule.scala b/src/main/scala/net/bdew/lib/sensors/multiblock/BlockRedstoneSensorModule.scala index 0f56e41..ca072d4 100644 --- a/src/main/scala/net/bdew/lib/sensors/multiblock/BlockRedstoneSensorModule.scala +++ b/src/main/scala/net/bdew/lib/sensors/multiblock/BlockRedstoneSensorModule.scala @@ -19,8 +19,21 @@ import net.minecraft.util.{ChatComponentTranslation, IIcon} import net.minecraft.world.{IBlockAccess, World} import net.minecraftforge.common.util.ForgeDirection -trait BlockRedstoneSensorModule[T <: TileRedstoneSensorModule] extends BlockModule[T] with BaseRotatableBlock with GuiProvider { - override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, meta: Int, xOffs: Float, yOffs: Float, zOffs: Float): Boolean = { +trait BlockRedstoneSensorModule[T <: TileRedstoneSensorModule] + extends BlockModule[T] + with BaseRotatableBlock + with GuiProvider { + override def onBlockActivated( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer, + meta: Int, + xOffs: Float, + yOffs: Float, + zOffs: Float + ): Boolean = { if (player.isSneaking) return false if (world.isRemote) return true val te = getTE(world, x, y, z) @@ -28,7 +41,9 @@ trait BlockRedstoneSensorModule[T <: TileRedstoneSensorModule] extends BlockModu te.config.ensureValid(te.getCore.get) doOpenGui(world, x, y, z, player) } else { - player.addChatMessage(new ChatComponentTranslation("bdlib.multiblock.notconnected")) + player.addChatMessage( + new ChatComponentTranslation("bdlib.multiblock.notconnected") + ) } true } @@ -43,7 +58,13 @@ trait BlockRedstoneSensorModule[T <: TileRedstoneSensorModule] extends BlockModu override def getFacing(world: IBlockAccess, x: Int, y: Int, z: Int) = Misc.forgeDirection(world.getBlockMetadata(x, y, z) & 7) - override def setFacing(world: World, x: Int, y: Int, z: Int, facing: ForgeDirection) = { + override def setFacing( + world: World, + x: Int, + y: Int, + z: Int, + facing: ForgeDirection + ) = { val m = world.getBlockMetadata(x, y, z) & 8 world.setBlockMetadataWithNotify(x, y, z, m | facing.ordinal(), 3) notifyTarget(world, x, y, z) @@ -59,18 +80,35 @@ trait BlockRedstoneSensorModule[T <: TileRedstoneSensorModule] extends BlockModu } override def getIcon(meta: Int, kind: IconType.Value) = kind match { - case IconType.BACK => bottomIcon + case IconType.BACK => bottomIcon case IconType.FRONT => if ((meta & 8) == 8) frontIconOn else frontIcon - case IconType.SIDE => if ((meta & 8) == 8) sideIconOn else sideIcon + case IconType.SIDE => if ((meta & 8) == 8) sideIconOn else sideIcon } override def canProvidePower = true - override def isSideSolid(world: IBlockAccess, x: Int, y: Int, z: Int, side: ForgeDirection) = true + override def isSideSolid( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: ForgeDirection + ) = true - override def isProvidingWeakPower(w: IBlockAccess, x: Int, y: Int, z: Int, side: Int) = { + override def isProvidingWeakPower( + w: IBlockAccess, + x: Int, + y: Int, + z: Int, + side: Int + ) = { val m = w.getBlockMetadata(x, y, z) - if (((m & 7) == Misc.forgeDirection(side).getOpposite.ordinal()) && ((m & 8) == 8)) + if ( + ((m & 7) == Misc + .forgeDirection(side) + .getOpposite + .ordinal()) && ((m & 8) == 8) + ) 15 else 0 diff --git a/src/main/scala/net/bdew/lib/sensors/multiblock/SensorOutput.scala b/src/main/scala/net/bdew/lib/sensors/multiblock/SensorOutput.scala index ddb14ff..1b1b883 100644 --- a/src/main/scala/net/bdew/lib/sensors/multiblock/SensorOutput.scala +++ b/src/main/scala/net/bdew/lib/sensors/multiblock/SensorOutput.scala @@ -16,7 +16,11 @@ import net.bdew.lib.Misc import net.bdew.lib.gui._ import net.bdew.lib.multiblock.interact.CIOutputFaces import net.bdew.lib.render.connected.BlockAdditionalRender -import net.bdew.lib.sensors.{GenericSensorParameter, GenericSensorType, SensorSystem} +import net.bdew.lib.sensors.{ + GenericSensorParameter, + GenericSensorType, + SensorSystem +} import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraft.tileentity.TileEntity @@ -26,7 +30,8 @@ trait SensorOutput extends GenericSensorType[TileEntity, Boolean] { override def defaultParameter = system.DisabledParameter - case class SensorOutputFlowParameter(output: Int) extends GenericSensorParameter(system) { + case class SensorOutputFlowParameter(output: Int) + extends GenericSensorParameter(system) { override val uid: String = "output." + output } @@ -39,23 +44,40 @@ trait SensorOutput extends GenericSensorType[TileEntity, Boolean] { system.DisabledParameter } - override def saveParameter(p: GenericSensorParameter, tag: NBTTagCompound): Unit = p match { + override def saveParameter( + p: GenericSensorParameter, + tag: NBTTagCompound + ): Unit = p match { case SensorOutputFlowParameter(n) => tag.setInteger("output", n) - case _ => + case _ => } - override def isValidParameter(p: GenericSensorParameter, obj: TileEntity): Boolean = (p, obj) match { - case (SensorOutputFlowParameter(n), x: CIOutputFaces) => x.outputFaces.inverted.isDefinedAt(n) + override def isValidParameter( + p: GenericSensorParameter, + obj: TileEntity + ): Boolean = (p, obj) match { + case (SensorOutputFlowParameter(n), x: CIOutputFaces) => + x.outputFaces.inverted.isDefinedAt(n) case (param, _) if param == system.DisabledParameter => true + case _ => false + } + + override def getResult( + param: GenericSensorParameter, + obj: TileEntity + ): Boolean = (param, obj) match { + case (SensorOutputFlowParameter(n), x: CIOutputFaces) => + getResultFromOutput(x, n) case _ => false } - override def getResult(param: GenericSensorParameter, obj: TileEntity): Boolean = (param, obj) match { - case (SensorOutputFlowParameter(n), x: CIOutputFaces) => getResultFromOutput(x, n) - case _ => false - } - - override def paramClicked(current: GenericSensorParameter, item: ItemStack, button: Int, mod: Int, obj: TileEntity) = + override def paramClicked( + current: GenericSensorParameter, + item: ItemStack, + button: Int, + mod: Int, + obj: TileEntity + ) = if (mod == 0 && (button == 0 || button == 1) && item == null) (current, obj) match { case (SensorOutputFlowParameter(n), x: CIOutputFaces) => @@ -78,36 +100,82 @@ trait SensorOutput extends GenericSensorType[TileEntity, Boolean] { else current @SideOnly(Side.CLIENT) - override def drawParameter(rect: Rect, target: DrawTarget, obj: TileEntity, param: GenericSensorParameter): Unit = (param, obj) match { + override def drawParameter( + rect: Rect, + target: DrawTarget, + obj: TileEntity, + param: GenericSensorParameter + ): Unit = (param, obj) match { case (SensorOutputFlowParameter(output), te: CIOutputFaces) => val faces = te.outputFaces.inverted if (faces.isDefinedAt(output)) { val bf = faces(output) bf.origin.block(te.getWorldObj) foreach { block => - target.drawTexture(rect, Texture(Texture.BLOCKS, block.getIcon(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face.ordinal()))) + target.drawTexture( + rect, + Texture( + Texture.BLOCKS, + block.getIcon( + te.getWorldObj, + bf.origin.x, + bf.origin.y, + bf.origin.z, + bf.face.ordinal() + ) + ) + ) if (block.isInstanceOf[BlockAdditionalRender]) { - for (over <- block.asInstanceOf[BlockAdditionalRender].getFaceOverlays(te.getWorldObj, bf.origin.x, bf.origin.y, bf.origin.z, bf.face)) - target.drawTexture(rect, Texture(Texture.BLOCKS, over.icon), over.color) + for ( + over <- block + .asInstanceOf[BlockAdditionalRender] + .getFaceOverlays( + te.getWorldObj, + bf.origin.x, + bf.origin.y, + bf.origin.z, + bf.face + ) + ) + target.drawTexture( + rect, + Texture(Texture.BLOCKS, over.icon), + over.color + ) } } } - case _ => target.drawTexture(rect, system.DisabledParameter.texture, system.DisabledParameter.textureColor) + case _ => + target.drawTexture( + rect, + system.DisabledParameter.texture, + system.DisabledParameter.textureColor + ) } - override def getParamTooltip(obj: TileEntity, param: GenericSensorParameter) = (param, obj) match { - case (SensorOutputFlowParameter(output), te: CIOutputFaces) => - val faces = te.outputFaces.inverted - var list = List.empty[String] - list :+= Misc.toLocal(te.resources.unlocalizedOutputName(output)) - if (faces.isDefinedAt(output)) { - val bf = faces(output) - bf.origin.block(te.getWorldObj) foreach { block => - list :+= block.getLocalizedName - list :+= "%d, %d, %d - %s".format(bf.x, bf.y, bf.z, Misc.toLocal("bdlib.multiblock.face." + bf.face.toString.toLowerCase(Locale.US))) + override def getParamTooltip(obj: TileEntity, param: GenericSensorParameter) = + (param, obj) match { + case (SensorOutputFlowParameter(output), te: CIOutputFaces) => + val faces = te.outputFaces.inverted + var list = List.empty[String] + list :+= Misc.toLocal(te.resources.unlocalizedOutputName(output)) + if (faces.isDefinedAt(output)) { + val bf = faces(output) + bf.origin.block(te.getWorldObj) foreach { block => + list :+= block.getLocalizedName + list :+= "%d, %d, %d - %s".format( + bf.x, + bf.y, + bf.z, + Misc.toLocal( + "bdlib.multiblock.face." + bf.face.toString.toLowerCase( + Locale.US + ) + ) + ) + } } - } - list - case _ => super.getParamTooltip(obj, param) - } + list + case _ => super.getParamTooltip(obj, param) + } } diff --git a/src/main/scala/net/bdew/lib/sensors/multiblock/TileRedstoneSensorModule.scala b/src/main/scala/net/bdew/lib/sensors/multiblock/TileRedstoneSensorModule.scala index 50bb1ba..ce5fe8c 100644 --- a/src/main/scala/net/bdew/lib/sensors/multiblock/TileRedstoneSensorModule.scala +++ b/src/main/scala/net/bdew/lib/sensors/multiblock/TileRedstoneSensorModule.scala @@ -17,7 +17,10 @@ import net.minecraft.block.Block import net.minecraft.tileentity.TileEntity import net.minecraft.world.World -abstract class TileRedstoneSensorModule(val system: RedstoneSensors[TileEntity], block: BlockRedstoneSensorModule[_]) extends TileModule { +abstract class TileRedstoneSensorModule( + val system: RedstoneSensors[TileEntity], + block: BlockRedstoneSensorModule[_] +) extends TileModule { override val kind = "Sensor" override def getCore = getCoreAs[CIRedstoneSensors] @@ -38,7 +41,8 @@ abstract class TileRedstoneSensorModule(val system: RedstoneSensors[TileEntity], } override def canConnectToCore(br: BlockRef): Boolean = - br.getTile[CIRedstoneSensors](worldObj).exists(_.redstoneSensorSystem == system) + br.getTile[CIRedstoneSensors](worldObj) + .exists(_.redstoneSensorSystem == system) def isSignalOn = block.isSignalOn(worldObj, xCoord, yCoord, zCoord) @@ -49,6 +53,15 @@ abstract class TileRedstoneSensorModule(val system: RedstoneSensors[TileEntity], } }) - override def shouldRefresh(oldBlock: Block, newBlock: Block, oldMeta: Int, newMeta: Int, world: World, x: Int, y: Int, z: Int) = + override def shouldRefresh( + oldBlock: Block, + newBlock: Block, + oldMeta: Int, + newMeta: Int, + world: World, + x: Int, + y: Int, + z: Int + ) = newBlock != oldBlock } diff --git a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorParam.scala b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorParam.scala index 8cc4d57..49b263b 100644 --- a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorParam.scala +++ b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorParam.scala @@ -15,12 +15,18 @@ import net.bdew.lib.sensors.SensorPair import scala.collection.mutable -class WidgetSensorParam[T](val p: Point, config: => SensorPair[T, _], obj: => Option[T]) extends Widget { +class WidgetSensorParam[T]( + val p: Point, + config: => SensorPair[T, _], + obj: => Option[T] +) extends Widget { override val rect = new Rect(p, 16, 16) override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = for (x <- obj; s <- config.sensor.getParamTooltip(x, config.param)) tip += s override def draw(mouse: Point) = - obj foreach (x => config.sensor.drawParameter(rect, parent, x, config.param)) + obj foreach (x => + config.sensor.drawParameter(rect, parent, x, config.param) + ) } diff --git a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorResult.scala b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorResult.scala index 59e44b2..5039fec 100644 --- a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorResult.scala +++ b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorResult.scala @@ -15,7 +15,11 @@ import net.bdew.lib.sensors.SensorSystem import scala.collection.mutable -class WidgetSensorResult[T](val p: Point, state: => T, system: SensorSystem[_, T]) extends Widget { +class WidgetSensorResult[T]( + val p: Point, + state: => T, + system: SensorSystem[_, T] +) extends Widget { override val rect = new Rect(p, 16, 16) override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = diff --git a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorType.scala b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorType.scala index a29f538..e22e912 100644 --- a/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorType.scala +++ b/src/main/scala/net/bdew/lib/sensors/widgets/WidgetSensorType.scala @@ -15,14 +15,16 @@ import net.bdew.lib.sensors.GenericSensorType import scala.collection.mutable -class WidgetSensorType[T](val p: Point, sensor: => GenericSensorType[T, _], obj: => Option[T]) extends Widget { +class WidgetSensorType[T]( + val p: Point, + sensor: => GenericSensorType[T, _], + obj: => Option[T] +) extends Widget { override val rect = new Rect(p, 16, 16) override def handleTooltip(p: Point, tip: mutable.MutableList[String]) = for (x <- obj; s <- sensor.getTooltip(x)) tip += s - override def draw(mouse: Point) = obj foreach (x => sensor.drawSensor(rect, parent, x)) + override def draw(mouse: Point) = + obj foreach (x => sensor.drawSensor(rect, parent, x)) } - - - diff --git a/src/main/scala/net/bdew/lib/tile/ExposeTank.scala b/src/main/scala/net/bdew/lib/tile/ExposeTank.scala index b852e00..65edf18 100644 --- a/src/main/scala/net/bdew/lib/tile/ExposeTank.scala +++ b/src/main/scala/net/bdew/lib/tile/ExposeTank.scala @@ -22,21 +22,33 @@ trait ExposeTank extends TileEntity with IFluidHandler { return tank.fill(resource, doFill) } - def drain(from: ForgeDirection, resource: FluidStack, doDrain: Boolean): FluidStack = { + def drain( + from: ForgeDirection, + resource: FluidStack, + doDrain: Boolean + ): FluidStack = { val tank = getTankFromDirection(from) - if (tank == null || resource == null || !resource.isFluidEqual(tank.getFluid)) return null + if ( + tank == null || resource == null || !resource.isFluidEqual(tank.getFluid) + ) return null return tank.drain(resource.amount, doDrain) } - def drain(from: ForgeDirection, maxDrain: Int, doDrain: Boolean): FluidStack = { + def drain( + from: ForgeDirection, + maxDrain: Int, + doDrain: Boolean + ): FluidStack = { val tank = getTankFromDirection(from) if (tank == null) return null getTankFromDirection(from).drain(maxDrain, doDrain) } - def canFill(from: ForgeDirection, fluid: Fluid): Boolean = getTankFromDirection(from) != null + def canFill(from: ForgeDirection, fluid: Fluid): Boolean = + getTankFromDirection(from) != null - def canDrain(from: ForgeDirection, fluid: Fluid): Boolean = getTankFromDirection(from) != null + def canDrain(from: ForgeDirection, fluid: Fluid): Boolean = + getTankFromDirection(from) != null def getTankInfo(from: ForgeDirection): Array[FluidTankInfo] = { val tank = getTankFromDirection(from) diff --git a/src/main/scala/net/bdew/lib/tile/TankEmulator.scala b/src/main/scala/net/bdew/lib/tile/TankEmulator.scala index bbbaa28..ebd6453 100644 --- a/src/main/scala/net/bdew/lib/tile/TankEmulator.scala +++ b/src/main/scala/net/bdew/lib/tile/TankEmulator.scala @@ -13,13 +13,18 @@ import net.bdew.lib.Misc import net.bdew.lib.data.base.DataSlotNumeric import net.minecraftforge.fluids.{Fluid, FluidStack, FluidTankInfo, IFluidTank} -case class TankEmulator[T: Numeric](fluid: Fluid, ds: DataSlotNumeric[T], capacity: Int) extends IFluidTank { +case class TankEmulator[T: Numeric]( + fluid: Fluid, + ds: DataSlotNumeric[T], + capacity: Int +) extends IFluidTank { val num = implicitly[Numeric[T]] override def getFluidAmount: Int = num.toDouble(ds).floor.toInt override def getCapacity: Int = capacity - override def getFluid: FluidStack = if (getFluidAmount > 0) new FluidStack(fluid, getFluidAmount) else null + override def getFluid: FluidStack = + if (getFluidAmount > 0) new FluidStack(fluid, getFluidAmount) else null override def getInfo: FluidTankInfo = new FluidTankInfo(this) diff --git a/src/main/scala/net/bdew/lib/tile/TileExtended.scala b/src/main/scala/net/bdew/lib/tile/TileExtended.scala index 0097205..ff34907 100644 --- a/src/main/scala/net/bdew/lib/tile/TileExtended.scala +++ b/src/main/scala/net/bdew/lib/tile/TileExtended.scala @@ -43,10 +43,19 @@ class TileExtended extends TileEntity { if (!sendClientUpdate.hasListeners) return null val tag = new NBTTagCompound sendClientUpdate.trigger(tag) - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, ACT_CLIENT, tag) + return new S35PacketUpdateTileEntity( + this.xCoord, + this.yCoord, + this.zCoord, + ACT_CLIENT, + tag + ) } - override final def onDataPacket(net: NetworkManager, pkt: S35PacketUpdateTileEntity) { + override final def onDataPacket( + net: NetworkManager, + pkt: S35PacketUpdateTileEntity + ) { if (pkt.func_148853_f == ACT_CLIENT) handleClientUpdate.trigger(pkt.func_148857_g) else diff --git a/src/main/scala/net/bdew/lib/tile/inventory/BreakableInventoryBlock.scala b/src/main/scala/net/bdew/lib/tile/inventory/BreakableInventoryBlock.scala index 583212e..7d15988 100644 --- a/src/main/scala/net/bdew/lib/tile/inventory/BreakableInventoryBlock.scala +++ b/src/main/scala/net/bdew/lib/tile/inventory/BreakableInventoryBlock.scala @@ -15,7 +15,14 @@ import net.minecraft.world.World trait BreakableInventoryBlock extends Block { this: HasTE[_ <: BreakableInventoryTile] => - override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, meta: Int) { + override def breakBlock( + world: World, + x: Int, + y: Int, + z: Int, + block: Block, + meta: Int + ) { if (!world.isRemote) { getTE(world, x, y, z).dropItems() } diff --git a/src/main/scala/net/bdew/lib/tile/inventory/InventoryProxy.scala b/src/main/scala/net/bdew/lib/tile/inventory/InventoryProxy.scala index 1b990af..adbd6c1 100644 --- a/src/main/scala/net/bdew/lib/tile/inventory/InventoryProxy.scala +++ b/src/main/scala/net/bdew/lib/tile/inventory/InventoryProxy.scala @@ -25,17 +25,27 @@ trait InventoryProxy extends TileEntity with IInventory { super.markDirty() } - override def getSizeInventory = targetInventory map (_.getSizeInventory) getOrElse 0 - override def getInventoryStackLimit = targetInventory map (_.getInventoryStackLimit) getOrElse 64 + override def getSizeInventory = + targetInventory map (_.getSizeInventory) getOrElse 0 + override def getInventoryStackLimit = + targetInventory map (_.getInventoryStackLimit) getOrElse 64 - override def getStackInSlot(slot: Int) = targetInventory.map(_.getStackInSlot(slot)).orNull - override def getStackInSlotOnClosing(slot: Int) = targetInventory.map(_.getStackInSlotOnClosing(slot)).orNull - override def setInventorySlotContents(slot: Int, item: ItemStack) = targetInventory.foreach(_.setInventorySlotContents(slot, item)) - override def decrStackSize(slot: Int, num: Int) = targetInventory.map(_.decrStackSize(slot, num)).orNull + override def getStackInSlot(slot: Int) = + targetInventory.map(_.getStackInSlot(slot)).orNull + override def getStackInSlotOnClosing(slot: Int) = + targetInventory.map(_.getStackInSlotOnClosing(slot)).orNull + override def setInventorySlotContents(slot: Int, item: ItemStack) = + targetInventory.foreach(_.setInventorySlotContents(slot, item)) + override def decrStackSize(slot: Int, num: Int) = + targetInventory.map(_.decrStackSize(slot, num)).orNull - override def isItemValidForSlot(slot: Int, item: ItemStack) = targetInventory.exists(_.isItemValidForSlot(slot, item)) - override def isUseableByPlayer(player: EntityPlayer) = targetInventory.exists(_.isUseableByPlayer(player)) + override def isItemValidForSlot(slot: Int, item: ItemStack) = + targetInventory.exists(_.isItemValidForSlot(slot, item)) + override def isUseableByPlayer(player: EntityPlayer) = + targetInventory.exists(_.isUseableByPlayer(player)) - override def getInventoryName = targetInventory.map(_.getInventoryName).getOrElse("") - override def hasCustomInventoryName = targetInventory.exists(_.hasCustomInventoryName) + override def getInventoryName = + targetInventory.map(_.getInventoryName).getOrElse("") + override def hasCustomInventoryName = + targetInventory.exists(_.hasCustomInventoryName) } diff --git a/src/main/scala/net/bdew/lib/tile/inventory/MultipleInventoryAdapter.scala b/src/main/scala/net/bdew/lib/tile/inventory/MultipleInventoryAdapter.scala index 2ee99db..ad8451a 100644 --- a/src/main/scala/net/bdew/lib/tile/inventory/MultipleInventoryAdapter.scala +++ b/src/main/scala/net/bdew/lib/tile/inventory/MultipleInventoryAdapter.scala @@ -13,14 +13,20 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.IInventory import net.minecraft.item.ItemStack -class MultipleInventoryAdapter(val map: Map[Int, (IInventory, Int)]) extends IInventory { +class MultipleInventoryAdapter(val map: Map[Int, (IInventory, Int)]) + extends IInventory { def this(inventories: Iterable[IInventory]) = - this((inventories flatMap { inv => (0 until inv.getSizeInventory).map((inv, _)) }).zipWithIndex.map(_.swap).toMap) + this((inventories flatMap { inv => + (0 until inv.getSizeInventory).map((inv, _)) + }).zipWithIndex.map(_.swap).toMap) def this(inventories: IInventory*) = - this((inventories flatMap { inv => (0 until inv.getSizeInventory).map((inv, _)) }).zipWithIndex.map(_.swap).toMap) + this((inventories flatMap { inv => + (0 until inv.getSizeInventory).map((inv, _)) + }).zipWithIndex.map(_.swap).toMap) lazy val inventories = map.values.map(_._1).toSet - override lazy val getInventoryStackLimit = inventories.map(_.getInventoryStackLimit).min + override lazy val getInventoryStackLimit = + inventories.map(_.getInventoryStackLimit).min override lazy val getSizeInventory = map.keySet.max + 1 private def run[T](slot: Int, f: (IInventory, Int) => T): Option[T] = @@ -44,7 +50,8 @@ class MultipleInventoryAdapter(val map: Map[Int, (IInventory, Int)]) extends IIn override def markDirty() = inventories.foreach(_.markDirty()) override def closeInventory() = inventories.foreach(_.closeInventory()) override def openInventory() = inventories.foreach(_.openInventory()) - override def isUseableByPlayer(p: EntityPlayer) = inventories.exists(_.isUseableByPlayer(p)) + override def isUseableByPlayer(p: EntityPlayer) = + inventories.exists(_.isUseableByPlayer(p)) override def hasCustomInventoryName = false override def getInventoryName = "" diff --git a/src/main/scala/net/bdew/lib/tile/inventory/PersistentInventoryTile.scala b/src/main/scala/net/bdew/lib/tile/inventory/PersistentInventoryTile.scala index 3a22fe4..c707e8b 100644 --- a/src/main/scala/net/bdew/lib/tile/inventory/PersistentInventoryTile.scala +++ b/src/main/scala/net/bdew/lib/tile/inventory/PersistentInventoryTile.scala @@ -29,11 +29,13 @@ trait PersistentInventoryTile extends TileExtended with BaseInventory { }) persistSave.listen((tag: NBTTagCompound) => { - tag.setList("Items", + tag.setList( + "Items", for ((item, i) <- inv.view.zipWithIndex if item != null) yield Misc.applyMutator(new NBTTagCompound) { itemNbt => itemNbt.setByte("Slot", i.asInstanceOf[Byte]) item.writeToNBT(itemNbt) - }) + } + ) }) } diff --git a/src/main/scala/net/bdew/lib/tile/inventory/SidedInventory.scala b/src/main/scala/net/bdew/lib/tile/inventory/SidedInventory.scala index 7adb5a3..3ed11d4 100644 --- a/src/main/scala/net/bdew/lib/tile/inventory/SidedInventory.scala +++ b/src/main/scala/net/bdew/lib/tile/inventory/SidedInventory.scala @@ -17,7 +17,8 @@ trait SidedInventory extends BaseInventory with ISidedInventory { def getAccessibleSlotsFromSide(side: Int): Array[Int] = inv.indices.toArray - def canInsertItem(slot: Int, stack: ItemStack, side: Int) = allowSided && isItemValidForSlot(slot, stack) + def canInsertItem(slot: Int, stack: ItemStack, side: Int) = + allowSided && isItemValidForSlot(slot, stack) def canExtractItem(slot: Int, stack: ItemStack, side: Int) = allowSided } diff --git a/src/main/scala/net/bdew/lib/tooltip/FluidTooltipProvider.scala b/src/main/scala/net/bdew/lib/tooltip/FluidTooltipProvider.scala index b78264d..6089087 100644 --- a/src/main/scala/net/bdew/lib/tooltip/FluidTooltipProvider.scala +++ b/src/main/scala/net/bdew/lib/tooltip/FluidTooltipProvider.scala @@ -10,7 +10,11 @@ package net.bdew.lib.tooltip import net.minecraft.item.ItemStack -import net.minecraftforge.fluids.{FluidContainerRegistry, FluidStack, IFluidContainerItem} +import net.minecraftforge.fluids.{ + FluidContainerRegistry, + FluidStack, + IFluidContainerItem +} trait FluidTooltipProvider extends TooltipProvider { def getFluid(is: ItemStack): Option[FluidStack] = { @@ -21,10 +25,21 @@ trait FluidTooltipProvider extends TooltipProvider { } } - override def shouldHandleTooltip(stack: ItemStack): Boolean = getFluid(stack) exists shouldHandleTooltip - override def handleTooltip(stack: ItemStack, advanced: Boolean, shift: Boolean): Iterable[String] = - getFluid(stack) map (f => handleTooltip(f, advanced, shift)) getOrElse Iterable.empty + override def shouldHandleTooltip(stack: ItemStack): Boolean = + getFluid(stack) exists shouldHandleTooltip + override def handleTooltip( + stack: ItemStack, + advanced: Boolean, + shift: Boolean + ): Iterable[String] = + getFluid(stack) map (f => + handleTooltip(f, advanced, shift) + ) getOrElse Iterable.empty def shouldHandleTooltip(fluid: FluidStack): Boolean - def handleTooltip(fluid: FluidStack, advanced: Boolean, shift: Boolean): Iterable[String] + def handleTooltip( + fluid: FluidStack, + advanced: Boolean, + shift: Boolean + ): Iterable[String] } diff --git a/src/main/scala/net/bdew/lib/tooltip/TooltipHandler.scala b/src/main/scala/net/bdew/lib/tooltip/TooltipHandler.scala index acf86c4..43d98fa 100644 --- a/src/main/scala/net/bdew/lib/tooltip/TooltipHandler.scala +++ b/src/main/scala/net/bdew/lib/tooltip/TooltipHandler.scala @@ -30,7 +30,13 @@ object TooltipHandler { val toAdd = for (provider <- registry) yield { try { if (provider.shouldHandleTooltip(ev.itemStack)) - Some(provider.handleTooltip(ev.itemStack, ev.showAdvancedItemTooltips, Client.shiftDown)) + Some( + provider.handleTooltip( + ev.itemStack, + ev.showAdvancedItemTooltips, + Client.shiftDown + ) + ) else None } catch { diff --git a/src/main/scala/net/bdew/lib/tooltip/TooltipProvider.scala b/src/main/scala/net/bdew/lib/tooltip/TooltipProvider.scala index 39e8c96..8598266 100644 --- a/src/main/scala/net/bdew/lib/tooltip/TooltipProvider.scala +++ b/src/main/scala/net/bdew/lib/tooltip/TooltipProvider.scala @@ -13,6 +13,9 @@ import net.minecraft.item.ItemStack trait TooltipProvider { def shouldHandleTooltip(stack: ItemStack): Boolean - def handleTooltip(stack: ItemStack, advanced: Boolean, shift: Boolean): Iterable[String] + def handleTooltip( + stack: ItemStack, + advanced: Boolean, + shift: Boolean + ): Iterable[String] } - diff --git a/src/main/scala/net/bdew/lib/world/BlockAccessProxy.scala b/src/main/scala/net/bdew/lib/world/BlockAccessProxy.scala index e39b7c3..79df271 100644 --- a/src/main/scala/net/bdew/lib/world/BlockAccessProxy.scala +++ b/src/main/scala/net/bdew/lib/world/BlockAccessProxy.scala @@ -22,12 +22,23 @@ class BlockAccessProxy(base: IBlockAccess) extends IBlockAccess { override def getTileEntity(x: Int, y: Int, z: Int) = base.getTileEntity(x, y, z) - override def isSideSolid(x: Int, y: Int, z: Int, side: ForgeDirection, default: Boolean) = + override def isSideSolid( + x: Int, + y: Int, + z: Int, + side: ForgeDirection, + default: Boolean + ) = base.isSideSolid(x, y, z, side, default) override def getHeight = base.getHeight - override def getLightBrightnessForSkyBlocks(x: Int, y: Int, z: Int, lightValue: Int) = + override def getLightBrightnessForSkyBlocks( + x: Int, + y: Int, + z: Int, + lightValue: Int + ) = base.getLightBrightnessForSkyBlocks(x, y, z, lightValue) override def isBlockProvidingPowerTo(x: Int, y: Int, z: Int, side: Int) =