diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..fd2792b6 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary +*.[xX][cC][fF] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary +*.[tT][tT][fF] binary +*.[oO][tT][fF] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..93c852a1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/java/thaumicenergistics/api/IThEBlocks.java b/src/main/java/thaumicenergistics/api/IThEBlocks.java index 5d3073c1..2b657d31 100644 --- a/src/main/java/thaumicenergistics/api/IThEBlocks.java +++ b/src/main/java/thaumicenergistics/api/IThEBlocks.java @@ -8,59 +8,58 @@ import javax.annotation.Nonnull; * @author Nividica * */ -public abstract class IThEBlocks -{ - /** - * Arcane Assembler. - */ - @Nonnull - public IThEItemDescription ArcaneAssembler; +public abstract class IThEBlocks { + /** + * Arcane Assembler. + */ + @Nonnull + public IThEItemDescription ArcaneAssembler; - /** - * Distilation Pattern Encoder. - */ - @Nonnull - public IThEItemDescription DistillationPatternEncoder; + /** + * Distilation Pattern Encoder. + */ + @Nonnull + public IThEItemDescription DistillationPatternEncoder; - /** - * Essentia Cell Workbench. - */ - @Nonnull - public IThEItemDescription EssentiaCellWorkbench; + /** + * Essentia Cell Workbench. + */ + @Nonnull + public IThEItemDescription EssentiaCellWorkbench; - /** - * Essentia Provider. - */ - @Nonnull - public IThEItemDescription EssentiaProvider; + /** + * Essentia Provider. + */ + @Nonnull + public IThEItemDescription EssentiaProvider; - /** - * Essentia Vibration Chamber. - */ - @Nonnull - public IThEItemDescription EssentiaVibrationChamber; + /** + * Essentia Vibration Chamber. + */ + @Nonnull + public IThEItemDescription EssentiaVibrationChamber; - /** - * Infusion Provider. - */ - @Nonnull - public IThEItemDescription InfusionProvider; + /** + * Infusion Provider. + */ + @Nonnull + public IThEItemDescription InfusionProvider; - /** - * Iron Gearbox. - */ - @Nonnull - public IThEItemDescription IronGearBox; + /** + * Iron Gearbox. + */ + @Nonnull + public IThEItemDescription IronGearBox; - /** - * Knowledge Inscriber. - */ - @Nonnull - public IThEItemDescription KnowledgeInscriber; + /** + * Knowledge Inscriber. + */ + @Nonnull + public IThEItemDescription KnowledgeInscriber; - /** - * Thaumium Gearbox. - */ - @Nonnull - public IThEItemDescription ThaumiumGearBox; + /** + * Thaumium Gearbox. + */ + @Nonnull + public IThEItemDescription ThaumiumGearBox; } diff --git a/src/main/java/thaumicenergistics/api/IThEConfig.java b/src/main/java/thaumicenergistics/api/IThEConfig.java index 6fa03fcd..51db3822 100644 --- a/src/main/java/thaumicenergistics/api/IThEConfig.java +++ b/src/main/java/thaumicenergistics/api/IThEConfig.java @@ -6,117 +6,116 @@ package thaumicenergistics.api; * @author Nividica * */ -public interface IThEConfig -{ - /** - * If true essentia gas will be blacklisted from ExtraCells. - * - * @return - */ - boolean blacklistEssentiaFluidInExtraCells(); +public interface IThEConfig { + /** + * If true essentia gas will be blacklisted from ExtraCells. + * + * @return + */ + boolean blacklistEssentiaFluidInExtraCells(); - /** - * Controls the conversion ratio of essentia/fluid.
- * 1 essentia unit is converted to this many mb's of fluid. - */ - int conversionMultiplier(); + /** + * Controls the conversion ratio of essentia/fluid.
+ * 1 essentia unit is converted to this many mb's of fluid. + */ + int conversionMultiplier(); - /** - * Can the Arcane Assembler be crafted. - * - * @return - */ - boolean craftArcaneAssembler(); + /** + * Can the Arcane Assembler be crafted. + * + * @return + */ + boolean craftArcaneAssembler(); - /** - * Can the ACT be crafted. - * - * @return - */ - boolean craftArcaneCraftingTerminal(); + /** + * Can the ACT be crafted. + * + * @return + */ + boolean craftArcaneCraftingTerminal(); - /** - * Can the DPE be crafted. - * - * @return - */ - boolean craftDistillationPatternEncoder(); + /** + * Can the DPE be crafted. + * + * @return + */ + boolean craftDistillationPatternEncoder(); - /** - * Can Essentia cells be crafted. - * - * @return - */ - boolean craftEssentiaCells(); + /** + * Can Essentia cells be crafted. + * + * @return + */ + boolean craftEssentiaCells(); - /** - * Can the Essentia Provider be crafted. - */ - boolean craftEssentiaProvider(); + /** + * Can the Essentia Provider be crafted. + */ + boolean craftEssentiaProvider(); - /** - * Can the EVC be crafted. - * - * @return - */ - boolean craftEssentiaVibrationChamber(); + /** + * Can the EVC be crafted. + * + * @return + */ + boolean craftEssentiaVibrationChamber(); - /** - * Can the golem backpack be crafted. - * - * @return - */ - boolean craftGolemWifiBackpack(); + /** + * Can the golem backpack be crafted. + * + * @return + */ + boolean craftGolemWifiBackpack(); - /** - * Can the Infusion Provider be crafted. - */ - boolean craftInfusionProvider(); + /** + * Can the Infusion Provider be crafted. + */ + boolean craftInfusionProvider(); - /** - * Controls if the import/export/storage can be crafted. - * - * @return - */ - boolean craftIOBuses(); + /** + * Controls if the import/export/storage can be crafted. + * + * @return + */ + boolean craftIOBuses(); - /** - * Can the VRI be crafted. - * - * @return - */ - boolean craftVisRelayInterface(); + /** + * Can the VRI be crafted. + * + * @return + */ + boolean craftVisRelayInterface(); - /** - * Can the WET be crafted. - * - * @return - */ - boolean craftWirelessEssentiaTerminal(); + /** + * Can the WET be crafted. + * + * @return + */ + boolean craftWirelessEssentiaTerminal(); - /** - * If true the iron and thaumium gearbox's will be rendered as a standard - * block. - */ - boolean disableGearboxModel(); + /** + * If true the iron and thaumium gearbox's will be rendered as a standard + * block. + */ + boolean disableGearboxModel(); - /** - * Controls if Certus Quartz can be duped in the crucible. - */ - boolean enableCertusQuartzDupe(); + /** + * Controls if Certus Quartz can be duped in the crucible. + */ + boolean enableCertusQuartzDupe(); - /** - * Is the wrench focus enabled. - * - * @return - */ - boolean enableWrenchFocus(); + /** + * Is the wrench focus enabled. + * + * @return + */ + boolean enableWrenchFocus(); - /** - * When enabled, overwrites the AE2 facade setting for certain Thaumcraft blocks, - * allowing them to become facades. - * - * @return - */ - boolean forceTCFacades(); + /** + * When enabled, overwrites the AE2 facade setting for certain Thaumcraft blocks, + * allowing them to become facades. + * + * @return + */ + boolean forceTCFacades(); } diff --git a/src/main/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java b/src/main/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java index b10608e1..575d3216 100644 --- a/src/main/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java +++ b/src/main/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java @@ -6,15 +6,14 @@ package thaumicenergistics.api; * @author Nividica * */ -public interface IThEEssentiaContainerPermission -{ - /** - * Can the container be partially filled? - */ - boolean canHoldPartialAmount(); +public interface IThEEssentiaContainerPermission { + /** + * Can the container be partially filled? + */ + boolean canHoldPartialAmount(); - /** - * The maximum amount this container can hold - */ - int maximumCapacity(); + /** + * The maximum amount this container can hold + */ + int maximumCapacity(); } diff --git a/src/main/java/thaumicenergistics/api/IThEEssentiaGas.java b/src/main/java/thaumicenergistics/api/IThEEssentiaGas.java index 96ea4f86..3d960273 100644 --- a/src/main/java/thaumicenergistics/api/IThEEssentiaGas.java +++ b/src/main/java/thaumicenergistics/api/IThEEssentiaGas.java @@ -9,14 +9,13 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IThEEssentiaGas -{ - /** - * Get the aspect of the gas.
- * Can be null if the gas itself is invalid. - * - * @return - */ - @Nullable - Aspect getAspect(); +public interface IThEEssentiaGas { + /** + * Get the aspect of the gas.
+ * Can be null if the gas itself is invalid. + * + * @return + */ + @Nullable + Aspect getAspect(); } diff --git a/src/main/java/thaumicenergistics/api/IThEInteractionHelper.java b/src/main/java/thaumicenergistics/api/IThEInteractionHelper.java index 1bb1577a..da630ca2 100644 --- a/src/main/java/thaumicenergistics/api/IThEInteractionHelper.java +++ b/src/main/java/thaumicenergistics/api/IThEInteractionHelper.java @@ -1,9 +1,9 @@ package thaumicenergistics.api; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import thaumcraft.api.aspects.Aspect; @@ -16,80 +16,79 @@ import thaumicenergistics.api.storage.IAspectStack; * @author Nividica * */ -public interface IThEInteractionHelper -{ - /** - * Converts an amount of milibuckets to an amount of Essentia. - * - * @return - */ - long convertEssentiaAmountToFluidAmount( long essentiaAmount ); +public interface IThEInteractionHelper { + /** + * Converts an amount of milibuckets to an amount of Essentia. + * + * @return + */ + long convertEssentiaAmountToFluidAmount(long essentiaAmount); - /** - * Converts an amount of Essentia to an amount of milibuckets. - * - * @return - */ - long convertFluidAmountToEssentiaAmount( long milibuckets ); + /** + * Converts an amount of Essentia to an amount of milibuckets. + * + * @return + */ + long convertFluidAmountToEssentiaAmount(long milibuckets); - /** - * Creates a new instance of an aspect stack. - * - * @param aspect - * @param stackSize - * @return - */ - @Nonnull - IAspectStack createAspectStack( @Nullable Aspect aspect, long stackSize ); + /** + * Creates a new instance of an aspect stack. + * + * @param aspect + * @param stackSize + * @return + */ + @Nonnull + IAspectStack createAspectStack(@Nullable Aspect aspect, long stackSize); - /** - * Returns the Arcane Crafting Terminals GUI class. - */ - @SideOnly(Side.CLIENT) - Class getArcaneCraftingTerminalGUIClass(); + /** + * Returns the Arcane Crafting Terminals GUI class. + */ + @SideOnly(Side.CLIENT) + Class getArcaneCraftingTerminalGUIClass(); - /** - * Opens the wireless gui for the specified player. - * The item the player is holding is used for the settings and power. - * Must be called from the server side. - * - * @param player - */ - void openWirelessTerminalGui( @Nonnull EntityPlayer player ); + /** + * Opens the wireless gui for the specified player. + * The item the player is holding is used for the settings and power. + * Must be called from the server side. + * + * @param player + */ + void openWirelessTerminalGui(@Nonnull EntityPlayer player); - /** - * The {@code IThEWirelessEssentiaTerminal} is assumed to be the item the player is holding, and is no longer needs to be passed in. - * - * - * @param player - * @param terminalInterface - * is now ignored - * @see #openWirelessTerminalGui(EntityPlayer) - */ - @Deprecated - void openWirelessTerminalGui( @Nonnull EntityPlayer player, IThEWirelessEssentiaTerminal terminalInterface ); + /** + * The {@code IThEWirelessEssentiaTerminal} is assumed to be the item the player is holding, and is no longer needs to be passed in. + * + * + * @param player + * @param terminalInterface + * is now ignored + * @see #openWirelessTerminalGui(EntityPlayer) + */ + @Deprecated + void openWirelessTerminalGui(@Nonnull EntityPlayer player, IThEWirelessEssentiaTerminal terminalInterface); - /** - * Registers a handler to receive golem events. - * - * @param handler - */ - void registerGolemHookHandler( @Nonnull IGolemHookHandler handler ); + /** + * Registers a handler to receive golem events. + * + * @param handler + */ + void registerGolemHookHandler(@Nonnull IGolemHookHandler handler); - /** - * Attempts to set the Arcane Crafting Terminals recipe to the items - * specified for the current player.
- * Call is ignored if player does not have an A.C.T. GUI open.
- * The items array should be of size 9. Items will be placed in the crafting - * grid according to index where - * - * Null items are allowed. - */ - @SideOnly(Side.CLIENT) - void setArcaneCraftingTerminalRecipe( @Nonnull ItemStack[] items ); + /** + * Attempts to set the Arcane Crafting Terminals recipe to the items + * specified for the current player.
+ * Call is ignored if player does not have an A.C.T. GUI open.
+ * The items array should be of size 9. Items will be placed in the crafting + * grid according to index where + * + * Null items are allowed. + */ + @SideOnly(Side.CLIENT) + void setArcaneCraftingTerminalRecipe(@Nonnull ItemStack[] items); } diff --git a/src/main/java/thaumicenergistics/api/IThEItemDescription.java b/src/main/java/thaumicenergistics/api/IThEItemDescription.java index 324c2501..8f613a66 100644 --- a/src/main/java/thaumicenergistics/api/IThEItemDescription.java +++ b/src/main/java/thaumicenergistics/api/IThEItemDescription.java @@ -12,46 +12,45 @@ import net.minecraft.item.ItemStack; * @author Nividica * */ -public interface IThEItemDescription -{ +public interface IThEItemDescription { - /** - * Gets the block of this item, if it has one. - * - * @return - */ - @Nullable - Block getBlock(); + /** + * Gets the block of this item, if it has one. + * + * @return + */ + @Nullable + Block getBlock(); - /** - * Gets the damage, or meta, value of the item. - * - * @return - */ - int getDamage(); + /** + * Gets the damage, or meta, value of the item. + * + * @return + */ + int getDamage(); - /** - * Gets the item. - * - * @return - */ - @Nonnull - Item getItem(); + /** + * Gets the item. + * + * @return + */ + @Nonnull + Item getItem(); - /** - * Gets a stack of size 1. - * - * @return - */ - @Nonnull - ItemStack getStack(); + /** + * Gets a stack of size 1. + * + * @return + */ + @Nonnull + ItemStack getStack(); - /** - * Gets a stack of the specified size. - * - * @param amount - * @return - */ - @Nonnull - ItemStack getStacks( int amount ); + /** + * Gets a stack of the specified size. + * + * @param amount + * @return + */ + @Nonnull + ItemStack getStacks(int amount); } diff --git a/src/main/java/thaumicenergistics/api/IThEItems.java b/src/main/java/thaumicenergistics/api/IThEItems.java index 18fbcb0c..6335eb9a 100644 --- a/src/main/java/thaumicenergistics/api/IThEItems.java +++ b/src/main/java/thaumicenergistics/api/IThEItems.java @@ -8,107 +8,106 @@ import javax.annotation.Nonnull; * @author Nividica * */ -public abstract class IThEItems -{ - /** - * Coalescence Core. - */ - @Nonnull - public IThEItemDescription CoalescenceCore; +public abstract class IThEItems { + /** + * Coalescence Core. + */ + @Nonnull + public IThEItemDescription CoalescenceCore; - /** - * Diffusion Core. - */ - @Nonnull - public IThEItemDescription DiffusionCore; + /** + * Diffusion Core. + */ + @Nonnull + public IThEItemDescription DiffusionCore; - /** - * 16 KiloByte essentia storage cell. - */ - @Nonnull - public IThEItemDescription EssentiaCell_16k; + /** + * 16 KiloByte essentia storage cell. + */ + @Nonnull + public IThEItemDescription EssentiaCell_16k; - /** - * 1 KiloByte essentia storage cell. - */ - @Nonnull - public IThEItemDescription EssentiaCell_1k; + /** + * 1 KiloByte essentia storage cell. + */ + @Nonnull + public IThEItemDescription EssentiaCell_1k; - /** - * 4 KiloByte essentia storage cell. - */ - @Nonnull - public IThEItemDescription EssentiaCell_4k; + /** + * 4 KiloByte essentia storage cell. + */ + @Nonnull + public IThEItemDescription EssentiaCell_4k; - /** - * 64 KiloByte essentia storage cell. - */ - @Nonnull - public IThEItemDescription EssentiaCell_64k; + /** + * 64 KiloByte essentia storage cell. + */ + @Nonnull + public IThEItemDescription EssentiaCell_64k; - /** - * Creative essentia storage cell. - */ - @Nonnull - public IThEItemDescription EssentiaCell_Creative; + /** + * Creative essentia storage cell. + */ + @Nonnull + public IThEItemDescription EssentiaCell_Creative; - /** - * Essentia storage cell housing. - */ - @Nonnull - public IThEItemDescription EssentiaCell_Casing; + /** + * Essentia storage cell housing. + */ + @Nonnull + public IThEItemDescription EssentiaCell_Casing; - /** - * 16 KiloByte essentia storage cell component. - */ - @Nonnull - public IThEItemDescription EssentiaStorageComponent_16k; + /** + * 16 KiloByte essentia storage cell component. + */ + @Nonnull + public IThEItemDescription EssentiaStorageComponent_16k; - /** - * 1 KiloByte essentia storage cell component. - */ - @Nonnull - public IThEItemDescription EssentiaStorageComponent_1k; + /** + * 1 KiloByte essentia storage cell component. + */ + @Nonnull + public IThEItemDescription EssentiaStorageComponent_1k; - /** - * 4 KiloByte essentia storage cell component. - */ - @Nonnull - public IThEItemDescription EssentiaStorageComponent_4k; + /** + * 4 KiloByte essentia storage cell component. + */ + @Nonnull + public IThEItemDescription EssentiaStorageComponent_4k; - /** - * 64 KiloByte essentia storage cell component. - */ - @Nonnull - public IThEItemDescription EssentiaStorageComponent_64k; + /** + * 64 KiloByte essentia storage cell component. + */ + @Nonnull + public IThEItemDescription EssentiaStorageComponent_64k; - /** - * Iron gear. - */ - @Nonnull - public IThEItemDescription IronGear; + /** + * Iron gear. + */ + @Nonnull + public IThEItemDescription IronGear; - /** - * Wireless essentia terminal - */ - @Nonnull - public IThEItemDescription WirelessEssentiaTerminal; + /** + * Wireless essentia terminal + */ + @Nonnull + public IThEItemDescription WirelessEssentiaTerminal; - /** - * Knowledge core. - */ - @Nonnull - public IThEItemDescription KnowledgeCore; + /** + * Knowledge core. + */ + @Nonnull + public IThEItemDescription KnowledgeCore; - /** - * AE Wrench wand focus. - */ - @Nonnull - public IThEItemDescription WandFocusAEWrench; + /** + * AE Wrench wand focus. + */ + @Nonnull + public IThEItemDescription WandFocusAEWrench; - /** - * Golem wireless backpack. - */ - @Nonnull - public IThEItemDescription GolemWifiBackpack; + /** + * Golem wireless backpack. + */ + @Nonnull + public IThEItemDescription GolemWifiBackpack; } diff --git a/src/main/java/thaumicenergistics/api/IThEParts.java b/src/main/java/thaumicenergistics/api/IThEParts.java index c488af4c..9ec91936 100644 --- a/src/main/java/thaumicenergistics/api/IThEParts.java +++ b/src/main/java/thaumicenergistics/api/IThEParts.java @@ -8,59 +8,58 @@ import javax.annotation.Nonnull; * @author Nividica * */ -public abstract class IThEParts -{ - /** - * Arcane crafting terminal. - */ - @Nonnull - public IThEItemDescription ArcaneCrafting_Terminal; +public abstract class IThEParts { + /** + * Arcane crafting terminal. + */ + @Nonnull + public IThEItemDescription ArcaneCrafting_Terminal; - /** - * Essentia export bus. - */ - @Nonnull - public IThEItemDescription Essentia_ExportBus; + /** + * Essentia export bus. + */ + @Nonnull + public IThEItemDescription Essentia_ExportBus; - /** - * Essentia import bus. - */ - @Nonnull - public IThEItemDescription Essentia_ImportBus; + /** + * Essentia import bus. + */ + @Nonnull + public IThEItemDescription Essentia_ImportBus; - /** - * Essentia level emitter. - */ - @Nonnull - public IThEItemDescription Essentia_LevelEmitter; + /** + * Essentia level emitter. + */ + @Nonnull + public IThEItemDescription Essentia_LevelEmitter; - /** - * Essentia storage bus. - */ - @Nonnull - public IThEItemDescription Essentia_StorageBus; + /** + * Essentia storage bus. + */ + @Nonnull + public IThEItemDescription Essentia_StorageBus; - /** - * Essentia terminal. - */ - @Nonnull - public IThEItemDescription Essentia_Terminal; + /** + * Essentia terminal. + */ + @Nonnull + public IThEItemDescription Essentia_Terminal; - /** - * Vis relay interface. - */ - @Nonnull - public IThEItemDescription VisRelay_Interface; + /** + * Vis relay interface. + */ + @Nonnull + public IThEItemDescription VisRelay_Interface; - /** - * Essentia storage monitor. - */ - @Nonnull - public IThEItemDescription Essentia_StorageMonitor; + /** + * Essentia storage monitor. + */ + @Nonnull + public IThEItemDescription Essentia_StorageMonitor; - /** - * Essentia conversion monitor. - */ - @Nonnull - public IThEItemDescription Essentia_ConversionMonitor; + /** + * Essentia conversion monitor. + */ + @Nonnull + public IThEItemDescription Essentia_ConversionMonitor; } diff --git a/src/main/java/thaumicenergistics/api/IThETransportPermissions.java b/src/main/java/thaumicenergistics/api/IThETransportPermissions.java index 02a2fd50..72fde7f8 100644 --- a/src/main/java/thaumicenergistics/api/IThETransportPermissions.java +++ b/src/main/java/thaumicenergistics/api/IThETransportPermissions.java @@ -14,90 +14,96 @@ import thaumcraft.api.aspects.IEssentiaContainerItem; * @author Nividica * */ -public interface IThETransportPermissions -{ +public interface IThETransportPermissions { - /** - * Adds a tile entity to both inject & extract whitelists. - * The tile must implement the interface {@link IAspectContainer}
- * Capacity is required to function properly - * - * @param tileClass - * @return True if added to the lists, False if not. - */ - boolean addAspectContainerTileToBothPermissions( @Nonnull Class tileClass, int capacity ); + /** + * Adds a tile entity to both inject & extract whitelists. + * The tile must implement the interface {@link IAspectContainer}
+ * Capacity is required to function properly + * + * @param tileClass + * @return True if added to the lists, False if not. + */ + boolean addAspectContainerTileToBothPermissions( + @Nonnull Class tileClass, int capacity); - /** - * Adds a tile entity to the extract whitelist. - * The tile must implement the interface {@link IAspectContainer}
- * Note: Capacity can be 0 if the tile doesn't truely 'contain' essentia. - * - * @param tileClass - * @return True if added to the list or already present, False otherwise. - */ - boolean addAspectContainerTileToExtractPermissions( @Nonnull Class tileClass, int capacity ); + /** + * Adds a tile entity to the extract whitelist. + * The tile must implement the interface {@link IAspectContainer}
+ * Note: Capacity can be 0 if the tile doesn't truely 'contain' essentia. + * + * @param tileClass + * @return True if added to the list or already present, False otherwise. + */ + boolean addAspectContainerTileToExtractPermissions( + @Nonnull Class tileClass, int capacity); - /** - * Adds a tile entity to the inject whitelist. - * The tile must implement the interface {@link IAspectContainer}
- * Capacity is required to function properly. - * - * @param tileClass - * @return True if added to the list, False if not. - */ - boolean addAspectContainerTileToInjectPermissions( @Nonnull Class tileClass, int capacity ); + /** + * Adds a tile entity to the inject whitelist. + * The tile must implement the interface {@link IAspectContainer}
+ * Capacity is required to function properly. + * + * @param tileClass + * @return True if added to the list, False if not. + */ + boolean addAspectContainerTileToInjectPermissions( + @Nonnull Class tileClass, int capacity); - /** - * Adds an item to the whitelist that must match the specified damage value. - * - * @param itemClass - * @param capacity - * @param damageValue - * @param canHoldPartialAmount - */ - void addEssentiaContainerItemToTransportPermissions( @Nonnull Class itemClass, int capacity, int damageValue, - boolean canHoldPartialAmount ); + /** + * Adds an item to the whitelist that must match the specified damage value. + * + * @param itemClass + * @param capacity + * @param damageValue + * @param canHoldPartialAmount + */ + void addEssentiaContainerItemToTransportPermissions( + @Nonnull Class itemClass, + int capacity, + int damageValue, + boolean canHoldPartialAmount); - /** - * Adds the specified item to the whitelist. - * - * @param containerItem - * @param capacity - * @param canHoldPartialAmount - */ - void addEssentiaContainerItemToTransportPermissions( @Nonnull ItemStack containerItem, int capacity, boolean canHoldPartialAmount ); + /** + * Adds the specified item to the whitelist. + * + * @param containerItem + * @param capacity + * @param canHoldPartialAmount + */ + void addEssentiaContainerItemToTransportPermissions( + @Nonnull ItemStack containerItem, int capacity, boolean canHoldPartialAmount); - /** - * Checks if the container can be extracted from - * - * @param container - * @return - */ - boolean canExtractFromAspectContainerTile( @Nonnull IAspectContainer container ); + /** + * Checks if the container can be extracted from + * + * @param container + * @return + */ + boolean canExtractFromAspectContainerTile(@Nonnull IAspectContainer container); - /** - * Checks if the container can be injected into - * - * @param container - * @return - */ - boolean canInjectToAspectContainerTile( @Nonnull IAspectContainer container ); + /** + * Checks if the container can be injected into + * + * @param container + * @return + */ + boolean canInjectToAspectContainerTile(@Nonnull IAspectContainer container); - /** - * Returns the registered capacity of the specified container. - * - * @param container - * @return Registered capacity, or -1 if not registered. - */ - int getAspectContainerTileCapacity( @Nonnull IAspectContainer container ); + /** + * Returns the registered capacity of the specified container. + * + * @param container + * @return Registered capacity, or -1 if not registered. + */ + int getAspectContainerTileCapacity(@Nonnull IAspectContainer container); - /** - * Gets the information about the container as it was registered to the - * whitelist. - * - * @param itemClass - * @param damageValue - * @return Info if was registered, null otherwise. - */ - IThEEssentiaContainerPermission getEssentiaContainerInfo( @Nonnull Class itemClass, int damageValue ); + /** + * Gets the information about the container as it was registered to the + * whitelist. + * + * @param itemClass + * @param damageValue + * @return Info if was registered, null otherwise. + */ + IThEEssentiaContainerPermission getEssentiaContainerInfo(@Nonnull Class itemClass, int damageValue); } diff --git a/src/main/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java b/src/main/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java index 4723893c..27b3552f 100644 --- a/src/main/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java @@ -1,8 +1,8 @@ package thaumicenergistics.api; -import javax.annotation.Nonnull; import appeng.api.features.INetworkEncodable; import appeng.api.implementations.items.IAEItemPowerStorage; +import javax.annotation.Nonnull; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -14,15 +14,13 @@ import net.minecraft.nbt.NBTTagCompound; * @author Nividica * */ -public interface IThEWirelessEssentiaTerminal - extends INetworkEncodable, IAEItemPowerStorage -{ - /** - * Gets the tag used to store the terminal data. - * - * @param terminalItemstack - * @return - */ - @Nonnull - NBTTagCompound getWETerminalTag( @Nonnull ItemStack terminalItemstack ); +public interface IThEWirelessEssentiaTerminal extends INetworkEncodable, IAEItemPowerStorage { + /** + * Gets the tag used to store the terminal data. + * + * @param terminalItemstack + * @return + */ + @Nonnull + NBTTagCompound getWETerminalTag(@Nonnull ItemStack terminalItemstack); } diff --git a/src/main/java/thaumicenergistics/api/ThEApi.java b/src/main/java/thaumicenergistics/api/ThEApi.java index c69b3fa2..399be9e8 100644 --- a/src/main/java/thaumicenergistics/api/ThEApi.java +++ b/src/main/java/thaumicenergistics/api/ThEApi.java @@ -1,10 +1,10 @@ package thaumicenergistics.api; +import com.google.common.collect.ImmutableList; import java.lang.reflect.Method; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import com.google.common.collect.ImmutableList; /** * Thaumic Energistics API @@ -12,83 +12,76 @@ import com.google.common.collect.ImmutableList; * @author Nividica * */ -public abstract class ThEApi -{ - protected static ThEApi api = null; +public abstract class ThEApi { + protected static ThEApi api = null; - /** - * Gets the Thaumic Energistics API. - * Note: Only available after the PREINIT event. - */ - @Nullable - public static ThEApi instance() - { - // Have we already retrieved the api? - if( ThEApi.api == null ) - { - try - { - // Attempt to locate the API implementation - Class clazz = Class.forName( "thaumicenergistics.implementaion.ThEAPIImplementation" ); + /** + * Gets the Thaumic Energistics API. + * Note: Only available after the PREINIT event. + */ + @Nullable + public static ThEApi instance() { + // Have we already retrieved the api? + if (ThEApi.api == null) { + try { + // Attempt to locate the API implementation + Class clazz = Class.forName("thaumicenergistics.implementaion.ThEAPIImplementation"); - // Get the instance method - Method instanceAccessor = clazz.getMethod( "instance" ); + // Get the instance method + Method instanceAccessor = clazz.getMethod("instance"); - // Attempt to get the API instance - ThEApi.api = (ThEApi)instanceAccessor.invoke( null ); - } - catch( Exception e ) - { - // Unable to locate the API, return null - return null; - } - } + // Attempt to get the API instance + ThEApi.api = (ThEApi) instanceAccessor.invoke(null); + } catch (Exception e) { + // Unable to locate the API, return null + return null; + } + } - return ThEApi.api; - } + return ThEApi.api; + } - /** - * Blocks - */ - @Nonnull - public abstract IThEBlocks blocks(); + /** + * Blocks + */ + @Nonnull + public abstract IThEBlocks blocks(); - /** - * Configuration - */ - @Nonnull - public abstract IThEConfig config(); + /** + * Configuration + */ + @Nonnull + public abstract IThEConfig config(); - /** - * Essentia Gasses - */ - @Nonnull - public abstract ImmutableList> essentiaGases(); + /** + * Essentia Gasses + */ + @Nonnull + public abstract ImmutableList> essentiaGases(); - /** - * Gets the ThE interaction manager - * - * @return - */ - @Nonnull - public abstract IThEInteractionHelper interact(); + /** + * Gets the ThE interaction manager + * + * @return + */ + @Nonnull + public abstract IThEInteractionHelper interact(); - /** - * Items - */ - @Nonnull - public abstract IThEItems items(); + /** + * Items + */ + @Nonnull + public abstract IThEItems items(); - /** - * Cable Parts - */ - @Nonnull - public abstract IThEParts parts(); - - /** - * Transport Permissions. - */ - @Nonnull - public abstract IThETransportPermissions transportPermissions(); + /** + * Cable Parts + */ + @Nonnull + public abstract IThEParts parts(); + /** + * Transport Permissions. + */ + @Nonnull + public abstract IThETransportPermissions transportPermissions(); } diff --git a/src/main/java/thaumicenergistics/api/entities/IGolemHookHandler.java b/src/main/java/thaumicenergistics/api/entities/IGolemHookHandler.java index 8218b15f..fcb5fb5b 100644 --- a/src/main/java/thaumicenergistics/api/entities/IGolemHookHandler.java +++ b/src/main/java/thaumicenergistics/api/entities/IGolemHookHandler.java @@ -1,9 +1,9 @@ package thaumicenergistics.api.entities; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -51,219 +51,242 @@ import thaumcraft.common.entities.golems.EntityGolemBase; * @see IGolemHookSyncRegistry * */ -public interface IGolemHookHandler -{ - /** - * Defines interaction levels. - * - * @author Nividica - * - */ - public static enum InteractionLevel - { - /** - * The interaction was not handled at all.
- *
    - *
  • GUI will be shown, if golem has one.
  • - *
  • customInteraction() will not be called.
  • - *
  • Sync data will not be sent.
  • - *
  • setupGolem() will not be called.
  • - *
- */ - NoInteraction, +public interface IGolemHookHandler { + /** + * Defines interaction levels. + * + * @author Nividica + * + */ + public static enum InteractionLevel { + /** + * The interaction was not handled at all.
+ *
    + *
  • GUI will be shown, if golem has one.
  • + *
  • customInteraction() will not be called.
  • + *
  • Sync data will not be sent.
  • + *
  • setupGolem() will not be called.
  • + *
+ */ + NoInteraction, - /** - * The interaction was handled, but no sync data changed, and golem does not need to be re-setup.
- *
    - *
  • GUI will not be shown
  • - *
  • customInteraction() called. - *
  • - *
  • Sync data will not be sent.
  • - *
  • setupGolem() will not be called.
  • - *
- */ - BasicInteraction, + /** + * The interaction was handled, but no sync data changed, and golem does not need to be re-setup.
+ *
    + *
  • GUI will not be shown
  • + *
  • customInteraction() called. + *
  • + *
  • Sync data will not be sent.
  • + *
  • setupGolem() will not be called.
  • + *
+ */ + BasicInteraction, - /** - * The interaction was handled and sync data changed, but the golem does not need to be re-setup
- *
    - *
  • GUI will not be shown
  • - *
  • customInteraction() called.
  • - *
  • Sync data sent.
  • - *
  • setupGolem() will not be called.
  • - *
- */ - SyncInteraction, + /** + * The interaction was handled and sync data changed, but the golem does not need to be re-setup
+ *
    + *
  • GUI will not be shown
  • + *
  • customInteraction() called.
  • + *
  • Sync data sent.
  • + *
  • setupGolem() will not be called.
  • + *
+ */ + SyncInteraction, - /** - * The interaction was handled and the golem needs to be re-setup. - *
    - *
  • GUI will not be shown
  • - *
  • customInteraction() called.
  • - *
  • Sync data sent.
  • - *
  • setupGolem() called.
  • - *
- */ - FullInteraction; - } + /** + * The interaction was handled and the golem needs to be re-setup. + *
    + *
  • GUI will not be shown
  • + *
  • customInteraction() called.
  • + *
  • Sync data sent.
  • + *
  • setupGolem() called.
  • + *
+ */ + FullInteraction; + } - /** - * Any data you wish to sync between the server and clients can be added here.
- * The added bytes are considered the default state, and will be added to all golems in that state. - * - * @param syncRegistry - */ - void addDefaultSyncEntries( @Nonnull IGolemHookSyncRegistry syncRegistry ); + /** + * Any data you wish to sync between the server and clients can be added here.
+ * The added bytes are considered the default state, and will be added to all golems in that state. + * + * @param syncRegistry + */ + void addDefaultSyncEntries(@Nonnull IGolemHookSyncRegistry syncRegistry); - /** - * Called when the golem was left clicked by a player holding the Golemancers Bell. - * - * @param golem - * @param handlerData - * Handler data attached to the golem. - * @param itemGolemPlacer - * Itemstack that will be used to hold the golem. - * @param player - * @param dismantled - * True if the golem will drop its core and upgrades. - * @param side - * Server or Client @Nonnull Side side - */ - void bellLeftClicked( @Nonnull final EntityGolemBase golem, @Nullable Object handlerData, @Nonnull ItemStack itemGolemPlacer, - @Nonnull EntityPlayer player, boolean dismantled, @Nonnull Side side ); + /** + * Called when the golem was left clicked by a player holding the Golemancers Bell. + * + * @param golem + * @param handlerData + * Handler data attached to the golem. + * @param itemGolemPlacer + * Itemstack that will be used to hold the golem. + * @param player + * @param dismantled + * True if the golem will drop its core and upgrades. + * @param side + * Server or Client @Nonnull Side side + */ + void bellLeftClicked( + @Nonnull final EntityGolemBase golem, + @Nullable Object handlerData, + @Nonnull ItemStack itemGolemPlacer, + @Nonnull EntityPlayer player, + boolean dismantled, + @Nonnull Side side); - /** - * Return true if you can handle this interaction.
- * - * @param golem - * @param handlerData - * Handler data attached to the golem. - * @param player - * @param side - * Server or Client - * @return The level of interaction. - */ - @Nonnull - InteractionLevel canHandleInteraction( @Nonnull final EntityGolemBase golem, @Nullable Object handlerData, @Nonnull EntityPlayer player, - @Nonnull Side side ); + /** + * Return true if you can handle this interaction.
+ * + * @param golem + * @param handlerData + * Handler data attached to the golem. + * @param player + * @param side + * Server or Client + * @return The level of interaction. + */ + @Nonnull + InteractionLevel canHandleInteraction( + @Nonnull final EntityGolemBase golem, + @Nullable Object handlerData, + @Nonnull EntityPlayer player, + @Nonnull Side side); - /** - * Called when the golem has been interacted with and it hasn't been handled by Thaumcraft.
- * - * @param golem - * @param handlerData - * Handler data attached to the golem. - * @param syncData - * @param player - * @param side - * Server or Client - * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. - */ - @Nullable - Object customInteraction( @Nonnull final EntityGolemBase golem, @Nullable Object handlerData, @Nonnull IGolemHookSyncRegistry syncData, - @Nonnull EntityPlayer player, @Nonnull Side side ); + /** + * Called when the golem has been interacted with and it hasn't been handled by Thaumcraft.
+ * + * @param golem + * @param handlerData + * Handler data attached to the golem. + * @param syncData + * @param player + * @param side + * Server or Client + * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. + */ + @Nullable + Object customInteraction( + @Nonnull final EntityGolemBase golem, + @Nullable Object handlerData, + @Nonnull IGolemHookSyncRegistry syncData, + @Nonnull EntityPlayer player, + @Nonnull Side side); - /** - * Called when a golem receives a tick, if {@code needsDynamicUpdate} returned true during registration.
- * If setting sync data, you do not need to track if the sync data has changed yourself. The {@code syncData} class - * tracks this internally and will only ever send updates if the data has actually changed. Although for performance reasons - * it would be a good idea to keep a tick counter and only set the data periodically if there is any processing involved.
- * Note: This is only called server side. - * - * @param golem - * @param serverHandlerData - * @param syncData - */ - void golemTick( @Nonnull EntityGolemBase golem, @Nullable Object serverHandlerData, @Nonnull IGolemHookSyncRegistry syncData ); + /** + * Called when a golem receives a tick, if {@code needsDynamicUpdate} returned true during registration.
+ * If setting sync data, you do not need to track if the sync data has changed yourself. The {@code syncData} class + * tracks this internally and will only ever send updates if the data has actually changed. Although for performance reasons + * it would be a good idea to keep a tick counter and only set the data periodically if there is any processing involved.
+ * Note: This is only called server side. + * + * @param golem + * @param serverHandlerData + * @param syncData + */ + void golemTick( + @Nonnull EntityGolemBase golem, + @Nullable Object serverHandlerData, + @Nonnull IGolemHookSyncRegistry syncData); - /** - * Return true if your handler wants to be called each time the golem gets a tick from the server. - * - * @return - */ - boolean needsDynamicUpdates(); + /** + * Return true if your handler wants to be called each time the golem gets a tick from the server. + * + * @return + */ + boolean needsDynamicUpdates(); - /** - * Return true if your handler wants to be called when a golem is rendered.
- * Note: This is called only once during registration. - * - * @return - */ - boolean needsRenderer(); + /** + * Return true if your handler wants to be called when a golem is rendered.
+ * Note: This is called only once during registration. + * + * @return + */ + boolean needsRenderer(); - /** - * Called when reading the golem's NBT.
- * Note: Called during a world load, not when the golem is placed via its item. - * - * @param golem - * @param nbtTag - * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. - */ - @Nullable - Object readEntityFromNBT( @Nonnull final EntityGolemBase golem, @Nonnull NBTTagCompound nbtTag ); + /** + * Called when reading the golem's NBT.
+ * Note: Called during a world load, not when the golem is placed via its item. + * + * @param golem + * @param nbtTag + * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. + */ + @Nullable + Object readEntityFromNBT(@Nonnull final EntityGolemBase golem, @Nonnull NBTTagCompound nbtTag); - /** - * Called when a golem is being rendered, if {@code needsRenderer} returned true during registration. - * - * @param golem - * @param clientHandlerData - * @param x - * @param y - * @param z - * @param partialElaspsedTick - */ - @SideOnly(Side.CLIENT) - void renderGolem( @Nonnull EntityGolemBase golem, @Nullable Object clientHandlerData, double x, double y, double z, - float partialElaspsedTick ); + /** + * Called when a golem is being rendered, if {@code needsRenderer} returned true during registration. + * + * @param golem + * @param clientHandlerData + * @param x + * @param y + * @param z + * @param partialElaspsedTick + */ + @SideOnly(Side.CLIENT) + void renderGolem( + @Nonnull EntityGolemBase golem, + @Nullable Object clientHandlerData, + double x, + double y, + double z, + float partialElaspsedTick); - /** - * Called just before the golem has finished setting up.
- * If you are adding an AI script(s) to the golem, be aware that Thaumcraft clears all of the golems scripts at the beginning of this call. You - * will need to add the script(s) each time this is called, but you do not need to worry about removing them.
- * Note: The golems inventory may not be ready. - * - * @param golem - * @param handlerData - * Handler data attached to the golem. - * @param side - * Server or Client - * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. - */ - @Nullable - Object setupGolem( @Nonnull final EntityGolemBase golem, @Nullable Object handlerData, @Nonnull IGolemHookSyncRegistry syncData, - @Nonnull Side side ); + /** + * Called just before the golem has finished setting up.
+ * If you are adding an AI script(s) to the golem, be aware that Thaumcraft clears all of the golems scripts at the beginning of this call. You + * will need to add the script(s) each time this is called, but you do not need to worry about removing them.
+ * Note: The golems inventory may not be ready. + * + * @param golem + * @param handlerData + * Handler data attached to the golem. + * @param side + * Server or Client + * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. + */ + @Nullable + Object setupGolem( + @Nonnull final EntityGolemBase golem, + @Nullable Object handlerData, + @Nonnull IGolemHookSyncRegistry syncData, + @Nonnull Side side); - /** - * Called when a golem is being spawned via it's item.
- * Note: This is not called if the item has no NBT data. - * - * @param golem - * @param itemGolemPlacer - * @param side - * Server or Client - * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. - */ - @Nullable - Object spawnGolemFromItemStack( @Nonnull final EntityGolemBase golem, @Nonnull ItemStack itemGolemPlacer, @Nonnull Side side ); + /** + * Called when a golem is being spawned via it's item.
+ * Note: This is not called if the item has no NBT data. + * + * @param golem + * @param itemGolemPlacer + * @param side + * Server or Client + * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. + */ + @Nullable + Object spawnGolemFromItemStack( + @Nonnull final EntityGolemBase golem, @Nonnull ItemStack itemGolemPlacer, @Nonnull Side side); - /** - * Called when sync data has changed. - * - * @param syncData - * @param clientHandlerData - * Handler data attached to the golem on the client side. - * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. - */ - @SideOnly(Side.CLIENT) - Object syncDataChanged( @Nonnull IGolemHookSyncRegistry syncData, @Nullable Object clientHandlerData ); + /** + * Called when sync data has changed. + * + * @param syncData + * @param clientHandlerData + * Handler data attached to the golem on the client side. + * @return Return the handler data you wish to attach to the golem, or null to clear any attached data. + */ + @SideOnly(Side.CLIENT) + Object syncDataChanged(@Nonnull IGolemHookSyncRegistry syncData, @Nullable Object clientHandlerData); - /** - * Called when saving the golem's NBT.
- * Note: Called during a world save, not when the golem is being turned into an item via Golemancer's Bell. - * - * @param golem - * @param serverHandlerData - * @param nbtTag - */ - void writeEntityNBT( @Nonnull final EntityGolemBase golem, @Nullable Object serverHandlerData, @Nonnull NBTTagCompound nbtTag ); + /** + * Called when saving the golem's NBT.
+ * Note: Called during a world save, not when the golem is being turned into an item via Golemancer's Bell. + * + * @param golem + * @param serverHandlerData + * @param nbtTag + */ + void writeEntityNBT( + @Nonnull final EntityGolemBase golem, @Nullable Object serverHandlerData, @Nonnull NBTTagCompound nbtTag); } diff --git a/src/main/java/thaumicenergistics/api/entities/IGolemHookSyncRegistry.java b/src/main/java/thaumicenergistics/api/entities/IGolemHookSyncRegistry.java index f7c9e482..c6127702 100644 --- a/src/main/java/thaumicenergistics/api/entities/IGolemHookSyncRegistry.java +++ b/src/main/java/thaumicenergistics/api/entities/IGolemHookSyncRegistry.java @@ -6,34 +6,33 @@ package thaumicenergistics.api.entities; * @author Nividica * */ -public interface IGolemHookSyncRegistry -{ - /** - * Returns the sync char if it is mapped, returns {@code defaultChar} otherwise. - * - * @param id - * @param defaultChar - * @return - */ - char getSyncCharOrDefault( int id, char defaultChar ); +public interface IGolemHookSyncRegistry { + /** + * Returns the sync char if it is mapped, returns {@code defaultChar} otherwise. + * + * @param id + * @param defaultChar + * @return + */ + char getSyncCharOrDefault(int id, char defaultChar); - /** - * Registers a new sync byte, and returns the ID that maps to it.
- * Note: This can only be called during registration, will throw exception otherwise. - * - * @param handler - * @param c - * Initial value of the char. - * @return The ID of the char. - */ - int registerSyncChar( IGolemHookHandler handler, char c ); + /** + * Registers a new sync byte, and returns the ID that maps to it.
+ * Note: This can only be called during registration, will throw exception otherwise. + * + * @param handler + * @param c + * Initial value of the char. + * @return The ID of the char. + */ + int registerSyncChar(IGolemHookHandler handler, char c); - /** - * Updates the sync char. - * - * @param handler - * @param id - * @param c - */ - void updateSyncChar( IGolemHookHandler handler, int id, char c ); + /** + * Updates the sync char. + * + * @param handler + * @param id + * @param c + */ + void updateSyncChar(IGolemHookHandler handler, int id, char c); } diff --git a/src/main/java/thaumicenergistics/api/grid/ICraftingIssuerHost.java b/src/main/java/thaumicenergistics/api/grid/ICraftingIssuerHost.java index e3746b6f..ea06145f 100644 --- a/src/main/java/thaumicenergistics/api/grid/ICraftingIssuerHost.java +++ b/src/main/java/thaumicenergistics/api/grid/ICraftingIssuerHost.java @@ -10,19 +10,17 @@ import net.minecraft.item.ItemStack; * @author Nividica * */ -public interface ICraftingIssuerHost - extends ITerminalHost -{ - /** - * Gets the icon for this terminal. - * - * @return - */ - ItemStack getIcon(); +public interface ICraftingIssuerHost extends ITerminalHost { + /** + * Gets the icon for this terminal. + * + * @return + */ + ItemStack getIcon(); - /** - * Launches the terminal's GUI. - * Used to return to the gui after crafting is confirmed or canceled. - */ - void launchGUI( EntityPlayer player ); + /** + * Launches the terminal's GUI. + * Used to return to the gui after crafting is confirmed or canceled. + */ + void launchGUI(EntityPlayer player); } diff --git a/src/main/java/thaumicenergistics/api/grid/IDigiVisSource.java b/src/main/java/thaumicenergistics/api/grid/IDigiVisSource.java index 85dfee88..29599d70 100644 --- a/src/main/java/thaumicenergistics/api/grid/IDigiVisSource.java +++ b/src/main/java/thaumicenergistics/api/grid/IDigiVisSource.java @@ -1,9 +1,9 @@ package thaumicenergistics.api.grid; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import appeng.api.networking.IGrid; import appeng.api.util.DimensionalCoord; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraftforge.common.util.ForgeDirection; import thaumcraft.api.aspects.Aspect; @@ -13,53 +13,52 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IDigiVisSource -{ - /** - * Drains digivis from this source. - * - * @param digiVisAspect - * @param amount - * @return The amount drained. - */ - int consumeVis( @Nonnull Aspect digiVisAspect, int amount ); +public interface IDigiVisSource { + /** + * Drains digivis from this source. + * + * @param digiVisAspect + * @param amount + * @return The amount drained. + */ + int consumeVis(@Nonnull Aspect digiVisAspect, int amount); - /** - * Get's the AE grid the source is attached to. - * - * @return - */ - @Nullable - IGrid getGrid(); + /** + * Get's the AE grid the source is attached to. + * + * @return + */ + @Nullable + IGrid getGrid(); - /** - * Returns the location of the source. - * - * @return - */ - @Nonnull - DimensionalCoord getLocation(); + /** + * Returns the location of the source. + * + * @return + */ + @Nonnull + DimensionalCoord getLocation(); - /** - * Gets the side of cable the source part is attached to. - * If this returns UNKNOWN, it is assumed the source is a whole block. - * - * @return - */ - @Nonnull - ForgeDirection getSide(); + /** + * Gets the side of cable the source part is attached to. + * If this returns UNKNOWN, it is assumed the source is a whole block. + * + * @return + */ + @Nonnull + ForgeDirection getSide(); - /** - * Get's the unique identifier for this source. - * - * @return - */ - long getUID(); + /** + * Get's the unique identifier for this source. + * + * @return + */ + long getUID(); - /** - * Is the source active? - * - * @return - */ - boolean isActive(); + /** + * Is the source active? + * + * @return + */ + boolean isActive(); } diff --git a/src/main/java/thaumicenergistics/api/grid/IEssentiaGrid.java b/src/main/java/thaumicenergistics/api/grid/IEssentiaGrid.java index 861ca670..f7e3cb05 100644 --- a/src/main/java/thaumicenergistics/api/grid/IEssentiaGrid.java +++ b/src/main/java/thaumicenergistics/api/grid/IEssentiaGrid.java @@ -8,8 +8,4 @@ import appeng.api.networking.IGridCache; * @author Nividica * */ -public interface IEssentiaGrid - extends IGridCache, IMEEssentiaMonitor -{ - -} +public interface IEssentiaGrid extends IGridCache, IMEEssentiaMonitor {} diff --git a/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcher.java b/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcher.java index da6ef551..80ebc056 100644 --- a/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcher.java +++ b/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcher.java @@ -9,13 +9,11 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IEssentiaWatcher - extends Collection -{ - /** - * Return the host for this watcher. - * - * @return - */ - IEssentiaWatcherHost getHost(); +public interface IEssentiaWatcher extends Collection { + /** + * Return the host for this watcher. + * + * @return + */ + IEssentiaWatcherHost getHost(); } diff --git a/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcherHost.java b/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcherHost.java index e63c4d4a..e3278252 100644 --- a/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcherHost.java +++ b/src/main/java/thaumicenergistics/api/grid/IEssentiaWatcherHost.java @@ -8,24 +8,23 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IEssentiaWatcherHost -{ - /** - * Called when essentia levels change in the network. - * - * @param aspect - * Aspect of the changed essentia. - * @param storedAmount - * The full amount stored in the network. - * @param changeAmount - * The amount that just changed. - */ - void onEssentiaChange( Aspect aspect, long storedAmount, long changeAmount ); +public interface IEssentiaWatcherHost { + /** + * Called when essentia levels change in the network. + * + * @param aspect + * Aspect of the changed essentia. + * @param storedAmount + * The full amount stored in the network. + * @param changeAmount + * The amount that just changed. + */ + void onEssentiaChange(Aspect aspect, long storedAmount, long changeAmount); - /** - * Providers the essentia watcher for your host. - * - * @param newWatcher - */ - void updateWatcher( IEssentiaWatcher newWatcher ); + /** + * Providers the essentia watcher for your host. + * + * @param newWatcher + */ + void updateWatcher(IEssentiaWatcher newWatcher); } diff --git a/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitor.java b/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitor.java index 8f45fd72..b9e2ec75 100644 --- a/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitor.java +++ b/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitor.java @@ -1,9 +1,9 @@ package thaumicenergistics.api.grid; -import java.util.Collection; -import javax.annotation.Nonnull; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; +import java.util.Collection; +import javax.annotation.Nonnull; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.storage.IAspectStack; @@ -13,63 +13,72 @@ import thaumicenergistics.api.storage.IAspectStack; * @author Nividica * */ -public interface IMEEssentiaMonitor -{ - /** - * Adds a listener to the essentia grid. - * - * @param listener - * @param verificationToken - * Token used to verify the receiver is still valid, and wants to continue receiving events. - */ - void addListener( @Nonnull IMEEssentiaMonitorReceiver listener, @Nonnull Object verificationToken ); +public interface IMEEssentiaMonitor { + /** + * Adds a listener to the essentia grid. + * + * @param listener + * @param verificationToken + * Token used to verify the receiver is still valid, and wants to continue receiving events. + */ + void addListener(@Nonnull IMEEssentiaMonitorReceiver listener, @Nonnull Object verificationToken); - /** - * Extract the specified essentia from the network.
- * - * @param aspect - * @param amount - * @param mode - * @param source - * @param powered - * If true will take the required power for the extraction, respecting the mode setting. - * @return The amount extracted. - */ - long extractEssentia( @Nonnull Aspect aspect, long amount, @Nonnull Actionable mode, @Nonnull BaseActionSource source, boolean powered ); + /** + * Extract the specified essentia from the network.
+ * + * @param aspect + * @param amount + * @param mode + * @param source + * @param powered + * If true will take the required power for the extraction, respecting the mode setting. + * @return The amount extracted. + */ + long extractEssentia( + @Nonnull Aspect aspect, + long amount, + @Nonnull Actionable mode, + @Nonnull BaseActionSource source, + boolean powered); - /** - * Returns the how much of the specified essentia is in the network. - * - * @param aspect - * @return - */ - long getEssentiaAmount( @Nonnull Aspect aspect ); + /** + * Returns the how much of the specified essentia is in the network. + * + * @param aspect + * @return + */ + long getEssentiaAmount(@Nonnull Aspect aspect); - /** - * Gets the list of essentia in the network. - * - * @return - */ - @Nonnull - Collection getEssentiaList(); + /** + * Gets the list of essentia in the network. + * + * @return + */ + @Nonnull + Collection getEssentiaList(); - /** - * Inject the specified essentia into the network.
- * - * @param aspect - * @param amount - * @param mode - * @param source - * @param powered - * If true will take the required power for the injection, respecting the mode setting. - * @return The amount that could not be injected. - */ - long injectEssentia( @Nonnull Aspect aspect, long amount, @Nonnull Actionable mode, @Nonnull BaseActionSource source, boolean powered ); + /** + * Inject the specified essentia into the network.
+ * + * @param aspect + * @param amount + * @param mode + * @param source + * @param powered + * If true will take the required power for the injection, respecting the mode setting. + * @return The amount that could not be injected. + */ + long injectEssentia( + @Nonnull Aspect aspect, + long amount, + @Nonnull Actionable mode, + @Nonnull BaseActionSource source, + boolean powered); - /** - * Removes a listener from the essentia grid. - * - * @param listener - */ - public void removeListener( @Nonnull IMEEssentiaMonitorReceiver listener ); + /** + * Removes a listener from the essentia grid. + * + * @param listener + */ + public void removeListener(@Nonnull IMEEssentiaMonitorReceiver listener); } diff --git a/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitorReceiver.java b/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitorReceiver.java index b543e6c1..d08ee018 100644 --- a/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitorReceiver.java +++ b/src/main/java/thaumicenergistics/api/grid/IMEEssentiaMonitorReceiver.java @@ -9,23 +9,22 @@ import thaumicenergistics.api.storage.IAspectStack; * @author Nividica * */ -public interface IMEEssentiaMonitorReceiver -{ - /** - * Verifies that the receiver is still valid.
- * If returning false the receiver will be removed from the monitor - * and the receiver should NOT call removeListener itself. - * - * @param verificationToken - * @return False if the receiver should no longer get updates. - */ - boolean isValid( @Nonnull Object verificationToken ); +public interface IMEEssentiaMonitorReceiver { + /** + * Verifies that the receiver is still valid.
+ * If returning false the receiver will be removed from the monitor + * and the receiver should NOT call removeListener itself. + * + * @param verificationToken + * @return False if the receiver should no longer get updates. + */ + boolean isValid(@Nonnull Object verificationToken); - /** - * Called when a change to the stored essentia occurs. - * - * @param fromMonitor - * @param changes - */ - void postChange( @Nonnull IMEEssentiaMonitor fromMonitor, @Nonnull Iterable changes ); + /** + * Called when a change to the stored essentia occurs. + * + * @param fromMonitor + * @param changes + */ + void postChange(@Nonnull IMEEssentiaMonitor fromMonitor, @Nonnull Iterable changes); } diff --git a/src/main/java/thaumicenergistics/api/gui/IAspectSelectorContainer.java b/src/main/java/thaumicenergistics/api/gui/IAspectSelectorContainer.java index bf6eb6a0..deee3d00 100644 --- a/src/main/java/thaumicenergistics/api/gui/IAspectSelectorContainer.java +++ b/src/main/java/thaumicenergistics/api/gui/IAspectSelectorContainer.java @@ -9,13 +9,12 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IAspectSelectorContainer -{ - /** - * Set the selected aspect. - * - * @param selectedAspect - * Null if no selection. - */ - void setSelectedAspect( @Nullable Aspect selectedAspect ); +public interface IAspectSelectorContainer { + /** + * Set the selected aspect. + * + * @param selectedAspect + * Null if no selection. + */ + void setSelectedAspect(@Nullable Aspect selectedAspect); } diff --git a/src/main/java/thaumicenergistics/api/gui/IAspectSelectorGui.java b/src/main/java/thaumicenergistics/api/gui/IAspectSelectorGui.java index 6e8aa367..3f266328 100644 --- a/src/main/java/thaumicenergistics/api/gui/IAspectSelectorGui.java +++ b/src/main/java/thaumicenergistics/api/gui/IAspectSelectorGui.java @@ -10,23 +10,20 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IAspectSelectorGui - extends IWidgetHost -{ - /** - * Return the selector container. - * - * @return - */ - @Nonnull - IAspectSelectorContainer getContainer(); - - /** - * Return the selected aspect, or null if no aspect is selected. - * - * @return - */ - @Nullable - Aspect getSelectedAspect(); +public interface IAspectSelectorGui extends IWidgetHost { + /** + * Return the selector container. + * + * @return + */ + @Nonnull + IAspectSelectorContainer getContainer(); + /** + * Return the selected aspect, or null if no aspect is selected. + * + * @return + */ + @Nullable + Aspect getSelectedAspect(); } diff --git a/src/main/java/thaumicenergistics/api/gui/IAspectSlotGui.java b/src/main/java/thaumicenergistics/api/gui/IAspectSlotGui.java index 515783aa..fe528d2a 100644 --- a/src/main/java/thaumicenergistics/api/gui/IAspectSlotGui.java +++ b/src/main/java/thaumicenergistics/api/gui/IAspectSlotGui.java @@ -10,13 +10,11 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IAspectSlotGui - extends IWidgetHost -{ - /** - * The list of aspects to display. - * - * @param aspectList - */ - void updateAspects( @Nonnull List aspectList ); +public interface IAspectSlotGui extends IWidgetHost { + /** + * The list of aspects to display. + * + * @param aspectList + */ + void updateAspects(@Nonnull List aspectList); } diff --git a/src/main/java/thaumicenergistics/api/gui/ICraftingIssuerContainer.java b/src/main/java/thaumicenergistics/api/gui/ICraftingIssuerContainer.java index 2d9ac0ab..511aaab3 100644 --- a/src/main/java/thaumicenergistics/api/gui/ICraftingIssuerContainer.java +++ b/src/main/java/thaumicenergistics/api/gui/ICraftingIssuerContainer.java @@ -9,13 +9,12 @@ import thaumicenergistics.api.grid.ICraftingIssuerHost; * @author Nividica * */ -public interface ICraftingIssuerContainer -{ - /** - * Gets the crafting issuer host terminal. - * - * @return - */ - @Nonnull - ICraftingIssuerHost getCraftingHost(); +public interface ICraftingIssuerContainer { + /** + * Gets the crafting issuer host terminal. + * + * @return + */ + @Nonnull + ICraftingIssuerHost getCraftingHost(); } diff --git a/src/main/java/thaumicenergistics/api/gui/IWidgetHost.java b/src/main/java/thaumicenergistics/api/gui/IWidgetHost.java index 5e94dcb7..1bf2839d 100644 --- a/src/main/java/thaumicenergistics/api/gui/IWidgetHost.java +++ b/src/main/java/thaumicenergistics/api/gui/IWidgetHost.java @@ -9,27 +9,26 @@ import net.minecraft.client.gui.FontRenderer; * @author Nividica * */ -public interface IWidgetHost -{ - /** - * Gets the font renderer for the GUI. - * - * @return - */ - @Nonnull - FontRenderer getFontRenderer(); +public interface IWidgetHost { + /** + * Gets the font renderer for the GUI. + * + * @return + */ + @Nonnull + FontRenderer getFontRenderer(); - /** - * Return the left of the GUI. - * - * @return - */ - int guiLeft(); + /** + * Return the left of the GUI. + * + * @return + */ + int guiLeft(); - /** - * Return the top of the GUI. - * - * @return - */ - int guiTop(); + /** + * Return the top of the GUI. + * + * @return + */ + int guiTop(); } diff --git a/src/main/java/thaumicenergistics/api/items/IRestrictedEssentiaContainerItem.java b/src/main/java/thaumicenergistics/api/items/IRestrictedEssentiaContainerItem.java index 4f2c5152..2255f5cb 100644 --- a/src/main/java/thaumicenergistics/api/items/IRestrictedEssentiaContainerItem.java +++ b/src/main/java/thaumicenergistics/api/items/IRestrictedEssentiaContainerItem.java @@ -10,14 +10,12 @@ import thaumcraft.api.aspects.IEssentiaContainerItem; * @author Nividica * */ -public interface IRestrictedEssentiaContainerItem - extends IEssentiaContainerItem -{ - /** - * Returns true if the container accepts the specified aspect. - * - * @param aspect - * @return - */ - boolean acceptsAspect( @Nonnull Aspect aspect ); +public interface IRestrictedEssentiaContainerItem extends IEssentiaContainerItem { + /** + * Returns true if the container accepts the specified aspect. + * + * @param aspect + * @return + */ + boolean acceptsAspect(@Nonnull Aspect aspect); } diff --git a/src/main/java/thaumicenergistics/api/storage/IAspectStack.java b/src/main/java/thaumicenergistics/api/storage/IAspectStack.java index 1b11d091..9a004358 100644 --- a/src/main/java/thaumicenergistics/api/storage/IAspectStack.java +++ b/src/main/java/thaumicenergistics/api/storage/IAspectStack.java @@ -1,8 +1,8 @@ package thaumicenergistics.api.storage; +import io.netty.buffer.ByteBuf; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import thaumcraft.api.aspects.Aspect; @@ -13,170 +13,168 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IAspectStack -{ - /** - * Changes the stack size by the delta amount and returns the new stack size. - * - * @param delta - * @return Adjusted stack size. - */ - long adjustStackSize( long delta ); +public interface IAspectStack { + /** + * Changes the stack size by the delta amount and returns the new stack size. + * + * @param delta + * @return Adjusted stack size. + */ + long adjustStackSize(long delta); - /** - * Creates a copy of this stack and returns it. - * - * @return Copy of the stack. - */ - @Nonnull - IAspectStack copy(); + /** + * Creates a copy of this stack and returns it. + * + * @return Copy of the stack. + */ + @Nonnull + IAspectStack copy(); - /** - * Returns the aspect that is stored. - * - * @return - */ - @Nullable - Aspect getAspect(); + /** + * Returns the aspect that is stored. + * + * @return + */ + @Nullable + Aspect getAspect(); - /** - * Gets the Thaumcraft description for the aspect. - * - * @return Localized description, or empty string if no aspect. - */ - @Nonnull - String getAspectDescription(); + /** + * Gets the Thaumcraft description for the aspect. + * + * @return Localized description, or empty string if no aspect. + */ + @Nonnull + String getAspectDescription(); - /** - * Gets the name of the aspect.
- * This method does not take into consideration if the player has yet discovered the aspect. - * - * @return - */ - @Nonnull - String getAspectName(); + /** + * Gets the name of the aspect.
+ * This method does not take into consideration if the player has yet discovered the aspect. + * + * @return + */ + @Nonnull + String getAspectName(); - /** - * Gets the display name of the aspect for the player. - * - * @param player - * @return - */ - @Nonnull - String getAspectName( @Nullable EntityPlayer player ); + /** + * Gets the display name of the aspect for the player. + * + * @param player + * @return + */ + @Nonnull + String getAspectName(@Nullable EntityPlayer player); - /** - * Gets the Thaumcraft tag for the aspect - * - * @return Thaumcraft tag, or empty string if no aspect. - */ - @Nonnull - String getAspectTag(); + /** + * Gets the Thaumcraft tag for the aspect + * + * @return Thaumcraft tag, or empty string if no aspect. + */ + @Nonnull + String getAspectTag(); - /** - * The chat color associated with this aspect. - * - * @return Chat prefix string, or empty string if no aspect. - */ - @Nonnull - String getChatColor(); + /** + * The chat color associated with this aspect. + * + * @return Chat prefix string, or empty string if no aspect. + */ + @Nonnull + String getChatColor(); - /** - * Returns true if the aspect is craftable. - * - * @return - */ - boolean getCraftable(); + /** + * Returns true if the aspect is craftable. + * + * @return + */ + boolean getCraftable(); - /** - * Returns the stack size. - * - * @return - */ - long getStackSize(); + /** + * Returns the stack size. + * + * @return + */ + long getStackSize(); - /** - * Returns true if the stack has a non-null aspect set. - * - * @return - */ - boolean hasAspect(); + /** + * Returns true if the stack has a non-null aspect set. + * + * @return + */ + boolean hasAspect(); - /** - * Checks if the player has discovered this aspect. - * - * @param player - * @return - */ - boolean hasPlayerDiscovered( @Nullable EntityPlayer player ); + /** + * Checks if the player has discovered this aspect. + * + * @param player + * @return + */ + boolean hasPlayerDiscovered(@Nullable EntityPlayer player); - /** - * Returns true if the size is not positive. - * - * @return - */ - boolean isEmpty(); + /** + * Returns true if the size is not positive. + * + * @return + */ + boolean isEmpty(); - /** - * Sets this stack to the data in the stream. - * - * @param stream - */ - void readFromStream( @Nonnull ByteBuf stream ); + /** + * Sets this stack to the data in the stream. + * + * @param stream + */ + void readFromStream(@Nonnull ByteBuf stream); - /** - * Sets everything. - * - * @param aspect - * @param size - * @param craftable - */ - void setAll( @Nullable Aspect aspect, long size, boolean craftable ); + /** + * Sets everything. + * + * @param aspect + * @param size + * @param craftable + */ + void setAll(@Nullable Aspect aspect, long size, boolean craftable); - /** - * Sets the values of this stack to match the passed stack.
- * If the stack is null, all values are reset. - * - * @param stack - */ - void setAll( @Nullable IAspectStack stack ); + /** + * Sets the values of this stack to match the passed stack.
+ * If the stack is null, all values are reset. + * + * @param stack + */ + void setAll(@Nullable IAspectStack stack); - /** - * Sets the aspect for the stack. - * - * @param aspect - */ - void setAspect( @Nullable Aspect aspect ); + /** + * Sets the aspect for the stack. + * + * @param aspect + */ + void setAspect(@Nullable Aspect aspect); - /** - * Sets if the aspect is craftable. - * - * @param craftable - */ - void setCraftable( boolean craftable ); + /** + * Sets if the aspect is craftable. + * + * @param craftable + */ + void setCraftable(boolean craftable); - /** - * Sets the size of the stack. - * - * @param size - */ - void setStackSize( long size ); + /** + * Sets the size of the stack. + * + * @param size + */ + void setStackSize(long size); - /** - * Writes this aspect stack to the specified NBT tag - * - * @param data - * The tag to write to - * @return The nbt tag passed in. - */ - @Nonnull - NBTTagCompound writeToNBT( @Nonnull NBTTagCompound data ); - - /** - * Writes the stack to a bytebuf stream. - * - * @param stream - */ - void writeToStream( @Nonnull ByteBuf stream ); + /** + * Writes this aspect stack to the specified NBT tag + * + * @param data + * The tag to write to + * @return The nbt tag passed in. + */ + @Nonnull + NBTTagCompound writeToNBT(@Nonnull NBTTagCompound data); + /** + * Writes the stack to a bytebuf stream. + * + * @param stream + */ + void writeToStream(@Nonnull ByteBuf stream); } diff --git a/src/main/java/thaumicenergistics/api/storage/IEssentiaRepo.java b/src/main/java/thaumicenergistics/api/storage/IEssentiaRepo.java index 309da3c4..a12dd581 100644 --- a/src/main/java/thaumicenergistics/api/storage/IEssentiaRepo.java +++ b/src/main/java/thaumicenergistics/api/storage/IEssentiaRepo.java @@ -12,119 +12,118 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IEssentiaRepo -{ +public interface IEssentiaRepo { - /** - * Returns a set of the stored aspects. - * - * @return - */ - @Nonnull - Set aspectSet(); + /** + * Returns a set of the stored aspects. + * + * @return + */ + @Nonnull + Set aspectSet(); - /** - * Removes all entries in the repo. - */ - void clear(); + /** + * Removes all entries in the repo. + */ + void clear(); - /** - * Returns true if the repo has the aspect stored. - * - * @param aspect - * @return - */ - boolean containsAspect( @Nonnull Aspect aspect ); + /** + * Returns true if the repo has the aspect stored. + * + * @param aspect + * @return + */ + boolean containsAspect(@Nonnull Aspect aspect); - /** - * Sets the repo to match the specified collection. - * Any existing data is removed. - * - * @param stacks - */ - void copyFrom( @Nonnull Collection stacks ); + /** + * Sets the repo to match the specified collection. + * Any existing data is removed. + * + * @param stacks + */ + void copyFrom(@Nonnull Collection stacks); - /** - * Gets the aspect stack associated with the aspect or null. - */ - IAspectStack get( @Nonnull Aspect aspect ); + /** + * Gets the aspect stack associated with the aspect or null. + */ + IAspectStack get(@Nonnull Aspect aspect); - /** - * Returns all aspect information stored in the repo. - * - * @return - */ - @Nonnull - Collection getAll(); + /** + * Returns all aspect information stored in the repo. + * + * @return + */ + @Nonnull + Collection getAll(); - /** - * Gets the aspect stack associated with the aspect or specified the default value. - */ - IAspectStack getOrDefault( @Nonnull Aspect aspect, @Nullable IAspectStack defaultValue ); + /** + * Gets the aspect stack associated with the aspect or specified the default value. + */ + IAspectStack getOrDefault(@Nonnull Aspect aspect, @Nullable IAspectStack defaultValue); - /** - * Returns true if the repo is empty. - * - * @return - */ - boolean isEmpty(); + /** + * Returns true if the repo is empty. + * + * @return + */ + boolean isEmpty(); - /** - * Changes the aspect in the repo by the specified values. - * - * @param aspect - * @param change - * @param isCraftable - * If this value is null and there is a stored value, its crafting status will remain the same. - * Otherwise it is set to false. - * @return The previous stack, if there was one. - */ - @Nullable - IAspectStack postChange( @Nonnull Aspect aspect, long change, Boolean isCraftable ); + /** + * Changes the aspect in the repo by the specified values. + * + * @param aspect + * @param change + * @param isCraftable + * If this value is null and there is a stored value, its crafting status will remain the same. + * Otherwise it is set to false. + * @return The previous stack, if there was one. + */ + @Nullable + IAspectStack postChange(@Nonnull Aspect aspect, long change, Boolean isCraftable); - /** - * Changes the aspect in the repo by the specified aspect stack. - * - * @param change - * @return The previous stack, if there was one. - */ - @Nullable - IAspectStack postChange( @Nonnull IAspectStack change ); + /** + * Changes the aspect in the repo by the specified aspect stack. + * + * @param change + * @return The previous stack, if there was one. + */ + @Nullable + IAspectStack postChange(@Nonnull IAspectStack change); - /** - * Removes an aspect from the repo.
- * Returns the removed stack, if there was one removed. - * - * @param aspect - * @return - */ - @Nullable - IAspectStack remove( Aspect aspect ); + /** + * Removes an aspect from the repo.
+ * Returns the removed stack, if there was one removed. + * + * @param aspect + * @return + */ + @Nullable + IAspectStack remove(Aspect aspect); - /** - * Sets the aspect in the repo by the specified values. - * - * @param aspect - * @param amount - * @param isCraftable - * @return The previous stack, if there was one. - */ - @Nullable - IAspectStack setAspect( @Nonnull Aspect aspect, long amount, boolean isCraftable ); + /** + * Sets the aspect in the repo by the specified values. + * + * @param aspect + * @param amount + * @param isCraftable + * @return The previous stack, if there was one. + */ + @Nullable + IAspectStack setAspect(@Nonnull Aspect aspect, long amount, boolean isCraftable); - /** - * Sets the aspect in the repo to the specified aspect stack. - * - * @param stack - * @return The previous stack, if there was one. - */ - @Nullable - IAspectStack setAspect( @Nonnull IAspectStack stack ); + /** + * Sets the aspect in the repo to the specified aspect stack. + * + * @param stack + * @return The previous stack, if there was one. + */ + @Nullable + IAspectStack setAspect(@Nonnull IAspectStack stack); - /** - * Returns the number of unique aspects stored. - * - * @return - */ - int size(); + /** + * Returns the number of unique aspects stored. + * + * @return + */ + int size(); } diff --git a/src/main/java/thaumicenergistics/api/storage/IInventoryUpdateReceiver.java b/src/main/java/thaumicenergistics/api/storage/IInventoryUpdateReceiver.java index bcf69af9..165110a6 100644 --- a/src/main/java/thaumicenergistics/api/storage/IInventoryUpdateReceiver.java +++ b/src/main/java/thaumicenergistics/api/storage/IInventoryUpdateReceiver.java @@ -8,12 +8,11 @@ import net.minecraft.inventory.IInventory; * @author Nividica * */ -public interface IInventoryUpdateReceiver -{ - /** - * Called when an inventory is changed. - * - * @param sourceInventory - */ - public void onInventoryChanged( IInventory sourceInventory ); +public interface IInventoryUpdateReceiver { + /** + * Called when an inventory is changed. + * + * @param sourceInventory + */ + public void onInventoryChanged(IInventory sourceInventory); } diff --git a/src/main/java/thaumicenergistics/api/tiles/IEssentiaTransportWithSimulate.java b/src/main/java/thaumicenergistics/api/tiles/IEssentiaTransportWithSimulate.java index fb04f83a..22aca917 100644 --- a/src/main/java/thaumicenergistics/api/tiles/IEssentiaTransportWithSimulate.java +++ b/src/main/java/thaumicenergistics/api/tiles/IEssentiaTransportWithSimulate.java @@ -1,7 +1,7 @@ package thaumicenergistics.api.tiles; -import javax.annotation.Nonnull; import appeng.api.config.Actionable; +import javax.annotation.Nonnull; import net.minecraftforge.common.util.ForgeDirection; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.IEssentiaTransport; @@ -12,17 +12,15 @@ import thaumcraft.api.aspects.IEssentiaTransport; * @author Nividica * */ -public interface IEssentiaTransportWithSimulate - extends IEssentiaTransport -{ - /** - * Adds essentia to the transport. - * - * @param aspect - * @param amount - * @param side - * @param mode - * @return Amount that was injected. - */ - int addEssentia( @Nonnull Aspect aspect, int amount, @Nonnull ForgeDirection side, @Nonnull Actionable mode ); +public interface IEssentiaTransportWithSimulate extends IEssentiaTransport { + /** + * Adds essentia to the transport. + * + * @param aspect + * @param amount + * @param side + * @param mode + * @return Amount that was injected. + */ + int addEssentia(@Nonnull Aspect aspect, int amount, @Nonnull ForgeDirection side, @Nonnull Actionable mode); } diff --git a/src/main/java/thaumicenergistics/client/ClientProxy.java b/src/main/java/thaumicenergistics/client/ClientProxy.java index 10f09d90..07a548a0 100644 --- a/src/main/java/thaumicenergistics/client/ClientProxy.java +++ b/src/main/java/thaumicenergistics/client/ClientProxy.java @@ -13,29 +13,22 @@ import thaumicenergistics.common.registries.Renderers; * @author Nividica * */ -public class ClientProxy - extends CommonProxy -{ - public ClientProxy() - { - MinecraftForge.EVENT_BUS.register( this ); - } +public class ClientProxy extends CommonProxy { + public ClientProxy() { + MinecraftForge.EVENT_BUS.register(this); + } - @Override - public void registerRenderers() - { - // Register the custom block renderers - Renderers.registerRenderers(); - } + @Override + public void registerRenderers() { + // Register the custom block renderers + Renderers.registerRenderers(); + } - @SubscribeEvent - public void registerTextures( final TextureStitchEvent.Pre event ) - { - // Register all block textures - for( BlockTextureManager texture : BlockTextureManager.ALLVALUES ) - { - texture.registerTexture( event.map ); - } - - } + @SubscribeEvent + public void registerTextures(final TextureStitchEvent.Pre event) { + // Register all block textures + for (BlockTextureManager texture : BlockTextureManager.ALLVALUES) { + texture.registerTexture(event.map); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/EnumGuiParticles.java b/src/main/java/thaumicenergistics/client/gui/EnumGuiParticles.java index d14102bd..fbf0c3f8 100644 --- a/src/main/java/thaumicenergistics/client/gui/EnumGuiParticles.java +++ b/src/main/java/thaumicenergistics/client/gui/EnumGuiParticles.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; /** * Particles that can be displayed in a GUI. @@ -14,114 +14,121 @@ import net.minecraft.util.ResourceLocation; * */ @SideOnly(Side.CLIENT) -public enum EnumGuiParticles -{ - Orb (thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 128, 16, 16, 16, 0, 16), - Rune (thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 96, 16, 16, 16, 0, 16), - Wispy (thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 80, 16, 16, 16, 0, 16), - Knowledge (thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 64, 16, 16, 16, 0, 4); +public enum EnumGuiParticles { + Orb(thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 128, 16, 16, 16, 0, 16), + Rune(thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 96, 16, 16, 16, 0, 16), + Wispy(thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 80, 16, 16, 16, 0, 16), + Knowledge(thaumcraft.client.fx.ParticleEngine.particleTexture, 0, 64, 16, 16, 16, 0, 4); - /** - * Location of the particle in the texture. - */ - private int txU, txV, width, height; + /** + * Location of the particle in the texture. + */ + private int txU, txV, width, height; - /** - * Amount that U and V change during each animation step. - */ - private int animationUStep, animationVStep; + /** + * Amount that U and V change during each animation step. + */ + private int animationUStep, animationVStep; - /** - * Number of frames in the animation. - * Can not be 0. - */ - private int FrameCount; + /** + * Number of frames in the animation. + * Can not be 0. + */ + private int FrameCount; - /** - * Texture used to draw the particle. - */ - private ResourceLocation texture; + /** + * Texture used to draw the particle. + */ + private ResourceLocation texture; - private EnumGuiParticles( final ResourceLocation textureLocation, final int U, final int V, final int width, final int height, - final int UStep, final int VStep, final int Frames ) - { - this.texture = textureLocation; - this.txU = U; - this.txV = V; - this.width = width; - this.height = height; - this.animationUStep = UStep; - this.animationVStep = VStep; - this.FrameCount = Frames; - } + private EnumGuiParticles( + final ResourceLocation textureLocation, + final int U, + final int V, + final int width, + final int height, + final int UStep, + final int VStep, + final int Frames) { + this.texture = textureLocation; + this.txU = U; + this.txV = V; + this.width = width; + this.height = height; + this.animationUStep = UStep; + this.animationVStep = VStep; + this.FrameCount = Frames; + } - /** - * Resets the engine state. - */ - public static void finishDraw() - { - // Set color to white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + /** + * Resets the engine state. + */ + public static void finishDraw() { + // Set color to white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - } + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + } - /** - * Draws the particle. - * If settings "needsPrepare" to false, prepare and finish must be called manually. - * However this can be useful if drawing multiple of the same particle. - * - * @param gui - * @param positionX - * @param positionY - * @param frameNumber - * @param red - * @param green - * @param blue - * @param needsPrepare - */ - public void drawParticle( final Gui gui, final int positionX, final int positionY, final int frameNumber, final float red, final float green, - final float blue, final boolean needsPrepare ) - { - if( needsPrepare ) - { - this.prepareDraw(); - } + /** + * Draws the particle. + * If settings "needsPrepare" to false, prepare and finish must be called manually. + * However this can be useful if drawing multiple of the same particle. + * + * @param gui + * @param positionX + * @param positionY + * @param frameNumber + * @param red + * @param green + * @param blue + * @param needsPrepare + */ + public void drawParticle( + final Gui gui, + final int positionX, + final int positionY, + final int frameNumber, + final float red, + final float green, + final float blue, + final boolean needsPrepare) { + if (needsPrepare) { + this.prepareDraw(); + } - // Wrap the frame number - int frameIndex = frameNumber % this.FrameCount; + // Wrap the frame number + int frameIndex = frameNumber % this.FrameCount; - // Calculate the U position - int U = this.txU + ( this.animationUStep * frameIndex ); + // Calculate the U position + int U = this.txU + (this.animationUStep * frameIndex); - // Calculate the V position - int V = this.txV + ( this.animationVStep * frameIndex ); + // Calculate the V position + int V = this.txV + (this.animationVStep * frameIndex); - // Set tint color - GL11.glColor4f( red, green, blue, 0.90f ); + // Set tint color + GL11.glColor4f(red, green, blue, 0.90f); - // Draw the particle - gui.drawTexturedModalRect( positionX, positionY, U, V, this.width, this.height ); + // Draw the particle + gui.drawTexturedModalRect(positionX, positionY, U, V, this.width, this.height); - if( needsPrepare ) - { - EnumGuiParticles.finishDraw(); - } - } + if (needsPrepare) { + EnumGuiParticles.finishDraw(); + } + } - /** - * Prepares the engine to draw this particle. - * Must be called before drawing, but can be called once then - * draw called multiple times for the same particle. - */ - public void prepareDraw() - { - // Bind the texture - Minecraft.getMinecraft().renderEngine.bindTexture( this.texture ); + /** + * Prepares the engine to draw this particle. + * Must be called before drawing, but can be called once then + * draw called multiple times for the same particle. + */ + public void prepareDraw() { + // Bind the texture + Minecraft.getMinecraft().renderEngine.bindTexture(this.texture); - // Enable alpha blending - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE ); - } + // Enable alpha blending + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiArcaneAssembler.java b/src/main/java/thaumicenergistics/client/gui/GuiArcaneAssembler.java index 1bc42758..166a419e 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiArcaneAssembler.java @@ -1,15 +1,15 @@ package thaumicenergistics.client.gui; -import java.util.Dictionary; -import java.util.Hashtable; -import org.apache.commons.lang3.StringUtils; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Dictionary; +import java.util.Hashtable; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.StatCollector; import net.minecraft.world.World; +import org.apache.commons.lang3.StringUtils; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; @@ -25,167 +25,177 @@ import thaumicenergistics.common.tiles.TileArcaneAssembler; * */ @SideOnly(Side.CLIENT) -public class GuiArcaneAssembler - extends ThEBaseGui -{ - /** - * Gui size. - */ - private static final int FULL_GUI_WIDTH = 247, MAIN_GUI_WIDTH = 176, UPGRADE_GUI_WIDTH = 234 - MAIN_GUI_WIDTH, GUI_HEIGHT = 197, - UPGRADE_GUI_HEIGHT = 104; +public class GuiArcaneAssembler extends ThEBaseGui { + /** + * Gui size. + */ + private static final int FULL_GUI_WIDTH = 247, + MAIN_GUI_WIDTH = 176, + UPGRADE_GUI_WIDTH = 234 - MAIN_GUI_WIDTH, + GUI_HEIGHT = 197, + UPGRADE_GUI_HEIGHT = 104; - /** - * Title position. - */ - private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; + /** + * Title position. + */ + private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; - /** - * Vis bar positions. - */ - private static final int VIS_EMPTY_Y = 87, VIS_FULL_Y = 202, VIS_BAR_HEIGHT = 16, VIS_BAR_WIDTH = 4; + /** + * Vis bar positions. + */ + private static final int VIS_EMPTY_Y = 87, VIS_FULL_Y = 202, VIS_BAR_HEIGHT = 16, VIS_BAR_WIDTH = 4; - /** - * Title displayed on the GUI - */ - private String title; + /** + * Title displayed on the GUI + */ + private String title; - /** - * Map's an aspect to an X location. - */ - private Dictionary visBarPositionMap = new Hashtable(); + /** + * Map's an aspect to an X location. + */ + private Dictionary visBarPositionMap = new Hashtable(); - /** - * True if the player is holding a network tool. - */ - private boolean hasNetworkTool = false; + /** + * True if the player is holding a network tool. + */ + private boolean hasNetworkTool = false; - /** - * Fake aspect used to simplify progress bar draw calls - */ - private Aspect progressAspect = Aspect.MECHANISM; + /** + * Fake aspect used to simplify progress bar draw calls + */ + private Aspect progressAspect = Aspect.MECHANISM; - public GuiArcaneAssembler( final EntityPlayer player, final World world, final int X, final int Y, final int Z ) - { - // Call super - super( new ContainerArcaneAssembler( player, world, X, Y, Z ) ); + public GuiArcaneAssembler(final EntityPlayer player, final World world, final int X, final int Y, final int Z) { + // Call super + super(new ContainerArcaneAssembler(player, world, X, Y, Z)); - this.hasNetworkTool = ( (ContainerArcaneAssembler)this.inventorySlots ).hasNetworkTool(); + this.hasNetworkTool = ((ContainerArcaneAssembler) this.inventorySlots).hasNetworkTool(); - // Set the GUI size - this.xSize = ( this.hasNetworkTool ? GuiArcaneAssembler.FULL_GUI_WIDTH : GuiArcaneAssembler.MAIN_GUI_WIDTH + - GuiArcaneAssembler.UPGRADE_GUI_WIDTH ); - this.ySize = GuiArcaneAssembler.GUI_HEIGHT; + // Set the GUI size + this.xSize = (this.hasNetworkTool + ? GuiArcaneAssembler.FULL_GUI_WIDTH + : GuiArcaneAssembler.MAIN_GUI_WIDTH + GuiArcaneAssembler.UPGRADE_GUI_WIDTH); + this.ySize = GuiArcaneAssembler.GUI_HEIGHT; - // Set the title - this.title = ThEStrings.Gui_TitleArcaneAssembler.getLocalized(); + // Set the title + this.title = ThEStrings.Gui_TitleArcaneAssembler.getLocalized(); - // Add the vis bar positions - this.visBarPositionMap.put( Aspect.AIR, 41 ); - this.visBarPositionMap.put( Aspect.WATER, 59 ); - this.visBarPositionMap.put( Aspect.FIRE, 77 ); - this.visBarPositionMap.put( Aspect.ORDER, 95 ); - this.visBarPositionMap.put( Aspect.ENTROPY, 113 ); - this.visBarPositionMap.put( Aspect.EARTH, 131 ); - this.visBarPositionMap.put( this.progressAspect, 149 ); - } + // Add the vis bar positions + this.visBarPositionMap.put(Aspect.AIR, 41); + this.visBarPositionMap.put(Aspect.WATER, 59); + this.visBarPositionMap.put(Aspect.FIRE, 77); + this.visBarPositionMap.put(Aspect.ORDER, 95); + this.visBarPositionMap.put(Aspect.ENTROPY, 113); + this.visBarPositionMap.put(Aspect.EARTH, 131); + this.visBarPositionMap.put(this.progressAspect, 149); + } - private void drawVisBar( final Aspect aspect, final float percent ) - { - // Calculate the height - int height = (int)Math.floor( percent * GuiArcaneAssembler.VIS_BAR_HEIGHT ); + private void drawVisBar(final Aspect aspect, final float percent) { + // Calculate the height + int height = (int) Math.floor(percent * GuiArcaneAssembler.VIS_BAR_HEIGHT); - if( height > 0 ) - { - // Calculate the X/U position - int xuPos = this.visBarPositionMap.get( aspect ); + if (height > 0) { + // Calculate the X/U position + int xuPos = this.visBarPositionMap.get(aspect); - // Calculate the Y pos - int yPos = GuiArcaneAssembler.VIS_EMPTY_Y + ( GuiArcaneAssembler.VIS_BAR_HEIGHT - height ); + // Calculate the Y pos + int yPos = GuiArcaneAssembler.VIS_EMPTY_Y + (GuiArcaneAssembler.VIS_BAR_HEIGHT - height); - // Calculate the v pos - int vPos = GuiArcaneAssembler.VIS_FULL_Y + ( GuiArcaneAssembler.VIS_BAR_HEIGHT - height ); + // Calculate the v pos + int vPos = GuiArcaneAssembler.VIS_FULL_Y + (GuiArcaneAssembler.VIS_BAR_HEIGHT - height); - // Draw the bar - this.drawTexturedModalRect( this.guiLeft + xuPos, this.guiTop + yPos, xuPos, vPos, GuiArcaneAssembler.VIS_BAR_WIDTH, height ); - } - } + // Draw the bar + this.drawTexturedModalRect( + this.guiLeft + xuPos, this.guiTop + yPos, xuPos, vPos, GuiArcaneAssembler.VIS_BAR_WIDTH, height); + } + } - /** - * Draw background - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + /** + * Draw background + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // Bind the workbench gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ARCANE_ASSEMBLER.getTexture() ); + // Bind the workbench gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ARCANE_ASSEMBLER.getTexture()); - // Draw the gui texture - if( this.hasNetworkTool ) - { - // Draw the full gui - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); - } - else - { - // Draw main body - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, GuiArcaneAssembler.MAIN_GUI_WIDTH, this.ySize ); + // Draw the gui texture + if (this.hasNetworkTool) { + // Draw the full gui + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + } else { + // Draw main body + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, GuiArcaneAssembler.MAIN_GUI_WIDTH, this.ySize); - // Draw upgrades - this.drawTexturedModalRect( this.guiLeft + GuiArcaneAssembler.MAIN_GUI_WIDTH, this.guiTop, GuiArcaneAssembler.MAIN_GUI_WIDTH, 0, - GuiArcaneAssembler.UPGRADE_GUI_WIDTH, GuiArcaneAssembler.UPGRADE_GUI_HEIGHT ); - } + // Draw upgrades + this.drawTexturedModalRect( + this.guiLeft + GuiArcaneAssembler.MAIN_GUI_WIDTH, + this.guiTop, + GuiArcaneAssembler.MAIN_GUI_WIDTH, + 0, + GuiArcaneAssembler.UPGRADE_GUI_WIDTH, + GuiArcaneAssembler.UPGRADE_GUI_HEIGHT); + } - // Get the aspect amounts - AspectList storedVis = ( (ContainerArcaneAssembler)this.inventorySlots ).assembler.getStoredVis(); + // Get the aspect amounts + AspectList storedVis = ((ContainerArcaneAssembler) this.inventorySlots).assembler.getStoredVis(); - // Draw the bars - for( Aspect aspect : TileArcaneAssembler.PRIMALS ) - { - float percent = storedVis.getAmount( aspect ) / (float)TileArcaneAssembler.MAX_STORED_CVIS; - this.drawVisBar( aspect, percent ); - } + // Draw the bars + for (Aspect aspect : TileArcaneAssembler.PRIMALS) { + float percent = storedVis.getAmount(aspect) / (float) TileArcaneAssembler.MAX_STORED_CVIS; + this.drawVisBar(aspect, percent); + } - // Draw crafting percent - this.drawVisBar( this.progressAspect, ( (ContainerArcaneAssembler)this.inventorySlots ).assembler.getPercentComplete() ); + // Draw crafting percent + this.drawVisBar( + this.progressAspect, ((ContainerArcaneAssembler) this.inventorySlots).assembler.getPercentComplete()); - // Call super - super.drawAEToolAndUpgradeSlots( alpha, mouseX, mouseY ); - } + // Call super + super.drawAEToolAndUpgradeSlots(alpha, mouseX, mouseY); + } - /** - * Draw the foreground - */ - @Override - public void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( this.title, GuiArcaneAssembler.TITLE_POS_X, GuiArcaneAssembler.TITLE_POS_Y, 0 ); + /** + * Draw the foreground + */ + @Override + public void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString(this.title, GuiArcaneAssembler.TITLE_POS_X, GuiArcaneAssembler.TITLE_POS_Y, 0); - // Is the mouse over any of the bars? - for( Aspect aspect : TileArcaneAssembler.PRIMALS ) - { - int left = this.visBarPositionMap.get( aspect ); - if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiArcaneAssembler.VIS_EMPTY_Y, left, GuiArcaneAssembler.VIS_BAR_HEIGHT, - GuiArcaneAssembler.VIS_BAR_WIDTH, mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Add the aspect name to the tooltip - this.tooltip.add( ThEGuiHelper.INSTANCE.getAspectChatColor( aspect ) + StringUtils.capitalize( aspect.getTag() ) ); + // Is the mouse over any of the bars? + for (Aspect aspect : TileArcaneAssembler.PRIMALS) { + int left = this.visBarPositionMap.get(aspect); + if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiArcaneAssembler.VIS_EMPTY_Y, + left, + GuiArcaneAssembler.VIS_BAR_HEIGHT, + GuiArcaneAssembler.VIS_BAR_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Add the aspect name to the tooltip + this.tooltip.add( + ThEGuiHelper.INSTANCE.getAspectChatColor(aspect) + StringUtils.capitalize(aspect.getTag())); - // Add the amount - int amount = ( (ContainerArcaneAssembler)this.inventorySlots ).assembler.getStoredVis().getAmount( aspect ); - this.tooltip.add( Float.toString( amount / 10.0F ) + " / 150" ); + // Add the amount + int amount = ((ContainerArcaneAssembler) this.inventorySlots) + .assembler + .getStoredVis() + .getAmount(aspect); + this.tooltip.add(Float.toString(amount / 10.0F) + " / 150"); - // Add the discount - float discount = ( (ContainerArcaneAssembler)this.inventorySlots ).assembler.getVisDiscountForAspect( aspect ); - this.tooltip.add( String.format( "%.0f%% %s", ( discount * 100.0F ), StatCollector.translateToLocal( "tc.vis.costavg" ) ) ); - - // Stop searching - break; - } - } - } + // Add the discount + float discount = + ((ContainerArcaneAssembler) this.inventorySlots).assembler.getVisDiscountForAspect(aspect); + this.tooltip.add(String.format( + "%.0f%% %s", (discount * 100.0F), StatCollector.translateToLocal("tc.vis.costavg"))); + // Stop searching + break; + } + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiArcaneCraftingTerminal.java b/src/main/java/thaumicenergistics/client/gui/GuiArcaneCraftingTerminal.java index cdf0ebfc..7b4f22d4 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiArcaneCraftingTerminal.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiArcaneCraftingTerminal.java @@ -1,10 +1,5 @@ package thaumicenergistics.client.gui; -import java.util.ArrayList; -import java.util.List; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; import appeng.api.config.*; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; @@ -15,6 +10,8 @@ import appeng.core.AEConfig; import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; @@ -22,6 +19,9 @@ import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; import thaumcraft.client.lib.UtilsFX; import thaumcraft.common.config.Config; import thaumicenergistics.client.gui.abstraction.GuiConstants_ACT; @@ -47,1214 +47,1184 @@ import thaumicenergistics.common.utils.ThEUtils; * */ @SideOnly(Side.CLIENT) -public class GuiArcaneCraftingTerminal - extends GuiConstants_ACT - implements ISortSource -{ - /** - * Renders an AE itemstack into the gui. - */ - private AppEngRenderItem aeItemRenderer = new AppEngRenderItem(); - - /** - * Translated title of the gui. - */ - private String guiTitle; - - /** - * Number of ME widgets - */ - private int widgetCount = GuiConstants_ACT.ME_DEFAULT_ROWS * GuiConstants_ACT.ME_COLUMNS; - - /** - * Widget 'slots'. - */ - private List itemWidgets = new ArrayList(); - - /** - * Player viewing the gui. - */ - private EntityPlayer player; - - /** - * Search field. - */ - private GuiTextField searchField; - - /** - * Item repository - */ - private final ItemRepo repo; - - /** - * How the items are sorted. - */ - private SortOrder sortingOrder = SortOrder.NAME; - - /** - * What direction are the items sorted. - */ - private SortDir sortingDirection = SortDir.ASCENDING; - - /** - * Which items can be viewed in the terminal. - */ - private ViewItems viewMode = ViewItems.ALL; - - /** - * Is the terminal small or tall? - */ - private TerminalStyle terminalStyle = TerminalStyle.SMALL; - - /** - * The Y offeset of the lower portion of the terminal. - */ - private int lowerTerminalYOffset = 0; - - /** - * Tracks mouse movement. - */ - private int previousMouseX = 0; - private int previousMouseY = 0; - - /** - * Tracks what widget was under the mouse last draw. - */ - private WidgetAEItem previousWidgetUnderMouse = null; - - /** - * Tracks the last time the tooltip was updated. - */ - private long lastTooltipUpdateTime = 0; - - /** - * TODO: Remove this and rework the widgets/slots to be MESlots. Such fun - * that will be. - */ - private MEItemAspectBridgeContainer meAspectBridge; - - /** - * The number of rows to use. - */ - private int numberOfWidgetRows = GuiConstants_ACT.ME_DEFAULT_ROWS; - - /** - * Button to set the sorting mode. - */ - private GuiButtonSortingMode btnSortingMode; - - /** - * Button to set accending or decending sorting. - */ - private GuiButtonSortingDirection btnSortingDirection; - - /** - * Button to change what items (regular | crafting) are shown. - */ - private GuiButtonViewType btnViewType; - - /** - * Button to change the search mode. - */ - private GuiButtonSearchMode btnSearchMode; - - /** - * Tracks if the repo/widgets needs to be updated. - */ - private boolean viewNeedsUpdate = true; - - /** - * Holds the cached tooltip of an item. - */ - private ArrayList cachedItemTooltip = new ArrayList(); - - /** - * Save the search string between sessions - */ - private static String memoryText = ""; - - public GuiArcaneCraftingTerminal( final PartArcaneCraftingTerminal part, final EntityPlayer player ) - { - // Call super - super( new ContainerPartArcaneCraftingTerminal( part, player ) ); - - // Set the player - this.player = player; - - // Set the width and height - this.xSize = GuiConstants_ACT.GUI_WIDTH; - this.ySize = GuiConstants_ACT.GUI_HEIGHT; - - // Set the title - this.guiTitle = ThEStrings.Gui_TitleArcaneCraftingTerminal.getLocalized(); - - // Create the repo - this.repo = new ItemRepo( this.scrollBar, this ); - - // Get the terminal style - this.terminalStyle = (TerminalStyle)AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ); - - } - - /** - * Checks if the click was a region deposit. - * - * @param mouseX - * @param mouseY - * @return True if click was handled. - */ - private boolean clickHandler_RegionDeposit( final int mouseX, final int mouseY ) - { - // Is the player holding the space key? - if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) - { - // Get the slot the mouse is over - Slot slotClicked = this.getSlotAtMousePosition( mouseX, mouseY ); - - // Was there a slot under the mouse? - if( slotClicked != null ) - { - // Ask the server to move the inventory - Packet_S_ArcaneCraftingTerminal.sendDepositRegion( this.player, slotClicked.slotNumber ); - - // Do not pass to super - return true; - } - } - - return false; - } - - /** - * Checks if the click was inside the search box. - * - * @param mouseX - * @param mouseY - * @param mouseButton - * @return True if click was handled. - */ - private boolean clickHandler_SearchBox( final int mouseX, final int mouseY, final int mouseButton ) - { - // Was the mouse right-clicked over the search field? - if( ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT ) && - ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiConstants_ACT.SEARCH_POS_Y, GuiConstants_ACT.SEARCH_POS_X, - GuiConstants_ACT.SEARCH_HEIGHT, GuiConstants_ACT.SEARCH_WIDTH, mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Clear the search field - this.searchField.setText( "" ); - - // Update the repo - this.repo.setSearchString( "" ); - memoryText = ""; - - // Repo needs update - this.viewNeedsUpdate = true; - - // Inform search field. - this.searchField.mouseClicked( mouseX - this.guiLeft, mouseY - this.guiTop, mouseButton ); - - // Do not pass to super - return true; - } - - return false; - } - - /** - * Checks if the click was inside the widgets. - * - * @param mouseX - * @param mouseY - * @param mouseButton - * @return True if click was handled. - */ - private boolean clickHandler_Widgets( final int mouseX, final int mouseY, final int mouseButton ) - { - // Was the click inside the ME grid? - if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiConstants_ACT.ME_ITEM_POS_Y, GuiConstants_ACT.ME_ITEM_POS_X, - this.numberOfWidgetRows * GuiConstants_ACT.ME_ROW_HEIGHT, GuiConstants_ACT.ME_GRID_WIDTH, mouseX, mouseY, this.guiLeft, - this.guiTop ) ) - { - // Click + empty hand is extract - boolean doExtract = ( this.player.inventory.getItemStack() == null ); - - // Shift+Right click is extract - doExtract |= ( Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) && ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT ) ); - - // Extracting? - if( doExtract ) - { - // Search for the widget the mouse is over, and send extract request. - this.sendItemWidgetClicked( mouseX, mouseY, mouseButton ); - } - else - { - // Inform the server the user would like to deposit the currently held item into the ME network. - Packet_S_ArcaneCraftingTerminal.sendDeposit( this.player, mouseButton ); - } - - // Do not pass to super - return true; - } - - return false; - } - - /** - * Extracts or inserts an item to/from the player held stack based on the - * direction the mouse wheel was scrolled. - * - * @param deltaZ - */ - private void doMEWheelAction( final int deltaZ, final int mouseX, final int mouseY ) - { - // Is the mouse inside the ME area? - if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiConstants_ACT.ME_ITEM_POS_Y, GuiConstants_ACT.ME_ITEM_POS_X, - this.numberOfWidgetRows * GuiConstants_ACT.ME_ROW_HEIGHT, GuiConstants_ACT.ME_GRID_WIDTH, - mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Which direction was the scroll? - if( deltaZ > 0 ) - { - // Is the player holding anything? - if( this.player.inventory.getItemStack() != null ) - { - // Inform the server the user would like to deposit 1 of the currently held items into the ME network. - Packet_S_ArcaneCraftingTerminal.sendDeposit( this.player, ThEGuiHelper.MOUSE_WHEEL_MOTION ); - } - } - else - { - // Extract an item based on the widget we are over - this.sendItemWidgetClicked( mouseX, mouseY, ThEGuiHelper.MOUSE_WHEEL_MOTION ); - - } - } - } - - /** - * Draws the crafting aspect's and their costs. - * - * @param craftingCost - */ - private void drawCraftingAspects( final List craftingCost ) - { - int posY = GuiConstants_ACT.ASPECT_COST_POS_Y + this.lowerTerminalYOffset; - int column = 0; - - // Draw each primal - for( ArcaneCrafingCost cost : craftingCost ) - { - // Set the alpha to full - float alpha = 1.0F; - - // Do we have enough vis for this aspect? - if( !cost.hasEnoughVis ) - { - // Ping-pong the alpha - alpha = ThEUtils.pingPongFromTime( GuiConstants_ACT.ASPECT_COST_BLINK_SPEED, - GuiConstants_ACT.ASPECT_COST_MIN_ALPHA, GuiConstants_ACT.ASPECT_COST_MAX_ALPHA ); - } - - // Calculate X position - int posX = GuiConstants_ACT.ASPECT_COST_POS_X + ( column * GuiConstants_ACT.ASPECT_COST_SPACING ); - - // Draw the aspect icon - UtilsFX.drawTag( posX, posY, cost.primal, cost.visCost, 0, this.zLevel, GL11.GL_ONE_MINUS_SRC_ALPHA, alpha, false ); - - // Should we move to the next row? - if( ++column == 2 ) - { - // Reset column - column = 0; - - // Increment Y - posY += GuiConstants_ACT.ASPECT_COST_SPACING; - } - } - } - - /** - * Draws the AE item widgets. - * - * @param mouseX - * @param mouseY - * @return - */ - private WidgetAEItem drawItemWidgets( final int mouseX, final int mouseY ) - { - boolean hasNoOverlay = true; - - WidgetAEItem widgetUnderMouse = null; - - // Draw the item widgets - for( int index = 0; index < this.widgetCount; ++index ) - { - // Get the widget - WidgetAEItem currentWidget = this.itemWidgets.get( index ); - - // Draw the widget - currentWidget.drawWidget(); - - // Is the mouse over this widget? - if( hasNoOverlay && currentWidget.isMouseOverWidget( mouseX, mouseY ) ) - { - // Draw the overlay - currentWidget.drawMouseHoverUnderlay(); - - // Set that we have an overlay - hasNoOverlay = false; - - // Set this widget as the widget under the mouse - widgetUnderMouse = currentWidget; - } - } - - return widgetUnderMouse; - } - - /** - * If the user has clicked on an item widget this will inform the server - * so that the item can be extracted from the AE network. - * - * @param mouseX - * @param mouseY - * @param mouseButton - */ - private void sendItemWidgetClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - for( int index = 0; index < this.widgetCount; ++index ) - { - // Get the widget - WidgetAEItem currentWidget = this.itemWidgets.get( index ); - - // Is the mouse over this widget - if( currentWidget.isMouseOverWidget( mouseX, mouseY ) ) - { - // Get the AE itemstack this widget represents - IAEItemStack widgetStack = currentWidget.getItemStack(); - - // Did we get an item? - if( widgetStack != null ) - { - // Should the item be crafted? - if( ( widgetStack.getStackSize() == 0 ) || ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_WHEEL ) ) - { - if( ( widgetStack.isCraftable() ) && ( mouseButton != ThEGuiHelper.MOUSE_BUTTON_RIGHT ) ) - { - Packet_S_ArcaneCraftingTerminal.sendAutoCraft( this.player, widgetStack ); - return; - } - } - - // Let the server know the user is requesting an itemstack. - Packet_S_ArcaneCraftingTerminal.sendExtract( this.player, widgetStack, mouseButton, GuiScreen.isShiftKeyDown() ); - } - - // Stop searching - return; - } - } - } - - /** - * Calculates the number of rows needed based on terminal style, and updates - * the gui parameters. - */ - private void setupTerminalStyle() - { - int extraRows = 0; - - // Tall? - if( this.terminalStyle == TerminalStyle.TALL ) - { - extraRows = Math.max( 0, ( ( this.height - GuiConstants_ACT.GUI_HEIGHT ) / 18 ) - 3 ); - } - - // Update the size and top of the GUI - this.ySize = GuiConstants_ACT.GUI_HEIGHT + ( extraRows * GuiConstants_ACT.ME_ROW_HEIGHT ); - this.guiTop = ( this.height - this.ySize ) / 2; - - // Update the number of rows - this.numberOfWidgetRows = GuiConstants_ACT.ME_DEFAULT_ROWS + extraRows; - - // Update number of widgets - this.widgetCount = this.numberOfWidgetRows * GuiConstants_ACT.ME_COLUMNS; - - // Create the aspect bridge - try - { - this.meAspectBridge = new MEItemAspectBridgeContainer( this.widgetCount ); - } - catch( Exception e ) - { - this.meAspectBridge = null; - } - - // Clear old widgets - this.itemWidgets.clear(); - - // Create the widgets and bridge slots - for( int row = 0; row < this.numberOfWidgetRows; ++row ) - { - for( int column = 0; column < GuiConstants_ACT.ME_COLUMNS; ++column ) - { - // Calculate the index and position - int index = ( row * GuiConstants_ACT.ME_COLUMNS ) + column; - int posX = GuiConstants_ACT.ME_ITEM_POS_X + ( column * ThEWidget.WIDGET_SIZE ); - int posY = GuiConstants_ACT.ME_ITEM_POS_Y + ( row * ThEWidget.WIDGET_SIZE ); - - // Create the ME slot - this.itemWidgets.add( new WidgetAEItem( this, posX, posY, this.aeItemRenderer ) ); - - // Add the bridge slot - if( this.meAspectBridge != null ) - { - this.meAspectBridge.addSlot( index, posX, posY ); - } - } - } - - // Update the scroll bar range - this.updateScrollbarRange(); - - // Update the scroll bar height - this.setScrollBarHeight( GuiConstants_ACT.SCROLLBAR_HEIGHT + ( extraRows * GuiConstants_ACT.ME_ROW_HEIGHT ) ); - - // Update the lower terminal portion Y offset - int prevYOffset = this.lowerTerminalYOffset; - this.lowerTerminalYOffset = ( extraRows * GuiConstants_ACT.ME_ROW_HEIGHT ); - - // Update the container - if( prevYOffset != this.lowerTerminalYOffset ) - { - ( (ContainerPartArcaneCraftingTerminal)this.inventorySlots ).changeSlotsYOffset( this.lowerTerminalYOffset - prevYOffset ); - } - - // Clear any tooltip - this.cachedItemTooltip.clear(); - - } - - /** - * Assigns the network items to the widgets - */ - private void updateMEWidgets() - { - int repoIndex = 0; - // List all items - for( int index = 0; index < this.widgetCount; ++index ) - { - IAEItemStack stack = this.repo.getReferenceItem( repoIndex++ ); - - // Did we get a stack? - if( stack != null ) - { - // Set the item - this.itemWidgets.get( index ).setItemStack( stack ); - if( this.meAspectBridge != null ) - { - this.meAspectBridge.setSlot( index, stack.getItemStack().copy() ); - } - } - else - { - // Set to null - this.itemWidgets.get( index ).setItemStack( null ); - if( this.meAspectBridge != null ) - { - this.meAspectBridge.setSlot( index, null ); - } - } - } - } - - /** - * Updates the scroll bar's range. - */ - private void updateScrollbarRange() - { - // Calculate the total number of rows needed to display ALL items - int totalNumberOfRows = (int)Math.ceil( this.repo.size() / (double)GuiConstants_ACT.ME_COLUMNS ); - - // Calculate the scroll based on how many rows can be shown - int max = Math.max( 0, totalNumberOfRows - this.numberOfWidgetRows ); - - // Update the scroll bar - this.scrollBar.setRange( 0, max, 2 ); - } - - /** - * Updates the sorting modes and refreshes the gui. - */ - private void updateSorting() - { - // Set the direction icon - this.btnSortingDirection.setSortingDirection( this.sortingDirection ); - - // Set the order icon - this.btnSortingMode.setSortMode( this.sortingOrder ); - - // Set the view mode - this.btnViewType.setViewMode( this.viewMode ); - - // Repo needs update - this.viewNeedsUpdate = true; - - } - - /** - * Updates the repo's view, the scroll bar range, and the widgets. - */ - private void updateView() - { - // Mark clean - this.viewNeedsUpdate = false; - - // Update repo view - this.repo.updateView(); - - // Update the scroll bar - this.updateScrollbarRange(); - - // Update the widgets - this.updateMEWidgets(); - } - - /** - * Draws the gui texture - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Does the view need updating? - if( this.viewNeedsUpdate ) - { - this.updateView(); - } - - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - // Set the texture - this.mc.renderEngine.bindTexture( GuiTextureManager.ARCANE_CRAFTING_TERMINAL.getTexture() ); - - // Draw the upper portion: Label, Search, First row - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, - GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT ); - - // Draw the extra rows - for( int i = 0; i < ( this.numberOfWidgetRows - GuiConstants_ACT.ME_DEFAULT_ROWS ); ++i ) - { - int yPos = this.guiTop + GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT + ( i * GuiConstants_ACT.ME_ROW_HEIGHT ); - - // Draw the texture - this.drawTexturedModalRect( this.guiLeft, yPos, 0, GuiConstants_ACT.GUI_TEXTURE_ROW_V, - GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, GuiConstants_ACT.ME_ROW_HEIGHT ); - } - - // Draw the lower portion, bottom two rows, crafting grid, player inventory - this.drawTexturedModalRect( this.guiLeft, this.guiTop + GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT + this.lowerTerminalYOffset, 0, - GuiConstants_ACT.ME_ROW_HEIGHT + 17, GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, - GuiConstants_ACT.GUI_TEXTURE_LOWER_HEIGHT + 18 ); - - // Draw view cells - this.drawTexturedModalRect( this.guiLeft + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, this.guiTop, - GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, 0, GuiConstants_ACT.GUI_VIEW_CELL_TEXTURE_WIDTH, - GuiConstants_ACT.GUI_VIEW_CELL_TEXTURE_HEIGHT ); - - // Bind the AE states texture - Minecraft.getMinecraft().renderEngine.bindTexture( AEStateIconsEnum.AE_STATES_TEXTURE ); - - // Draw the view cell backgrounds - int u = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getU(), v = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getV(); - int h = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getHeight(), w = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getWidth(); - int x = this.guiLeft + ContainerPartArcaneCraftingTerminal.VIEW_SLOT_XPOS, y = this.guiTop + - ContainerPartArcaneCraftingTerminal.VIEW_SLOT_YPOS; - for( int row = 0; row < 5; row++ ) - { - this.drawTexturedModalRect( x, y + ( row * 18 ), u, v, w, h ); - } - } - - /** - * Draw the foreground layer. - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Call super - super.drawGuiContainerForegroundLayer( mouseX, mouseY ); - - // Draw the title - this.fontRendererObj.drawString( this.guiTitle, GuiConstants_ACT.TITLE_POS_X, GuiConstants_ACT.TITLE_POS_Y, 0x000000 ); - - // Draw the search field. - this.searchField.drawTextBox(); - - // Enable lighting - GL11.glEnable( GL11.GL_LIGHTING ); - - // Draw the widgets and get which one the mouse is over - WidgetAEItem widgetUnderMouse = this.drawItemWidgets( mouseX, mouseY ); - - // Get the cost - List craftingCost = ( (ContainerPartArcaneCraftingTerminal)this.inventorySlots ).getCraftingCost( false ); - - // Does the current recipe have costs? - if( !craftingCost.isEmpty() ) - { - // Draw the costs - this.drawCraftingAspects( craftingCost ); - } - - // Should we force a tooltip update? - boolean forceTooltipUpdate = ( ( System.currentTimeMillis() - - this.lastTooltipUpdateTime ) >= GuiConstants_ACT.WIDGET_TOOLTIP_UPDATE_INTERVAL ); - - // Has the mouse moved, or timeout reached? - if( forceTooltipUpdate || ( this.previousMouseX != mouseX ) || ( this.previousMouseY != mouseY ) ) - { - // Do we have a widget under the mouse? - if( widgetUnderMouse != null ) - { - // Has the widget changed? - if( forceTooltipUpdate || ( widgetUnderMouse != this.previousWidgetUnderMouse ) ) - { - // Clear the tooltip - this.cachedItemTooltip.clear(); - - // Get the tooltip from the widget - widgetUnderMouse.getTooltip( this.cachedItemTooltip ); - - // Set the time - this.lastTooltipUpdateTime = System.currentTimeMillis(); - } - } - else - { - // Nothing to display - this.cachedItemTooltip.clear(); - } - - // Set the previous position - this.previousMouseX = mouseX; - this.previousMouseY = mouseY; - - // Set the previous widget - this.previousWidgetUnderMouse = widgetUnderMouse; - } - - // Add cached tooltip - if( !this.cachedItemTooltip.isEmpty() ) - { - this.tooltip.addAll( this.cachedItemTooltip ); - } - } - - /** - * Returns the scroll bar parameters. - * - * @return - */ - @Override - protected ScrollbarParams getScrollbarParameters() - { - return new ScrollbarParams( - GuiConstants_ACT.SCROLLBAR_POS_X, - GuiConstants_ACT.SCROLLBAR_POS_Y, - GuiConstants_ACT.SCROLLBAR_HEIGHT + - ( ( GuiConstants_ACT.ME_DEFAULT_ROWS - this.numberOfWidgetRows ) * GuiConstants_ACT.ME_ROW_HEIGHT ) ); - } - - /** - * Called when the player types a key. - */ - @Override - protected void keyTyped( final char key, final int keyID ) - { - // Did they press the escape key? - if( keyID == Keyboard.KEY_ESCAPE ) - { - // Close the screen. - this.mc.thePlayer.closeScreen(); - return; - } - - // Prevent only spaces - if( ( key == ' ' ) && ( this.searchField.getText().length() == 0 ) ) - { - return; - } - - if( this.searchField.textboxKeyTyped( key, keyID ) ) - { - // Get the search query - String newSearch = this.searchField.getText().trim().toLowerCase(); - - // Has the query changed? - if( !newSearch.equals( this.repo.getSearchString() ) ) - { - // Set the search string - this.repo.setSearchString( newSearch ); - memoryText = newSearch; - - // Repo needs update - this.viewNeedsUpdate = true; - } - } - else - { - super.keyTyped( key, keyID ); - } - - } - - /** - * Called when the mouse is clicked while the gui is open - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Handled by the widget area? - if( this.clickHandler_Widgets( mouseX, mouseY, mouseButton ) ) - { - return; - } - - // Handled by region deposit? - if( this.clickHandler_RegionDeposit( mouseX, mouseY ) ) - { - return; - } - - // Handled by search box? - if( this.clickHandler_SearchBox( mouseX, mouseY, mouseButton ) ) - { - return; - } - - // Get search mode - SearchBoxMode searchBoxMode = (SearchBoxMode)AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - - // Inform search field of click if auto mode is not on - if( !( ( searchBoxMode == SearchBoxMode.AUTOSEARCH ) || ( searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH ) ) ) - { - this.searchField.mouseClicked( mouseX - this.guiLeft, mouseY - this.guiTop, mouseButton ); - } - - // Pass to super - super.mouseClicked( mouseX, mouseY, mouseButton ); - } - - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - boolean sortingChanged = false; - - boolean wasLeftClick = true; - - // Which button was clicked? - switch ( mouseButton ) - { - case ThEGuiHelper.MOUSE_BUTTON_LEFT: - // Already true - break; - - case ThEGuiHelper.MOUSE_BUTTON_RIGHT: - // Set to false - wasLeftClick = false; - break; - - default: - // Don't handle any other buttons - return; - } - - switch ( button.id ) - { - // Clear grid - case GuiConstants_ACT.BUTTON_CLEAR_GRID_ID: - // Attempt to clear the grid - Packet_S_ArcaneCraftingTerminal.sendClearGrid( this.player ); - break; - - // Sort order - case GuiConstants_ACT.BUTTON_SORT_MODE_ID: - switch ( this.sortingOrder ) - { - case AMOUNT: - this.sortingOrder = ( wasLeftClick ? SortOrder.MOD : SortOrder.NAME ); - break; - - case INVTWEAKS: - break; - - case MOD: - this.sortingOrder = ( wasLeftClick ? SortOrder.NAME : SortOrder.AMOUNT ); - break; - - case NAME: - this.sortingOrder = ( wasLeftClick ? SortOrder.AMOUNT : SortOrder.MOD ); - break; - } - sortingChanged = true; - break; - - // Sorting direction - case GuiConstants_ACT.BUTTON_SORT_DIR_ID: - switch ( this.sortingDirection ) - { - case ASCENDING: - this.sortingDirection = SortDir.DESCENDING; - break; - - case DESCENDING: - this.sortingDirection = SortDir.ASCENDING; - break; - - } - sortingChanged = true; - break; - - // View type - case GuiConstants_ACT.BUTTON_VIEW_TYPE_ID: - - // Rotate view mode - this.viewMode = Platform.rotateEnum( this.viewMode, !wasLeftClick, Settings.VIEW_MODE.getPossibleValues() ); - - sortingChanged = true; - break; - - // Swap armor - case GuiConstants_ACT.BUTTON_SWAP_ARMOR_ID: - // Ask the server to swap the armor - Packet_S_ArcaneCraftingTerminal.sendSwapArmor( this.player ); - break; - - // Terminal style - case GuiConstants_ACT.BUTTON_TERM_STYLE_ID: - switch ( this.terminalStyle ) - { - case SMALL: - this.terminalStyle = TerminalStyle.TALL; - break; - - case TALL: - this.terminalStyle = TerminalStyle.SMALL; - break; - - default: - this.terminalStyle = TerminalStyle.SMALL; - break; - - } - - // Update the AE settings - AEConfig.instance.getConfigManager().putSetting( Settings.TERMINAL_STYLE, this.terminalStyle ); - - // Reinit - this.initGui(); - - break; - - // Search mode - case GuiConstants_ACT.BUTTON_SEARCH_MODE_ID: - // Rotate search mode - SearchBoxMode searchBoxMode = (SearchBoxMode)AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - searchBoxMode = Platform.rotateEnum( searchBoxMode, !wasLeftClick, Settings.SEARCH_MODE.getPossibleValues() ); - - // Set focus - this.searchField.setFocused( ( searchBoxMode == SearchBoxMode.AUTOSEARCH ) || ( searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH ) ); - - // Update the settings - AEConfig.instance.settings.putSetting( Settings.SEARCH_MODE, searchBoxMode ); - - // Update the button - this.btnSearchMode.setSearchMode( searchBoxMode ); - - // Clear the tooltip - this.cachedItemTooltip.clear(); - this.lastTooltipUpdateTime = 0; - - break; - } - - // Was the sorting mode changed? - if( sortingChanged ) - { - // Update the sorting - this.updateSorting(); - - // Reset the tooltip - this.lastTooltipUpdateTime = 0; - - // Send to server - Packet_S_ArcaneCraftingTerminal.sendMode( this.player, this.sortingOrder, this.sortingDirection, this.viewMode ); - } - } - - @Override - protected void onMouseWheel( final int deltaZ, final int mouseX, final int mouseY ) - { - // Is the mouse inside of, or to the left of, the GUI? - if( mouseX > ( this.guiLeft + GuiConstants_ACT.GUI_WIDTH ) ) - { - // Mouse is to the right of the gui - return; - } - - // Is shift being held? - if( GuiScreen.isShiftKeyDown() ) - { - // Extract or insert based on the motion of the wheel - this.doMEWheelAction( deltaZ, mouseX, mouseY ); - } - else - { - // Inform the scroll bar - this.scrollBar.wheel( deltaZ ); - - // Update the item widgets - this.onScrollbarMoved(); - } - } - - @Override - protected void onScrollbarMoved() - { - // Update the widgets - this.updateMEWidgets(); - - // Clear the tooltip - this.cachedItemTooltip.clear(); - this.lastTooltipUpdateTime = 0; - } - - /** - * Draws all screen elements, specifically calling on TC to draw the aspects - * of whatever the mouse is over. - */ - @Override - public void drawScreen( final int mouseX, final int mouseY, final float mouseBtn ) - { - // Call super - super.drawScreen( mouseX, mouseY, mouseBtn ); - - // Show TC aspects for items in the ME network. - if( ( this.meAspectBridge != null ) && ( !Config.showTags == Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) ) ) - { - this.meAspectBridge.renderAspects( this, this.player ); - } - } - - /** - * Gets the sorting order. - */ - @Override - public Enum getSortBy() - { - return this.sortingOrder; - } - - /** - * Gets the sorting direction. - */ - @Override - public Enum getSortDir() - { - return this.sortingDirection; - } - - /** - * Gets what items (stored vs crafting) to show. - */ - @Override - public Enum getSortDisplay() - { - return this.viewMode; - } - - /** - * Sets the gui up. - */ - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Reset the mouse wheel state. - Mouse.getDWheel(); - - // Enable repeat keys - Keyboard.enableRepeatEvents( true ); - - // Calculate row count - this.setupTerminalStyle(); - - // Get the current search box mode - SearchBoxMode searchBoxMode = (SearchBoxMode)AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - - if( this.searchField == null ) - { - // Set up the search bar - this.searchField = new GuiTextField( this.fontRendererObj, GuiConstants_ACT.SEARCH_POS_X, GuiConstants_ACT.SEARCH_POS_Y, - GuiConstants_ACT.SEARCH_WIDTH, GuiConstants_ACT.SEARCH_HEIGHT ); - - // Set the search field to draw in the foreground - this.searchField.setEnableBackgroundDrawing( false ); - - // Set maximum length - this.searchField.setMaxStringLength( GuiConstants_ACT.SEARCH_MAX_CHARS ); - } - - // Start focused? - this.searchField.setFocused( ( searchBoxMode == SearchBoxMode.AUTOSEARCH ) || ( searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH ) ); - - // Set the search string - this.searchField.setText(memoryText); - this.repo.setSearchString(memoryText); - - // Clear any existing buttons - this.buttonList.clear(); - - // Create the clear grid button - this.buttonList.add( new GuiButtonClearCraftingGrid( GuiConstants_ACT.BUTTON_CLEAR_GRID_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_CLEAR_GRID_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_CLEAR_GRID_POS_Y + - this.lowerTerminalYOffset, - 8, 8, true ) ); - - // Add sort order button - this.buttonList.add( this.btnSortingMode = new GuiButtonSortingMode( GuiConstants_ACT.BUTTON_SORT_MODE_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_SORT_MODE_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_SORT_MODE_POS_Y, - GuiConstants_ACT.BUTTON_AE_SIZE, GuiConstants_ACT.BUTTON_AE_SIZE ) ); - - // Add sort direction button - this.buttonList.add( this.btnSortingDirection = new GuiButtonSortingDirection( GuiConstants_ACT.BUTTON_SORT_DIR_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_SORT_DIR_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_SORT_DIR_POS_Y, - GuiConstants_ACT.BUTTON_AE_SIZE, GuiConstants_ACT.BUTTON_AE_SIZE ) ); - - // Add view type button - this.buttonList.add( this.btnViewType = new GuiButtonViewType( GuiConstants_ACT.BUTTON_VIEW_TYPE_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_VIEW_TYPE_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_VIEW_TYPE_POS_Y, - GuiConstants_ACT.BUTTON_AE_SIZE, GuiConstants_ACT.BUTTON_AE_SIZE ) ); - - // Add swap armor button - this.buttonList.add( new GuiButtonSwapArmor( GuiConstants_ACT.BUTTON_SWAP_ARMOR_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_SWAP_ARMOR_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_SWAP_ARMOR_POS_Y + - this.lowerTerminalYOffset, - 8, 8 ) ); - - // Add search mode button - this.buttonList.add( this.btnSearchMode = new GuiButtonSearchMode( GuiConstants_ACT.BUTTON_SEARCH_MODE_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_SEARCH_MODE_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_SEARCH_MODE_POS_Y, - GuiConstants_ACT.BUTTON_AE_SIZE, GuiConstants_ACT.BUTTON_AE_SIZE, searchBoxMode ) ); - - // Add terminal style button - this.buttonList.add( new GuiButtonTerminalStyle( GuiConstants_ACT.BUTTON_TERM_STYLE_ID, this.guiLeft + - GuiConstants_ACT.BUTTON_TERM_STYLE_POS_X, this.guiTop + GuiConstants_ACT.BUTTON_TERM_STYLE_POS_Y, - GuiConstants_ACT.BUTTON_AE_SIZE, GuiConstants_ACT.BUTTON_AE_SIZE, this.terminalStyle ) ); - - // Add the container as a listener - ( (ContainerPartArcaneCraftingTerminal)this.inventorySlots ).registerForUpdates(); - - // Request a full update from the server - Packet_S_ArcaneCraftingTerminal.sendFullListRequest( this.player ); - - } - - /** - * Called when the gui is closing. - */ - @Override - public void onGuiClosed() - { - // Call super - super.onGuiClosed(); - - // Disable repeat keys - Keyboard.enableRepeatEvents( false ); - } - - /** - * Called to update the amount of an item in the ME network. - * - * @param change - */ - public void onReceiveChange( final IAEItemStack change ) - { - // Is the item blacklisted? - if( AEHooks.isItemGUIBlacklisted( change ) ) - { - return; - } - - // Update the repository - this.repo.postUpdate( change ); - - // Repo needs update - this.viewNeedsUpdate = true; - } - - /** - * Called when the server sends a full list of all - * items in the AE network in response to our request. - * - * @param itemList - */ - public void onReceiveFullList( final IItemList itemList ) - { - // Clear the repo - this.repo.clear(); - - // Update the repository - for( IAEItemStack stack : itemList ) - { - this.onReceiveChange( stack ); - } - } - - /** - * Called when the server sends the sorting order and direction. - * - * @param order - * @param direction - */ - public void onReceiveSorting( final SortOrder order, final SortDir direction, final ViewItems viewMode ) - { - // Set the direction - this.sortingDirection = direction; - - // Set the order - this.sortingOrder = order; - - // Set view mode - this.viewMode = viewMode; - - // Update - this.updateSorting(); - } - - /** - * Called when the server wants the client to force an update to the aspect - * costs. - */ - public void onServerSendForceUpdateCost() - { - ( (ContainerPartArcaneCraftingTerminal)this.inventorySlots ).getCraftingCost( true ); - } - - /** - * Called when the view cells change. - */ - public void onViewCellsChanged( final ItemStack[] viewCells ) - { - // Update the repo - this.repo.setViewCell( viewCells ); - - // Repo needs update - this.viewNeedsUpdate = true; - } - +public class GuiArcaneCraftingTerminal extends GuiConstants_ACT implements ISortSource { + /** + * Renders an AE itemstack into the gui. + */ + private AppEngRenderItem aeItemRenderer = new AppEngRenderItem(); + + /** + * Translated title of the gui. + */ + private String guiTitle; + + /** + * Number of ME widgets + */ + private int widgetCount = GuiConstants_ACT.ME_DEFAULT_ROWS * GuiConstants_ACT.ME_COLUMNS; + + /** + * Widget 'slots'. + */ + private List itemWidgets = new ArrayList(); + + /** + * Player viewing the gui. + */ + private EntityPlayer player; + + /** + * Search field. + */ + private GuiTextField searchField; + + /** + * Item repository + */ + private final ItemRepo repo; + + /** + * How the items are sorted. + */ + private SortOrder sortingOrder = SortOrder.NAME; + + /** + * What direction are the items sorted. + */ + private SortDir sortingDirection = SortDir.ASCENDING; + + /** + * Which items can be viewed in the terminal. + */ + private ViewItems viewMode = ViewItems.ALL; + + /** + * Is the terminal small or tall? + */ + private TerminalStyle terminalStyle = TerminalStyle.SMALL; + + /** + * The Y offeset of the lower portion of the terminal. + */ + private int lowerTerminalYOffset = 0; + + /** + * Tracks mouse movement. + */ + private int previousMouseX = 0; + + private int previousMouseY = 0; + + /** + * Tracks what widget was under the mouse last draw. + */ + private WidgetAEItem previousWidgetUnderMouse = null; + + /** + * Tracks the last time the tooltip was updated. + */ + private long lastTooltipUpdateTime = 0; + + /** + * TODO: Remove this and rework the widgets/slots to be MESlots. Such fun + * that will be. + */ + private MEItemAspectBridgeContainer meAspectBridge; + + /** + * The number of rows to use. + */ + private int numberOfWidgetRows = GuiConstants_ACT.ME_DEFAULT_ROWS; + + /** + * Button to set the sorting mode. + */ + private GuiButtonSortingMode btnSortingMode; + + /** + * Button to set accending or decending sorting. + */ + private GuiButtonSortingDirection btnSortingDirection; + + /** + * Button to change what items (regular | crafting) are shown. + */ + private GuiButtonViewType btnViewType; + + /** + * Button to change the search mode. + */ + private GuiButtonSearchMode btnSearchMode; + + /** + * Tracks if the repo/widgets needs to be updated. + */ + private boolean viewNeedsUpdate = true; + + /** + * Holds the cached tooltip of an item. + */ + private ArrayList cachedItemTooltip = new ArrayList(); + + /** + * Save the search string between sessions + */ + private static String memoryText = ""; + + public GuiArcaneCraftingTerminal(final PartArcaneCraftingTerminal part, final EntityPlayer player) { + // Call super + super(new ContainerPartArcaneCraftingTerminal(part, player)); + + // Set the player + this.player = player; + + // Set the width and height + this.xSize = GuiConstants_ACT.GUI_WIDTH; + this.ySize = GuiConstants_ACT.GUI_HEIGHT; + + // Set the title + this.guiTitle = ThEStrings.Gui_TitleArcaneCraftingTerminal.getLocalized(); + + // Create the repo + this.repo = new ItemRepo(this.scrollBar, this); + + // Get the terminal style + this.terminalStyle = + (TerminalStyle) AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE); + } + + /** + * Checks if the click was a region deposit. + * + * @param mouseX + * @param mouseY + * @return True if click was handled. + */ + private boolean clickHandler_RegionDeposit(final int mouseX, final int mouseY) { + // Is the player holding the space key? + if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { + // Get the slot the mouse is over + Slot slotClicked = this.getSlotAtMousePosition(mouseX, mouseY); + + // Was there a slot under the mouse? + if (slotClicked != null) { + // Ask the server to move the inventory + Packet_S_ArcaneCraftingTerminal.sendDepositRegion(this.player, slotClicked.slotNumber); + + // Do not pass to super + return true; + } + } + + return false; + } + + /** + * Checks if the click was inside the search box. + * + * @param mouseX + * @param mouseY + * @param mouseButton + * @return True if click was handled. + */ + private boolean clickHandler_SearchBox(final int mouseX, final int mouseY, final int mouseButton) { + // Was the mouse right-clicked over the search field? + if ((mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT) + && ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiConstants_ACT.SEARCH_POS_Y, + GuiConstants_ACT.SEARCH_POS_X, + GuiConstants_ACT.SEARCH_HEIGHT, + GuiConstants_ACT.SEARCH_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Clear the search field + this.searchField.setText(""); + + // Update the repo + this.repo.setSearchString(""); + memoryText = ""; + + // Repo needs update + this.viewNeedsUpdate = true; + + // Inform search field. + this.searchField.mouseClicked(mouseX - this.guiLeft, mouseY - this.guiTop, mouseButton); + + // Do not pass to super + return true; + } + + return false; + } + + /** + * Checks if the click was inside the widgets. + * + * @param mouseX + * @param mouseY + * @param mouseButton + * @return True if click was handled. + */ + private boolean clickHandler_Widgets(final int mouseX, final int mouseY, final int mouseButton) { + // Was the click inside the ME grid? + if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiConstants_ACT.ME_ITEM_POS_Y, + GuiConstants_ACT.ME_ITEM_POS_X, + this.numberOfWidgetRows * GuiConstants_ACT.ME_ROW_HEIGHT, + GuiConstants_ACT.ME_GRID_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Click + empty hand is extract + boolean doExtract = (this.player.inventory.getItemStack() == null); + + // Shift+Right click is extract + doExtract |= (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && (mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT)); + + // Extracting? + if (doExtract) { + // Search for the widget the mouse is over, and send extract request. + this.sendItemWidgetClicked(mouseX, mouseY, mouseButton); + } else { + // Inform the server the user would like to deposit the currently held item into the ME network. + Packet_S_ArcaneCraftingTerminal.sendDeposit(this.player, mouseButton); + } + + // Do not pass to super + return true; + } + + return false; + } + + /** + * Extracts or inserts an item to/from the player held stack based on the + * direction the mouse wheel was scrolled. + * + * @param deltaZ + */ + private void doMEWheelAction(final int deltaZ, final int mouseX, final int mouseY) { + // Is the mouse inside the ME area? + if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiConstants_ACT.ME_ITEM_POS_Y, + GuiConstants_ACT.ME_ITEM_POS_X, + this.numberOfWidgetRows * GuiConstants_ACT.ME_ROW_HEIGHT, + GuiConstants_ACT.ME_GRID_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Which direction was the scroll? + if (deltaZ > 0) { + // Is the player holding anything? + if (this.player.inventory.getItemStack() != null) { + // Inform the server the user would like to deposit 1 of the currently held items into the ME + // network. + Packet_S_ArcaneCraftingTerminal.sendDeposit(this.player, ThEGuiHelper.MOUSE_WHEEL_MOTION); + } + } else { + // Extract an item based on the widget we are over + this.sendItemWidgetClicked(mouseX, mouseY, ThEGuiHelper.MOUSE_WHEEL_MOTION); + } + } + } + + /** + * Draws the crafting aspect's and their costs. + * + * @param craftingCost + */ + private void drawCraftingAspects(final List craftingCost) { + int posY = GuiConstants_ACT.ASPECT_COST_POS_Y + this.lowerTerminalYOffset; + int column = 0; + + // Draw each primal + for (ArcaneCrafingCost cost : craftingCost) { + // Set the alpha to full + float alpha = 1.0F; + + // Do we have enough vis for this aspect? + if (!cost.hasEnoughVis) { + // Ping-pong the alpha + alpha = ThEUtils.pingPongFromTime( + GuiConstants_ACT.ASPECT_COST_BLINK_SPEED, + GuiConstants_ACT.ASPECT_COST_MIN_ALPHA, + GuiConstants_ACT.ASPECT_COST_MAX_ALPHA); + } + + // Calculate X position + int posX = GuiConstants_ACT.ASPECT_COST_POS_X + (column * GuiConstants_ACT.ASPECT_COST_SPACING); + + // Draw the aspect icon + UtilsFX.drawTag( + posX, posY, cost.primal, cost.visCost, 0, this.zLevel, GL11.GL_ONE_MINUS_SRC_ALPHA, alpha, false); + + // Should we move to the next row? + if (++column == 2) { + // Reset column + column = 0; + + // Increment Y + posY += GuiConstants_ACT.ASPECT_COST_SPACING; + } + } + } + + /** + * Draws the AE item widgets. + * + * @param mouseX + * @param mouseY + * @return + */ + private WidgetAEItem drawItemWidgets(final int mouseX, final int mouseY) { + boolean hasNoOverlay = true; + + WidgetAEItem widgetUnderMouse = null; + + // Draw the item widgets + for (int index = 0; index < this.widgetCount; ++index) { + // Get the widget + WidgetAEItem currentWidget = this.itemWidgets.get(index); + + // Draw the widget + currentWidget.drawWidget(); + + // Is the mouse over this widget? + if (hasNoOverlay && currentWidget.isMouseOverWidget(mouseX, mouseY)) { + // Draw the overlay + currentWidget.drawMouseHoverUnderlay(); + + // Set that we have an overlay + hasNoOverlay = false; + + // Set this widget as the widget under the mouse + widgetUnderMouse = currentWidget; + } + } + + return widgetUnderMouse; + } + + /** + * If the user has clicked on an item widget this will inform the server + * so that the item can be extracted from the AE network. + * + * @param mouseX + * @param mouseY + * @param mouseButton + */ + private void sendItemWidgetClicked(final int mouseX, final int mouseY, final int mouseButton) { + for (int index = 0; index < this.widgetCount; ++index) { + // Get the widget + WidgetAEItem currentWidget = this.itemWidgets.get(index); + + // Is the mouse over this widget + if (currentWidget.isMouseOverWidget(mouseX, mouseY)) { + // Get the AE itemstack this widget represents + IAEItemStack widgetStack = currentWidget.getItemStack(); + + // Did we get an item? + if (widgetStack != null) { + // Should the item be crafted? + if ((widgetStack.getStackSize() == 0) || (mouseButton == ThEGuiHelper.MOUSE_BUTTON_WHEEL)) { + if ((widgetStack.isCraftable()) && (mouseButton != ThEGuiHelper.MOUSE_BUTTON_RIGHT)) { + Packet_S_ArcaneCraftingTerminal.sendAutoCraft(this.player, widgetStack); + return; + } + } + + // Let the server know the user is requesting an itemstack. + Packet_S_ArcaneCraftingTerminal.sendExtract( + this.player, widgetStack, mouseButton, GuiScreen.isShiftKeyDown()); + } + + // Stop searching + return; + } + } + } + + /** + * Calculates the number of rows needed based on terminal style, and updates + * the gui parameters. + */ + private void setupTerminalStyle() { + int extraRows = 0; + + // Tall? + if (this.terminalStyle == TerminalStyle.TALL) { + extraRows = Math.max(0, ((this.height - GuiConstants_ACT.GUI_HEIGHT) / 18) - 3); + } + + // Update the size and top of the GUI + this.ySize = GuiConstants_ACT.GUI_HEIGHT + (extraRows * GuiConstants_ACT.ME_ROW_HEIGHT); + this.guiTop = (this.height - this.ySize) / 2; + + // Update the number of rows + this.numberOfWidgetRows = GuiConstants_ACT.ME_DEFAULT_ROWS + extraRows; + + // Update number of widgets + this.widgetCount = this.numberOfWidgetRows * GuiConstants_ACT.ME_COLUMNS; + + // Create the aspect bridge + try { + this.meAspectBridge = new MEItemAspectBridgeContainer(this.widgetCount); + } catch (Exception e) { + this.meAspectBridge = null; + } + + // Clear old widgets + this.itemWidgets.clear(); + + // Create the widgets and bridge slots + for (int row = 0; row < this.numberOfWidgetRows; ++row) { + for (int column = 0; column < GuiConstants_ACT.ME_COLUMNS; ++column) { + // Calculate the index and position + int index = (row * GuiConstants_ACT.ME_COLUMNS) + column; + int posX = GuiConstants_ACT.ME_ITEM_POS_X + (column * ThEWidget.WIDGET_SIZE); + int posY = GuiConstants_ACT.ME_ITEM_POS_Y + (row * ThEWidget.WIDGET_SIZE); + + // Create the ME slot + this.itemWidgets.add(new WidgetAEItem(this, posX, posY, this.aeItemRenderer)); + + // Add the bridge slot + if (this.meAspectBridge != null) { + this.meAspectBridge.addSlot(index, posX, posY); + } + } + } + + // Update the scroll bar range + this.updateScrollbarRange(); + + // Update the scroll bar height + this.setScrollBarHeight(GuiConstants_ACT.SCROLLBAR_HEIGHT + (extraRows * GuiConstants_ACT.ME_ROW_HEIGHT)); + + // Update the lower terminal portion Y offset + int prevYOffset = this.lowerTerminalYOffset; + this.lowerTerminalYOffset = (extraRows * GuiConstants_ACT.ME_ROW_HEIGHT); + + // Update the container + if (prevYOffset != this.lowerTerminalYOffset) { + ((ContainerPartArcaneCraftingTerminal) this.inventorySlots) + .changeSlotsYOffset(this.lowerTerminalYOffset - prevYOffset); + } + + // Clear any tooltip + this.cachedItemTooltip.clear(); + } + + /** + * Assigns the network items to the widgets + */ + private void updateMEWidgets() { + int repoIndex = 0; + // List all items + for (int index = 0; index < this.widgetCount; ++index) { + IAEItemStack stack = this.repo.getReferenceItem(repoIndex++); + + // Did we get a stack? + if (stack != null) { + // Set the item + this.itemWidgets.get(index).setItemStack(stack); + if (this.meAspectBridge != null) { + this.meAspectBridge.setSlot(index, stack.getItemStack().copy()); + } + } else { + // Set to null + this.itemWidgets.get(index).setItemStack(null); + if (this.meAspectBridge != null) { + this.meAspectBridge.setSlot(index, null); + } + } + } + } + + /** + * Updates the scroll bar's range. + */ + private void updateScrollbarRange() { + // Calculate the total number of rows needed to display ALL items + int totalNumberOfRows = (int) Math.ceil(this.repo.size() / (double) GuiConstants_ACT.ME_COLUMNS); + + // Calculate the scroll based on how many rows can be shown + int max = Math.max(0, totalNumberOfRows - this.numberOfWidgetRows); + + // Update the scroll bar + this.scrollBar.setRange(0, max, 2); + } + + /** + * Updates the sorting modes and refreshes the gui. + */ + private void updateSorting() { + // Set the direction icon + this.btnSortingDirection.setSortingDirection(this.sortingDirection); + + // Set the order icon + this.btnSortingMode.setSortMode(this.sortingOrder); + + // Set the view mode + this.btnViewType.setViewMode(this.viewMode); + + // Repo needs update + this.viewNeedsUpdate = true; + } + + /** + * Updates the repo's view, the scroll bar range, and the widgets. + */ + private void updateView() { + // Mark clean + this.viewNeedsUpdate = false; + + // Update repo view + this.repo.updateView(); + + // Update the scroll bar + this.updateScrollbarRange(); + + // Update the widgets + this.updateMEWidgets(); + } + + /** + * Draws the gui texture + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Does the view need updating? + if (this.viewNeedsUpdate) { + this.updateView(); + } + + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Set the texture + this.mc.renderEngine.bindTexture(GuiTextureManager.ARCANE_CRAFTING_TERMINAL.getTexture()); + + // Draw the upper portion: Label, Search, First row + this.drawTexturedModalRect( + this.guiLeft, + this.guiTop, + 0, + 0, + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, + GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT); + + // Draw the extra rows + for (int i = 0; i < (this.numberOfWidgetRows - GuiConstants_ACT.ME_DEFAULT_ROWS); ++i) { + int yPos = this.guiTop + GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT + (i * GuiConstants_ACT.ME_ROW_HEIGHT); + + // Draw the texture + this.drawTexturedModalRect( + this.guiLeft, + yPos, + 0, + GuiConstants_ACT.GUI_TEXTURE_ROW_V, + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, + GuiConstants_ACT.ME_ROW_HEIGHT); + } + + // Draw the lower portion, bottom two rows, crafting grid, player inventory + this.drawTexturedModalRect( + this.guiLeft, + this.guiTop + GuiConstants_ACT.GUI_UPPER_TEXTURE_HEIGHT + this.lowerTerminalYOffset, + 0, + GuiConstants_ACT.ME_ROW_HEIGHT + 17, + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, + GuiConstants_ACT.GUI_TEXTURE_LOWER_HEIGHT + 18); + + // Draw view cells + this.drawTexturedModalRect( + this.guiLeft + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, + this.guiTop, + GuiConstants_ACT.GUI_MAIN_BODY_WIDTH, + 0, + GuiConstants_ACT.GUI_VIEW_CELL_TEXTURE_WIDTH, + GuiConstants_ACT.GUI_VIEW_CELL_TEXTURE_HEIGHT); + + // Bind the AE states texture + Minecraft.getMinecraft().renderEngine.bindTexture(AEStateIconsEnum.AE_STATES_TEXTURE); + + // Draw the view cell backgrounds + int u = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getU(), v = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getV(); + int h = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getHeight(), w = AEStateIconsEnum.VIEW_CELL_BACKGROUND.getWidth(); + int x = this.guiLeft + ContainerPartArcaneCraftingTerminal.VIEW_SLOT_XPOS, + y = this.guiTop + ContainerPartArcaneCraftingTerminal.VIEW_SLOT_YPOS; + for (int row = 0; row < 5; row++) { + this.drawTexturedModalRect(x, y + (row * 18), u, v, w, h); + } + } + + /** + * Draw the foreground layer. + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Call super + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + + // Draw the title + this.fontRendererObj.drawString( + this.guiTitle, GuiConstants_ACT.TITLE_POS_X, GuiConstants_ACT.TITLE_POS_Y, 0x000000); + + // Draw the search field. + this.searchField.drawTextBox(); + + // Enable lighting + GL11.glEnable(GL11.GL_LIGHTING); + + // Draw the widgets and get which one the mouse is over + WidgetAEItem widgetUnderMouse = this.drawItemWidgets(mouseX, mouseY); + + // Get the cost + List craftingCost = + ((ContainerPartArcaneCraftingTerminal) this.inventorySlots).getCraftingCost(false); + + // Does the current recipe have costs? + if (!craftingCost.isEmpty()) { + // Draw the costs + this.drawCraftingAspects(craftingCost); + } + + // Should we force a tooltip update? + boolean forceTooltipUpdate = ((System.currentTimeMillis() - this.lastTooltipUpdateTime) + >= GuiConstants_ACT.WIDGET_TOOLTIP_UPDATE_INTERVAL); + + // Has the mouse moved, or timeout reached? + if (forceTooltipUpdate || (this.previousMouseX != mouseX) || (this.previousMouseY != mouseY)) { + // Do we have a widget under the mouse? + if (widgetUnderMouse != null) { + // Has the widget changed? + if (forceTooltipUpdate || (widgetUnderMouse != this.previousWidgetUnderMouse)) { + // Clear the tooltip + this.cachedItemTooltip.clear(); + + // Get the tooltip from the widget + widgetUnderMouse.getTooltip(this.cachedItemTooltip); + + // Set the time + this.lastTooltipUpdateTime = System.currentTimeMillis(); + } + } else { + // Nothing to display + this.cachedItemTooltip.clear(); + } + + // Set the previous position + this.previousMouseX = mouseX; + this.previousMouseY = mouseY; + + // Set the previous widget + this.previousWidgetUnderMouse = widgetUnderMouse; + } + + // Add cached tooltip + if (!this.cachedItemTooltip.isEmpty()) { + this.tooltip.addAll(this.cachedItemTooltip); + } + } + + /** + * Returns the scroll bar parameters. + * + * @return + */ + @Override + protected ScrollbarParams getScrollbarParameters() { + return new ScrollbarParams( + GuiConstants_ACT.SCROLLBAR_POS_X, + GuiConstants_ACT.SCROLLBAR_POS_Y, + GuiConstants_ACT.SCROLLBAR_HEIGHT + + ((GuiConstants_ACT.ME_DEFAULT_ROWS - this.numberOfWidgetRows) + * GuiConstants_ACT.ME_ROW_HEIGHT)); + } + + /** + * Called when the player types a key. + */ + @Override + protected void keyTyped(final char key, final int keyID) { + // Did they press the escape key? + if (keyID == Keyboard.KEY_ESCAPE) { + // Close the screen. + this.mc.thePlayer.closeScreen(); + return; + } + + // Prevent only spaces + if ((key == ' ') && (this.searchField.getText().length() == 0)) { + return; + } + + if (this.searchField.textboxKeyTyped(key, keyID)) { + // Get the search query + String newSearch = this.searchField.getText().trim().toLowerCase(); + + // Has the query changed? + if (!newSearch.equals(this.repo.getSearchString())) { + // Set the search string + this.repo.setSearchString(newSearch); + memoryText = newSearch; + + // Repo needs update + this.viewNeedsUpdate = true; + } + } else { + super.keyTyped(key, keyID); + } + } + + /** + * Called when the mouse is clicked while the gui is open + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Handled by the widget area? + if (this.clickHandler_Widgets(mouseX, mouseY, mouseButton)) { + return; + } + + // Handled by region deposit? + if (this.clickHandler_RegionDeposit(mouseX, mouseY)) { + return; + } + + // Handled by search box? + if (this.clickHandler_SearchBox(mouseX, mouseY, mouseButton)) { + return; + } + + // Get search mode + SearchBoxMode searchBoxMode = (SearchBoxMode) AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + + // Inform search field of click if auto mode is not on + if (!((searchBoxMode == SearchBoxMode.AUTOSEARCH) || (searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH))) { + this.searchField.mouseClicked(mouseX - this.guiLeft, mouseY - this.guiTop, mouseButton); + } + + // Pass to super + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + boolean sortingChanged = false; + + boolean wasLeftClick = true; + + // Which button was clicked? + switch (mouseButton) { + case ThEGuiHelper.MOUSE_BUTTON_LEFT: + // Already true + break; + + case ThEGuiHelper.MOUSE_BUTTON_RIGHT: + // Set to false + wasLeftClick = false; + break; + + default: + // Don't handle any other buttons + return; + } + + switch (button.id) { + // Clear grid + case GuiConstants_ACT.BUTTON_CLEAR_GRID_ID: + // Attempt to clear the grid + Packet_S_ArcaneCraftingTerminal.sendClearGrid(this.player); + break; + + // Sort order + case GuiConstants_ACT.BUTTON_SORT_MODE_ID: + switch (this.sortingOrder) { + case AMOUNT: + this.sortingOrder = (wasLeftClick ? SortOrder.MOD : SortOrder.NAME); + break; + + case INVTWEAKS: + break; + + case MOD: + this.sortingOrder = (wasLeftClick ? SortOrder.NAME : SortOrder.AMOUNT); + break; + + case NAME: + this.sortingOrder = (wasLeftClick ? SortOrder.AMOUNT : SortOrder.MOD); + break; + } + sortingChanged = true; + break; + + // Sorting direction + case GuiConstants_ACT.BUTTON_SORT_DIR_ID: + switch (this.sortingDirection) { + case ASCENDING: + this.sortingDirection = SortDir.DESCENDING; + break; + + case DESCENDING: + this.sortingDirection = SortDir.ASCENDING; + break; + } + sortingChanged = true; + break; + + // View type + case GuiConstants_ACT.BUTTON_VIEW_TYPE_ID: + + // Rotate view mode + this.viewMode = + Platform.rotateEnum(this.viewMode, !wasLeftClick, Settings.VIEW_MODE.getPossibleValues()); + + sortingChanged = true; + break; + + // Swap armor + case GuiConstants_ACT.BUTTON_SWAP_ARMOR_ID: + // Ask the server to swap the armor + Packet_S_ArcaneCraftingTerminal.sendSwapArmor(this.player); + break; + + // Terminal style + case GuiConstants_ACT.BUTTON_TERM_STYLE_ID: + switch (this.terminalStyle) { + case SMALL: + this.terminalStyle = TerminalStyle.TALL; + break; + + case TALL: + this.terminalStyle = TerminalStyle.SMALL; + break; + + default: + this.terminalStyle = TerminalStyle.SMALL; + break; + } + + // Update the AE settings + AEConfig.instance.getConfigManager().putSetting(Settings.TERMINAL_STYLE, this.terminalStyle); + + // Reinit + this.initGui(); + + break; + + // Search mode + case GuiConstants_ACT.BUTTON_SEARCH_MODE_ID: + // Rotate search mode + SearchBoxMode searchBoxMode = + (SearchBoxMode) AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + searchBoxMode = + Platform.rotateEnum(searchBoxMode, !wasLeftClick, Settings.SEARCH_MODE.getPossibleValues()); + + // Set focus + this.searchField.setFocused( + (searchBoxMode == SearchBoxMode.AUTOSEARCH) || (searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH)); + + // Update the settings + AEConfig.instance.settings.putSetting(Settings.SEARCH_MODE, searchBoxMode); + + // Update the button + this.btnSearchMode.setSearchMode(searchBoxMode); + + // Clear the tooltip + this.cachedItemTooltip.clear(); + this.lastTooltipUpdateTime = 0; + + break; + } + + // Was the sorting mode changed? + if (sortingChanged) { + // Update the sorting + this.updateSorting(); + + // Reset the tooltip + this.lastTooltipUpdateTime = 0; + + // Send to server + Packet_S_ArcaneCraftingTerminal.sendMode( + this.player, this.sortingOrder, this.sortingDirection, this.viewMode); + } + } + + @Override + protected void onMouseWheel(final int deltaZ, final int mouseX, final int mouseY) { + // Is the mouse inside of, or to the left of, the GUI? + if (mouseX > (this.guiLeft + GuiConstants_ACT.GUI_WIDTH)) { + // Mouse is to the right of the gui + return; + } + + // Is shift being held? + if (GuiScreen.isShiftKeyDown()) { + // Extract or insert based on the motion of the wheel + this.doMEWheelAction(deltaZ, mouseX, mouseY); + } else { + // Inform the scroll bar + this.scrollBar.wheel(deltaZ); + + // Update the item widgets + this.onScrollbarMoved(); + } + } + + @Override + protected void onScrollbarMoved() { + // Update the widgets + this.updateMEWidgets(); + + // Clear the tooltip + this.cachedItemTooltip.clear(); + this.lastTooltipUpdateTime = 0; + } + + /** + * Draws all screen elements, specifically calling on TC to draw the aspects + * of whatever the mouse is over. + */ + @Override + public void drawScreen(final int mouseX, final int mouseY, final float mouseBtn) { + // Call super + super.drawScreen(mouseX, mouseY, mouseBtn); + + // Show TC aspects for items in the ME network. + if ((this.meAspectBridge != null) && (!Config.showTags == Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))) { + this.meAspectBridge.renderAspects(this, this.player); + } + } + + /** + * Gets the sorting order. + */ + @Override + public Enum getSortBy() { + return this.sortingOrder; + } + + /** + * Gets the sorting direction. + */ + @Override + public Enum getSortDir() { + return this.sortingDirection; + } + + /** + * Gets what items (stored vs crafting) to show. + */ + @Override + public Enum getSortDisplay() { + return this.viewMode; + } + + /** + * Sets the gui up. + */ + @Override + public void initGui() { + // Call super + super.initGui(); + + // Reset the mouse wheel state. + Mouse.getDWheel(); + + // Enable repeat keys + Keyboard.enableRepeatEvents(true); + + // Calculate row count + this.setupTerminalStyle(); + + // Get the current search box mode + SearchBoxMode searchBoxMode = (SearchBoxMode) AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + + if (this.searchField == null) { + // Set up the search bar + this.searchField = new GuiTextField( + this.fontRendererObj, + GuiConstants_ACT.SEARCH_POS_X, + GuiConstants_ACT.SEARCH_POS_Y, + GuiConstants_ACT.SEARCH_WIDTH, + GuiConstants_ACT.SEARCH_HEIGHT); + + // Set the search field to draw in the foreground + this.searchField.setEnableBackgroundDrawing(false); + + // Set maximum length + this.searchField.setMaxStringLength(GuiConstants_ACT.SEARCH_MAX_CHARS); + } + + // Start focused? + this.searchField.setFocused( + (searchBoxMode == SearchBoxMode.AUTOSEARCH) || (searchBoxMode == SearchBoxMode.NEI_AUTOSEARCH)); + + // Set the search string + this.searchField.setText(memoryText); + this.repo.setSearchString(memoryText); + + // Clear any existing buttons + this.buttonList.clear(); + + // Create the clear grid button + this.buttonList.add(new GuiButtonClearCraftingGrid( + GuiConstants_ACT.BUTTON_CLEAR_GRID_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_CLEAR_GRID_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_CLEAR_GRID_POS_Y + this.lowerTerminalYOffset, + 8, + 8, + true)); + + // Add sort order button + this.buttonList.add( + this.btnSortingMode = new GuiButtonSortingMode( + GuiConstants_ACT.BUTTON_SORT_MODE_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_SORT_MODE_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_SORT_MODE_POS_Y, + GuiConstants_ACT.BUTTON_AE_SIZE, + GuiConstants_ACT.BUTTON_AE_SIZE)); + + // Add sort direction button + this.buttonList.add( + this.btnSortingDirection = new GuiButtonSortingDirection( + GuiConstants_ACT.BUTTON_SORT_DIR_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_SORT_DIR_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_SORT_DIR_POS_Y, + GuiConstants_ACT.BUTTON_AE_SIZE, + GuiConstants_ACT.BUTTON_AE_SIZE)); + + // Add view type button + this.buttonList.add( + this.btnViewType = new GuiButtonViewType( + GuiConstants_ACT.BUTTON_VIEW_TYPE_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_VIEW_TYPE_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_VIEW_TYPE_POS_Y, + GuiConstants_ACT.BUTTON_AE_SIZE, + GuiConstants_ACT.BUTTON_AE_SIZE)); + + // Add swap armor button + this.buttonList.add(new GuiButtonSwapArmor( + GuiConstants_ACT.BUTTON_SWAP_ARMOR_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_SWAP_ARMOR_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_SWAP_ARMOR_POS_Y + this.lowerTerminalYOffset, + 8, + 8)); + + // Add search mode button + this.buttonList.add( + this.btnSearchMode = new GuiButtonSearchMode( + GuiConstants_ACT.BUTTON_SEARCH_MODE_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_SEARCH_MODE_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_SEARCH_MODE_POS_Y, + GuiConstants_ACT.BUTTON_AE_SIZE, + GuiConstants_ACT.BUTTON_AE_SIZE, + searchBoxMode)); + + // Add terminal style button + this.buttonList.add(new GuiButtonTerminalStyle( + GuiConstants_ACT.BUTTON_TERM_STYLE_ID, + this.guiLeft + GuiConstants_ACT.BUTTON_TERM_STYLE_POS_X, + this.guiTop + GuiConstants_ACT.BUTTON_TERM_STYLE_POS_Y, + GuiConstants_ACT.BUTTON_AE_SIZE, + GuiConstants_ACT.BUTTON_AE_SIZE, + this.terminalStyle)); + + // Add the container as a listener + ((ContainerPartArcaneCraftingTerminal) this.inventorySlots).registerForUpdates(); + + // Request a full update from the server + Packet_S_ArcaneCraftingTerminal.sendFullListRequest(this.player); + } + + /** + * Called when the gui is closing. + */ + @Override + public void onGuiClosed() { + // Call super + super.onGuiClosed(); + + // Disable repeat keys + Keyboard.enableRepeatEvents(false); + } + + /** + * Called to update the amount of an item in the ME network. + * + * @param change + */ + public void onReceiveChange(final IAEItemStack change) { + // Is the item blacklisted? + if (AEHooks.isItemGUIBlacklisted(change)) { + return; + } + + // Update the repository + this.repo.postUpdate(change); + + // Repo needs update + this.viewNeedsUpdate = true; + } + + /** + * Called when the server sends a full list of all + * items in the AE network in response to our request. + * + * @param itemList + */ + public void onReceiveFullList(final IItemList itemList) { + // Clear the repo + this.repo.clear(); + + // Update the repository + for (IAEItemStack stack : itemList) { + this.onReceiveChange(stack); + } + } + + /** + * Called when the server sends the sorting order and direction. + * + * @param order + * @param direction + */ + public void onReceiveSorting(final SortOrder order, final SortDir direction, final ViewItems viewMode) { + // Set the direction + this.sortingDirection = direction; + + // Set the order + this.sortingOrder = order; + + // Set view mode + this.viewMode = viewMode; + + // Update + this.updateSorting(); + } + + /** + * Called when the server wants the client to force an update to the aspect + * costs. + */ + public void onServerSendForceUpdateCost() { + ((ContainerPartArcaneCraftingTerminal) this.inventorySlots).getCraftingCost(true); + } + + /** + * Called when the view cells change. + */ + public void onViewCellsChanged(final ItemStack[] viewCells) { + // Update the repo + this.repo.setViewCell(viewCells); + + // Repo needs update + this.viewNeedsUpdate = true; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiCraftAmountBridge.java b/src/main/java/thaumicenergistics/client/gui/GuiCraftAmountBridge.java index 6f7de501..6fbca7e6 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiCraftAmountBridge.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiCraftAmountBridge.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui; -import java.lang.reflect.Field; import appeng.client.gui.implementations.GuiCraftAmount; import appeng.client.gui.widgets.GuiTabButton; import appeng.core.localization.GuiText; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.Field; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.EntityPlayer; @@ -20,116 +20,96 @@ import thaumicenergistics.common.network.packet.server.Packet_S_ConfirmCraftingJ * */ @SideOnly(Side.CLIENT) -public class GuiCraftAmountBridge - extends GuiCraftAmount -{ - /** - * The thing that issued the crafting request. - */ - protected ICraftingIssuerHost host; +public class GuiCraftAmountBridge extends GuiCraftAmount { + /** + * The thing that issued the crafting request. + */ + protected ICraftingIssuerHost host; - /** - * Button that returns to the terminal's GUI. - */ - protected GuiTabButton buttonReturnToTerminalHost; + /** + * Button that returns to the terminal's GUI. + */ + protected GuiTabButton buttonReturnToTerminalHost; - /** - * The player that is using the GUI. - */ - protected EntityPlayer player; + /** + * The player that is using the GUI. + */ + protected EntityPlayer player; - /** - * The next button. - */ - protected GuiButton buttonNext; + /** + * The next button. + */ + protected GuiButton buttonNext; - /** - * The amount-to-craft text box. - */ - protected GuiTextField amountToCraft; + /** + * The amount-to-craft text box. + */ + protected GuiTextField amountToCraft; - public GuiCraftAmountBridge( final EntityPlayer player, final ICraftingIssuerHost craftingHost ) - { - // Call super - super( player.inventory, craftingHost ); + public GuiCraftAmountBridge(final EntityPlayer player, final ICraftingIssuerHost craftingHost) { + // Call super + super(player.inventory, craftingHost); - // Set the host - this.host = craftingHost; + // Set the host + this.host = craftingHost; - // Set the player - this.player = player; - } + // Set the player + this.player = player; + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - if( btn == this.buttonReturnToTerminalHost ) - { - // Change back to host GUI - this.host.launchGUI( this.player ); - } - else if( btn == this.buttonNext ) - { - try - { - // Parse the amount - long amount = Long.parseLong( this.amountToCraft.getText() ); + @Override + protected void actionPerformed(final GuiButton btn) { + if (btn == this.buttonReturnToTerminalHost) { + // Change back to host GUI + this.host.launchGUI(this.player); + } else if (btn == this.buttonNext) { + try { + // Parse the amount + long amount = Long.parseLong(this.amountToCraft.getText()); - // Ask server to show confirm gui - Packet_S_ConfirmCraftingJob.sendConfirmAutoCraft( this.player, amount, isShiftKeyDown() ); - } - catch( final NumberFormatException e ) - { - // Reset amount to 1 - this.amountToCraft.setText( "1" ); - } - } - else - { - // Call super - super.actionPerformed( btn ); - } - } + // Ask server to show confirm gui + Packet_S_ConfirmCraftingJob.sendConfirmAutoCraft(this.player, amount, isShiftKeyDown()); + } catch (final NumberFormatException e) { + // Reset amount to 1 + this.amountToCraft.setText("1"); + } + } else { + // Call super + super.actionPerformed(btn); + } + } - @Override - public void initGui() - { - // Call super - super.initGui(); + @Override + public void initGui() { + // Call super + super.initGui(); - // Get the icon of the host - ItemStack myIcon = this.host.getIcon(); + // Get the icon of the host + ItemStack myIcon = this.host.getIcon(); - // Create the return button - this.buttonReturnToTerminalHost = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ); - this.buttonList.add( this.buttonReturnToTerminalHost ); + // Create the return button + this.buttonReturnToTerminalHost = + new GuiTabButton(this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender); + this.buttonList.add(this.buttonReturnToTerminalHost); - // Get the next button - for( Object buttonObj : this.buttonList ) - { - if( buttonObj instanceof GuiButton ) - { - GuiButton button = (GuiButton)buttonObj; - if( button.displayString == GuiText.Next.getLocal() ) - { - this.buttonNext = button; - break; - } - } - } - - // Get the amount to craft - Field atcField; - try - { - atcField = GuiCraftAmount.class.getDeclaredField( "amountToCraft" ); - atcField.setAccessible( true ); - this.amountToCraft = (GuiTextField)atcField.get( this ); - } - catch( Exception e ) - { - } - - } + // Get the next button + for (Object buttonObj : this.buttonList) { + if (buttonObj instanceof GuiButton) { + GuiButton button = (GuiButton) buttonObj; + if (button.displayString == GuiText.Next.getLocal()) { + this.buttonNext = button; + break; + } + } + } + // Get the amount to craft + Field atcField; + try { + atcField = GuiCraftAmount.class.getDeclaredField("amountToCraft"); + atcField.setAccessible(true); + this.amountToCraft = (GuiTextField) atcField.get(this); + } catch (Exception e) { + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiCraftConfirmBridge.java b/src/main/java/thaumicenergistics/client/gui/GuiCraftConfirmBridge.java index be9c9038..82ec8897 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiCraftConfirmBridge.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiCraftConfirmBridge.java @@ -15,47 +15,41 @@ import thaumicenergistics.api.grid.ICraftingIssuerHost; * */ @SideOnly(Side.CLIENT) -public class GuiCraftConfirmBridge - extends GuiCraftConfirm -{ - /** - * Player using this GUI - */ - protected EntityPlayer player; +public class GuiCraftConfirmBridge extends GuiCraftConfirm { + /** + * Player using this GUI + */ + protected EntityPlayer player; - /** - * The thing that issued the crafting request. - */ - protected ICraftingIssuerHost host; + /** + * The thing that issued the crafting request. + */ + protected ICraftingIssuerHost host; - public GuiCraftConfirmBridge( final EntityPlayer player, final ICraftingIssuerHost craftingHost ) - { - // Call super - super( player.inventory, craftingHost ); + public GuiCraftConfirmBridge(final EntityPlayer player, final ICraftingIssuerHost craftingHost) { + // Call super + super(player.inventory, craftingHost); - // Set the player - this.player = player; + // Set the player + this.player = player; - // Set the host - this.host = craftingHost; - } + // Set the host + this.host = craftingHost; + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - // Sanity check - if( btn == null ) - { - return; - } + @Override + protected void actionPerformed(final GuiButton btn) { + // Sanity check + if (btn == null) { + return; + } - // Call super - super.actionPerformed( btn ); + // Call super + super.actionPerformed(btn); - // Cancel button or start button? - if( ( btn == super.getCancelButton() ) || ( btn.displayString.equals( GuiText.Start.getLocal() ) ) ) - { - this.host.launchGUI( this.player ); - } - } + // Cancel button or start button? + if ((btn == super.getCancelButton()) || (btn.displayString.equals(GuiText.Start.getLocal()))) { + this.host.launchGUI(this.player); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiDistillationPatternEncoder.java b/src/main/java/thaumicenergistics/client/gui/GuiDistillationPatternEncoder.java index 0ab1a3aa..f4b4a939 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiDistillationPatternEncoder.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiDistillationPatternEncoder.java @@ -1,10 +1,9 @@ package thaumicenergistics.client.gui; -import java.util.ArrayList; -import java.util.Iterator; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Iterator; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; @@ -13,6 +12,7 @@ import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumcraft.common.config.ConfigItems; import thaumicenergistics.api.storage.IInventoryUpdateReceiver; @@ -34,291 +34,280 @@ import thaumicenergistics.common.utils.ThEUtils; * */ @SideOnly(Side.CLIENT) -public class GuiDistillationPatternEncoder - extends ThEBaseGui - implements IInventoryUpdateReceiver -{ - /** - * Gui size. - */ - private static final int GUI_WIDTH = 176, GUI_HEIGHT = 234; +public class GuiDistillationPatternEncoder extends ThEBaseGui implements IInventoryUpdateReceiver { + /** + * Gui size. + */ + private static final int GUI_WIDTH = 176, GUI_HEIGHT = 234; - /** - * Position of the title string. - */ - private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; + /** + * Position of the title string. + */ + private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; - /** - * Position of the encode button - */ - private static final int BUTTON_ENCODE_POS_X = 146, BUTTON_ENCODE_POS_Y = 94; + /** + * Position of the encode button + */ + private static final int BUTTON_ENCODE_POS_X = 146, BUTTON_ENCODE_POS_Y = 94; - /** - * Half of the size of a standard item - */ - private static final int ITEM_HALF_SIZE = 8; + /** + * Half of the size of a standard item + */ + private static final int ITEM_HALF_SIZE = 8; - /** - * Scale to draw the Thaumometer at. - */ - private static final float THAUMOMETER_SCALE = 2.8f; + /** + * Scale to draw the Thaumometer at. + */ + private static final float THAUMOMETER_SCALE = 2.8f; - /** - * Title of the gui. - */ - private final String title; + /** + * Title of the gui. + */ + private final String title; - /** - * The GUI's container. - */ - private final ContainerDistillationPatternEncoder deContainer; + /** + * The GUI's container. + */ + private final ContainerDistillationPatternEncoder deContainer; - /** - * Thaumcraft's thaumometer - */ - private final ItemStack thaumometer = new ItemStack( ConfigItems.itemThaumometer ); + /** + * Thaumcraft's thaumometer + */ + private final ItemStack thaumometer = new ItemStack(ConfigItems.itemThaumometer); - /** - * Particles - */ - private final ArrayList particles = new ArrayList(); + /** + * Particles + */ + private final ArrayList particles = new ArrayList(); - /** - * The encode button. - */ - private GuiButtonEncodePattern buttonEncode; + /** + * The encode button. + */ + private GuiButtonEncodePattern buttonEncode; - /** - * Set true when the source item may have been changed. - */ - private boolean sourceItemDirty = false; + /** + * Set true when the source item may have been changed. + */ + private boolean sourceItemDirty = false; - public GuiDistillationPatternEncoder( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( new ContainerDistillationPatternEncoder( player, world, x, y, z ) ); + public GuiDistillationPatternEncoder( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(new ContainerDistillationPatternEncoder(player, world, x, y, z)); - // Set the title - this.title = ThEStrings.Block_DistillationEncoder.getLocalized(); + // Set the title + this.title = ThEStrings.Block_DistillationEncoder.getLocalized(); - // Set the GUI size - this.xSize = GuiDistillationPatternEncoder.GUI_WIDTH; - this.ySize = GuiDistillationPatternEncoder.GUI_HEIGHT; + // Set the GUI size + this.xSize = GuiDistillationPatternEncoder.GUI_WIDTH; + this.ySize = GuiDistillationPatternEncoder.GUI_HEIGHT; - // Set the container - this.deContainer = (ContainerDistillationPatternEncoder)this.inventorySlots; - this.deContainer.slotUpdateReceiver = this; + // Set the container + this.deContainer = (ContainerDistillationPatternEncoder) this.inventorySlots; + this.deContainer.slotUpdateReceiver = this; + } - } + /** + * Checks for item changes to the source item. + */ + private void checkSourceItem() { + // Clear the dirty bit + this.sourceItemDirty = false; - /** - * Checks for item changes to the source item. - */ - private void checkSourceItem() - { - // Clear the dirty bit - this.sourceItemDirty = false; + // Clear any existing particles + this.particles.clear(); - // Clear any existing particles - this.particles.clear(); + // Is there a source item to check? + if (!this.deContainer.slotSourceItem.getHasStack()) { + // Done + return; + } - // Is there a source item to check? - if( !this.deContainer.slotSourceItem.getHasStack() ) - { - // Done - return; - } + // Check each slot + boolean isItemScanned = false; + for (Slot slot : this.deContainer.slotSourceAspects) { + // Does the slot have a stack? + if (slot.getHasStack()) { + // Get the aspect for that stack + Aspect aspect = ItemCraftingAspect.getAspect(slot.getStack()); + if (aspect != null) { + // Found something + isItemScanned = true; - // Check each slot - boolean isItemScanned = false; - for( Slot slot : this.deContainer.slotSourceAspects ) - { - // Does the slot have a stack? - if( slot.getHasStack() ) - { - // Get the aspect for that stack - Aspect aspect = ItemCraftingAspect.getAspect( slot.getStack() ); - if( aspect != null ) - { - // Found something - isItemScanned = true; + // Create the animator + GuiParticleAnimator gpa = new GuiParticleAnimator( + this.deContainer.slotSourceItem.xDisplayPosition, + this.deContainer.slotSourceItem.yDisplayPosition, + slot.xDisplayPosition, + slot.yDisplayPosition, + 0.3f, + EnumGuiParticles.Orb); - // Create the animator - GuiParticleAnimator gpa = new GuiParticleAnimator( this.deContainer.slotSourceItem.xDisplayPosition, - this.deContainer.slotSourceItem.yDisplayPosition, - slot.xDisplayPosition, - slot.yDisplayPosition, - 0.3f, - EnumGuiParticles.Orb ); + // Set FPS + gpa.setFPS(30); - // Set FPS - gpa.setFPS( 30 ); + // Set the color + float[] argb = ThEGuiHelper.INSTANCE.convertPackedColorToARGBf(aspect.getColor()); + gpa.setColor(argb[1], argb[2], argb[3]); - // Set the color - float[] argb = ThEGuiHelper.INSTANCE.convertPackedColorToARGBf( aspect.getColor() ); - gpa.setColor( argb[1], argb[2], argb[3] ); + // Add to the list + this.particles.add(gpa); + } + } else { + break; + } + } - // Add to the list - this.particles.add( gpa ); - } - } - else - { - break; - } - } + if (isItemScanned) { + // Play the on sound + ThEUtils.playClientSound(null, "thaumcraft:hhon"); + } else { + // Play the off sound + ThEUtils.playClientSound(null, "thaumcraft:hhoff"); + } + } - if( isItemScanned ) - { - // Play the on sound - ThEUtils.playClientSound( null, "thaumcraft:hhon" ); - } - else - { - // Play the off sound - ThEUtils.playClientSound( null, "thaumcraft:hhoff" ); - } + /** + * Draw the background. + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - } + // Bind the encoder gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.DISTILLATION_ENCODER.getTexture()); - /** - * Draw the background. - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + // Draw the gui texture + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - // Bind the encoder gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.DISTILLATION_ENCODER.getTexture() ); + // Calculate the position and rotation of the thaumometer + float th_PosX = (float) this.guiLeft + + ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_X + + GuiDistillationPatternEncoder.ITEM_HALF_SIZE; + float th_PosY = this.guiTop + + (ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_Y - 0.25f) + + GuiDistillationPatternEncoder.ITEM_HALF_SIZE; + float th_Rotation = (System.currentTimeMillis() % 36000) * 0.02f; + float th_ScaleOffset = (float) Math.sin(th_Rotation * 0.15f) * 0.1f; - // Draw the gui texture - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); + // Disable depth testing and push the matrix + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); - // Calculate the position and rotation of the thaumometer - float th_PosX = (float)this.guiLeft + ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_X + - GuiDistillationPatternEncoder.ITEM_HALF_SIZE; - float th_PosY = this.guiTop + ( ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_Y - 0.25f ) + - GuiDistillationPatternEncoder.ITEM_HALF_SIZE; - float th_Rotation = ( System.currentTimeMillis() % 36000 ) * 0.02f; - float th_ScaleOffset = (float)Math.sin( th_Rotation * 0.15f ) * 0.1f; + // Translate + GL11.glTranslatef(th_PosX, th_PosY, 0.0F); - // Disable depth testing and push the matrix - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glPushMatrix(); + // Scale + GL11.glScalef( + GuiDistillationPatternEncoder.THAUMOMETER_SCALE + th_ScaleOffset, + GuiDistillationPatternEncoder.THAUMOMETER_SCALE + th_ScaleOffset, + 1.0f); - // Translate - GL11.glTranslatef( th_PosX, th_PosY, 0.0F ); + // Rotate + GL11.glRotatef(th_Rotation, 0.0f, 0.0f, 1.0f); - // Scale - GL11.glScalef( GuiDistillationPatternEncoder.THAUMOMETER_SCALE + th_ScaleOffset, - GuiDistillationPatternEncoder.THAUMOMETER_SCALE + th_ScaleOffset, 1.0f ); + // Draw thaumometer + GuiScreen.itemRender.renderItemAndEffectIntoGUI( + this.fontRendererObj, + this.mc.getTextureManager(), + this.thaumometer, + -GuiDistillationPatternEncoder.ITEM_HALF_SIZE, + -GuiDistillationPatternEncoder.ITEM_HALF_SIZE); - // Rotate - GL11.glRotatef( th_Rotation, 0.0f, 0.0f, 1.0f ); + // Restore + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } - // Draw thaumometer - GuiScreen.itemRender.renderItemAndEffectIntoGUI( this.fontRendererObj, this.mc.getTextureManager(), - this.thaumometer, -GuiDistillationPatternEncoder.ITEM_HALF_SIZE, -GuiDistillationPatternEncoder.ITEM_HALF_SIZE ); + /** + * Draw the foreground. + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString( + this.title, GuiDistillationPatternEncoder.TITLE_POS_X, GuiDistillationPatternEncoder.TITLE_POS_Y, 0); - // Restore - GL11.glPopMatrix(); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } + // Check the source item + if (this.sourceItemDirty) { + this.checkSourceItem(); + } - /** - * Draw the foreground. - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( this.title, GuiDistillationPatternEncoder.TITLE_POS_X, GuiDistillationPatternEncoder.TITLE_POS_Y, 0 ); + // Any particles? + if (this.particles.size() > 0) { + // Prep + EnumGuiParticles.Orb.prepareDraw(); - // Check the source item - if( this.sourceItemDirty ) - { - this.checkSourceItem(); - } + // Draw each + for (Iterator iterator = this.particles.iterator(); iterator.hasNext(); ) { + if (!iterator.next().draw(this, false)) { + // Remove if done. + iterator.remove(); + } + } - // Any particles? - if( this.particles.size() > 0 ) - { - // Prep - EnumGuiParticles.Orb.prepareDraw(); + // Finish + EnumGuiParticles.finishDraw(); + } + } - // Draw each - for( Iterator iterator = this.particles.iterator(); iterator.hasNext(); ) - { - if( !iterator.next().draw( this, false ) ) - { - // Remove if done. - iterator.remove(); - } - } + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Call super + super.mouseClicked(mouseX, mouseY, mouseButton); - // Finish - EnumGuiParticles.finishDraw(); - } + // Was the mouse clicked over a widget? + for (Slot slot : this.deContainer.slotSourceAspects) { + if (slot.getHasStack() + && ThEGuiHelper.INSTANCE.isPointInGuiRegion( + slot.yDisplayPosition, + slot.xDisplayPosition, + 18, + 18, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Play clicky sound + ThEUtils.playClientSound(null, "gui.button.press"); + break; + } + } + } - } + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Encode button? + if (button == this.buttonEncode) { + // Ask server to encode + Packet_S_DistillationEncoder.sendEncodePattern(this.deContainer.getPlayer()); + } + } - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Call super - super.mouseClicked( mouseX, mouseY, mouseButton ); + @Override + public void initGui() { + // Call super + super.initGui(); - // Was the mouse clicked over a widget? - for( Slot slot : this.deContainer.slotSourceAspects ) - { - if( slot.getHasStack() && ThEGuiHelper.INSTANCE.isPointInGuiRegion( - slot.yDisplayPosition, slot.xDisplayPosition, - 18, 18, mouseX, mouseY, - this.guiLeft, this.guiTop ) ) - { - // Play clicky sound - ThEUtils.playClientSound( null, "gui.button.press" ); - break; - } - } - } + // Create the encode button + this.buttonEncode = new GuiButtonEncodePattern( + 0, + GuiDistillationPatternEncoder.BUTTON_ENCODE_POS_X + this.guiLeft, + GuiDistillationPatternEncoder.BUTTON_ENCODE_POS_Y + this.guiTop, + AEStateIconsEnum.STANDARD_ICON_SIZE, + AEStateIconsEnum.STANDARD_ICON_SIZE); + this.buttonList.add(this.buttonEncode); - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Encode button? - if( button == this.buttonEncode ) - { - // Ask server to encode - Packet_S_DistillationEncoder.sendEncodePattern( this.deContainer.getPlayer() ); - } - } + // Reset flags + this.sourceItemDirty = false; + } - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Create the encode button - this.buttonEncode = new GuiButtonEncodePattern( 0, GuiDistillationPatternEncoder.BUTTON_ENCODE_POS_X + this.guiLeft, - GuiDistillationPatternEncoder.BUTTON_ENCODE_POS_Y + this.guiTop, - AEStateIconsEnum.STANDARD_ICON_SIZE, - AEStateIconsEnum.STANDARD_ICON_SIZE ); - this.buttonList.add( this.buttonEncode ); - - // Reset flags - this.sourceItemDirty = false; - } - - /** - * Called by the container when the source item has changed. - */ - @Override - public void onInventoryChanged( final IInventory sourceInventory ) - { - this.sourceItemDirty = true; - } + /** + * Called by the container when the source item has changed. + */ + @Override + public void onInventoryChanged(final IInventory sourceInventory) { + this.sourceItemDirty = true; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellTerminal.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellTerminal.java index 347d07b3..3f822162 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellTerminal.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellTerminal.java @@ -1,14 +1,11 @@ package thaumicenergistics.client.gui; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; import appeng.api.config.ViewItems; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; @@ -17,6 +14,9 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.IThEWirelessEssentiaTerminal; import thaumicenergistics.api.gui.IAspectSelectorContainer; @@ -48,849 +48,799 @@ import thaumicenergistics.common.storage.AspectStackComparator.AspectStackCompar * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaCellTerminal - extends GuiConstants_ECT - implements IAspectSelectorGui -{ - - /** - * Local translation of the title. - */ - private final String guiTitle; - - /** - * Local translation of name prefix for selected aspect info. - */ - private final String selectedInfoNamePrefix; - - /** - * Local translation of amount prefix for selected aspect info. - */ - private final String selectedInfoAmountPrefix; - - /** - * The player viewing this gui - */ - protected EntityPlayer player; - - /** - * Scroll bar position - */ - protected int currentScroll = 0; - - /** - * Search field - */ - protected GuiTextField searchBar; - - /** - * Widgets. - */ - protected final WidgetAspectSelector[] aspectWidgets; - - /** - * Aspect stacks that match the search term. - */ - protected ArrayList matchingSearchStacks = new ArrayList(); - - /** - * What the user is searching for - */ - protected String searchTerm = ""; - - /** - * The container associated with this gui - */ - protected ContainerEssentiaCellTerminalBase baseContainer; - - /** - * Mode used to sort the aspects - */ - protected AspectStackComparatorMode sortMode = AspectStackComparatorMode.MODE_ALPHABETIC; - - /** - * Set to true when the widgets need to be updated. - */ - protected boolean flagWidgetsNeedUpdate = false; - - /** - * The sorting mode button. - */ - protected GuiButtonSortingMode buttonSortingMode = null; - - /** - * Button to change what aspects (regular | crafting) are shown. - */ - protected GuiButtonViewType buttonViewMode; - - /** - * The cached amount of the selected stack. - */ - private long cacheAmountSelected = -1; - - /** - * The cached display string of the selected stack. - */ - private String cacheAmountDisplay = "0"; - - /** - * Tracks how many rows of the grid can not be displayed without scrolling. - */ - private int previousOverflowRows = 0; - - /** - * Compares aspect stacks - */ - private final AspectStackComparator stackComparator; - - /** - * Which items can be viewed in the terminal. - */ - private ViewItems viewMode = ViewItems.ALL; - - /** - * The currently selected aspect - */ - private IAspectStack selectedAspectStack; - - /** - * Creates the gui. - * - * @param player - * Player viewing this gui. - * @param container - * Container associated with the gui. - */ - protected GuiEssentiaCellTerminal( final EntityPlayer player, final ContainerEssentiaCellTerminalBase container, final String title ) - { - // Call super - super( container ); - - // Set the container. - this.baseContainer = container; - - // Set the player - this.player = player; - - // Set the X size - this.xSize = GuiConstants_ECT.GUI_WIDTH; - - // Set the Y size - this.ySize = GuiConstants_ECT.GUI_HEIGHT; - - // Set the title - this.guiTitle = title; - - // Set the name prefix - this.selectedInfoNamePrefix = ThEStrings.Gui_SelectedAspect.getLocalized() + ": "; - - // Set the amount prefix - this.selectedInfoAmountPrefix = ThEStrings.Gui_SelectedAmount.getLocalized() + ": "; - - // Create the widgets - this.aspectWidgets = new WidgetAspectSelector[GuiConstants_ECT.WIDGETS_PER_PAGE]; - // Rows - for( int y = 0; y < GuiConstants_ECT.WIDGET_ROWS_PER_PAGE; y++ ) - { - // Columns - for( int x = 0; x < GuiConstants_ECT.WIDGETS_PER_ROW; x++ ) - { - WidgetAspectSelector widget = new WidgetAspectSelector( this, null, - GuiConstants_ECT.WIDGET_OFFSET_X + ( x * ThEWidget.WIDGET_SIZE ), - GuiConstants_ECT.WIDGET_OFFSET_Y + ( y * ThEWidget.WIDGET_SIZE ), - player ); - this.aspectWidgets[( y * GuiConstants_ECT.WIDGETS_PER_ROW ) + x] = widget; - } - } - - // Create the comparator - this.stackComparator = new AspectStackComparator(); - - } - - /** - * Creates the GUI for an essentia cell inside an ME chest. - * - * @param player - * Player viewing the gui. - * @param world - * World the chest is in. - * @param x - * X position of the chest. - * @param y - * Y position of the chest. - * @param z - * Z position of the chest. - * @return - */ - public static GuiEssentiaCellTerminal NewEssentiaCellGui( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - return new GuiEssentiaCellTerminal( player, new ContainerEssentiaCell( player, world, x, y, z ), - ThEStrings.Gui_TitleEssentiaCell.getLocalized() ); - } - - /** - * Creates the GUI for an essentia terminal. - * - * @param terminal - * @param player - * @return - */ - public static GuiEssentiaCellTerminal NewEssentiaTerminalGui( final PartEssentiaTerminal terminal, final EntityPlayer player ) - { - return new GuiEssentiaCellTerminal( player, new ContainerEssentiaTerminal( terminal, player ), - ThEStrings.Part_EssentiaTerminal.getLocalized() ); - } - - /** - * Creates the GUI for a wireless essentia terminal. - * - * @param player - * @return - */ - public static GuiEssentiaCellTerminal NewWirelessEssentiaTerminalGui( final EntityPlayer player ) - { - // Valid player? - if( ( player == null ) || ( player instanceof FakePlayer ) ) - { - return null; - } - - // Get the item the player is holding. - ItemStack wirelessTerminal = player.getHeldItem(); - - // Ensure the stack is valid - if( ( wirelessTerminal == null ) ) - { - // Invalid stack - return null; - } - - // Ensure the stack's item implements the wireless interface - if( !( wirelessTerminal.getItem() instanceof IThEWirelessEssentiaTerminal ) ) - { - // Invalid item. - return null; - } - - // Get the interface - IThEWirelessEssentiaTerminal terminalInterface = (IThEWirelessEssentiaTerminal)wirelessTerminal.getItem(); - - // Create the handler - HandlerWirelessEssentiaTerminal handler = new HandlerWirelessEssentiaTerminal( player, null, terminalInterface, wirelessTerminal ); - - // Create the gui - return new GuiEssentiaCellTerminal( player, new ContainerWirelessEssentiaTerminal( player, handler ), - ThEStrings.Part_EssentiaTerminal.getLocalized() ); - } - - /** - * True if the mouse is over the widget area - * - * @param mouseX - * @param mouseY - * @return - */ - private boolean isMouseOverWidgetArea( final int mouseX, final int mouseY ) - { - return ThEGuiHelper.INSTANCE.isPointInGuiRegion( - GuiConstants_ECT.WIDGET_OFFSET_Y, GuiConstants_ECT.WIDGET_OFFSET_X, - GuiConstants_ECT.WIDGET_ROWS_PER_PAGE * ThEWidget.WIDGET_SIZE, - GuiConstants_ECT.WIDGETS_PER_ROW * ThEWidget.WIDGET_SIZE, - mouseX, mouseY, this.guiLeft, this.guiTop ); - } - - /** - * Refreshes our aspect list to match that of the container. - */ - private void onListUpdate() - { - // Update the scrollbar - this.updateScrollMaximum(); - - // Update the search results - this.updateView(); - - // Update the selected aspect - this.updateSelectedAspect(); - - // Mark for widget update - this.flagWidgetsNeedUpdate = true; - } - - /** - * Updates the scroll bar's range. - */ - private void updateScrollMaximum() - { - // Calculate the number of widgets the will overflow - double overflowWidgets = Math.max( 0, this.matchingSearchStacks.size() - GuiConstants_ECT.WIDGETS_PER_PAGE ); - - // Calculate how many rows will overflow - int overflowRows = (int)Math.ceil( overflowWidgets / GuiConstants_ECT.WIDGETS_PER_ROW ); - - // Update if the range has changed - if( overflowRows != this.previousOverflowRows ) - { - // Update the scroll bar - this.scrollBar.setRange( 0, overflowRows, 1 ); - this.onScrollbarMoved(); - this.previousOverflowRows = overflowRows; - } - - // Mark for widget update - this.flagWidgetsNeedUpdate = true; - } - - /** - * Refreshes our selected aspect to match that of the container. - */ - private void updateSelectedAspect() - { - // No selection by default - this.selectedAspectStack = null; - - // Check all aspects - for( IAspectStack aspectStack : this.baseContainer.getAspectStackList() ) - { - // Does this match? - if( aspectStack.getAspect() == this.baseContainer.getSelectedAspect() ) - { - // Set our selection - this.selectedAspectStack = aspectStack; - - // Done - return; - } - } - - } - - /** - * Updates the matching widgets based on the viewing conditions. - */ - private void updateView() - { - // Clear the matching widgets - this.matchingSearchStacks.clear(); - - // Get the full list - Collection stacks = this.baseContainer.getAspectStackList(); - - boolean hideCraftable = ( this.viewMode == ViewItems.STORED ); - boolean hideStored = ( this.viewMode == ViewItems.CRAFTABLE ); - - // Examine each of the possible aspects - for( IAspectStack stack : stacks ) - { - // Is this stack valid for the current view mode? - if( ( hideStored && !stack.getCraftable() ) || ( hideCraftable && stack.isEmpty() ) ) - { - continue; - } - - // Is the search term in this aspects tag or name? - if( ( this.searchTerm == "" ) || ( stack.getAspectName().contains( this.searchTerm ) ) || - ( stack.getAspectTag().contains( this.searchTerm ) ) ) - { - this.matchingSearchStacks.add( stack ); - } - } - - // Set the comparator mode - this.stackComparator.setMode( this.sortMode ); - - // Sort the results - Collections.sort( this.matchingSearchStacks, this.stackComparator ); - - // Update scrollbar - this.updateScrollMaximum(); - - // Mark for widget update - this.flagWidgetsNeedUpdate = true; - - } - - /** - * Called when the update flag is true. - */ - private void updateWidgets() - { - // Get the number of matches - int numberOfSearchMatches = this.matchingSearchStacks.size(); - - // Calculate the row offset - int rowOffset = this.currentScroll * GuiConstants_ECT.WIDGETS_PER_ROW; - - // Update each widget - int matchIndex = -1; - for( int widgetIndex = 0; widgetIndex < this.aspectWidgets.length; ++widgetIndex ) - { - // Calculate the match index - matchIndex = widgetIndex + rowOffset; - - // Is the index greater than the number of matches? - if( matchIndex >= numberOfSearchMatches ) - { - // Set the aspect to null - this.aspectWidgets[widgetIndex].clearWidget(); - } - else - { - // Set the aspect - this.aspectWidgets[widgetIndex].setAspect( this.matchingSearchStacks.get( matchIndex ) ); - - // Set crafting mode - this.aspectWidgets[widgetIndex].setHideAmount( ( this.viewMode == ViewItems.CRAFTABLE ) ); - } - } - - this.flagWidgetsNeedUpdate = false; - } - - /** - * Draws the GUI background image. - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int sizeX, final int sizeY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - // Set the texture to the gui's texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_TERMINAL.getTexture() ); - - // Draw the gui - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); - - // Draw the search field. - this.searchBar.drawTextBox(); - } - - /** - * Draw the foreground layer. - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Call super - super.drawGuiContainerForegroundLayer( mouseX, mouseY ); - - // Draw the title - this.fontRendererObj.drawString( this.guiTitle, GuiConstants_ECT.TITLE_POS_X, GuiConstants_ECT.TITLE_POS_Y, 0 ); - - // Draw the widgets - this.drawWidgets( mouseX, mouseY ); - - // Is there a selected aspect? - if( this.selectedAspectStack != null ) - { - // Update the display amount? - if( this.selectedAspectStack.getStackSize() != this.cacheAmountSelected ) - { - // Convert the selected amount into a string - this.cacheAmountDisplay = Long.toString( this.selectedAspectStack.getStackSize() ); - - // Cache the amount - this.cacheAmountSelected = this.selectedAspectStack.getStackSize(); - } - - // Get the name of the aspect - String aspectName = this.selectedAspectStack.getAspectName( this.player ); - - // Draw the name - this.fontRendererObj.drawString( this.selectedInfoNamePrefix + aspectName, - GuiConstants_ECT.SELECTED_INFO_POS_X, GuiConstants_ECT.SELECTED_INFO_NAME_POS_Y, 0 ); - - // Draw the amount - this.fontRendererObj.drawString( this.selectedInfoAmountPrefix + this.cacheAmountDisplay, - GuiConstants_ECT.SELECTED_INFO_POS_X, GuiConstants_ECT.SELECTED_INFO_AMOUNT_POS_Y, 0 ); - } - } - - @Override - protected ScrollbarParams getScrollbarParameters() - { - return new ScrollbarParams( GuiConstants_ECT.SCROLLBAR_POS_X, GuiConstants_ECT.SCROLLBAR_POS_Y, GuiConstants_ECT.SCROLLBAR_HEIGHT ); - } - - /** - * Called when the player types a key. - */ - @Override - protected void keyTyped( final char key, final int keyID ) - { - // Pass the key to the search field. - this.searchBar.textboxKeyTyped( key, keyID ); - - // Did they press the escape key? - if( keyID == Keyboard.KEY_ESCAPE ) - { - // Slot the screen. - this.mc.thePlayer.closeScreen(); - } - else if( this.searchBar.isFocused() ) - { - // Get the search term - this.searchTerm = this.searchBar.getText().trim().toLowerCase(); - - // Re-search the widgets - this.updateView(); - } - // Disable numeric key hotbar swaping. - else if( !Character.isDigit( key ) ) - { - super.keyTyped( key, keyID ); - } - - } - - /** - * Called when the player clicks the mouse. - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseBtn ) - { - // Boolean trackers for cleaner code - final boolean isLeftClick = ( mouseBtn == ThEGuiHelper.MOUSE_BUTTON_LEFT ); - final boolean isRightClick = ( mouseBtn == ThEGuiHelper.MOUSE_BUTTON_RIGHT ); - final boolean isMiddleClick = ( mouseBtn == ThEGuiHelper.MOUSE_BUTTON_WHEEL ); - - if( this.isMouseOverWidgetArea( mouseX, mouseY ) ) - { - // Is the view mode crafting? - boolean viewingCraftable = ( this.viewMode == ViewItems.CRAFTABLE ); - - // Is the player holding anything? - boolean playerHoldingItem = ( this.player.inventory.getItemStack() != null ); - - // Check each widget - for( WidgetAspectSelector widget : this.aspectWidgets ) - { - // Is the mouse over this widget? - if( widget.isMouseOverWidget( mouseX, mouseY ) ) - { - // Is the player holding something? - if( playerHoldingItem ) - { - // Inform the server - Packet_S_EssentiaCellTerminal.sendInteractWithHeldItem( this.player, widget.getAspect() ); - } - else - { - // Check if the aspect is to be crafted - if( ( !isRightClick && widget.hasAspect() && widget.getCraftable() ) && - ( viewingCraftable || ( isMiddleClick || ( isLeftClick && ( widget.getAmount() == 0 ) ) ) ) ) - { - // Send request - Packet_S_EssentiaCellTerminal.sendAutoCraft( this.player, widget.getAspect() ); - - } - - // Send the click - widget.onMouseClicked(); - } - - // Stop searching - return; - } - } - } - - // Is the mouse over the search bar? - boolean mouseOverSearchBar = ( mouseX >= this.searchBar.xPosition ) && ( mouseX < ( this.searchBar.xPosition + this.searchBar.width ) ) && - ( mouseY >= this.searchBar.yPosition ) && ( mouseY < ( this.searchBar.yPosition + this.searchBar.height ) ); - if( mouseOverSearchBar ) - { - // Left click? - if( isLeftClick ) - { - // Pass to search field. - this.searchBar.mouseClicked( mouseX, mouseY, mouseBtn ); - - // Done - return; - - } - // Right click? - else if( isRightClick ) - { - // Clear the search text - this.searchTerm = ""; - this.searchBar.setText( this.searchTerm ); - - // Update the widgets - this.updateView(); - - // Done - return; - } - } - - // Call super - super.mouseClicked( mouseX, mouseY, mouseBtn ); - - } - - /** - * Called when a button is clicked. - */ - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Ignore all middle clicks. - if( mouseButton == ThEGuiHelper.MOUSE_BUTTON_WHEEL ) - { - return; - } - - // Is the button the sort mode button? - if( button == this.buttonSortingMode ) - { - // Request update from server - Packet_S_EssentiaCellTerminal.sendChangeSorting( this.player, ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT ) ); - } - else if( button == this.buttonViewMode ) - { - // Request update from server - Packet_S_EssentiaCellTerminal.sendChangeView( this.player, ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT ) ); - } - } - - @Override - protected void onMouseWheel( final int deltaZ, final int mouseX, final int mouseY ) - { - // Is the mouse inside of, or to the left of, the GUI? - if( mouseX > ( this.guiLeft + GuiConstants_ECT.GUI_WIDTH ) ) - { - // Mouse is to the right of the gui - return; - } - - // Is shift not being held down? - if( !GuiScreen.isShiftKeyDown() ) - { - // Inform the scroll bar - this.scrollBar.wheel( deltaZ ); - this.onScrollbarMoved(); - } - - } - - @Override - protected void onScrollbarMoved() - { - // Set the scroll - this.currentScroll = this.scrollBar.getCurrentScroll(); - - // Mark for widget update - this.flagWidgetsNeedUpdate = true; - } - - /** - * Draw the widgets - * - * @param mouseX - * @param mouseY - */ - public void drawWidgets( final int mouseX, final int mouseY ) - { - // Do the widgets need to be updated? - if( this.flagWidgetsNeedUpdate ) - { - // Update first - this.updateWidgets(); - } - - // Anything to draw? - if( !this.matchingSearchStacks.isEmpty() ) - { - for( int widgetIndex = 0; widgetIndex < this.aspectWidgets.length; ++widgetIndex ) - { - // Get the widget - WidgetAspectSelector widget = this.aspectWidgets[widgetIndex]; - - // Does the widget not have an aspect? - if( !widget.hasAspect() ) - { - // Nothing more to draw - break; - } - - // Draw the widget - widget.drawWidget(); - - // Is the mouse over this widget? - if( this.tooltip.isEmpty() && widget.isMouseOverWidget( mouseX, mouseY ) ) - { - // Get the tooltip from the widget - widget.getTooltip( this.tooltip ); - } - } - } - else - { - this.currentScroll = 0; - } - } - - /** - * Gets the container associated with the gui - */ - @Override - public IAspectSelectorContainer getContainer() - { - return this.baseContainer; - } - - /** - * Gets the currently selected aspect. - */ - @Override - public Aspect getSelectedAspect() - { - return( this.selectedAspectStack != null ? this.selectedAspectStack.getAspect() : null ); - } - - /** - * Sets the gui up. - */ - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Reset the mouse wheel state. - Mouse.getDWheel(); - - // Enable repeat keys - Keyboard.enableRepeatEvents( true ); - - // Get the aspect list - this.onListUpdate(); - - // Set up the search bar - this.searchBar = new GuiTextField( this.fontRendererObj, - this.guiLeft + GuiConstants_ECT.SEARCH_X_OFFSET, - this.guiTop + GuiConstants_ECT.SEARCH_Y_OFFSET, - GuiConstants_ECT.SEARCH_WIDTH, GuiConstants_ECT.SEARCH_HEIGHT ); - - // Set the search bar to draw in the foreground - this.searchBar.setEnableBackgroundDrawing( false ); - - // Start focused - this.searchBar.setFocused( false ); - - // Set maximum length - this.searchBar.setMaxStringLength( GuiConstants_ECT.SEARCH_MAX_CHARS ); - - // Clear any existing buttons - this.buttonList.clear(); - - // Add the sort mode button - this.buttonSortingMode = new GuiButtonSortingMode( 0, - this.guiLeft + GuiConstants_ECT.BUTTON_SORT_MODE_POS_X, - this.guiTop + GuiConstants_ECT.BUTTON_SORT_MODE_POS_Y, - GuiConstants_ECT.MODE_BUTTON_SIZE, GuiConstants_ECT.MODE_BUTTON_SIZE ); - this.buttonList.add( this.buttonSortingMode ); - - // Add view type button - this.buttonViewMode = new GuiButtonViewType( 1, - this.guiLeft + GuiConstants_ECT.BUTTON_VIEW_MODE_POS_X, - this.guiTop + GuiConstants_ECT.BUTTON_VIEW_MODE_POS_Y, - GuiConstants_ECT.MODE_BUTTON_SIZE, GuiConstants_ECT.MODE_BUTTON_SIZE ); - this.buttonList.add( this.buttonViewMode ); - } - - /** - * Called when the gui is closing. - */ - @Override - public void onGuiClosed() - { - // Call super - super.onGuiClosed(); - - // Disable repeat keys - Keyboard.enableRepeatEvents( false ); - } - - /** - * Called when the server sends a full list of network aspects. - * - * @param aspectStackList - */ - public void onReceiveAspectList( final Collection aspectStackList ) - { - // Update the container - this.baseContainer.onReceivedAspectList( aspectStackList ); - - // Update the gui - this.onListUpdate(); - } - - /** - * Called when an aspect in the list changes amount. - * - * @param change - */ - public void onReceiveAspectListChange( final IAspectStack change ) - { - // Update the container - this.baseContainer.onReceivedAspectListChange( change ); - - // Update the gui - this.onListUpdate(); - - } - - /** - * Called when the server sends a change to the selected aspect. - * - * @param selectedAspect - */ - public void onReceiveSelectedAspect( final Aspect selectedAspect ) - { - // Update the container - this.baseContainer.onReceivedSelectedAspect( selectedAspect ); - - // Update the gui - this.updateSelectedAspect(); - } - - /** - * Called when the server sends a change in the sorting mode. - * - * @param sortMode - */ - public void onViewingModesChanged( final AspectStackComparatorMode sortMode, final ViewItems viewMode ) - { - // Update the sort button - this.buttonSortingMode.setSortMode( this.sortMode = sortMode ); - - // Update view mode - this.buttonViewMode.setViewMode( this.viewMode = viewMode ); - - // Update the view - this.updateView(); - } - - /** - * Called when a new view mode is sent. - * - * @param mode - */ - public void onViewModeChanged( final ViewItems mode ) - { - // Set the mode - this.viewMode = mode; - - // Update the view - this.updateView(); - - // Mark for widget update - this.flagWidgetsNeedUpdate = true; - } - +public class GuiEssentiaCellTerminal extends GuiConstants_ECT implements IAspectSelectorGui { + + /** + * Local translation of the title. + */ + private final String guiTitle; + + /** + * Local translation of name prefix for selected aspect info. + */ + private final String selectedInfoNamePrefix; + + /** + * Local translation of amount prefix for selected aspect info. + */ + private final String selectedInfoAmountPrefix; + + /** + * The player viewing this gui + */ + protected EntityPlayer player; + + /** + * Scroll bar position + */ + protected int currentScroll = 0; + + /** + * Search field + */ + protected GuiTextField searchBar; + + /** + * Widgets. + */ + protected final WidgetAspectSelector[] aspectWidgets; + + /** + * Aspect stacks that match the search term. + */ + protected ArrayList matchingSearchStacks = new ArrayList(); + + /** + * What the user is searching for + */ + protected String searchTerm = ""; + + /** + * The container associated with this gui + */ + protected ContainerEssentiaCellTerminalBase baseContainer; + + /** + * Mode used to sort the aspects + */ + protected AspectStackComparatorMode sortMode = AspectStackComparatorMode.MODE_ALPHABETIC; + + /** + * Set to true when the widgets need to be updated. + */ + protected boolean flagWidgetsNeedUpdate = false; + + /** + * The sorting mode button. + */ + protected GuiButtonSortingMode buttonSortingMode = null; + + /** + * Button to change what aspects (regular | crafting) are shown. + */ + protected GuiButtonViewType buttonViewMode; + + /** + * The cached amount of the selected stack. + */ + private long cacheAmountSelected = -1; + + /** + * The cached display string of the selected stack. + */ + private String cacheAmountDisplay = "0"; + + /** + * Tracks how many rows of the grid can not be displayed without scrolling. + */ + private int previousOverflowRows = 0; + + /** + * Compares aspect stacks + */ + private final AspectStackComparator stackComparator; + + /** + * Which items can be viewed in the terminal. + */ + private ViewItems viewMode = ViewItems.ALL; + + /** + * The currently selected aspect + */ + private IAspectStack selectedAspectStack; + + /** + * Creates the gui. + * + * @param player + * Player viewing this gui. + * @param container + * Container associated with the gui. + */ + protected GuiEssentiaCellTerminal( + final EntityPlayer player, final ContainerEssentiaCellTerminalBase container, final String title) { + // Call super + super(container); + + // Set the container. + this.baseContainer = container; + + // Set the player + this.player = player; + + // Set the X size + this.xSize = GuiConstants_ECT.GUI_WIDTH; + + // Set the Y size + this.ySize = GuiConstants_ECT.GUI_HEIGHT; + + // Set the title + this.guiTitle = title; + + // Set the name prefix + this.selectedInfoNamePrefix = ThEStrings.Gui_SelectedAspect.getLocalized() + ": "; + + // Set the amount prefix + this.selectedInfoAmountPrefix = ThEStrings.Gui_SelectedAmount.getLocalized() + ": "; + + // Create the widgets + this.aspectWidgets = new WidgetAspectSelector[GuiConstants_ECT.WIDGETS_PER_PAGE]; + // Rows + for (int y = 0; y < GuiConstants_ECT.WIDGET_ROWS_PER_PAGE; y++) { + // Columns + for (int x = 0; x < GuiConstants_ECT.WIDGETS_PER_ROW; x++) { + WidgetAspectSelector widget = new WidgetAspectSelector( + this, + null, + GuiConstants_ECT.WIDGET_OFFSET_X + (x * ThEWidget.WIDGET_SIZE), + GuiConstants_ECT.WIDGET_OFFSET_Y + (y * ThEWidget.WIDGET_SIZE), + player); + this.aspectWidgets[(y * GuiConstants_ECT.WIDGETS_PER_ROW) + x] = widget; + } + } + + // Create the comparator + this.stackComparator = new AspectStackComparator(); + } + + /** + * Creates the GUI for an essentia cell inside an ME chest. + * + * @param player + * Player viewing the gui. + * @param world + * World the chest is in. + * @param x + * X position of the chest. + * @param y + * Y position of the chest. + * @param z + * Z position of the chest. + * @return + */ + public static GuiEssentiaCellTerminal NewEssentiaCellGui( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + return new GuiEssentiaCellTerminal( + player, + new ContainerEssentiaCell(player, world, x, y, z), + ThEStrings.Gui_TitleEssentiaCell.getLocalized()); + } + + /** + * Creates the GUI for an essentia terminal. + * + * @param terminal + * @param player + * @return + */ + public static GuiEssentiaCellTerminal NewEssentiaTerminalGui( + final PartEssentiaTerminal terminal, final EntityPlayer player) { + return new GuiEssentiaCellTerminal( + player, + new ContainerEssentiaTerminal(terminal, player), + ThEStrings.Part_EssentiaTerminal.getLocalized()); + } + + /** + * Creates the GUI for a wireless essentia terminal. + * + * @param player + * @return + */ + public static GuiEssentiaCellTerminal NewWirelessEssentiaTerminalGui(final EntityPlayer player) { + // Valid player? + if ((player == null) || (player instanceof FakePlayer)) { + return null; + } + + // Get the item the player is holding. + ItemStack wirelessTerminal = player.getHeldItem(); + + // Ensure the stack is valid + if ((wirelessTerminal == null)) { + // Invalid stack + return null; + } + + // Ensure the stack's item implements the wireless interface + if (!(wirelessTerminal.getItem() instanceof IThEWirelessEssentiaTerminal)) { + // Invalid item. + return null; + } + + // Get the interface + IThEWirelessEssentiaTerminal terminalInterface = (IThEWirelessEssentiaTerminal) wirelessTerminal.getItem(); + + // Create the handler + HandlerWirelessEssentiaTerminal handler = + new HandlerWirelessEssentiaTerminal(player, null, terminalInterface, wirelessTerminal); + + // Create the gui + return new GuiEssentiaCellTerminal( + player, + new ContainerWirelessEssentiaTerminal(player, handler), + ThEStrings.Part_EssentiaTerminal.getLocalized()); + } + + /** + * True if the mouse is over the widget area + * + * @param mouseX + * @param mouseY + * @return + */ + private boolean isMouseOverWidgetArea(final int mouseX, final int mouseY) { + return ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiConstants_ECT.WIDGET_OFFSET_Y, + GuiConstants_ECT.WIDGET_OFFSET_X, + GuiConstants_ECT.WIDGET_ROWS_PER_PAGE * ThEWidget.WIDGET_SIZE, + GuiConstants_ECT.WIDGETS_PER_ROW * ThEWidget.WIDGET_SIZE, + mouseX, + mouseY, + this.guiLeft, + this.guiTop); + } + + /** + * Refreshes our aspect list to match that of the container. + */ + private void onListUpdate() { + // Update the scrollbar + this.updateScrollMaximum(); + + // Update the search results + this.updateView(); + + // Update the selected aspect + this.updateSelectedAspect(); + + // Mark for widget update + this.flagWidgetsNeedUpdate = true; + } + + /** + * Updates the scroll bar's range. + */ + private void updateScrollMaximum() { + // Calculate the number of widgets the will overflow + double overflowWidgets = Math.max(0, this.matchingSearchStacks.size() - GuiConstants_ECT.WIDGETS_PER_PAGE); + + // Calculate how many rows will overflow + int overflowRows = (int) Math.ceil(overflowWidgets / GuiConstants_ECT.WIDGETS_PER_ROW); + + // Update if the range has changed + if (overflowRows != this.previousOverflowRows) { + // Update the scroll bar + this.scrollBar.setRange(0, overflowRows, 1); + this.onScrollbarMoved(); + this.previousOverflowRows = overflowRows; + } + + // Mark for widget update + this.flagWidgetsNeedUpdate = true; + } + + /** + * Refreshes our selected aspect to match that of the container. + */ + private void updateSelectedAspect() { + // No selection by default + this.selectedAspectStack = null; + + // Check all aspects + for (IAspectStack aspectStack : this.baseContainer.getAspectStackList()) { + // Does this match? + if (aspectStack.getAspect() == this.baseContainer.getSelectedAspect()) { + // Set our selection + this.selectedAspectStack = aspectStack; + + // Done + return; + } + } + } + + /** + * Updates the matching widgets based on the viewing conditions. + */ + private void updateView() { + // Clear the matching widgets + this.matchingSearchStacks.clear(); + + // Get the full list + Collection stacks = this.baseContainer.getAspectStackList(); + + boolean hideCraftable = (this.viewMode == ViewItems.STORED); + boolean hideStored = (this.viewMode == ViewItems.CRAFTABLE); + + // Examine each of the possible aspects + for (IAspectStack stack : stacks) { + // Is this stack valid for the current view mode? + if ((hideStored && !stack.getCraftable()) || (hideCraftable && stack.isEmpty())) { + continue; + } + + // Is the search term in this aspects tag or name? + if ((this.searchTerm == "") + || (stack.getAspectName().contains(this.searchTerm)) + || (stack.getAspectTag().contains(this.searchTerm))) { + this.matchingSearchStacks.add(stack); + } + } + + // Set the comparator mode + this.stackComparator.setMode(this.sortMode); + + // Sort the results + Collections.sort(this.matchingSearchStacks, this.stackComparator); + + // Update scrollbar + this.updateScrollMaximum(); + + // Mark for widget update + this.flagWidgetsNeedUpdate = true; + } + + /** + * Called when the update flag is true. + */ + private void updateWidgets() { + // Get the number of matches + int numberOfSearchMatches = this.matchingSearchStacks.size(); + + // Calculate the row offset + int rowOffset = this.currentScroll * GuiConstants_ECT.WIDGETS_PER_ROW; + + // Update each widget + int matchIndex = -1; + for (int widgetIndex = 0; widgetIndex < this.aspectWidgets.length; ++widgetIndex) { + // Calculate the match index + matchIndex = widgetIndex + rowOffset; + + // Is the index greater than the number of matches? + if (matchIndex >= numberOfSearchMatches) { + // Set the aspect to null + this.aspectWidgets[widgetIndex].clearWidget(); + } else { + // Set the aspect + this.aspectWidgets[widgetIndex].setAspect(this.matchingSearchStacks.get(matchIndex)); + + // Set crafting mode + this.aspectWidgets[widgetIndex].setHideAmount((this.viewMode == ViewItems.CRAFTABLE)); + } + } + + this.flagWidgetsNeedUpdate = false; + } + + /** + * Draws the GUI background image. + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int sizeX, final int sizeY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Set the texture to the gui's texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_TERMINAL.getTexture()); + + // Draw the gui + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + + // Draw the search field. + this.searchBar.drawTextBox(); + } + + /** + * Draw the foreground layer. + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Call super + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + + // Draw the title + this.fontRendererObj.drawString(this.guiTitle, GuiConstants_ECT.TITLE_POS_X, GuiConstants_ECT.TITLE_POS_Y, 0); + + // Draw the widgets + this.drawWidgets(mouseX, mouseY); + + // Is there a selected aspect? + if (this.selectedAspectStack != null) { + // Update the display amount? + if (this.selectedAspectStack.getStackSize() != this.cacheAmountSelected) { + // Convert the selected amount into a string + this.cacheAmountDisplay = Long.toString(this.selectedAspectStack.getStackSize()); + + // Cache the amount + this.cacheAmountSelected = this.selectedAspectStack.getStackSize(); + } + + // Get the name of the aspect + String aspectName = this.selectedAspectStack.getAspectName(this.player); + + // Draw the name + this.fontRendererObj.drawString( + this.selectedInfoNamePrefix + aspectName, + GuiConstants_ECT.SELECTED_INFO_POS_X, + GuiConstants_ECT.SELECTED_INFO_NAME_POS_Y, + 0); + + // Draw the amount + this.fontRendererObj.drawString( + this.selectedInfoAmountPrefix + this.cacheAmountDisplay, + GuiConstants_ECT.SELECTED_INFO_POS_X, + GuiConstants_ECT.SELECTED_INFO_AMOUNT_POS_Y, + 0); + } + } + + @Override + protected ScrollbarParams getScrollbarParameters() { + return new ScrollbarParams( + GuiConstants_ECT.SCROLLBAR_POS_X, GuiConstants_ECT.SCROLLBAR_POS_Y, GuiConstants_ECT.SCROLLBAR_HEIGHT); + } + + /** + * Called when the player types a key. + */ + @Override + protected void keyTyped(final char key, final int keyID) { + // Pass the key to the search field. + this.searchBar.textboxKeyTyped(key, keyID); + + // Did they press the escape key? + if (keyID == Keyboard.KEY_ESCAPE) { + // Slot the screen. + this.mc.thePlayer.closeScreen(); + } else if (this.searchBar.isFocused()) { + // Get the search term + this.searchTerm = this.searchBar.getText().trim().toLowerCase(); + + // Re-search the widgets + this.updateView(); + } + // Disable numeric key hotbar swaping. + else if (!Character.isDigit(key)) { + super.keyTyped(key, keyID); + } + } + + /** + * Called when the player clicks the mouse. + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseBtn) { + // Boolean trackers for cleaner code + final boolean isLeftClick = (mouseBtn == ThEGuiHelper.MOUSE_BUTTON_LEFT); + final boolean isRightClick = (mouseBtn == ThEGuiHelper.MOUSE_BUTTON_RIGHT); + final boolean isMiddleClick = (mouseBtn == ThEGuiHelper.MOUSE_BUTTON_WHEEL); + + if (this.isMouseOverWidgetArea(mouseX, mouseY)) { + // Is the view mode crafting? + boolean viewingCraftable = (this.viewMode == ViewItems.CRAFTABLE); + + // Is the player holding anything? + boolean playerHoldingItem = (this.player.inventory.getItemStack() != null); + + // Check each widget + for (WidgetAspectSelector widget : this.aspectWidgets) { + // Is the mouse over this widget? + if (widget.isMouseOverWidget(mouseX, mouseY)) { + // Is the player holding something? + if (playerHoldingItem) { + // Inform the server + Packet_S_EssentiaCellTerminal.sendInteractWithHeldItem(this.player, widget.getAspect()); + } else { + // Check if the aspect is to be crafted + if ((!isRightClick && widget.hasAspect() && widget.getCraftable()) + && (viewingCraftable + || (isMiddleClick || (isLeftClick && (widget.getAmount() == 0))))) { + // Send request + Packet_S_EssentiaCellTerminal.sendAutoCraft(this.player, widget.getAspect()); + } + + // Send the click + widget.onMouseClicked(); + } + + // Stop searching + return; + } + } + } + + // Is the mouse over the search bar? + boolean mouseOverSearchBar = (mouseX >= this.searchBar.xPosition) + && (mouseX < (this.searchBar.xPosition + this.searchBar.width)) + && (mouseY >= this.searchBar.yPosition) + && (mouseY < (this.searchBar.yPosition + this.searchBar.height)); + if (mouseOverSearchBar) { + // Left click? + if (isLeftClick) { + // Pass to search field. + this.searchBar.mouseClicked(mouseX, mouseY, mouseBtn); + + // Done + return; + + } + // Right click? + else if (isRightClick) { + // Clear the search text + this.searchTerm = ""; + this.searchBar.setText(this.searchTerm); + + // Update the widgets + this.updateView(); + + // Done + return; + } + } + + // Call super + super.mouseClicked(mouseX, mouseY, mouseBtn); + } + + /** + * Called when a button is clicked. + */ + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Ignore all middle clicks. + if (mouseButton == ThEGuiHelper.MOUSE_BUTTON_WHEEL) { + return; + } + + // Is the button the sort mode button? + if (button == this.buttonSortingMode) { + // Request update from server + Packet_S_EssentiaCellTerminal.sendChangeSorting( + this.player, (mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT)); + } else if (button == this.buttonViewMode) { + // Request update from server + Packet_S_EssentiaCellTerminal.sendChangeView(this.player, (mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT)); + } + } + + @Override + protected void onMouseWheel(final int deltaZ, final int mouseX, final int mouseY) { + // Is the mouse inside of, or to the left of, the GUI? + if (mouseX > (this.guiLeft + GuiConstants_ECT.GUI_WIDTH)) { + // Mouse is to the right of the gui + return; + } + + // Is shift not being held down? + if (!GuiScreen.isShiftKeyDown()) { + // Inform the scroll bar + this.scrollBar.wheel(deltaZ); + this.onScrollbarMoved(); + } + } + + @Override + protected void onScrollbarMoved() { + // Set the scroll + this.currentScroll = this.scrollBar.getCurrentScroll(); + + // Mark for widget update + this.flagWidgetsNeedUpdate = true; + } + + /** + * Draw the widgets + * + * @param mouseX + * @param mouseY + */ + public void drawWidgets(final int mouseX, final int mouseY) { + // Do the widgets need to be updated? + if (this.flagWidgetsNeedUpdate) { + // Update first + this.updateWidgets(); + } + + // Anything to draw? + if (!this.matchingSearchStacks.isEmpty()) { + for (int widgetIndex = 0; widgetIndex < this.aspectWidgets.length; ++widgetIndex) { + // Get the widget + WidgetAspectSelector widget = this.aspectWidgets[widgetIndex]; + + // Does the widget not have an aspect? + if (!widget.hasAspect()) { + // Nothing more to draw + break; + } + + // Draw the widget + widget.drawWidget(); + + // Is the mouse over this widget? + if (this.tooltip.isEmpty() && widget.isMouseOverWidget(mouseX, mouseY)) { + // Get the tooltip from the widget + widget.getTooltip(this.tooltip); + } + } + } else { + this.currentScroll = 0; + } + } + + /** + * Gets the container associated with the gui + */ + @Override + public IAspectSelectorContainer getContainer() { + return this.baseContainer; + } + + /** + * Gets the currently selected aspect. + */ + @Override + public Aspect getSelectedAspect() { + return (this.selectedAspectStack != null ? this.selectedAspectStack.getAspect() : null); + } + + /** + * Sets the gui up. + */ + @Override + public void initGui() { + // Call super + super.initGui(); + + // Reset the mouse wheel state. + Mouse.getDWheel(); + + // Enable repeat keys + Keyboard.enableRepeatEvents(true); + + // Get the aspect list + this.onListUpdate(); + + // Set up the search bar + this.searchBar = new GuiTextField( + this.fontRendererObj, + this.guiLeft + GuiConstants_ECT.SEARCH_X_OFFSET, + this.guiTop + GuiConstants_ECT.SEARCH_Y_OFFSET, + GuiConstants_ECT.SEARCH_WIDTH, + GuiConstants_ECT.SEARCH_HEIGHT); + + // Set the search bar to draw in the foreground + this.searchBar.setEnableBackgroundDrawing(false); + + // Start focused + this.searchBar.setFocused(false); + + // Set maximum length + this.searchBar.setMaxStringLength(GuiConstants_ECT.SEARCH_MAX_CHARS); + + // Clear any existing buttons + this.buttonList.clear(); + + // Add the sort mode button + this.buttonSortingMode = new GuiButtonSortingMode( + 0, + this.guiLeft + GuiConstants_ECT.BUTTON_SORT_MODE_POS_X, + this.guiTop + GuiConstants_ECT.BUTTON_SORT_MODE_POS_Y, + GuiConstants_ECT.MODE_BUTTON_SIZE, + GuiConstants_ECT.MODE_BUTTON_SIZE); + this.buttonList.add(this.buttonSortingMode); + + // Add view type button + this.buttonViewMode = new GuiButtonViewType( + 1, + this.guiLeft + GuiConstants_ECT.BUTTON_VIEW_MODE_POS_X, + this.guiTop + GuiConstants_ECT.BUTTON_VIEW_MODE_POS_Y, + GuiConstants_ECT.MODE_BUTTON_SIZE, + GuiConstants_ECT.MODE_BUTTON_SIZE); + this.buttonList.add(this.buttonViewMode); + } + + /** + * Called when the gui is closing. + */ + @Override + public void onGuiClosed() { + // Call super + super.onGuiClosed(); + + // Disable repeat keys + Keyboard.enableRepeatEvents(false); + } + + /** + * Called when the server sends a full list of network aspects. + * + * @param aspectStackList + */ + public void onReceiveAspectList(final Collection aspectStackList) { + // Update the container + this.baseContainer.onReceivedAspectList(aspectStackList); + + // Update the gui + this.onListUpdate(); + } + + /** + * Called when an aspect in the list changes amount. + * + * @param change + */ + public void onReceiveAspectListChange(final IAspectStack change) { + // Update the container + this.baseContainer.onReceivedAspectListChange(change); + + // Update the gui + this.onListUpdate(); + } + + /** + * Called when the server sends a change to the selected aspect. + * + * @param selectedAspect + */ + public void onReceiveSelectedAspect(final Aspect selectedAspect) { + // Update the container + this.baseContainer.onReceivedSelectedAspect(selectedAspect); + + // Update the gui + this.updateSelectedAspect(); + } + + /** + * Called when the server sends a change in the sorting mode. + * + * @param sortMode + */ + public void onViewingModesChanged(final AspectStackComparatorMode sortMode, final ViewItems viewMode) { + // Update the sort button + this.buttonSortingMode.setSortMode(this.sortMode = sortMode); + + // Update view mode + this.buttonViewMode.setViewMode(this.viewMode = viewMode); + + // Update the view + this.updateView(); + } + + /** + * Called when a new view mode is sent. + * + * @param mode + */ + public void onViewModeChanged(final ViewItems mode) { + // Set the mode + this.viewMode = mode; + + // Update the view + this.updateView(); + + // Mark for widget update + this.flagWidgetsNeedUpdate = true; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellWorkbench.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellWorkbench.java index f76610d0..1d84a42b 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellWorkbench.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaCellWorkbench.java @@ -1,15 +1,13 @@ package thaumicenergistics.client.gui; -import java.util.List; - -import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IAspectSlotGui; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; @@ -31,289 +29,270 @@ import thaumicenergistics.common.tiles.TileEssentiaCellWorkbench; * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaCellWorkbench - extends ThEBaseGui - implements IAspectSlotGui -{ - private class SimpleAspectWidget - extends WidgetAspectSlot - { +public class GuiEssentiaCellWorkbench extends ThEBaseGui implements IAspectSlotGui { + private class SimpleAspectWidget extends WidgetAspectSlot { - public SimpleAspectWidget( final int ID, final int posX, final int posY, final EntityPlayer player ) - { - super( GuiEssentiaCellWorkbench.this, player, null, ID, posX, posY ); - } + public SimpleAspectWidget(final int ID, final int posX, final int posY, final EntityPlayer player) { + super(GuiEssentiaCellWorkbench.this, player, null, ID, posX, posY); + } - @Override - public void mouseClicked( final Aspect withAspect ) - { - // Ignored - } + @Override + public void mouseClicked(final Aspect withAspect) { + // Ignored + } + } - } + /** + * Gui size. + */ + private static final int GUI_WIDTH = 176, GUI_HEIGHT = 251; - /** - * Gui size. - */ - private static final int GUI_WIDTH = 176, GUI_HEIGHT = 251; + /** + * Title position. + */ + private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; - /** - * Title position. - */ - private static final int TITLE_POS_X = 6, TITLE_POS_Y = 6; + /** + * Widget starting position. + */ + private static final int WIDGET_POS_X = 7, WIDGET_POS_Y = 28; - /** - * Widget starting position. - */ - private static final int WIDGET_POS_X = 7, WIDGET_POS_Y = 28; + /** + * Number of widgets per row. + */ + private static final int WIDGETS_PER_ROW = 9; - /** - * Number of widgets per row. - */ - private static final int WIDGETS_PER_ROW = 9; + /** + * Number of widget rows. + */ + private static final int WIDGET_ROWS = 7; - /** - * Number of widget rows. - */ - private static final int WIDGET_ROWS = 7; + /** + * How many partition widgets to make. + */ + private static final int NUMBER_OF_WIDGETS = 63; - /** - * How many partition widgets to make. - */ - private static final int NUMBER_OF_WIDGETS = 63; + /** + * Cache the cell background icon. + */ + private static final AEStateIconsEnum CELL_BG_ICON = AEStateIconsEnum.ME_CELL_BACKGROUND; - /** - * Cache the cell background icon. - */ - private static final AEStateIconsEnum CELL_BG_ICON = AEStateIconsEnum.ME_CELL_BACKGROUND; + /** + * Partition to current, button info. + */ + private static final int BUTTON_PARTITION_CURRENT_ID = 0, + BUTTON_PARTITION_CURRENT_X = -18, + BUTTON_PARTITION_CURRENT_Y = 28; - /** - * Partition to current, button info. - */ - private static final int BUTTON_PARTITION_CURRENT_ID = 0, BUTTON_PARTITION_CURRENT_X = -18, BUTTON_PARTITION_CURRENT_Y = 28; + /** + * Clear partitioning, button info. + */ + private static final int BUTTON_CLEAR_ID = 1, BUTTON_CLEAR_X = -18, BUTTON_CLEAR_Y = 8; + /** + * The player viewing the gui. + */ + private final EntityPlayer player; - /** - * Clear partitioning, button info. - */ - private static final int BUTTON_CLEAR_ID = 1, BUTTON_CLEAR_X = -18, BUTTON_CLEAR_Y = 8; - /** - * The player viewing the gui. - */ - private final EntityPlayer player; + /** + * Title of the window + */ + private final String title; - /** - * Title of the window - */ - private final String title; + /** + * Array of aspect widgets used to show partition aspects. + */ + private final SimpleAspectWidget[] partitionWidgets; - /** - * Array of aspect widgets used to show partition aspects. - */ - private final SimpleAspectWidget[] partitionWidgets; + /** + * Cell Workbench. + */ + public final TileEssentiaCellWorkbench workbench; - /** - * Cell Workbench. - */ - public final TileEssentiaCellWorkbench workbench; + public GuiEssentiaCellWorkbench( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(new ContainerEssentiaCellWorkbench(player, world, x, y, z)); - public GuiEssentiaCellWorkbench( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( new ContainerEssentiaCellWorkbench( player, world, x, y, z ) ); + // Set the player + this.player = player; - // Set the player - this.player = player; + // Set the width and height + this.xSize = GuiEssentiaCellWorkbench.GUI_WIDTH; + this.ySize = GuiEssentiaCellWorkbench.GUI_HEIGHT; - // Set the width and height - this.xSize = GuiEssentiaCellWorkbench.GUI_WIDTH; - this.ySize = GuiEssentiaCellWorkbench.GUI_HEIGHT; + // Set the title + this.title = ThEStrings.Gui_TitleEssentiaCellWorkbench.getLocalized(); - // Set the title - this.title = ThEStrings.Gui_TitleEssentiaCellWorkbench.getLocalized(); + // Create the widget array + this.partitionWidgets = new SimpleAspectWidget[GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS]; - // Create the widget array - this.partitionWidgets = new SimpleAspectWidget[GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS]; + // Get the workbench + this.workbench = ((ContainerEssentiaCellWorkbench) this.inventorySlots).workbench; + } - // Get the workbench - this.workbench = ( (ContainerEssentiaCellWorkbench)this.inventorySlots ).workbench; - } + /** + * Draw background + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - /** - * Draw background - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + // Bind the workbench gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.CELL_WORKBENCH.getTexture()); - // Bind the workbench gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.CELL_WORKBENCH.getTexture() ); + // Draw the gui texture + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - // Draw the gui texture - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); + // Bind the AE states texture + Minecraft.getMinecraft().renderEngine.bindTexture(AEStateIconsEnum.AE_STATES_TEXTURE); - // Bind the AE states texture - Minecraft.getMinecraft().renderEngine.bindTexture( AEStateIconsEnum.AE_STATES_TEXTURE ); + // Draw the cell slot background + this.drawTexturedModalRect( + this.guiLeft + ContainerEssentiaCellWorkbench.CELL_SLOT_X, + this.guiTop + ContainerEssentiaCellWorkbench.CELL_SLOT_Y, + GuiEssentiaCellWorkbench.CELL_BG_ICON.getU(), + GuiEssentiaCellWorkbench.CELL_BG_ICON.getV(), + GuiEssentiaCellWorkbench.CELL_BG_ICON.getWidth(), + GuiEssentiaCellWorkbench.CELL_BG_ICON.getHeight()); + } - // Draw the cell slot background - this.drawTexturedModalRect( this.guiLeft + ContainerEssentiaCellWorkbench.CELL_SLOT_X, this.guiTop + - ContainerEssentiaCellWorkbench.CELL_SLOT_Y, - GuiEssentiaCellWorkbench.CELL_BG_ICON.getU(), - GuiEssentiaCellWorkbench.CELL_BG_ICON.getV(), GuiEssentiaCellWorkbench.CELL_BG_ICON.getWidth(), - GuiEssentiaCellWorkbench.CELL_BG_ICON.getHeight() ); + /** + * Draw the foreground + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString( + this.title, GuiEssentiaCellWorkbench.TITLE_POS_X, GuiEssentiaCellWorkbench.TITLE_POS_Y, 0); - } + // Draw the widgets + SimpleAspectWidget widgetUnderMouse = null, currentWidget; + for (int index = 0; index < GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS; index++) { + // Get the widget + currentWidget = this.partitionWidgets[index]; - /** - * Draw the foreground - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( this.title, GuiEssentiaCellWorkbench.TITLE_POS_X, GuiEssentiaCellWorkbench.TITLE_POS_Y, 0 ); + // Draw the widget + currentWidget.drawWidget(); - // Draw the widgets - SimpleAspectWidget widgetUnderMouse = null, currentWidget; - for( int index = 0; index < GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS; index++ ) - { - // Get the widget - currentWidget = this.partitionWidgets[index]; + // Is the mouse over it? + if ((widgetUnderMouse == null) && (currentWidget.isMouseOverWidget(mouseX, mouseY))) { + // Mark this widget as the one under the mouse + widgetUnderMouse = currentWidget; + } + } - // Draw the widget - currentWidget.drawWidget(); + // Is there a widget under the mouse? + if (widgetUnderMouse != null) { + // Get the widgets tooltip + widgetUnderMouse.getTooltip(this.tooltip); + } + } - // Is the mouse over it? - if( ( widgetUnderMouse == null ) && ( currentWidget.isMouseOverWidget( mouseX, mouseY ) ) ) - { - // Mark this widget as the one under the mouse - widgetUnderMouse = currentWidget; - } - } + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Call super + super.mouseClicked(mouseX, mouseY, mouseButton); - // Is there a widget under the mouse? - if( widgetUnderMouse != null ) - { - // Get the widgets tooltip - widgetUnderMouse.getTooltip( this.tooltip ); - } - } + for (SimpleAspectWidget partitionWidget : this.partitionWidgets) { + if (partitionWidget.isMouseOverWidget(mouseX, mouseY)) { + // Get the aspect of the currently held item + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( + this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Call super - super.mouseClicked( mouseX, mouseY, mouseButton ); + // Get the aspect of the widget + Aspect widgetAspect = partitionWidget.getAspect(); - for( SimpleAspectWidget partitionWidget : this.partitionWidgets ) - { - if( partitionWidget.isMouseOverWidget( mouseX, mouseY ) ) - { - // Get the aspect of the currently held item - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); + // Add? + if ((widgetAspect == null) && (itemAspect != null)) { + Packet_S_EssentiaCellWorkbench.sendAddAspect(this.player, this.workbench, itemAspect); + } + // Remove? + else if ((widgetAspect != null) && (itemAspect == null)) { + Packet_S_EssentiaCellWorkbench.sendRemoveAspect(this.player, this.workbench, widgetAspect); - // Get the aspect of the widget - Aspect widgetAspect = partitionWidget.getAspect(); + } + // Replace? + else if ((widgetAspect != null) && (itemAspect != null)) { + Packet_S_EssentiaCellWorkbench.sendReplaceAspect( + this.player, this.workbench, widgetAspect, itemAspect); + } - // Add? - if( ( widgetAspect == null ) && ( itemAspect != null ) ) - { - Packet_S_EssentiaCellWorkbench.sendAddAspect( this.player, this.workbench, itemAspect ); - } - // Remove? - else if( ( widgetAspect != null ) && ( itemAspect == null ) ) - { - Packet_S_EssentiaCellWorkbench.sendRemoveAspect( this.player, this.workbench, widgetAspect ); + // Stop searching + break; + } + } + this.draggedStack = null; + } - } - // Replace? - else if( ( widgetAspect != null ) && ( itemAspect != null ) ) - { - Packet_S_EssentiaCellWorkbench.sendReplaceAspect( this.player, this.workbench, widgetAspect, itemAspect ); + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Which button was clicked? + switch (button.id) { + case GuiEssentiaCellWorkbench.BUTTON_CLEAR_ID: + Packet_S_EssentiaCellWorkbench.sendClearPartitioning(this.player, this.workbench); + break; - } + case GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_ID: + Packet_S_EssentiaCellWorkbench.sendPartitionToContents(this.player, this.workbench); + break; + } + } - // Stop searching - break; - } - } - this.draggedStack = null; - } + @Override + public void initGui() { + // Call super + super.initGui(); - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Which button was clicked? - switch ( button.id ) - { - case GuiEssentiaCellWorkbench.BUTTON_CLEAR_ID: - Packet_S_EssentiaCellWorkbench.sendClearPartitioning( this.player, this.workbench ); - break; + // Create the widgets + for (int y = 0; y < GuiEssentiaCellWorkbench.WIDGET_ROWS; y++) { + // Calculate the Y position of this row + int rowYPosition = GuiEssentiaCellWorkbench.WIDGET_POS_Y + (y * 18); - case GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_ID: - Packet_S_EssentiaCellWorkbench.sendPartitionToContents( this.player, this.workbench ); - break; - } - } + for (int x = 0; x < GuiEssentiaCellWorkbench.WIDGETS_PER_ROW; x++) { + // Calculate the X position of the widget + int wPosX = GuiEssentiaCellWorkbench.WIDGET_POS_X + (x * 18); - @Override - public void initGui() - { - // Call super - super.initGui(); + // Calculate the index of the widget + int wIndex = (x + (y * GuiEssentiaCellWorkbench.WIDGETS_PER_ROW)); - // Create the widgets - for( int y = 0; y < GuiEssentiaCellWorkbench.WIDGET_ROWS; y++ ) - { - // Calculate the Y position of this row - int rowYPosition = GuiEssentiaCellWorkbench.WIDGET_POS_Y + ( y * 18 ); + // Create the widget + this.partitionWidgets[wIndex] = new SimpleAspectWidget(wIndex, wPosX, rowYPosition, this.player); + } + } - for( int x = 0; x < GuiEssentiaCellWorkbench.WIDGETS_PER_ROW; x++ ) - { - // Calculate the X position of the widget - int wPosX = GuiEssentiaCellWorkbench.WIDGET_POS_X + ( x * 18 ); + // Create the un-partition button + this.buttonList.add(new GuiButtonSetCellPartitioningToCurrent( + GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_ID, + this.guiLeft + GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_X, + this.guiTop + GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_Y)); - // Calculate the index of the widget - int wIndex = ( x + ( y * GuiEssentiaCellWorkbench.WIDGETS_PER_ROW ) ); + // Create the partition to current button + this.buttonList.add(new GuiButtonClearCellPartitioning( + GuiEssentiaCellWorkbench.BUTTON_CLEAR_ID, + this.guiLeft + GuiEssentiaCellWorkbench.BUTTON_CLEAR_X, + this.guiTop + GuiEssentiaCellWorkbench.BUTTON_CLEAR_Y)); - // Create the widget - this.partitionWidgets[wIndex] = new SimpleAspectWidget( wIndex, wPosX, rowYPosition, this.player ); - } - } + // Request the list + Packet_S_EssentiaCellWorkbench.sendGetPartitionList(this.player, this.workbench); + } - // Create the un-partition button - this.buttonList.add( new GuiButtonSetCellPartitioningToCurrent( GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_ID, this.guiLeft + - GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_X, this.guiTop + GuiEssentiaCellWorkbench.BUTTON_PARTITION_CURRENT_Y ) ); + /** + * Updates the partition widgets to show the aspects in the specified list. + */ + @Override + public void updateAspects(final List aspectList) { + // Get the number of aspects in the list + int count = aspectList.size(); - // Create the partition to current button - this.buttonList.add( new GuiButtonClearCellPartitioning( GuiEssentiaCellWorkbench.BUTTON_CLEAR_ID, this.guiLeft + - GuiEssentiaCellWorkbench.BUTTON_CLEAR_X, this.guiTop + GuiEssentiaCellWorkbench.BUTTON_CLEAR_Y ) ); - - // Request the list - Packet_S_EssentiaCellWorkbench.sendGetPartitionList( this.player, this.workbench ); - } - - /** - * Updates the partition widgets to show the aspects in the specified list. - */ - @Override - public void updateAspects( final List aspectList ) - { - // Get the number of aspects in the list - int count = aspectList.size(); - - // Set the aspects - for( int index = 0; index < count; index++ ) - { - this.partitionWidgets[index].setAspect( aspectList.get( index ), 1, false ); - } - - // Clear the rest - for( int index = count; index < GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS; index++ ) - { - this.partitionWidgets[index].setAspect( null ); - } - } + // Set the aspects + for (int index = 0; index < count; index++) { + this.partitionWidgets[index].setAspect(aspectList.get(index), 1, false); + } + // Clear the rest + for (int index = count; index < GuiEssentiaCellWorkbench.NUMBER_OF_WIDGETS; index++) { + this.partitionWidgets[index].setAspect(null); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaIO.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaIO.java index c96b74d2..3ca2f05e 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaIO.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaIO.java @@ -1,16 +1,14 @@ package thaumicenergistics.client.gui; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; import appeng.api.config.RedstoneMode; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IAspectSlotGui; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; @@ -35,477 +33,455 @@ import thaumicenergistics.common.parts.ThEPartEssentiaIOBus_Base; * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaIO - extends ThEBaseGui - implements WidgetAspectSlot.IConfigurable, IAspectSlotGui -{ - - /** - * Number of rows and columns in the filter grid. - */ - private static final int FILTER_GRID_SIZE = 3; - - /** - * Controls if the widget is drawn. - * if filterSize >= this, the widget can be drawn. - */ - private static final byte[] WIDGET_CONFIG_BYTES = new byte[] { 2, 1, 2, 1, 0, 1, 2, 1, 2 }; - - /** - * Starting X position for widgets. - */ - private static final int WIDGET_X_POSITION = 61; - - /** - * Starting Y position for widgets. - */ - private static final int WIDGET_Y_POSITION = 21; - - /** - * Height of the gui - */ - private static final int GUI_HEIGHT = 184; - - /** - * Width of the gui when the player does not have a network tool. - */ - private static final int GUI_WIDTH_NO_TOOL = 211; - - /** - * Width of the gui when the player has a network tool. - */ - private static final int GUI_WIDTH_WITH_TOOL = 246; - - /** - * Width of the main body of the gui. - * Ignores upgrade and network tool areas. - */ - private static final int GUI_MAIN_WIDTH = 176; - - /** - * Width of the upgrade area of the gui. - */ - private static final int GUI_UPGRADES_WIDTH = 35; - - /** - * Height of the upgrade area of the gui. - */ - private static final int GUI_UPGRADES_HEIGHT = 86; - - /** - * Position of the title string. - */ - private static final int TITLE_POS_X = 6, TITLE_POS_Y = 5; - - /** - * Redstone Control button placement - */ - private static final int REDSTONE_CONTROL_BUTTON_POS_Y = 2, REDSTONE_CONTROL_BUTTON_POS_X = -18, REDSTONE_CONTROL_BUTTON_SIZE = 16, - REDSTONE_CONTROL_BUTTON_ID = 0; - - /** - * Void button placement - */ - private static final int ALLOW_VOID_BUTTON_POS_Y = 2, ALLOW_VOID_BUTTON_POS_X = -19, ALLOW_VOID_BUTTON_ID = 1; - - private static final int CRAFTING_MODE_BUTTON_POS_Y = 40, CRAFTING_MODE_BUTTON_POS_X = -18, CRAFTING_MODE_BUTTON_ID = 2; - - /** - * The part associated with this gui. - */ - private ThEPartEssentiaIOBus_Base part; - - /** - * The player viewing this bus gui. - */ - private EntityPlayer player; - - /** - * The size of the buses filter (0-2). - */ - private byte filterSize; - - /** - * Filter widgets. - */ - private List aspectSlotList = new ArrayList(); - - /** - * Filter aspects. - */ - private List filteredAspects = new ArrayList(); - - /** - * True if the player has a network tool in their inventory. - */ - private boolean hasNetworkTool; - - /** - * Tracks the redstone mode of the bus. - */ - private RedstoneMode redstoneMode = RedstoneMode.HIGH_SIGNAL; - - /** - * Title of the gui - */ - private final String guiTitle; - - /** - * Shown when the bus is redstone controlled - */ - private GuiButtonRedstoneModes redstoneControlButton = null; - - /** - * Button controlling if voiding is allowed. - */ - private GuiButtonAllowVoid voidModeButton = null; - - /** - * Shown when the bus has crafting card - */ - private GuiButtonCraftingMode craftingModeButton = null; - - /** - * Creates the gui - * - * @param partBus - * @param player - */ - public GuiEssentiaIO( final ThEPartEssentiaIOBus_Base partBus, final EntityPlayer player ) - { - // Call super - super( new ContainerPartEssentiaIOBus( partBus, player ) ); - - // Set the bus - this.part = partBus; - - // Set the player - this.player = player; - - // Check if the player has a network tool - this.hasNetworkTool = ( (ContainerPartEssentiaIOBus)this.inventorySlots ).hasNetworkTool(); - - // Set the width - this.xSize = ( this.hasNetworkTool ? GuiEssentiaIO.GUI_WIDTH_WITH_TOOL : GuiEssentiaIO.GUI_WIDTH_NO_TOOL ); - - // Set the height - this.ySize = GuiEssentiaIO.GUI_HEIGHT; - - // Set the title - if( partBus instanceof PartEssentiaImportBus ) - { - // Import - this.guiTitle = AEPartsEnum.EssentiaImportBus.getLocalizedName(); - } - else if( partBus instanceof PartEssentiaExportBus ) - { - // Export - this.guiTitle = AEPartsEnum.EssentiaExportBus.getLocalizedName(); - } - else - { - this.guiTitle = ""; - } - } - - /** - * Draws the GUI background layer - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - // Get the GUI texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_IO_BUS.getTexture() ); - - // Does the user have a network tool? - if( this.hasNetworkTool ) - { - // Draw the full gui - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, GuiEssentiaIO.GUI_WIDTH_WITH_TOOL, GuiEssentiaIO.GUI_HEIGHT ); - } - else - { - // Draw main gui - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, GuiEssentiaIO.GUI_MAIN_WIDTH, GuiEssentiaIO.GUI_HEIGHT ); - - // Draw upgrade slots - this.drawTexturedModalRect( this.guiLeft + GuiEssentiaIO.GUI_MAIN_WIDTH, this.guiTop, GuiEssentiaIO.GUI_MAIN_WIDTH, 0, - GuiEssentiaIO.GUI_UPGRADES_WIDTH, GuiEssentiaIO.GUI_UPGRADES_HEIGHT ); - } - - // Call super - super.drawAEToolAndUpgradeSlots( alpha, mouseX, mouseY ); - } - - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Call super - super.drawGuiContainerForegroundLayer( mouseX, mouseY ); - - // Draw the title - this.fontRendererObj.drawString( this.guiTitle, GuiEssentiaIO.TITLE_POS_X, GuiEssentiaIO.TITLE_POS_Y, 0x000000 ); - - boolean hoverUnderlayRendered = false; - - WidgetAspectSlot slotUnderMouse = null; - - for( int i = 0; i < 9; i++ ) - { - WidgetAspectSlot slotWidget = this.aspectSlotList.get( i ); - - if( ( !hoverUnderlayRendered ) && ( slotWidget.canRender() ) && ( slotWidget.isMouseOverWidget( mouseX, mouseY ) ) ) - { - slotWidget.drawMouseHoverUnderlay(); - - slotUnderMouse = slotWidget; - - hoverUnderlayRendered = true; - } - - slotWidget.drawWidget(); - } - - // Should we get the tooltip from the slot? - if( slotUnderMouse != null ) - { - // Add the tooltip from the widget - slotUnderMouse.getTooltip( this.tooltip ); - } - } - - /** - * Called when the mouse is clicked. - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Call super - super.mouseClicked( mouseX, mouseY, mouseButton ); - - // Loop over all widgets - for( WidgetAspectSlot aspectSlot : this.aspectSlotList ) - { - // Is the mouse over this widget? - if( aspectSlot.isMouseOverWidget( mouseX, mouseY ) ) - { - // Get the aspect of the currently held item - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); - - // Is there an aspect? - if( itemAspect != null ) - { - // Are we already filtering for this aspect? - if( this.filteredAspects.contains( itemAspect ) ) - { - // Ignore - return; - } - - } - - // Inform the slot it was clicked - aspectSlot.mouseClicked( itemAspect ); - - // Stop searching - break; - } - } - this.draggedStack = null; - } - - /** - * Called when a button is pressed - */ - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Was the clicked button the redstone mode button? - if( button.id == GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_ID ) - { - Packet_S_EssentiaIOBus.sendRedstoneModeChange( this.player, this.part ); - } - // Void button? - else if( button.id == GuiEssentiaIO.ALLOW_VOID_BUTTON_ID ) - { - if( this.part instanceof PartEssentiaExportBus ) - { - Packet_S_EssentiaIOBus.sendVoidModeChange( this.player, (PartEssentiaExportBus)this.part ); - } - } - else if( button.id == GuiEssentiaIO.CRAFTING_MODE_BUTTON_ID ) - { - if( this.part instanceof PartEssentiaExportBus ) - { - Packet_S_EssentiaIOBus.sendCraftingModeChange( this.player, this.part ); - } - } - } - - @Override - public byte getConfigState() - { - return this.filterSize; - } - - /** - * Sets the gui up. - */ - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Add the slots - for( int row = 0; row < GuiEssentiaIO.FILTER_GRID_SIZE; row++ ) - { - for( int column = 0; column < GuiEssentiaIO.FILTER_GRID_SIZE; column++ ) - { - // Calculate the index - int index = ( row * GuiEssentiaIO.FILTER_GRID_SIZE ) + column; - - // Calculate the x position - int xPos = GuiEssentiaIO.WIDGET_X_POSITION + ( column * ThEWidget.WIDGET_SIZE ); - - // Calculate the y position - int yPos = GuiEssentiaIO.WIDGET_Y_POSITION + ( row * ThEWidget.WIDGET_SIZE ); - - this.aspectSlotList.add( new WidgetAspectSlot( this, this.player, this.part, index, xPos, yPos, this, - GuiEssentiaIO.WIDGET_CONFIG_BYTES[index] ) ); - } - } - - // Create the redstone control button - this.redstoneControlButton = new GuiButtonRedstoneModes( GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_ID, this.guiLeft + - GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_POS_X, this.guiTop + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_POS_Y, - GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_SIZE, GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_SIZE, this.redstoneMode, false ); - - // Create the allow void button if export bus - if( this.part instanceof PartEssentiaExportBus ) - { - this.voidModeButton = new GuiButtonAllowVoid( GuiEssentiaIO.ALLOW_VOID_BUTTON_ID, this.guiLeft + GuiEssentiaIO.ALLOW_VOID_BUTTON_POS_X, - this.guiTop + GuiEssentiaIO.ALLOW_VOID_BUTTON_POS_Y ); - this.buttonList.add( this.voidModeButton ); - - craftingModeButton = new GuiButtonCraftingMode(CRAFTING_MODE_BUTTON_ID, this.guiLeft +CRAFTING_MODE_BUTTON_POS_X, this.guiTop + CRAFTING_MODE_BUTTON_POS_Y, 16, 16); - } - - // Request a full update from the server - Packet_S_EssentiaIOBus.sendRequestFilterList( this.player, this.part ); - } - - /** - * Called when the server sends a filter size update. - * - * @param filterSize - */ - public void onReceiveFilterSize( final byte filterSize ) - { - // Inform our part - this.part.onReceiveFilterSize( filterSize ); - - this.filterSize = filterSize; - - for (WidgetAspectSlot slot : this.aspectSlotList) { - if (!slot.canRender()) { - slot.setAspect(null); - } - - } - } - - /** - * Called when the server sends if the bus is redstone controlled. - * - * @param newRedstoneControled - */ - public void onReceiveRedstoneControlled( final boolean newRedstoneControled ) - { - // Show/hide the redstone control button - if( newRedstoneControled && !this.buttonList.contains( this.redstoneControlButton ) ) - { - // Remove from the list - this.buttonList.add( this.redstoneControlButton ); - - // Adjust void mode button Y - if( this.voidModeButton != null ) - { - this.voidModeButton.yPosition += 18; - } - } - else if( !newRedstoneControled && this.buttonList.contains( this.redstoneControlButton ) ) - { - // Add to list - this.buttonList.remove( this.redstoneControlButton ); - - // Adjust void mode button Y - if( this.voidModeButton != null ) - { - this.voidModeButton.yPosition -= 18; - } - } - } - - public void onReceiveRedstoneMode( final RedstoneMode redstoneMode ) - { - // Set the button state - this.redstoneControlButton.setRedstoneMode( redstoneMode ); - - // Mark the mode - this.redstoneMode = redstoneMode; - } - - public void onReceiveHasCrafting( final boolean hasCrafting ) - { - if (hasCrafting && !buttonList.contains(craftingModeButton)) - { - buttonList.add(craftingModeButton); - } - else if (!hasCrafting && buttonList.contains(craftingModeButton)) - { - buttonList.remove(craftingModeButton); - } - } - public void onReceiveCraftingOnly( final boolean craftingOnly ) - { - if (craftingModeButton != null) - { - craftingModeButton.setAlwaysCraft(craftingOnly); - } - } - /** - * Called when the server sends the void mode status - * - * @param isVoidAllowed - */ - public void onServerSendVoidMode( final boolean isVoidAllowed ) - { - // Set the void mode if there is a void button - if( this.voidModeButton != null ) - { - this.voidModeButton.setIsVoidAllowed( isVoidAllowed ); - } - } - - @Override - public void updateAspects( final List aspectList ) - { - // Inform our part - this.part.onReceiveFilterList( aspectList ); - - int count = Math.min( this.aspectSlotList.size(), aspectList.size() ); - - for( int i = 0; i < count; i++ ) - { - this.aspectSlotList.get( i ).setAspect( aspectList.get( i ), 1, false ); - } - - this.filteredAspects = aspectList; - - } - +public class GuiEssentiaIO extends ThEBaseGui implements WidgetAspectSlot.IConfigurable, IAspectSlotGui { + + /** + * Number of rows and columns in the filter grid. + */ + private static final int FILTER_GRID_SIZE = 3; + + /** + * Controls if the widget is drawn. + * if filterSize >= this, the widget can be drawn. + */ + private static final byte[] WIDGET_CONFIG_BYTES = new byte[] {2, 1, 2, 1, 0, 1, 2, 1, 2}; + + /** + * Starting X position for widgets. + */ + private static final int WIDGET_X_POSITION = 61; + + /** + * Starting Y position for widgets. + */ + private static final int WIDGET_Y_POSITION = 21; + + /** + * Height of the gui + */ + private static final int GUI_HEIGHT = 184; + + /** + * Width of the gui when the player does not have a network tool. + */ + private static final int GUI_WIDTH_NO_TOOL = 211; + + /** + * Width of the gui when the player has a network tool. + */ + private static final int GUI_WIDTH_WITH_TOOL = 246; + + /** + * Width of the main body of the gui. + * Ignores upgrade and network tool areas. + */ + private static final int GUI_MAIN_WIDTH = 176; + + /** + * Width of the upgrade area of the gui. + */ + private static final int GUI_UPGRADES_WIDTH = 35; + + /** + * Height of the upgrade area of the gui. + */ + private static final int GUI_UPGRADES_HEIGHT = 86; + + /** + * Position of the title string. + */ + private static final int TITLE_POS_X = 6, TITLE_POS_Y = 5; + + /** + * Redstone Control button placement + */ + private static final int REDSTONE_CONTROL_BUTTON_POS_Y = 2, + REDSTONE_CONTROL_BUTTON_POS_X = -18, + REDSTONE_CONTROL_BUTTON_SIZE = 16, + REDSTONE_CONTROL_BUTTON_ID = 0; + + /** + * Void button placement + */ + private static final int ALLOW_VOID_BUTTON_POS_Y = 2, ALLOW_VOID_BUTTON_POS_X = -19, ALLOW_VOID_BUTTON_ID = 1; + + private static final int CRAFTING_MODE_BUTTON_POS_Y = 40, + CRAFTING_MODE_BUTTON_POS_X = -18, + CRAFTING_MODE_BUTTON_ID = 2; + + /** + * The part associated with this gui. + */ + private ThEPartEssentiaIOBus_Base part; + + /** + * The player viewing this bus gui. + */ + private EntityPlayer player; + + /** + * The size of the buses filter (0-2). + */ + private byte filterSize; + + /** + * Filter widgets. + */ + private List aspectSlotList = new ArrayList(); + + /** + * Filter aspects. + */ + private List filteredAspects = new ArrayList(); + + /** + * True if the player has a network tool in their inventory. + */ + private boolean hasNetworkTool; + + /** + * Tracks the redstone mode of the bus. + */ + private RedstoneMode redstoneMode = RedstoneMode.HIGH_SIGNAL; + + /** + * Title of the gui + */ + private final String guiTitle; + + /** + * Shown when the bus is redstone controlled + */ + private GuiButtonRedstoneModes redstoneControlButton = null; + + /** + * Button controlling if voiding is allowed. + */ + private GuiButtonAllowVoid voidModeButton = null; + + /** + * Shown when the bus has crafting card + */ + private GuiButtonCraftingMode craftingModeButton = null; + + /** + * Creates the gui + * + * @param partBus + * @param player + */ + public GuiEssentiaIO(final ThEPartEssentiaIOBus_Base partBus, final EntityPlayer player) { + // Call super + super(new ContainerPartEssentiaIOBus(partBus, player)); + + // Set the bus + this.part = partBus; + + // Set the player + this.player = player; + + // Check if the player has a network tool + this.hasNetworkTool = ((ContainerPartEssentiaIOBus) this.inventorySlots).hasNetworkTool(); + + // Set the width + this.xSize = (this.hasNetworkTool ? GuiEssentiaIO.GUI_WIDTH_WITH_TOOL : GuiEssentiaIO.GUI_WIDTH_NO_TOOL); + + // Set the height + this.ySize = GuiEssentiaIO.GUI_HEIGHT; + + // Set the title + if (partBus instanceof PartEssentiaImportBus) { + // Import + this.guiTitle = AEPartsEnum.EssentiaImportBus.getLocalizedName(); + } else if (partBus instanceof PartEssentiaExportBus) { + // Export + this.guiTitle = AEPartsEnum.EssentiaExportBus.getLocalizedName(); + } else { + this.guiTitle = ""; + } + } + + /** + * Draws the GUI background layer + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Get the GUI texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_IO_BUS.getTexture()); + + // Does the user have a network tool? + if (this.hasNetworkTool) { + // Draw the full gui + this.drawTexturedModalRect( + this.guiLeft, this.guiTop, 0, 0, GuiEssentiaIO.GUI_WIDTH_WITH_TOOL, GuiEssentiaIO.GUI_HEIGHT); + } else { + // Draw main gui + this.drawTexturedModalRect( + this.guiLeft, this.guiTop, 0, 0, GuiEssentiaIO.GUI_MAIN_WIDTH, GuiEssentiaIO.GUI_HEIGHT); + + // Draw upgrade slots + this.drawTexturedModalRect( + this.guiLeft + GuiEssentiaIO.GUI_MAIN_WIDTH, + this.guiTop, + GuiEssentiaIO.GUI_MAIN_WIDTH, + 0, + GuiEssentiaIO.GUI_UPGRADES_WIDTH, + GuiEssentiaIO.GUI_UPGRADES_HEIGHT); + } + + // Call super + super.drawAEToolAndUpgradeSlots(alpha, mouseX, mouseY); + } + + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Call super + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + + // Draw the title + this.fontRendererObj.drawString(this.guiTitle, GuiEssentiaIO.TITLE_POS_X, GuiEssentiaIO.TITLE_POS_Y, 0x000000); + + boolean hoverUnderlayRendered = false; + + WidgetAspectSlot slotUnderMouse = null; + + for (int i = 0; i < 9; i++) { + WidgetAspectSlot slotWidget = this.aspectSlotList.get(i); + + if ((!hoverUnderlayRendered) + && (slotWidget.canRender()) + && (slotWidget.isMouseOverWidget(mouseX, mouseY))) { + slotWidget.drawMouseHoverUnderlay(); + + slotUnderMouse = slotWidget; + + hoverUnderlayRendered = true; + } + + slotWidget.drawWidget(); + } + + // Should we get the tooltip from the slot? + if (slotUnderMouse != null) { + // Add the tooltip from the widget + slotUnderMouse.getTooltip(this.tooltip); + } + } + + /** + * Called when the mouse is clicked. + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Call super + super.mouseClicked(mouseX, mouseY, mouseButton); + + // Loop over all widgets + for (WidgetAspectSlot aspectSlot : this.aspectSlotList) { + // Is the mouse over this widget? + if (aspectSlot.isMouseOverWidget(mouseX, mouseY)) { + // Get the aspect of the currently held item + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( + this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); + + // Is there an aspect? + if (itemAspect != null) { + // Are we already filtering for this aspect? + if (this.filteredAspects.contains(itemAspect)) { + // Ignore + return; + } + } + + // Inform the slot it was clicked + aspectSlot.mouseClicked(itemAspect); + + // Stop searching + break; + } + } + this.draggedStack = null; + } + + /** + * Called when a button is pressed + */ + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Was the clicked button the redstone mode button? + if (button.id == GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_ID) { + Packet_S_EssentiaIOBus.sendRedstoneModeChange(this.player, this.part); + } + // Void button? + else if (button.id == GuiEssentiaIO.ALLOW_VOID_BUTTON_ID) { + if (this.part instanceof PartEssentiaExportBus) { + Packet_S_EssentiaIOBus.sendVoidModeChange(this.player, (PartEssentiaExportBus) this.part); + } + } else if (button.id == GuiEssentiaIO.CRAFTING_MODE_BUTTON_ID) { + if (this.part instanceof PartEssentiaExportBus) { + Packet_S_EssentiaIOBus.sendCraftingModeChange(this.player, this.part); + } + } + } + + @Override + public byte getConfigState() { + return this.filterSize; + } + + /** + * Sets the gui up. + */ + @Override + public void initGui() { + // Call super + super.initGui(); + + // Add the slots + for (int row = 0; row < GuiEssentiaIO.FILTER_GRID_SIZE; row++) { + for (int column = 0; column < GuiEssentiaIO.FILTER_GRID_SIZE; column++) { + // Calculate the index + int index = (row * GuiEssentiaIO.FILTER_GRID_SIZE) + column; + + // Calculate the x position + int xPos = GuiEssentiaIO.WIDGET_X_POSITION + (column * ThEWidget.WIDGET_SIZE); + + // Calculate the y position + int yPos = GuiEssentiaIO.WIDGET_Y_POSITION + (row * ThEWidget.WIDGET_SIZE); + + this.aspectSlotList.add(new WidgetAspectSlot( + this, + this.player, + this.part, + index, + xPos, + yPos, + this, + GuiEssentiaIO.WIDGET_CONFIG_BYTES[index])); + } + } + + // Create the redstone control button + this.redstoneControlButton = new GuiButtonRedstoneModes( + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_ID, + this.guiLeft + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_POS_X, + this.guiTop + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_POS_Y, + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_SIZE, + GuiEssentiaIO.REDSTONE_CONTROL_BUTTON_SIZE, + this.redstoneMode, + false); + + // Create the allow void button if export bus + if (this.part instanceof PartEssentiaExportBus) { + this.voidModeButton = new GuiButtonAllowVoid( + GuiEssentiaIO.ALLOW_VOID_BUTTON_ID, + this.guiLeft + GuiEssentiaIO.ALLOW_VOID_BUTTON_POS_X, + this.guiTop + GuiEssentiaIO.ALLOW_VOID_BUTTON_POS_Y); + this.buttonList.add(this.voidModeButton); + + craftingModeButton = new GuiButtonCraftingMode( + CRAFTING_MODE_BUTTON_ID, + this.guiLeft + CRAFTING_MODE_BUTTON_POS_X, + this.guiTop + CRAFTING_MODE_BUTTON_POS_Y, + 16, + 16); + } + + // Request a full update from the server + Packet_S_EssentiaIOBus.sendRequestFilterList(this.player, this.part); + } + + /** + * Called when the server sends a filter size update. + * + * @param filterSize + */ + public void onReceiveFilterSize(final byte filterSize) { + // Inform our part + this.part.onReceiveFilterSize(filterSize); + + this.filterSize = filterSize; + + for (WidgetAspectSlot slot : this.aspectSlotList) { + if (!slot.canRender()) { + slot.setAspect(null); + } + } + } + + /** + * Called when the server sends if the bus is redstone controlled. + * + * @param newRedstoneControled + */ + public void onReceiveRedstoneControlled(final boolean newRedstoneControled) { + // Show/hide the redstone control button + if (newRedstoneControled && !this.buttonList.contains(this.redstoneControlButton)) { + // Remove from the list + this.buttonList.add(this.redstoneControlButton); + + // Adjust void mode button Y + if (this.voidModeButton != null) { + this.voidModeButton.yPosition += 18; + } + } else if (!newRedstoneControled && this.buttonList.contains(this.redstoneControlButton)) { + // Add to list + this.buttonList.remove(this.redstoneControlButton); + + // Adjust void mode button Y + if (this.voidModeButton != null) { + this.voidModeButton.yPosition -= 18; + } + } + } + + public void onReceiveRedstoneMode(final RedstoneMode redstoneMode) { + // Set the button state + this.redstoneControlButton.setRedstoneMode(redstoneMode); + + // Mark the mode + this.redstoneMode = redstoneMode; + } + + public void onReceiveHasCrafting(final boolean hasCrafting) { + if (hasCrafting && !buttonList.contains(craftingModeButton)) { + buttonList.add(craftingModeButton); + } else if (!hasCrafting && buttonList.contains(craftingModeButton)) { + buttonList.remove(craftingModeButton); + } + } + + public void onReceiveCraftingOnly(final boolean craftingOnly) { + if (craftingModeButton != null) { + craftingModeButton.setAlwaysCraft(craftingOnly); + } + } + /** + * Called when the server sends the void mode status + * + * @param isVoidAllowed + */ + public void onServerSendVoidMode(final boolean isVoidAllowed) { + // Set the void mode if there is a void button + if (this.voidModeButton != null) { + this.voidModeButton.setIsVoidAllowed(isVoidAllowed); + } + } + + @Override + public void updateAspects(final List aspectList) { + // Inform our part + this.part.onReceiveFilterList(aspectList); + + int count = Math.min(this.aspectSlotList.size(), aspectList.size()); + + for (int i = 0; i < count; i++) { + this.aspectSlotList.get(i).setAspect(aspectList.get(i), 1, false); + } + + this.filteredAspects = aspectList; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaLevelEmitter.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaLevelEmitter.java index c6e0e1c0..7b4f2bb8 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaLevelEmitter.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaLevelEmitter.java @@ -1,14 +1,14 @@ package thaumicenergistics.client.gui; -import java.util.List; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; import appeng.api.config.RedstoneMode; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IAspectSlotGui; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; @@ -29,438 +29,428 @@ import thaumicenergistics.common.parts.PartEssentiaLevelEmitter; * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaLevelEmitter - extends ThEBaseGui - implements IAspectSlotGui -{ - /** - * Normal button labels - */ - private static final String[] BUTTON_LABELS = { "+1", "+10", "+100", "-1", "-10", "-100" }; - - /** - * Button labels when shift is being pressed. - */ - private static final String[] BUTTON_LABELS_SHIFTED = { "+100", "+1000", "+10000", "-100", "-1000", "-10000" }; - - /** - * Width of the gui - */ - private static final int GUI_WIDTH = 176; - - /** - * Height of the gui - */ - private static final int GUI_HEIGHT = 184; - - /** - * The button index of the redstone mode button. - */ - private static final int REDSTONE_MODE_BUTTON_INDEX = 6; - - /** - * X position of the title string. - */ - private static final int TITLE_POS_X = 8; - - /** - * Y position of the title string. - */ - private static final int TITLE_POS_Y = 5; - - /** - * X offset for the amount field. - */ - private static final int AMOUNT_OFFSET_X = 25; - - /** - * Y offset for the amount field. - */ - private static final int AMOUNT_OFFSET_Y = 44; - - /** - * Width of the amount field. - */ - private static final int AMOUNT_WIDTH = 80; - - /** - * Height of the amount field. - */ - private static final int AMOUNT_HEIGHT = 10; - - /** - * Horizontal padding between buttons. - */ - private static final int BUTTON_PADDING_HORZ = 8; - - /** - * Vertical padding between buttons. - */ - private static final int BUTTON_PADDING_VERT = 22; - - /** - * X position to start drawing buttons. - */ - private static final int BUTTON_POS_X = 15; - - /** - * Y position to start drawing buttons. - */ - private static final int BUTTON_POS_Y = 17; - - /** - * Width of the buttons. - */ - private static final int BUTTON_WIDTH = 42; - - /** - * Height of the buttons. - */ - private static final int BUTTON_HEIGHT = 20; - - /** - * Number of button rows. - */ - private static final int BUTTON_ROWS = 2; - - /** - * Number of button columns. - */ - private static final int BUTTON_COLUMNS = 3; - - /** - * X position of the redstone button. - */ - private static final int REDSTONE_BUTTON_POS_X = -18; - - /** - * Y position of the redstone button. - */ - private static final int REDSTONE_BUTTON_POS_Y = 2; - - /** - * Width and height of the redstone button. - */ - private static final int REDSTONE_BUTTON_SIZE = 16; - - /** - * X position of the filter widget. - */ - private static final int FILTER_WIDGET_POS_X = 123; - - /** - * Y position of the filter widget. - */ - private static final int FILTER_WIDGET_POS_Y = 39; - - /** - * The maximum number of characters that can be typed in the amount field. - */ - private static final int AMOUNT_MAX_CHARS = 10; - - /** - * Amount text field - */ - private DigitTextField amountField; - - /** - * AE part associated with the gui. - */ - private PartEssentiaLevelEmitter part; - - /** - * Player viewing the gui. - */ - private EntityPlayer player; - - /** - * Filter slot. - */ - private WidgetAspectSlot aspectFilterSlot; - - /** - * Create the GUI. - * - * @param part - * AE part associated with the gui. - * @param player - * Player viewing the gui. - */ - public GuiEssentiaLevelEmitter( final PartEssentiaLevelEmitter part, final EntityPlayer player ) - { - // Call super - super( new ContainerPartEssentiaLevelEmitter( part, player ) ); - - // Set the player - this.player = player; - - // Set the part - this.part = part; - - // Create the filter slot - this.aspectFilterSlot = new WidgetAspectSlot( this, this.player, this.part, GuiEssentiaLevelEmitter.FILTER_WIDGET_POS_X, - GuiEssentiaLevelEmitter.FILTER_WIDGET_POS_Y ); - - // Set the width and height - this.xSize = GuiEssentiaLevelEmitter.GUI_WIDTH; - this.ySize = GuiEssentiaLevelEmitter.GUI_HEIGHT; - } - - /** - * Draw the gui background - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - // Set the texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_LEVEL_EMITTER.getTexture() ); - - // Draw the gui texture. - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, GuiEssentiaLevelEmitter.GUI_WIDTH, GuiEssentiaLevelEmitter.GUI_HEIGHT ); - } - - /** - * Draw the foreground - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( AEPartsEnum.EssentiaLevelEmitter.getLocalizedName(), GuiEssentiaLevelEmitter.TITLE_POS_X, - GuiEssentiaLevelEmitter.TITLE_POS_Y, 0 ); - - // Draw underlay when mouse is over slot. - if( this.aspectFilterSlot.isMouseOverWidget( mouseX, mouseY ) ) - { - // Draw underlay - this.aspectFilterSlot.drawMouseHoverUnderlay(); - - // Get tooltip - this.aspectFilterSlot.getTooltip( this.tooltip ); - } - - // Draw the filter widget - this.aspectFilterSlot.drawWidget(); - - // Draw the text field - this.amountField.drawTextBox(); - } - - /** - * Called when the player types a key - */ - @Override - protected void keyTyped( final char key, final int keyID ) - { - // Pass to super - super.keyTyped( key, keyID ); - - // Ensure they was numeric and the string isnt too long to parse, or backspace - if( ( Character.isDigit( key ) && ( this.amountField.getText().length() < GuiEssentiaLevelEmitter.AMOUNT_MAX_CHARS ) ) || - ( keyID == Keyboard.KEY_BACK ) ) - { - // Pass to the amount field - this.amountField.textboxKeyTyped( key, keyID ); - - // Convert the text field into a long - long wantedAmount = 0; - try - { - wantedAmount = Long.parseLong( this.amountField.getText() ); - } - catch( NumberFormatException e ) - { - } - - // Update the server - Packet_S_EssentiaEmitter.sendWantedAmount( wantedAmount, this.part, this.player ); - } - } - - /** - * Called when the player clicks a mouse button - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseBtn ) - { - // Pass to super - super.mouseClicked( mouseX, mouseY, mouseBtn ); - - // Is the mouse over the widget? - if( this.aspectFilterSlot.isMouseOverWidget( mouseX, mouseY ) ) - { - // Pass to the widget - this.aspectFilterSlot.mouseClicked(EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy())); - } - this.draggedStack = null; - } - - /** - * Called when a button is clicked. - */ - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Get the index of the button that was clicked - int index = button.id; - - // Was one of the amount buttons pressed? - if( ( index >= 0 ) && ( index < GuiEssentiaLevelEmitter.BUTTON_LABELS.length ) ) - { - try - { - // Read the adjustment - int adjustment = Integer.parseInt( button.displayString ); - - // Update the server - Packet_S_EssentiaEmitter.sendWantedAmountDelta( adjustment, this.part, this.player ); - } - catch( NumberFormatException e ) - { - } - } - // Was the redstone mode button pressed? - else if( index == GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX ) - { - // Update the server - Packet_S_EssentiaEmitter.sendRedstoneModeToggle( this.part, this.player ); - } - } - - /** - * Draws the screen and all the components in it. - */ - @Override - public void drawScreen( final int x, final int y, final float f ) - { - // Call super - super.drawScreen( x, y, f ); - - // Get the number of buttons - int count = GuiEssentiaLevelEmitter.BUTTON_LABELS.length; - - // Loop over the buttons - for( int buttonIndex = 0; buttonIndex < count; buttonIndex++ ) - { - // Get the button for this index - GuiButton currentButton = (GuiButton)this.buttonList.get( buttonIndex ); - - // Is shift being held? - if( Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ) ) - { - // Shifted label - currentButton.displayString = ( BUTTON_LABELS_SHIFTED[buttonIndex] ); - } - else - { - // Normal label - currentButton.displayString = ( BUTTON_LABELS[buttonIndex] ); - } - } - } - - /** - * Sets up the gui - */ - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Enable repeat keys - Keyboard.enableRepeatEvents( true ); - - // Create the amount field - this.amountField = new DigitTextField( this.fontRendererObj, GuiEssentiaLevelEmitter.AMOUNT_OFFSET_X, - GuiEssentiaLevelEmitter.AMOUNT_OFFSET_Y, GuiEssentiaLevelEmitter.AMOUNT_WIDTH, GuiEssentiaLevelEmitter.AMOUNT_HEIGHT ); - - // Start focused - this.amountField.setFocused( true ); - - // Draw in the forground - this.amountField.setEnableBackgroundDrawing( false ); - - // Text color white - this.amountField.setTextColor( 0xFFFFFFFF ); - - // Reset the button list - this.buttonList.clear(); - - // Add adjustment buttons - for( int row = 0; row < GuiEssentiaLevelEmitter.BUTTON_ROWS; row++ ) - { - // Calculate the y position of this row - int yPos = ( this.guiTop + GuiEssentiaLevelEmitter.BUTTON_POS_Y ) + - ( row * ( GuiEssentiaLevelEmitter.BUTTON_HEIGHT + GuiEssentiaLevelEmitter.BUTTON_PADDING_VERT ) ); - - for( int column = 0; column < GuiEssentiaLevelEmitter.BUTTON_COLUMNS; column++ ) - { - // Calculate the button index - int buttonIndex = ( row * 3 ) + column; - - // Calculate the x position of the button - int xPos = ( ( this.guiLeft + GuiEssentiaLevelEmitter.BUTTON_POS_X ) + - ( column * ( GuiEssentiaLevelEmitter.BUTTON_WIDTH + GuiEssentiaLevelEmitter.BUTTON_PADDING_HORZ ) ) ); - - this.buttonList.add( new GuiButton( buttonIndex, xPos, yPos, GuiEssentiaLevelEmitter.BUTTON_WIDTH, - GuiEssentiaLevelEmitter.BUTTON_HEIGHT, GuiEssentiaLevelEmitter.BUTTON_LABELS[buttonIndex] ) ); - } - } - - // Add the redstone mode button - this.buttonList.add( new GuiButtonRedstoneModes( GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX, this.guiLeft + - GuiEssentiaLevelEmitter.REDSTONE_BUTTON_POS_X, this.guiTop + GuiEssentiaLevelEmitter.REDSTONE_BUTTON_POS_Y, - GuiEssentiaLevelEmitter.REDSTONE_BUTTON_SIZE, GuiEssentiaLevelEmitter.REDSTONE_BUTTON_SIZE, RedstoneMode.LOW_SIGNAL, true ) ); - } - - /** - * Called when the gui is closing. - */ - @Override - public void onGuiClosed() - { - // Disable repeat keys - Keyboard.enableRepeatEvents( false ); - } - - /** - * Sets the redstone mode - * - * @param mode - */ - public void onReceiveRedstoneMode( final RedstoneMode mode ) - { - ( (GuiButtonRedstoneModes)this.buttonList.get( GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX ) ).setRedstoneMode( mode ); - } - - /** - * Returns the amount - * - * @param amount - */ - public void onReceiveThresholdValue( final long amount ) - { - this.amountField.setText( Long.toString( amount ) ); - } - - /** - * Sets the filtered aspect - */ - @Override - public void updateAspects( final List aspectList ) - { - if( ( aspectList == null ) || ( aspectList.isEmpty() ) ) - { - this.aspectFilterSlot.setAspect( null ); - } - else - { - this.aspectFilterSlot.setAspect( aspectList.get( 0 ), 1, false ); - } - } - +public class GuiEssentiaLevelEmitter extends ThEBaseGui implements IAspectSlotGui { + /** + * Normal button labels + */ + private static final String[] BUTTON_LABELS = {"+1", "+10", "+100", "-1", "-10", "-100"}; + + /** + * Button labels when shift is being pressed. + */ + private static final String[] BUTTON_LABELS_SHIFTED = {"+100", "+1000", "+10000", "-100", "-1000", "-10000"}; + + /** + * Width of the gui + */ + private static final int GUI_WIDTH = 176; + + /** + * Height of the gui + */ + private static final int GUI_HEIGHT = 184; + + /** + * The button index of the redstone mode button. + */ + private static final int REDSTONE_MODE_BUTTON_INDEX = 6; + + /** + * X position of the title string. + */ + private static final int TITLE_POS_X = 8; + + /** + * Y position of the title string. + */ + private static final int TITLE_POS_Y = 5; + + /** + * X offset for the amount field. + */ + private static final int AMOUNT_OFFSET_X = 25; + + /** + * Y offset for the amount field. + */ + private static final int AMOUNT_OFFSET_Y = 44; + + /** + * Width of the amount field. + */ + private static final int AMOUNT_WIDTH = 80; + + /** + * Height of the amount field. + */ + private static final int AMOUNT_HEIGHT = 10; + + /** + * Horizontal padding between buttons. + */ + private static final int BUTTON_PADDING_HORZ = 8; + + /** + * Vertical padding between buttons. + */ + private static final int BUTTON_PADDING_VERT = 22; + + /** + * X position to start drawing buttons. + */ + private static final int BUTTON_POS_X = 15; + + /** + * Y position to start drawing buttons. + */ + private static final int BUTTON_POS_Y = 17; + + /** + * Width of the buttons. + */ + private static final int BUTTON_WIDTH = 42; + + /** + * Height of the buttons. + */ + private static final int BUTTON_HEIGHT = 20; + + /** + * Number of button rows. + */ + private static final int BUTTON_ROWS = 2; + + /** + * Number of button columns. + */ + private static final int BUTTON_COLUMNS = 3; + + /** + * X position of the redstone button. + */ + private static final int REDSTONE_BUTTON_POS_X = -18; + + /** + * Y position of the redstone button. + */ + private static final int REDSTONE_BUTTON_POS_Y = 2; + + /** + * Width and height of the redstone button. + */ + private static final int REDSTONE_BUTTON_SIZE = 16; + + /** + * X position of the filter widget. + */ + private static final int FILTER_WIDGET_POS_X = 123; + + /** + * Y position of the filter widget. + */ + private static final int FILTER_WIDGET_POS_Y = 39; + + /** + * The maximum number of characters that can be typed in the amount field. + */ + private static final int AMOUNT_MAX_CHARS = 10; + + /** + * Amount text field + */ + private DigitTextField amountField; + + /** + * AE part associated with the gui. + */ + private PartEssentiaLevelEmitter part; + + /** + * Player viewing the gui. + */ + private EntityPlayer player; + + /** + * Filter slot. + */ + private WidgetAspectSlot aspectFilterSlot; + + /** + * Create the GUI. + * + * @param part + * AE part associated with the gui. + * @param player + * Player viewing the gui. + */ + public GuiEssentiaLevelEmitter(final PartEssentiaLevelEmitter part, final EntityPlayer player) { + // Call super + super(new ContainerPartEssentiaLevelEmitter(part, player)); + + // Set the player + this.player = player; + + // Set the part + this.part = part; + + // Create the filter slot + this.aspectFilterSlot = new WidgetAspectSlot( + this, + this.player, + this.part, + GuiEssentiaLevelEmitter.FILTER_WIDGET_POS_X, + GuiEssentiaLevelEmitter.FILTER_WIDGET_POS_Y); + + // Set the width and height + this.xSize = GuiEssentiaLevelEmitter.GUI_WIDTH; + this.ySize = GuiEssentiaLevelEmitter.GUI_HEIGHT; + } + + /** + * Draw the gui background + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Set the texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_LEVEL_EMITTER.getTexture()); + + // Draw the gui texture. + this.drawTexturedModalRect( + this.guiLeft, this.guiTop, 0, 0, GuiEssentiaLevelEmitter.GUI_WIDTH, GuiEssentiaLevelEmitter.GUI_HEIGHT); + } + + /** + * Draw the foreground + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString( + AEPartsEnum.EssentiaLevelEmitter.getLocalizedName(), + GuiEssentiaLevelEmitter.TITLE_POS_X, + GuiEssentiaLevelEmitter.TITLE_POS_Y, + 0); + + // Draw underlay when mouse is over slot. + if (this.aspectFilterSlot.isMouseOverWidget(mouseX, mouseY)) { + // Draw underlay + this.aspectFilterSlot.drawMouseHoverUnderlay(); + + // Get tooltip + this.aspectFilterSlot.getTooltip(this.tooltip); + } + + // Draw the filter widget + this.aspectFilterSlot.drawWidget(); + + // Draw the text field + this.amountField.drawTextBox(); + } + + /** + * Called when the player types a key + */ + @Override + protected void keyTyped(final char key, final int keyID) { + // Pass to super + super.keyTyped(key, keyID); + + // Ensure they was numeric and the string isnt too long to parse, or backspace + if ((Character.isDigit(key) && (this.amountField.getText().length() < GuiEssentiaLevelEmitter.AMOUNT_MAX_CHARS)) + || (keyID == Keyboard.KEY_BACK)) { + // Pass to the amount field + this.amountField.textboxKeyTyped(key, keyID); + + // Convert the text field into a long + long wantedAmount = 0; + try { + wantedAmount = Long.parseLong(this.amountField.getText()); + } catch (NumberFormatException e) { + } + + // Update the server + Packet_S_EssentiaEmitter.sendWantedAmount(wantedAmount, this.part, this.player); + } + } + + /** + * Called when the player clicks a mouse button + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseBtn) { + // Pass to super + super.mouseClicked(mouseX, mouseY, mouseBtn); + + // Is the mouse over the widget? + if (this.aspectFilterSlot.isMouseOverWidget(mouseX, mouseY)) { + // Pass to the widget + this.aspectFilterSlot.mouseClicked(EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( + this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy())); + } + this.draggedStack = null; + } + + /** + * Called when a button is clicked. + */ + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Get the index of the button that was clicked + int index = button.id; + + // Was one of the amount buttons pressed? + if ((index >= 0) && (index < GuiEssentiaLevelEmitter.BUTTON_LABELS.length)) { + try { + // Read the adjustment + int adjustment = Integer.parseInt(button.displayString); + + // Update the server + Packet_S_EssentiaEmitter.sendWantedAmountDelta(adjustment, this.part, this.player); + } catch (NumberFormatException e) { + } + } + // Was the redstone mode button pressed? + else if (index == GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX) { + // Update the server + Packet_S_EssentiaEmitter.sendRedstoneModeToggle(this.part, this.player); + } + } + + /** + * Draws the screen and all the components in it. + */ + @Override + public void drawScreen(final int x, final int y, final float f) { + // Call super + super.drawScreen(x, y, f); + + // Get the number of buttons + int count = GuiEssentiaLevelEmitter.BUTTON_LABELS.length; + + // Loop over the buttons + for (int buttonIndex = 0; buttonIndex < count; buttonIndex++) { + // Get the button for this index + GuiButton currentButton = (GuiButton) this.buttonList.get(buttonIndex); + + // Is shift being held? + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { + // Shifted label + currentButton.displayString = (BUTTON_LABELS_SHIFTED[buttonIndex]); + } else { + // Normal label + currentButton.displayString = (BUTTON_LABELS[buttonIndex]); + } + } + } + + /** + * Sets up the gui + */ + @Override + public void initGui() { + // Call super + super.initGui(); + + // Enable repeat keys + Keyboard.enableRepeatEvents(true); + + // Create the amount field + this.amountField = new DigitTextField( + this.fontRendererObj, + GuiEssentiaLevelEmitter.AMOUNT_OFFSET_X, + GuiEssentiaLevelEmitter.AMOUNT_OFFSET_Y, + GuiEssentiaLevelEmitter.AMOUNT_WIDTH, + GuiEssentiaLevelEmitter.AMOUNT_HEIGHT); + + // Start focused + this.amountField.setFocused(true); + + // Draw in the forground + this.amountField.setEnableBackgroundDrawing(false); + + // Text color white + this.amountField.setTextColor(0xFFFFFFFF); + + // Reset the button list + this.buttonList.clear(); + + // Add adjustment buttons + for (int row = 0; row < GuiEssentiaLevelEmitter.BUTTON_ROWS; row++) { + // Calculate the y position of this row + int yPos = (this.guiTop + GuiEssentiaLevelEmitter.BUTTON_POS_Y) + + (row * (GuiEssentiaLevelEmitter.BUTTON_HEIGHT + GuiEssentiaLevelEmitter.BUTTON_PADDING_VERT)); + + for (int column = 0; column < GuiEssentiaLevelEmitter.BUTTON_COLUMNS; column++) { + // Calculate the button index + int buttonIndex = (row * 3) + column; + + // Calculate the x position of the button + int xPos = ((this.guiLeft + GuiEssentiaLevelEmitter.BUTTON_POS_X) + + (column + * (GuiEssentiaLevelEmitter.BUTTON_WIDTH + + GuiEssentiaLevelEmitter.BUTTON_PADDING_HORZ))); + + this.buttonList.add(new GuiButton( + buttonIndex, + xPos, + yPos, + GuiEssentiaLevelEmitter.BUTTON_WIDTH, + GuiEssentiaLevelEmitter.BUTTON_HEIGHT, + GuiEssentiaLevelEmitter.BUTTON_LABELS[buttonIndex])); + } + } + + // Add the redstone mode button + this.buttonList.add(new GuiButtonRedstoneModes( + GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX, + this.guiLeft + GuiEssentiaLevelEmitter.REDSTONE_BUTTON_POS_X, + this.guiTop + GuiEssentiaLevelEmitter.REDSTONE_BUTTON_POS_Y, + GuiEssentiaLevelEmitter.REDSTONE_BUTTON_SIZE, + GuiEssentiaLevelEmitter.REDSTONE_BUTTON_SIZE, + RedstoneMode.LOW_SIGNAL, + true)); + } + + /** + * Called when the gui is closing. + */ + @Override + public void onGuiClosed() { + // Disable repeat keys + Keyboard.enableRepeatEvents(false); + } + + /** + * Sets the redstone mode + * + * @param mode + */ + public void onReceiveRedstoneMode(final RedstoneMode mode) { + ((GuiButtonRedstoneModes) this.buttonList.get(GuiEssentiaLevelEmitter.REDSTONE_MODE_BUTTON_INDEX)) + .setRedstoneMode(mode); + } + + /** + * Returns the amount + * + * @param amount + */ + public void onReceiveThresholdValue(final long amount) { + this.amountField.setText(Long.toString(amount)); + } + + /** + * Sets the filtered aspect + */ + @Override + public void updateAspects(final List aspectList) { + if ((aspectList == null) || (aspectList.isEmpty())) { + this.aspectFilterSlot.setAspect(null); + } else { + this.aspectFilterSlot.setAspect(aspectList.get(0), 1, false); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaStorageBus.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaStorageBus.java index 82264abc..a0064e2b 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaStorageBus.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaStorageBus.java @@ -1,17 +1,15 @@ package thaumicenergistics.client.gui; -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.ItemStack; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IAspectSlotGui; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; @@ -36,318 +34,309 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaStorageBus - extends ThEBaseGui - implements IAspectSlotGui -{ - /** - * The number of columns in the gui. - */ - private static final int WIDGET_COLUMNS = 3; +public class GuiEssentiaStorageBus extends ThEBaseGui implements IAspectSlotGui { + /** + * The number of columns in the gui. + */ + private static final int WIDGET_COLUMNS = 3; - /** - * The number of rows in the gui. - */ - private static final int WIDGET_ROWS = 3; + /** + * The number of rows in the gui. + */ + private static final int WIDGET_ROWS = 3; - /** - * The starting X position of the widgets. - */ - private static final int WIDGET_X_POS = 61; + /** + * The starting X position of the widgets. + */ + private static final int WIDGET_X_POS = 61; - /** - * The starting Y position of the widgets. - */ - private static final int WIDGET_Y_POS = 21; + /** + * The starting Y position of the widgets. + */ + private static final int WIDGET_Y_POS = 21; - /** - * The width of the gui with a network tool. - */ - private static final int GUI_WIDTH_NETWORK_TOOL = 246; + /** + * The width of the gui with a network tool. + */ + private static final int GUI_WIDTH_NETWORK_TOOL = 246; - /** - * The width of the gui without a network too - */ - private static final int GUI_WIDTH_NO_TOOL = 210; + /** + * The width of the gui without a network too + */ + private static final int GUI_WIDTH_NO_TOOL = 210; - /** - * The height of the gui - */ - private static final int GUI_HEIGHT = 184; + /** + * The height of the gui + */ + private static final int GUI_HEIGHT = 184; - /** - * X position of the title string. - */ - private static final int TITLE_X_POS = 6; + /** + * X position of the title string. + */ + private static final int TITLE_X_POS = 6; - /** - * Y position of the title string. - */ - private static final int TITLE_Y_POS = 5; + /** + * Y position of the title string. + */ + private static final int TITLE_Y_POS = 5; - /** - * ID of the priority button - */ - private static final int BUTTON_PRIORITY_ID = 0; + /** + * ID of the priority button + */ + private static final int BUTTON_PRIORITY_ID = 0; - /** - * X offset position of the priority button - */ - private static final int BUTTON_PRIORITY_X_POSITION = 154; + /** + * X offset position of the priority button + */ + private static final int BUTTON_PRIORITY_X_POSITION = 154; - private static final int BUTTON_ALLOW_VOID_ID = 1; + private static final int BUTTON_ALLOW_VOID_ID = 1; - private static final int BUTTON_ALLOW_VOID_X_POS = -18; + private static final int BUTTON_ALLOW_VOID_X_POS = -18; - private static final int BUTTON_ALLOW_VOID_Y_POS = 8; + private static final int BUTTON_ALLOW_VOID_Y_POS = 8; - /** - * Player viewing this gui. - */ - private EntityPlayer player; + /** + * Player viewing this gui. + */ + private EntityPlayer player; - /** - * Filter widget list - */ - private List aspectWidgetList = new ArrayList(); + /** + * Filter widget list + */ + private List aspectWidgetList = new ArrayList(); - /** - * Filter aspect list - */ - private List filteredAspects = new ArrayList(); + /** + * Filter aspect list + */ + private List filteredAspects = new ArrayList(); - /** - * Does the player have a network tool? - */ - private boolean hasNetworkTool; + /** + * Does the player have a network tool? + */ + private boolean hasNetworkTool; - /** - * Storage bus associated with this gui - */ - private PartEssentiaStorageBus storageBus; + /** + * Storage bus associated with this gui + */ + private PartEssentiaStorageBus storageBus; - /** - * Title of the gui - */ - private final String guiTitle = AEPartsEnum.EssentiaStorageBus.getLocalizedName(); + /** + * Title of the gui + */ + private final String guiTitle = AEPartsEnum.EssentiaStorageBus.getLocalizedName(); - /** - * Is the storage buss allowed to void excess essentia? - */ - private boolean isVoidAllowed = false; + /** + * Is the storage buss allowed to void excess essentia? + */ + private boolean isVoidAllowed = false; - /** - * Creates the GUI. - * - * @param storageBus - * The part associated with the gui. - * @param player - * The player viewing the gui. - * @param container - * The inventory container. - */ - public GuiEssentiaStorageBus( final PartEssentiaStorageBus storageBus, final EntityPlayer player ) - { - // Call super - super( new ContainerPartEssentiaStorageBus( storageBus, player ) ); + /** + * Creates the GUI. + * + * @param storageBus + * The part associated with the gui. + * @param player + * The player viewing the gui. + * @param container + * The inventory container. + */ + public GuiEssentiaStorageBus(final PartEssentiaStorageBus storageBus, final EntityPlayer player) { + // Call super + super(new ContainerPartEssentiaStorageBus(storageBus, player)); - // Set the player - this.player = player; + // Set the player + this.player = player; - // Set the storage bus - this.storageBus = storageBus; + // Set the storage bus + this.storageBus = storageBus; - // Set the network tool - this.hasNetworkTool = ( (ContainerPartEssentiaStorageBus)this.inventorySlots ).hasNetworkTool(); + // Set the network tool + this.hasNetworkTool = ((ContainerPartEssentiaStorageBus) this.inventorySlots).hasNetworkTool(); - // Set the width and height - this.xSize = ( this.hasNetworkTool ? GuiEssentiaStorageBus.GUI_WIDTH_NETWORK_TOOL : GuiEssentiaStorageBus.GUI_WIDTH_NO_TOOL ); - this.ySize = GuiEssentiaStorageBus.GUI_HEIGHT; - } + // Set the width and height + this.xSize = (this.hasNetworkTool + ? GuiEssentiaStorageBus.GUI_WIDTH_NETWORK_TOOL + : GuiEssentiaStorageBus.GUI_WIDTH_NO_TOOL); + this.ySize = GuiEssentiaStorageBus.GUI_HEIGHT; + } - /** - * Draws the gui background - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + /** + * Draws the gui background + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // Set the texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_STORAGE_BUS.getTexture() ); + // Set the texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_STORAGE_BUS.getTexture()); - // Draw main gui - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, 176, 222 ); + // Draw main gui + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 222); - // Draw upgrade slot - this.drawTexturedModalRect( this.guiLeft + 179, this.guiTop, 179, 0, 32, 32 ); + // Draw upgrade slot + this.drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 32); - if( this.hasNetworkTool ) - { - this.drawTexturedModalRect( this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68 ); - } + if (this.hasNetworkTool) { + this.drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68); + } - // Call super - super.drawAEToolAndUpgradeSlots( alpha, mouseX, mouseY ); + // Call super + super.drawAEToolAndUpgradeSlots(alpha, mouseX, mouseY); + } - } + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Call super + super.drawGuiContainerForegroundLayer(mouseX, mouseY); - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Call super - super.drawGuiContainerForegroundLayer( mouseX, mouseY ); + // Draw the title + this.fontRendererObj.drawString( + this.guiTitle, GuiEssentiaStorageBus.TITLE_X_POS, GuiEssentiaStorageBus.TITLE_Y_POS, 0x000000); - // Draw the title - this.fontRendererObj.drawString( this.guiTitle, GuiEssentiaStorageBus.TITLE_X_POS, GuiEssentiaStorageBus.TITLE_Y_POS, 0x000000 ); + WidgetAspectSlot slotUnderMouse = null; - WidgetAspectSlot slotUnderMouse = null; + // Draw widgets + for (WidgetAspectSlot currentWidget : this.aspectWidgetList) { + if ((slotUnderMouse == null) + && (currentWidget.canRender()) + && (currentWidget.isMouseOverWidget(mouseX, mouseY))) { + // Draw the underlay + currentWidget.drawMouseHoverUnderlay(); - // Draw widgets - for( WidgetAspectSlot currentWidget : this.aspectWidgetList ) - { - if( ( slotUnderMouse == null ) && ( currentWidget.canRender() ) && ( currentWidget.isMouseOverWidget( mouseX, mouseY ) ) ) - { - // Draw the underlay - currentWidget.drawMouseHoverUnderlay(); + // Set the slot + slotUnderMouse = currentWidget; + } - // Set the slot - slotUnderMouse = currentWidget; - } + // Draw the widget + currentWidget.drawWidget(); + } - // Draw the widget - currentWidget.drawWidget(); - } + // Should we get the tooltip from the slot? + if (slotUnderMouse != null) { + // Add the tooltip from the widget + slotUnderMouse.getTooltip(this.tooltip); + } + } - // Should we get the tooltip from the slot? - if( slotUnderMouse != null ) - { - // Add the tooltip from the widget - slotUnderMouse.getTooltip( this.tooltip ); - } - } + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Call super + super.mouseClicked(mouseX, mouseY, mouseButton); - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Call super - super.mouseClicked( mouseX, mouseY, mouseButton ); + for (WidgetAspectSlot aspectSlot : this.aspectWidgetList) { + if (aspectSlot.isMouseOverWidget(mouseX, mouseY)) { + // Get the aspect of the currently held item + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( + this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); - for( WidgetAspectSlot aspectSlot : this.aspectWidgetList ) - { - if( aspectSlot.isMouseOverWidget( mouseX, mouseY ) ) - { - // Get the aspect of the currently held item - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(this.draggedStack == null ? this.player.inventory.getItemStack() : this.draggedStack.copy()); + // Is there an aspect? + if (itemAspect != null) { + // Are we already filtering for this aspect? + if (this.filteredAspects.contains(itemAspect)) { + // Ignore + return; + } + } - // Is there an aspect? - if( itemAspect != null ) - { - // Are we already filtering for this aspect? - if( this.filteredAspects.contains( itemAspect ) ) - { - // Ignore - return; - } + aspectSlot.mouseClicked(itemAspect); - } + break; + } + } + this.draggedStack = null; + } - aspectSlot.mouseClicked( itemAspect ); + /** + * Called when a button is clicked. + */ + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Was the priority button clicked? + if (button.id == GuiEssentiaStorageBus.BUTTON_PRIORITY_ID) { + // Get the storage buses host + TileEntity host = this.storageBus.getHostTile(); - break; - } - } - this.draggedStack = null; - } + // Get the side the storage bus is attached to + ForgeDirection side = this.storageBus.getSide(); - /** - * Called when a button is clicked. - */ - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Was the priority button clicked? - if( button.id == GuiEssentiaStorageBus.BUTTON_PRIORITY_ID ) - { - // Get the storage buses host - TileEntity host = this.storageBus.getHostTile(); + // Ask the server to change to the priority gui + Packet_S_ChangeGui.sendGuiChange( + ThEGuiHandler.generateSidedID(ThEGuiHandler.PRIORITY_ID, side), + this.player, + host.getWorldObj(), + host.xCoord, + host.yCoord, + host.zCoord); - // Get the side the storage bus is attached to - ForgeDirection side = this.storageBus.getSide(); + } else if (button.id == GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID) { + // Toggle the mode + this.isVoidAllowed = !this.isVoidAllowed; - // Ask the server to change to the priority gui - Packet_S_ChangeGui.sendGuiChange( ThEGuiHandler.generateSidedID( ThEGuiHandler.PRIORITY_ID, side ), this.player, - host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); + // Update the button + ((GuiButtonAllowVoid) this.buttonList.get(GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID)) + .setIsVoidAllowed(this.isVoidAllowed); - } - else if( button.id == GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID ) - { - // Toggle the mode - this.isVoidAllowed = !this.isVoidAllowed; + // Update the server + Packet_S_EssentiaStorageBus.setVoidAllowed(this.player, this.storageBus, this.isVoidAllowed); + } + } - // Update the button - ( (GuiButtonAllowVoid)this.buttonList.get( GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID ) ).setIsVoidAllowed( this.isVoidAllowed ); + @Override + public void initGui() { + super.initGui(); - // Update the server - Packet_S_EssentiaStorageBus.setVoidAllowed( this.player, this.storageBus, this.isVoidAllowed ); - } + // Create the widgets + for (int row = 0; row < GuiEssentiaStorageBus.WIDGET_ROWS; row++) { + for (int column = 0; column < GuiEssentiaStorageBus.WIDGET_COLUMNS; column++) { + this.aspectWidgetList.add(new WidgetAspectSlot( + this, + this.player, + this.storageBus, + (row * GuiEssentiaStorageBus.WIDGET_COLUMNS) + column, + GuiEssentiaStorageBus.WIDGET_X_POS + (ThEWidget.WIDGET_SIZE * column), + GuiEssentiaStorageBus.WIDGET_Y_POS + (ThEWidget.WIDGET_SIZE * row))); + } + } - } + // Create the priority tab button + this.buttonList.add(new GuiButtonAETab( + GuiEssentiaStorageBus.BUTTON_PRIORITY_ID, + this.guiLeft + GuiEssentiaStorageBus.BUTTON_PRIORITY_X_POSITION, + this.guiTop, + AEStateIconsEnum.WRENCH, + "gui.appliedenergistics2.Priority")); - @Override - public void initGui() - { - super.initGui(); + // Create the allow void button + this.buttonList.add(new GuiButtonAllowVoid( + GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID, + this.guiLeft + GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_X_POS, + this.guiTop + GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_Y_POS)); + } - // Create the widgets - for( int row = 0; row < GuiEssentiaStorageBus.WIDGET_ROWS; row++ ) - { - for( int column = 0; column < GuiEssentiaStorageBus.WIDGET_COLUMNS; column++ ) - { - this.aspectWidgetList.add( new WidgetAspectSlot( this, this.player, this.storageBus, - ( row * GuiEssentiaStorageBus.WIDGET_COLUMNS ) + column, - GuiEssentiaStorageBus.WIDGET_X_POS + ( ThEWidget.WIDGET_SIZE * column ), - GuiEssentiaStorageBus.WIDGET_Y_POS + ( ThEWidget.WIDGET_SIZE * row ) ) ); - } - } + /** + * Called when the server has sent a change to void mode. + * + * @param isVoidAllowed + */ + public void onServerSentVoidMode(final boolean isVoidAllowed) { + // Set the mode + this.isVoidAllowed = isVoidAllowed; - // Create the priority tab button - this.buttonList.add( new GuiButtonAETab( GuiEssentiaStorageBus.BUTTON_PRIORITY_ID, this.guiLeft + - GuiEssentiaStorageBus.BUTTON_PRIORITY_X_POSITION, this.guiTop, AEStateIconsEnum.WRENCH, - "gui.appliedenergistics2.Priority" ) ); + // Update the button + ((GuiButtonAllowVoid) this.buttonList.get(GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID)) + .setIsVoidAllowed(this.isVoidAllowed); + } - // Create the allow void button - this.buttonList.add( new GuiButtonAllowVoid( GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID, this.guiLeft + - GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_X_POS, this.guiTop + GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_Y_POS ) ); - } + @Override + public void updateAspects(final List aspectList) { + int count = Math.min(this.aspectWidgetList.size(), aspectList.size()); - /** - * Called when the server has sent a change to void mode. - * - * @param isVoidAllowed - */ - public void onServerSentVoidMode( final boolean isVoidAllowed ) - { - // Set the mode - this.isVoidAllowed = isVoidAllowed; - - // Update the button - ( (GuiButtonAllowVoid)this.buttonList.get( GuiEssentiaStorageBus.BUTTON_ALLOW_VOID_ID ) ).setIsVoidAllowed( this.isVoidAllowed ); - } - - @Override - public void updateAspects( final List aspectList ) - { - int count = Math.min( this.aspectWidgetList.size(), aspectList.size() ); - - for( int i = 0; i < count; i++ ) - { - this.aspectWidgetList.get( i ).setAspect( aspectList.get( i ), 1, false ); - } - - this.filteredAspects = aspectList; - - } + for (int i = 0; i < count; i++) { + this.aspectWidgetList.get(i).setAspect(aspectList.get(i), 1, false); + } + this.filteredAspects = aspectList; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaVibrationChamber.java index 0e409479..831f8dd2 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiEssentiaVibrationChamber.java @@ -1,12 +1,12 @@ package thaumicenergistics.client.gui; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; import thaumicenergistics.client.textures.GuiTextureManager; @@ -20,193 +20,220 @@ import thaumicenergistics.common.tiles.TileEssentiaVibrationChamber; * */ @SideOnly(Side.CLIENT) -public class GuiEssentiaVibrationChamber - extends ThEBaseGui -{ +public class GuiEssentiaVibrationChamber extends ThEBaseGui { - /** - * The width & height of the gui - */ - private static final int GUI_WIDTH = 176, GUI_HEIGHT = 82; + /** + * The width & height of the gui + */ + private static final int GUI_WIDTH = 176, GUI_HEIGHT = 82; - /** - * Dimensions and location of the power bar. - */ - private static final int POWER_POS_X = 96, POWER_POS_Y = 32, POWER_TEX_U = 51, POWER_TEX_V = 83, POWER_WIDTH = 6, POWER_HEIGHT = 18; + /** + * Dimensions and location of the power bar. + */ + private static final int POWER_POS_X = 96, + POWER_POS_Y = 32, + POWER_TEX_U = 51, + POWER_TEX_V = 83, + POWER_WIDTH = 6, + POWER_HEIGHT = 18; - /** - * Dimensions and location of the essentia storage level bar. - */ - private static final int STORED_POS_X = 62, STORED_POS_Y = 16, STORED_TEX_X = 200, STORED_WIDTH = 8, STORED_HEIGHT = 48; + /** + * Dimensions and location of the essentia storage level bar. + */ + private static final int STORED_POS_X = 62, + STORED_POS_Y = 16, + STORED_TEX_X = 200, + STORED_WIDTH = 8, + STORED_HEIGHT = 48; - /** - * Dimensions and location of the essentia storage vial. - */ - private static final int VIAL_POS_X = 61, VIAL_POS_Y = 12, VIAL_TEX_X = 232, VIAL_WIDTH = 11, VIAL_HEIGHT = 56; + /** + * Dimensions and location of the essentia storage vial. + */ + private static final int VIAL_POS_X = 61, VIAL_POS_Y = 12, VIAL_TEX_X = 232, VIAL_WIDTH = 11, VIAL_HEIGHT = 56; - /** - * Dimensions and location of the progress fire. - */ - private static final int FIRE_POS_X = 78, FIRE_POS_Y = 30, FIRE_TEX_X = 177, FIRE_WIDTH = 15, FIRE_HEIGHT = 20; + /** + * Dimensions and location of the progress fire. + */ + private static final int FIRE_POS_X = 78, FIRE_POS_Y = 30, FIRE_TEX_X = 177, FIRE_WIDTH = 15, FIRE_HEIGHT = 20; - /** - * Thaumcraft's alchemy furnace GUI texture - */ - private static final ResourceLocation alchemyFurnaceTexture = new ResourceLocation( "thaumcraft", "textures/gui/gui_alchemyfurnace.png" ); + /** + * Thaumcraft's alchemy furnace GUI texture + */ + private static final ResourceLocation alchemyFurnaceTexture = + new ResourceLocation("thaumcraft", "textures/gui/gui_alchemyfurnace.png"); - /** - * Reference to the container. - */ - private final ContainerEssentiaVibrationChamber container; + /** + * Reference to the container. + */ + private final ContainerEssentiaVibrationChamber container; - public GuiEssentiaVibrationChamber( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Create the container and call super - super( new ContainerEssentiaVibrationChamber( player, world, x, y, z ) ); - this.container = (ContainerEssentiaVibrationChamber)this.inventorySlots; + public GuiEssentiaVibrationChamber( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Create the container and call super + super(new ContainerEssentiaVibrationChamber(player, world, x, y, z)); + this.container = (ContainerEssentiaVibrationChamber) this.inventorySlots; - // Set the width and height - this.xSize = GuiEssentiaVibrationChamber.GUI_WIDTH; - this.ySize = GuiEssentiaVibrationChamber.GUI_HEIGHT; - } + // Set the width and height + this.xSize = GuiEssentiaVibrationChamber.GUI_WIDTH; + this.ySize = GuiEssentiaVibrationChamber.GUI_HEIGHT; + } - /** - * Draws elements from the Thaumcraft texture. - */ - private void drawTC_Textures() - { - // Bind the alchemy furnace gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiEssentiaVibrationChamber.alchemyFurnaceTexture ); + /** + * Draws elements from the Thaumcraft texture. + */ + private void drawTC_Textures() { + // Bind the alchemy furnace gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiEssentiaVibrationChamber.alchemyFurnaceTexture); - // Draw stored essentia amount underlay - int storedHeightOffset = (int)( GuiEssentiaVibrationChamber.STORED_HEIGHT * this.container.getStoredEssentiaPercent() ); + // Draw stored essentia amount underlay + int storedHeightOffset = + (int) (GuiEssentiaVibrationChamber.STORED_HEIGHT * this.container.getStoredEssentiaPercent()); - this.drawTexturedModalRect( this.guiLeft + GuiEssentiaVibrationChamber.STORED_POS_X, this.guiTop + GuiEssentiaVibrationChamber.STORED_POS_Y + - storedHeightOffset, - GuiEssentiaVibrationChamber.STORED_TEX_X, storedHeightOffset, GuiEssentiaVibrationChamber.STORED_WIDTH, - GuiEssentiaVibrationChamber.STORED_HEIGHT - storedHeightOffset ); + this.drawTexturedModalRect( + this.guiLeft + GuiEssentiaVibrationChamber.STORED_POS_X, + this.guiTop + GuiEssentiaVibrationChamber.STORED_POS_Y + storedHeightOffset, + GuiEssentiaVibrationChamber.STORED_TEX_X, + storedHeightOffset, + GuiEssentiaVibrationChamber.STORED_WIDTH, + GuiEssentiaVibrationChamber.STORED_HEIGHT - storedHeightOffset); - // Enable alpha blending - GL11.glEnable( GL11.GL_BLEND ); + // Enable alpha blending + GL11.glEnable(GL11.GL_BLEND); - // Set the blending mode - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + // Set the blending mode + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - // Draw stored essentia amount overlay (Vial) - this.drawTexturedModalRect( this.guiLeft + GuiEssentiaVibrationChamber.VIAL_POS_X, this.guiTop + GuiEssentiaVibrationChamber.VIAL_POS_Y, - GuiEssentiaVibrationChamber.VIAL_TEX_X, 0, GuiEssentiaVibrationChamber.VIAL_WIDTH, GuiEssentiaVibrationChamber.VIAL_HEIGHT ); + // Draw stored essentia amount overlay (Vial) + this.drawTexturedModalRect( + this.guiLeft + GuiEssentiaVibrationChamber.VIAL_POS_X, + this.guiTop + GuiEssentiaVibrationChamber.VIAL_POS_Y, + GuiEssentiaVibrationChamber.VIAL_TEX_X, + 0, + GuiEssentiaVibrationChamber.VIAL_WIDTH, + GuiEssentiaVibrationChamber.VIAL_HEIGHT); - // Draw fire/progress - int progressHeightOffset = (int)( GuiEssentiaVibrationChamber.FIRE_HEIGHT * this.container.getTicksRemainingPercent() ); + // Draw fire/progress + int progressHeightOffset = + (int) (GuiEssentiaVibrationChamber.FIRE_HEIGHT * this.container.getTicksRemainingPercent()); - this.drawTexturedModalRect( this.guiLeft + GuiEssentiaVibrationChamber.FIRE_POS_X, this.guiTop + GuiEssentiaVibrationChamber.FIRE_POS_Y + - progressHeightOffset, - GuiEssentiaVibrationChamber.FIRE_TEX_X, progressHeightOffset, GuiEssentiaVibrationChamber.FIRE_WIDTH, - GuiEssentiaVibrationChamber.FIRE_HEIGHT - progressHeightOffset ); + this.drawTexturedModalRect( + this.guiLeft + GuiEssentiaVibrationChamber.FIRE_POS_X, + this.guiTop + GuiEssentiaVibrationChamber.FIRE_POS_Y + progressHeightOffset, + GuiEssentiaVibrationChamber.FIRE_TEX_X, + progressHeightOffset, + GuiEssentiaVibrationChamber.FIRE_WIDTH, + GuiEssentiaVibrationChamber.FIRE_HEIGHT - progressHeightOffset); - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - } + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + } - /** - * Draws elements from the Thaumic Energistics texture. - */ - private void drawThE_Textures() - { + /** + * Draws elements from the Thaumic Energistics texture. + */ + private void drawThE_Textures() { - // Bind the chamber gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTexture() ); + // Bind the chamber gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTexture()); - // Draw the GUI - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); + // Draw the GUI + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - // Calculate the height - int powerBarHeightOffset = (int)( GuiEssentiaVibrationChamber.POWER_HEIGHT * this.container.getPowerPercent() ); + // Calculate the height + int powerBarHeightOffset = (int) (GuiEssentiaVibrationChamber.POWER_HEIGHT * this.container.getPowerPercent()); - // Draw the power bar - this.drawTexturedModalRect( - this.guiLeft + GuiEssentiaVibrationChamber.POWER_POS_X, - this.guiTop + GuiEssentiaVibrationChamber.POWER_POS_Y + powerBarHeightOffset, - GuiEssentiaVibrationChamber.POWER_TEX_U, - GuiEssentiaVibrationChamber.POWER_TEX_V + powerBarHeightOffset, - GuiEssentiaVibrationChamber.POWER_WIDTH, - GuiEssentiaVibrationChamber.POWER_HEIGHT - powerBarHeightOffset ); + // Draw the power bar + this.drawTexturedModalRect( + this.guiLeft + GuiEssentiaVibrationChamber.POWER_POS_X, + this.guiTop + GuiEssentiaVibrationChamber.POWER_POS_Y + powerBarHeightOffset, + GuiEssentiaVibrationChamber.POWER_TEX_U, + GuiEssentiaVibrationChamber.POWER_TEX_V + powerBarHeightOffset, + GuiEssentiaVibrationChamber.POWER_WIDTH, + GuiEssentiaVibrationChamber.POWER_HEIGHT - powerBarHeightOffset); + } - } + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // No tint + no cutout + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // No tint + no cutout - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + // Draw from the thaumic energistics texture + this.drawThE_Textures(); - // Draw from the thaumic energistics texture - this.drawThE_Textures(); + // Draw from the thaumcraft texture + this.drawTC_Textures(); + } - // Draw from the thaumcraft texture - this.drawTC_Textures(); + @Override + public void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Is the mouse over the essentia storage? + if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiEssentiaVibrationChamber.VIAL_POS_Y, + GuiEssentiaVibrationChamber.VIAL_POS_X, + GuiEssentiaVibrationChamber.VIAL_HEIGHT, + GuiEssentiaVibrationChamber.VIAL_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Get the stored Aspect + Aspect storedAspect = this.container.getStoredEssentiaAspect(); - } + // Get the stored amount + int storedAmount = this.container.getStoredEssentiaAmount(); - @Override - public void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Is the mouse over the essentia storage? - if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiEssentiaVibrationChamber.VIAL_POS_Y, GuiEssentiaVibrationChamber.VIAL_POS_X, - GuiEssentiaVibrationChamber.VIAL_HEIGHT, GuiEssentiaVibrationChamber.VIAL_WIDTH, mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Get the stored Aspect - Aspect storedAspect = this.container.getStoredEssentiaAspect(); + // Anything stored? + if ((storedAmount > 0) && (storedAspect != null)) { + // Add stored info + this.tooltip.add(String.format("%s x %d", storedAspect.getName(), storedAmount)); + } else { + // Empty + this.tooltip.add("Empty"); + } + } + // Is the mouse over the fire? + else if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiEssentiaVibrationChamber.FIRE_POS_Y, + GuiEssentiaVibrationChamber.FIRE_POS_X, + GuiEssentiaVibrationChamber.FIRE_HEIGHT, + GuiEssentiaVibrationChamber.FIRE_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Get the aspect being processed + Aspect processingAspect = this.container.getProcessingAspect(); - // Get the stored amount - int storedAmount = this.container.getStoredEssentiaAmount(); + // Anything being processed? + if (processingAspect != null) { + // Calculate the seconds remaining + float secondsRemaining = (this.container.getTicksRemaining() / 20.0F); - // Anything stored? - if( ( storedAmount > 0 ) && ( storedAspect != null ) ) - { - // Add stored info - this.tooltip.add( String.format( "%s x %d", storedAspect.getName(), storedAmount ) ); - } - else - { - // Empty - this.tooltip.add( "Empty" ); - } - } - // Is the mouse over the fire? - else if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiEssentiaVibrationChamber.FIRE_POS_Y, GuiEssentiaVibrationChamber.FIRE_POS_X, - GuiEssentiaVibrationChamber.FIRE_HEIGHT, GuiEssentiaVibrationChamber.FIRE_WIDTH, mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Get the aspect being processed - Aspect processingAspect = this.container.getProcessingAspect(); + // Add the aspect + this.tooltip.add(String.format("Processing: %s", processingAspect.getName())); - // Anything being processed? - if( processingAspect != null ) - { - // Calculate the seconds remaining - float secondsRemaining = ( this.container.getTicksRemaining() / 20.0F ); - - // Add the aspect - this.tooltip.add( String.format( "Processing: %s", processingAspect.getName() ) ); - - // Add the time - this.tooltip.add( String.format( "Time Remaining: %.0fs", secondsRemaining ) ); - } - } - // Is the mouse over the power bar? - else if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( GuiEssentiaVibrationChamber.POWER_POS_Y, GuiEssentiaVibrationChamber.POWER_POS_X, - GuiEssentiaVibrationChamber.POWER_HEIGHT, GuiEssentiaVibrationChamber.POWER_WIDTH, mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // Add the power per tick - this.tooltip.add( String.format( "%.0f AE/t", this.container.getPowerPerTick() ) ); - } - } - - @Override - public void initGui() - { - // Call super - super.initGui(); - } + // Add the time + this.tooltip.add(String.format("Time Remaining: %.0fs", secondsRemaining)); + } + } + // Is the mouse over the power bar? + else if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + GuiEssentiaVibrationChamber.POWER_POS_Y, + GuiEssentiaVibrationChamber.POWER_POS_X, + GuiEssentiaVibrationChamber.POWER_HEIGHT, + GuiEssentiaVibrationChamber.POWER_WIDTH, + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // Add the power per tick + this.tooltip.add(String.format("%.0f AE/t", this.container.getPowerPerTick())); + } + } + @Override + public void initGui() { + // Call super + super.initGui(); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiKnowledgeInscriber.java b/src/main/java/thaumicenergistics/client/gui/GuiKnowledgeInscriber.java index 260d202d..619db63d 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiKnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiKnowledgeInscriber.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.gui; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -8,6 +7,7 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; import thaumicenergistics.client.gui.buttons.GuiButtonClearCraftingGrid; import thaumicenergistics.client.gui.buttons.GuiButtonSaveDelete; @@ -26,267 +26,266 @@ import thaumicenergistics.common.tiles.TileKnowledgeInscriber; * */ @SideOnly(Side.CLIENT) -public class GuiKnowledgeInscriber - extends ThEBaseGui -{ - /** - * Gui size. - */ - private static final int GUI_WIDTH = 210; +public class GuiKnowledgeInscriber extends ThEBaseGui { + /** + * Gui size. + */ + private static final int GUI_WIDTH = 210; - /** - * Gui size. - */ - private static final int GUI_HEIGHT = 244; + /** + * Gui size. + */ + private static final int GUI_HEIGHT = 244; - /** - * Save/Delete button position. - */ - private static final int BUTTON_SAVE_POS_X = 141; + /** + * Save/Delete button position. + */ + private static final int BUTTON_SAVE_POS_X = 141; - /** - * Save/Delete button position. - */ - private static final int BUTTON_SAVE_POS_Y = 109; + /** + * Save/Delete button position. + */ + private static final int BUTTON_SAVE_POS_Y = 109; - /** - * Clear button position. - */ - private static final int BUTTON_CLEAR_POS_X = 80; + /** + * Clear button position. + */ + private static final int BUTTON_CLEAR_POS_X = 80; - /** - * Clear button position. - */ - private static final int BUTTON_CLEAR_POS_Y = 89; + /** + * Clear button position. + */ + private static final int BUTTON_CLEAR_POS_Y = 89; - /** - * Position of the title string. - */ - private static final int TITLE_POS_X = 6; + /** + * Position of the title string. + */ + private static final int TITLE_POS_X = 6; - /** - * Position of the title string. - */ - private static final int TITLE_POS_Y = 6; + /** + * Position of the title string. + */ + private static final int TITLE_POS_Y = 6; - /** - * Player viewing the GUI. - */ - private final EntityPlayer player; + /** + * Player viewing the GUI. + */ + private final EntityPlayer player; - /** - * Save particles - */ - private final GuiParticleAnimator[] particles; + /** + * Save particles + */ + private final GuiParticleAnimator[] particles; - /** - * GUI Title - */ - private final String title; + /** + * GUI Title + */ + private final String title; - /** - * Save / Delete button. - */ - private GuiButtonSaveDelete buttonSave; + /** + * Save / Delete button. + */ + private GuiButtonSaveDelete buttonSave; - /** - * Clear grid button. - */ - private GuiButtonClearCraftingGrid buttonClear; + /** + * Clear grid button. + */ + private GuiButtonClearCraftingGrid buttonClear; - /** - * State of the save button. - */ - private CoreSaveState saveState = CoreSaveState.Disabled_MissingCore; + /** + * State of the save button. + */ + private CoreSaveState saveState = CoreSaveState.Disabled_MissingCore; - /** - * True if particles need to be drawn. - */ - private boolean hasParticlesToDraw = false; + /** + * True if particles need to be drawn. + */ + private boolean hasParticlesToDraw = false; - public GuiKnowledgeInscriber( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( new ContainerKnowledgeInscriber( player, world, x, y, z ) ); + public GuiKnowledgeInscriber(final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(new ContainerKnowledgeInscriber(player, world, x, y, z)); - // Set the player - this.player = player; + // Set the player + this.player = player; - // Set the GUI size - this.xSize = GuiKnowledgeInscriber.GUI_WIDTH; - this.ySize = GuiKnowledgeInscriber.GUI_HEIGHT; + // Set the GUI size + this.xSize = GuiKnowledgeInscriber.GUI_WIDTH; + this.ySize = GuiKnowledgeInscriber.GUI_HEIGHT; - // Set title - this.title = ThEStrings.Block_KnowledgeInscriber.getLocalized(); + // Set title + this.title = ThEStrings.Block_KnowledgeInscriber.getLocalized(); - // Setup the particles - this.particles = new GuiParticleAnimator[ContainerKnowledgeInscriber.CRAFTING_COLS * ContainerKnowledgeInscriber.CRAFTING_ROWS]; - for( int index = 0; index < this.particles.length; ++index ) - { - this.particles[index] = this.createSaveParticle( index ); - } - } + // Setup the particles + this.particles = new GuiParticleAnimator + [ContainerKnowledgeInscriber.CRAFTING_COLS * ContainerKnowledgeInscriber.CRAFTING_ROWS]; + for (int index = 0; index < this.particles.length; ++index) { + this.particles[index] = this.createSaveParticle(index); + } + } - /** - * Creates a particle for the specified slot number. - * - * @param slotNumber - * @return - */ - private GuiParticleAnimator createSaveParticle( final int slotNumber ) - { - int startX = ContainerKnowledgeInscriber.CRAFTING_SLOT_X + - ( ( slotNumber % ContainerKnowledgeInscriber.CRAFTING_COLS ) * ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING ); + /** + * Creates a particle for the specified slot number. + * + * @param slotNumber + * @return + */ + private GuiParticleAnimator createSaveParticle(final int slotNumber) { + int startX = ContainerKnowledgeInscriber.CRAFTING_SLOT_X + + ((slotNumber % ContainerKnowledgeInscriber.CRAFTING_COLS) + * ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING); - int startY = ContainerKnowledgeInscriber.CRAFTING_SLOT_Y + - ( ( slotNumber / ContainerKnowledgeInscriber.CRAFTING_COLS ) * ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING ); + int startY = ContainerKnowledgeInscriber.CRAFTING_SLOT_Y + + ((slotNumber / ContainerKnowledgeInscriber.CRAFTING_COLS) + * ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING); - // Create the animator - GuiParticleAnimator gpa = new GuiParticleAnimator( startX, startY, - ContainerKnowledgeInscriber.KCORE_SLOT_X, ContainerKnowledgeInscriber.KCORE_SLOT_Y, - 0.4f, EnumGuiParticles.Knowledge ); + // Create the animator + GuiParticleAnimator gpa = new GuiParticleAnimator( + startX, + startY, + ContainerKnowledgeInscriber.KCORE_SLOT_X, + ContainerKnowledgeInscriber.KCORE_SLOT_Y, + 0.4f, + EnumGuiParticles.Knowledge); - // Set color - gpa.setColor( 0.2f, 0.5f, 1.0f ); + // Set color + gpa.setColor(0.2f, 0.5f, 1.0f); - // Set delay - gpa.setDelayTime( slotNumber * 50L ); + // Set delay + gpa.setDelayTime(slotNumber * 50L); - return gpa; - } + return gpa; + } - /** - * Draws all save particles. - */ - private void drawSaveParticles() - { - // Assume all particles are drawn - this.hasParticlesToDraw = false; + /** + * Draws all save particles. + */ + private void drawSaveParticles() { + // Assume all particles are drawn + this.hasParticlesToDraw = false; - EnumGuiParticles.Knowledge.prepareDraw(); - for( int index = 0; index < this.particles.length; ++index ) - { - // Draw the particle - this.hasParticlesToDraw |= this.particles[index].draw( this, false ); - } - EnumGuiParticles.finishDraw(); - } + EnumGuiParticles.Knowledge.prepareDraw(); + for (int index = 0; index < this.particles.length; ++index) { + // Draw the particle + this.hasParticlesToDraw |= this.particles[index].draw(this, false); + } + EnumGuiParticles.finishDraw(); + } - /** - * Draw background - */ - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Calculate the color shifts - long slowTime = ( System.currentTimeMillis() / 100 ); - float redBounce = Math.abs( 1.0F - ( ( ( slowTime % 50 ) / 50.0F ) * 2.0F ) ); - float greenBounce = 1.0F - redBounce; + /** + * Draw background + */ + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Calculate the color shifts + long slowTime = (System.currentTimeMillis() / 100); + float redBounce = Math.abs(1.0F - (((slowTime % 50) / 50.0F) * 2.0F)); + float greenBounce = 1.0F - redBounce; - // Shift color - GL11.glColor4f( redBounce, greenBounce, 1.0F, 1.0F ); + // Shift color + GL11.glColor4f(redBounce, greenBounce, 1.0F, 1.0F); - // Bind the research background - Minecraft.getMinecraft().renderEngine.bindTexture( new ResourceLocation( ThaumicEnergistics.MOD_ID, - "textures/research/Research.Background.png" ) ); + // Bind the research background + Minecraft.getMinecraft() + .renderEngine + .bindTexture( + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/research/Research.Background.png")); - // Calculate the X position - int xpos = (int)( slowTime % 10 ); + // Calculate the X position + int xpos = (int) (slowTime % 10); - // Draw the background - this.drawTexturedModalRect( this.guiLeft + 80, this.guiTop + 106, 55 - xpos, 25, 35, 20 ); + // Draw the background + this.drawTexturedModalRect(this.guiLeft + 80, this.guiTop + 106, 55 - xpos, 25, 35, 20); - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // Bind the workbench gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.KNOWLEDGE_INSCRIBER.getTexture() ); + // Bind the workbench gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.KNOWLEDGE_INSCRIBER.getTexture()); - // Draw the gui texture - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); - } + // Draw the gui texture + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + } - /** - * Draw the foreground - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( this.title, GuiKnowledgeInscriber.TITLE_POS_X, GuiKnowledgeInscriber.TITLE_POS_Y, 0 ); + /** + * Draw the foreground + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString( + this.title, GuiKnowledgeInscriber.TITLE_POS_X, GuiKnowledgeInscriber.TITLE_POS_Y, 0); - // Any particles to draw? - if( this.hasParticlesToDraw ) - { - this.drawSaveParticles(); - } - } + // Any particles to draw? + if (this.hasParticlesToDraw) { + this.drawSaveParticles(); + } + } - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Was the clicked button the save button? - if( button == this.buttonSave ) - { - // Send the request to the server - Packet_S_KnowledgeInscriber.sendSaveDelete( this.player ); - } - else if( button == this.buttonClear ) - { - // Send the request to the server - Packet_S_KnowledgeInscriber.sendClearGrid( this.player ); - } - } + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Was the clicked button the save button? + if (button == this.buttonSave) { + // Send the request to the server + Packet_S_KnowledgeInscriber.sendSaveDelete(this.player); + } else if (button == this.buttonClear) { + // Send the request to the server + Packet_S_KnowledgeInscriber.sendClearGrid(this.player); + } + } - @Override - public void initGui() - { - // Call super - super.initGui(); + @Override + public void initGui() { + // Call super + super.initGui(); - this.buttonList.clear(); + this.buttonList.clear(); - // Create the save/delete button - this.buttonSave = new GuiButtonSaveDelete( 0, this.guiLeft + GuiKnowledgeInscriber.BUTTON_SAVE_POS_X, - this.guiTop + GuiKnowledgeInscriber.BUTTON_SAVE_POS_Y, this.saveState ); - this.buttonList.add( this.buttonSave ); + // Create the save/delete button + this.buttonSave = new GuiButtonSaveDelete( + 0, + this.guiLeft + GuiKnowledgeInscriber.BUTTON_SAVE_POS_X, + this.guiTop + GuiKnowledgeInscriber.BUTTON_SAVE_POS_Y, + this.saveState); + this.buttonList.add(this.buttonSave); - // Create the clear grid button - this.buttonClear = new GuiButtonClearCraftingGrid( 1, this.guiLeft + GuiKnowledgeInscriber.BUTTON_CLEAR_POS_X, - this.guiTop + GuiKnowledgeInscriber.BUTTON_CLEAR_POS_Y, 8, 8, false ); - this.buttonList.add( this.buttonClear ); + // Create the clear grid button + this.buttonClear = new GuiButtonClearCraftingGrid( + 1, + this.guiLeft + GuiKnowledgeInscriber.BUTTON_CLEAR_POS_X, + this.guiTop + GuiKnowledgeInscriber.BUTTON_CLEAR_POS_Y, + 8, + 8, + false); + this.buttonList.add(this.buttonClear); - // Request full update - Packet_S_KnowledgeInscriber.sendFullUpdateRequest( this.player ); - } + // Request full update + Packet_S_KnowledgeInscriber.sendFullUpdateRequest(this.player); + } - /** - * Called when the server sends a change in the save/load button - * functionality. - * - * @param saveState - * @param justSaved - */ - public void onReceiveSaveState( final CoreSaveState saveState, final boolean justSaved ) - { - // Set the state - this.saveState = saveState; + /** + * Called when the server sends a change in the save/load button + * functionality. + * + * @param saveState + * @param justSaved + */ + public void onReceiveSaveState(final CoreSaveState saveState, final boolean justSaved) { + // Set the state + this.saveState = saveState; - // Update the button - if( this.buttonSave != null ) - { - this.buttonSave.setSaveState( saveState ); - } + // Update the button + if (this.buttonSave != null) { + this.buttonSave.setSaveState(saveState); + } - // Was a pattern just saved? - if( justSaved ) - { - // Reset all particles - for( int index = 0; index < this.particles.length; ++index ) - { - this.particles[index].reset(); - } - this.hasParticlesToDraw = true; - } - } + // Was a pattern just saved? + if (justSaved) { + // Reset all particles + for (int index = 0; index < this.particles.length; ++index) { + this.particles[index].reset(); + } + this.hasParticlesToDraw = true; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiParticleAnimator.java b/src/main/java/thaumicenergistics/client/gui/GuiParticleAnimator.java index 6908aa47..7f68e547 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiParticleAnimator.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiParticleAnimator.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui; -import javax.annotation.Nonnull; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nonnull; import net.minecraft.client.gui.Gui; /** @@ -12,213 +12,204 @@ import net.minecraft.client.gui.Gui; * */ @SideOnly(Side.CLIENT) -public class GuiParticleAnimator -{ - /** - * Distance from start to destination. - */ - private final int distanceX; +public class GuiParticleAnimator { + /** + * Distance from start to destination. + */ + private final int distanceX; - /** - * Distance from start to destination. - */ - private final int distanceY; + /** + * Distance from start to destination. + */ + private final int distanceY; - /** - * The amount of time the particle is alive for. - */ - private final long timeToLive; + /** + * The amount of time the particle is alive for. + */ + private final long timeToLive; - /** - * Time when the particle was created. - */ - private long epoch; + /** + * Time when the particle was created. + */ + private long epoch; - /** - * How complete the animation is. - */ - private double percentComplete; + /** + * How complete the animation is. + */ + private double percentComplete; - /** - * The number of MS to wait before starting the animation. - */ - private long delayTime = 0; + /** + * The number of MS to wait before starting the animation. + */ + private long delayTime = 0; - /** - * Color of the particle. - */ - private float red = 1.0f; + /** + * Color of the particle. + */ + private float red = 1.0f; - /** - * Color of the particle. - */ - private float green = 1.0f; + /** + * Color of the particle. + */ + private float green = 1.0f; - /** - * Color of the particle. - */ - private float blue = 1.0f; + /** + * Color of the particle. + */ + private float blue = 1.0f; - /** - * Particle frames per second. - */ - private int framesPerSecond = 1; + /** + * Particle frames per second. + */ + private int framesPerSecond = 1; - /** - * Starting position. - */ - public final int startingX; + /** + * Starting position. + */ + public final int startingX; - /** - * Starting position. - */ - public final int startingY; + /** + * Starting position. + */ + public final int startingY; - /** - * Destination position. - */ - public final int destinationX; + /** + * Destination position. + */ + public final int destinationX; - /** - * Destination position. - */ - public final int destinationY; + /** + * Destination position. + */ + public final int destinationY; - /** - * The particle to draw. - */ - public final EnumGuiParticles theParticle; + /** + * The particle to draw. + */ + public final EnumGuiParticles theParticle; - public GuiParticleAnimator( final int startX, final int startY, final int destX, final int destY, final float time, - @Nonnull final EnumGuiParticles particle ) - { - // Set starting position - this.startingX = startX; - this.startingY = startY; + public GuiParticleAnimator( + final int startX, + final int startY, + final int destX, + final int destY, + final float time, + @Nonnull final EnumGuiParticles particle) { + // Set starting position + this.startingX = startX; + this.startingY = startY; - // Set destination - this.destinationX = destX; - this.destinationY = destY; + // Set destination + this.destinationX = destX; + this.destinationY = destY; - // Set TTL - this.timeToLive = (long)( time * 1000.0f ); - if( this.timeToLive <= 0 ) - { - this.percentComplete = 1.0f; - } + // Set TTL + this.timeToLive = (long) (time * 1000.0f); + if (this.timeToLive <= 0) { + this.percentComplete = 1.0f; + } - // Set epoch - this.epoch = System.currentTimeMillis(); + // Set epoch + this.epoch = System.currentTimeMillis(); - // Set particle - this.theParticle = particle; + // Set particle + this.theParticle = particle; - // Calculate distance - this.distanceX = destX - startX; - this.distanceY = destY - startY; - } + // Calculate distance + this.distanceX = destX - startX; + this.distanceY = destY - startY; + } - /** - * Returns false if the particle has reached the end of its life. - * - * @param gui - * @param needsPrepare - * @return - */ - public boolean draw( final Gui gui, final boolean needsPrepare ) - { - // Check percentage - if( this.percentComplete == 1.0f ) - { - return false; - } + /** + * Returns false if the particle has reached the end of its life. + * + * @param gui + * @param needsPrepare + * @return + */ + public boolean draw(final Gui gui, final boolean needsPrepare) { + // Check percentage + if (this.percentComplete == 1.0f) { + return false; + } - // Calculate frame number - int frame = (int)( System.currentTimeMillis() / ( 1000 / this.framesPerSecond ) ); + // Calculate frame number + int frame = (int) (System.currentTimeMillis() / (1000 / this.framesPerSecond)); - // Draw - return this.draw( gui, frame, needsPrepare ); - } + // Draw + return this.draw(gui, frame, needsPrepare); + } - /** - * Returns false if the particle has reached the end of its life. - * - * @param gui - * @param particleFrame - * @param needsPrepare - * @return - */ - public boolean draw( final Gui gui, final int particleFrame, final boolean needsPrepare ) - { - // Check percentage - if( this.percentComplete == 1.0f ) - { - return false; - } + /** + * Returns false if the particle has reached the end of its life. + * + * @param gui + * @param particleFrame + * @param needsPrepare + * @return + */ + public boolean draw(final Gui gui, final int particleFrame, final boolean needsPrepare) { + // Check percentage + if (this.percentComplete == 1.0f) { + return false; + } - // Calculate percentage - this.percentComplete = ( ( System.currentTimeMillis() - this.epoch ) / (double)this.timeToLive ); - if( this.percentComplete > 1.0f ) - { - this.percentComplete = 1.0f; - } - else if( this.percentComplete < 0 ) - { - // Delayed - return true; - } + // Calculate percentage + this.percentComplete = ((System.currentTimeMillis() - this.epoch) / (double) this.timeToLive); + if (this.percentComplete > 1.0f) { + this.percentComplete = 1.0f; + } else if (this.percentComplete < 0) { + // Delayed + return true; + } - // Calculate position - int posX = this.startingX + (int)( this.distanceX * this.percentComplete ); - int posY = this.startingY + (int)( this.distanceY * this.percentComplete ); + // Calculate position + int posX = this.startingX + (int) (this.distanceX * this.percentComplete); + int posY = this.startingY + (int) (this.distanceY * this.percentComplete); - // Draw the particle - this.theParticle.drawParticle( gui, posX, posY, particleFrame, this.red, this.green, this.blue, needsPrepare ); + // Draw the particle + this.theParticle.drawParticle(gui, posX, posY, particleFrame, this.red, this.green, this.blue, needsPrepare); - return true; - } + return true; + } - /** - * Resets the particle back to it's original state. - */ - public void reset() - { - this.epoch = System.currentTimeMillis() + this.delayTime; - this.percentComplete = 0; - } + /** + * Resets the particle back to it's original state. + */ + public void reset() { + this.epoch = System.currentTimeMillis() + this.delayTime; + this.percentComplete = 0; + } - /** - * Sets the color of the particle. - * - * @param red - * @param green - * @param blue - */ - public void setColor( final float red, final float green, final float blue ) - { - this.red = red; - this.green = green; - this.blue = blue; - } + /** + * Sets the color of the particle. + * + * @param red + * @param green + * @param blue + */ + public void setColor(final float red, final float green, final float blue) { + this.red = red; + this.green = green; + this.blue = blue; + } - /** - * Sets the number of MS to wait before starting the animation. - * - * @param timeMS - */ - public void setDelayTime( final long timeMS ) - { - this.delayTime = timeMS; - this.epoch += this.delayTime; - } + /** + * Sets the number of MS to wait before starting the animation. + * + * @param timeMS + */ + public void setDelayTime(final long timeMS) { + this.delayTime = timeMS; + this.epoch += this.delayTime; + } - /** - * Sets the frames per second - * - * @param fps - */ - public void setFPS( final int fps ) - { - this.framesPerSecond = fps; - } + /** + * Sets the frames per second + * + * @param fps + */ + public void setFPS(final int fps) { + this.framesPerSecond = fps; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/GuiPriority.java b/src/main/java/thaumicenergistics/client/gui/GuiPriority.java index 57bd25b9..a630239a 100644 --- a/src/main/java/thaumicenergistics/client/gui/GuiPriority.java +++ b/src/main/java/thaumicenergistics/client/gui/GuiPriority.java @@ -1,7 +1,5 @@ package thaumicenergistics.client.gui; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; import appeng.core.localization.GuiText; import appeng.helpers.IPriorityHost; import cpw.mods.fml.relauncher.Side; @@ -10,6 +8,8 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; import thaumicenergistics.client.gui.abstraction.ThEBaseGui; import thaumicenergistics.client.gui.buttons.GuiButtonAETab; import thaumicenergistics.client.gui.widget.DigitTextField; @@ -27,378 +27,359 @@ import thaumicenergistics.common.parts.ThEPartBase; * */ @SideOnly(Side.CLIENT) -public class GuiPriority - extends ThEBaseGui -{ - private static class AdjustmentButtonDef - { - enum EnumButtonWidth - { - Small (25), - Medium (35), - Large (45); - - public final int width; - - private EnumButtonWidth( final int width ) - { - this.width = width; - } - } - - /** - * Height of all buttons - */ - private static final int BUTTON_HEIGHT = 20; - - /** - * Width of the button - */ - public final int width; - - /** - * Caption of the button - */ - public final String caption; - - /** - * Amount the button represents - */ - public final int amount; - - /** - * Creates the button definition - * - * @param buttonWidth - * @param amount - */ - public AdjustmentButtonDef( final EnumButtonWidth buttonWidth, final int amount ) - { - // Set the width - this.width = buttonWidth.width; - - // Set the caption - this.caption = ( amount > 0 ? "+" : "" ) + Integer.toString( amount ); - - // Set the amount - this.amount = amount; - } - - /** - * Creates a GUI button based of this definition - * - * @param ID - * @param xPosition - * @param yPosition - * @return - */ - public GuiButton makeButton( final int ID, final int xPosition, final int yPosition ) - { - return new GuiButton( ID, xPosition, yPosition, this.width, AdjustmentButtonDef.BUTTON_HEIGHT, this.caption ); - } - - } - - private static final AdjustmentButtonDef[] ADJUSTMENT_BUTTONS = new AdjustmentButtonDef[] { - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Small, 1 ), - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Medium, 10 ), - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Large, 100 ), - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Small, -1 ), - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Medium, -10 ), - new AdjustmentButtonDef( AdjustmentButtonDef.EnumButtonWidth.Large, -100 ) }; - - /** - * The width of the gui - */ - private static final int GUI_WIDTH = 176; - - /** - * The height of the gui - */ - private static final int GUI_HEIGHT = 107; - - /** - * ID of the switch tab - */ - private static final int PART_SWITCH_BUTTON_ID = 0; - - /** - * X position of the switch tab - */ - private static final int PART_SWITCH_BUTTON_X_POSITION = 154; - - /** - * Starting ID of the adjustment buttons - */ - private static final int ADJUSTMENT_BUTTONS_ID = 1; - - /** - * Starting X position for each row of buttons - */ - private static final int ADJUSTMENT_BUTTONS_X_POSITION = 35; - - /** - * Y position for each row - */ - private static final int[] ADJUSTMENT_BUTTONS_Y_POSITION = new int[] { 30, 70 }; - - /** - * Amount of empty space between buttons - */ - private static final int ADJUSTMENT_BUTTONS_X_PADDING = 5; - - /** - * X offset for the amount field. - */ - private static final int AMOUNT_OFFSET_X = 61; - - /** - * Y offset for the amount field. - */ - private static final int AMOUNT_OFFSET_Y = 57; - - /** - * Width of the amount field. - */ - private static final int AMOUNT_WIDTH = 80; - - /** - * Height of the amount field. - */ - private static final int AMOUNT_HEIGHT = 10; - - /** - * The maximum number of characters that can be typed in the amount field. - */ - private static final int AMOUNT_MAX_CHARS = 8; - - /** - * X position of the title string. - */ - private static final int TITLE_POS_X = 6; - - /** - * Y position of the title string. - */ - private static final int TITLE_POS_Y = 6; - - /** - * The part we are adjusting the priority of - */ - private final ThEPartBase part; - - /** - * The player viewing the gui. - */ - private final EntityPlayer player; - - /** - * Title of the window - */ - private final String title; - - /** - * Amount text field - */ - private DigitTextField amountField; - - /** - * Create the gui. - * - * @param host - * @param player - */ - public GuiPriority( final IPriorityHost host, final EntityPlayer player ) - { - // Call super and pass the priority container - super( new ContainerPriority( host, player ) ); - - // Get the part - this.part = (ThEPartBase)host; - - // Set the player - this.player = player; - - // Set the width and height - this.xSize = GuiPriority.GUI_WIDTH; - this.ySize = GuiPriority.GUI_HEIGHT; - - // Set the title - this.title = GuiText.Priority.getLocal(); - } - - @Override - protected void drawGuiContainerBackgroundLayer( final float alpha, final int mouseX, final int mouseY ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - // Bind the priority gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.PRIORITY.getTexture() ); - - this.drawTexturedModalRect( this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize ); - - } - - /** - * Draw the foreground - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Draw the title - this.fontRendererObj.drawString( this.title, GuiPriority.TITLE_POS_X, GuiPriority.TITLE_POS_Y, 0 ); - - // Draw the text field - this.amountField.drawTextBox(); - } - - /** - * Called when the player types a key - */ - @Override - protected void keyTyped( final char key, final int keyID ) - { - // Pass to super - super.keyTyped( key, keyID ); - - // Ensure the string isn't too long to parse - if( this.amountField.getText().length() < GuiPriority.AMOUNT_MAX_CHARS ) - { - // Pass to the amount field - this.amountField.textboxKeyTyped( key, keyID ); - - // Check if they are intending to type a negative number - if( this.amountField.getText().equals( "-" ) ) - { - return; - } - - // Convert the text field into a long - int newPriority = 0; - try - { - newPriority = Integer.parseInt( this.amountField.getText() ); - } - catch( NumberFormatException e ) - { - } - - // Update the server - Packet_S_Priority.sendPriority( newPriority, this.player ); - } - } - - /** - * Called when a button is clicked. - */ - @Override - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - // Was the priority button clicked? - if( button.id == GuiPriority.PART_SWITCH_BUTTON_ID ) - { - // Get the storage buses host - TileEntity host = this.part.getHostTile(); - - // Ask the server to change to the priority gui - Packet_S_ChangeGui.sendGuiChangeToPart( this.part, this.player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); - return; - - } - - // Assume it was an adjustment button - try - { - // Get the definition - AdjustmentButtonDef abDef = GuiPriority.ADJUSTMENT_BUTTONS[button.id - GuiPriority.ADJUSTMENT_BUTTONS_ID]; - - // Send the adjustment to the server - Packet_S_Priority.sendPriorityDelta( abDef.amount, this.player ); - } - catch( IndexOutOfBoundsException e ) - { - return; - } - - } - - @Override - public void initGui() - { - // Call super - super.initGui(); - - // Enable repeat keys - Keyboard.enableRepeatEvents( true ); - - // Create the part switch button - this.buttonList.add( new GuiButtonAETab( GuiPriority.PART_SWITCH_BUTTON_ID, this.guiLeft + GuiPriority.PART_SWITCH_BUTTON_X_POSITION, - this.guiTop, AEStateIconsEnum.WRENCH, this.part.getUnlocalizedName() ) ); - - // Create the adjustment buttons - int buttonXPosition = GuiPriority.ADJUSTMENT_BUTTONS_X_POSITION; - int buttonYPosition = GuiPriority.ADJUSTMENT_BUTTONS_Y_POSITION[0]; - for( int adjustmentButtonIndex = 0; adjustmentButtonIndex < GuiPriority.ADJUSTMENT_BUTTONS.length; adjustmentButtonIndex++ ) - { - // Get the button def - AdjustmentButtonDef def = GuiPriority.ADJUSTMENT_BUTTONS[adjustmentButtonIndex]; - - // Calculate the ID - int ID = GuiPriority.ADJUSTMENT_BUTTONS_ID + adjustmentButtonIndex; - - // Are we moving into row 2? - if( adjustmentButtonIndex == ( GuiPriority.ADJUSTMENT_BUTTONS.length / 2 ) ) - { - // Reset X - buttonXPosition = GuiPriority.ADJUSTMENT_BUTTONS_X_POSITION; - - // Set Y - buttonYPosition = GuiPriority.ADJUSTMENT_BUTTONS_Y_POSITION[1]; - } - - // Add the button - this.buttonList.add( def.makeButton( ID, this.guiLeft + buttonXPosition, this.guiTop + buttonYPosition ) ); - - // Increment X - buttonXPosition += def.width + GuiPriority.ADJUSTMENT_BUTTONS_X_PADDING; - } - // Create the amount field - this.amountField = new DigitTextField( this.fontRendererObj, GuiPriority.AMOUNT_OFFSET_X, GuiPriority.AMOUNT_OFFSET_Y, - GuiPriority.AMOUNT_WIDTH, GuiPriority.AMOUNT_HEIGHT ); - - // Start focused - this.amountField.setFocused( true ); - - // Draw in the forground - this.amountField.setEnableBackgroundDrawing( false ); - - // Text color white - this.amountField.setTextColor( 0xFFFFFFFF ); - - // Ask for the priority from the server - Packet_S_Priority.sendPriorityRequest( this.player ); - } - - /** - * Called when the gui is closing. - */ - @Override - public void onGuiClosed() - { - // Disable repeat keys - Keyboard.enableRepeatEvents( false ); - } - - /** - * Called when the server sends the priority. - * - * @param priority - */ - public void onServerSendPriority( final int priority ) - { - // Set the textbox text - this.amountField.setText( Integer.toString( priority ) ); - } - +public class GuiPriority extends ThEBaseGui { + private static class AdjustmentButtonDef { + enum EnumButtonWidth { + Small(25), + Medium(35), + Large(45); + + public final int width; + + private EnumButtonWidth(final int width) { + this.width = width; + } + } + + /** + * Height of all buttons + */ + private static final int BUTTON_HEIGHT = 20; + + /** + * Width of the button + */ + public final int width; + + /** + * Caption of the button + */ + public final String caption; + + /** + * Amount the button represents + */ + public final int amount; + + /** + * Creates the button definition + * + * @param buttonWidth + * @param amount + */ + public AdjustmentButtonDef(final EnumButtonWidth buttonWidth, final int amount) { + // Set the width + this.width = buttonWidth.width; + + // Set the caption + this.caption = (amount > 0 ? "+" : "") + Integer.toString(amount); + + // Set the amount + this.amount = amount; + } + + /** + * Creates a GUI button based of this definition + * + * @param ID + * @param xPosition + * @param yPosition + * @return + */ + public GuiButton makeButton(final int ID, final int xPosition, final int yPosition) { + return new GuiButton(ID, xPosition, yPosition, this.width, AdjustmentButtonDef.BUTTON_HEIGHT, this.caption); + } + } + + private static final AdjustmentButtonDef[] ADJUSTMENT_BUTTONS = new AdjustmentButtonDef[] { + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Small, 1), + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Medium, 10), + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Large, 100), + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Small, -1), + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Medium, -10), + new AdjustmentButtonDef(AdjustmentButtonDef.EnumButtonWidth.Large, -100) + }; + + /** + * The width of the gui + */ + private static final int GUI_WIDTH = 176; + + /** + * The height of the gui + */ + private static final int GUI_HEIGHT = 107; + + /** + * ID of the switch tab + */ + private static final int PART_SWITCH_BUTTON_ID = 0; + + /** + * X position of the switch tab + */ + private static final int PART_SWITCH_BUTTON_X_POSITION = 154; + + /** + * Starting ID of the adjustment buttons + */ + private static final int ADJUSTMENT_BUTTONS_ID = 1; + + /** + * Starting X position for each row of buttons + */ + private static final int ADJUSTMENT_BUTTONS_X_POSITION = 35; + + /** + * Y position for each row + */ + private static final int[] ADJUSTMENT_BUTTONS_Y_POSITION = new int[] {30, 70}; + + /** + * Amount of empty space between buttons + */ + private static final int ADJUSTMENT_BUTTONS_X_PADDING = 5; + + /** + * X offset for the amount field. + */ + private static final int AMOUNT_OFFSET_X = 61; + + /** + * Y offset for the amount field. + */ + private static final int AMOUNT_OFFSET_Y = 57; + + /** + * Width of the amount field. + */ + private static final int AMOUNT_WIDTH = 80; + + /** + * Height of the amount field. + */ + private static final int AMOUNT_HEIGHT = 10; + + /** + * The maximum number of characters that can be typed in the amount field. + */ + private static final int AMOUNT_MAX_CHARS = 8; + + /** + * X position of the title string. + */ + private static final int TITLE_POS_X = 6; + + /** + * Y position of the title string. + */ + private static final int TITLE_POS_Y = 6; + + /** + * The part we are adjusting the priority of + */ + private final ThEPartBase part; + + /** + * The player viewing the gui. + */ + private final EntityPlayer player; + + /** + * Title of the window + */ + private final String title; + + /** + * Amount text field + */ + private DigitTextField amountField; + + /** + * Create the gui. + * + * @param host + * @param player + */ + public GuiPriority(final IPriorityHost host, final EntityPlayer player) { + // Call super and pass the priority container + super(new ContainerPriority(host, player)); + + // Get the part + this.part = (ThEPartBase) host; + + // Set the player + this.player = player; + + // Set the width and height + this.xSize = GuiPriority.GUI_WIDTH; + this.ySize = GuiPriority.GUI_HEIGHT; + + // Set the title + this.title = GuiText.Priority.getLocal(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(final float alpha, final int mouseX, final int mouseY) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + // Bind the priority gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.PRIORITY.getTexture()); + + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + } + + /** + * Draw the foreground + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Draw the title + this.fontRendererObj.drawString(this.title, GuiPriority.TITLE_POS_X, GuiPriority.TITLE_POS_Y, 0); + + // Draw the text field + this.amountField.drawTextBox(); + } + + /** + * Called when the player types a key + */ + @Override + protected void keyTyped(final char key, final int keyID) { + // Pass to super + super.keyTyped(key, keyID); + + // Ensure the string isn't too long to parse + if (this.amountField.getText().length() < GuiPriority.AMOUNT_MAX_CHARS) { + // Pass to the amount field + this.amountField.textboxKeyTyped(key, keyID); + + // Check if they are intending to type a negative number + if (this.amountField.getText().equals("-")) { + return; + } + + // Convert the text field into a long + int newPriority = 0; + try { + newPriority = Integer.parseInt(this.amountField.getText()); + } catch (NumberFormatException e) { + } + + // Update the server + Packet_S_Priority.sendPriority(newPriority, this.player); + } + } + + /** + * Called when a button is clicked. + */ + @Override + protected void onButtonClicked(final GuiButton button, final int mouseButton) { + // Was the priority button clicked? + if (button.id == GuiPriority.PART_SWITCH_BUTTON_ID) { + // Get the storage buses host + TileEntity host = this.part.getHostTile(); + + // Ask the server to change to the priority gui + Packet_S_ChangeGui.sendGuiChangeToPart( + this.part, this.player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord); + return; + } + + // Assume it was an adjustment button + try { + // Get the definition + AdjustmentButtonDef abDef = GuiPriority.ADJUSTMENT_BUTTONS[button.id - GuiPriority.ADJUSTMENT_BUTTONS_ID]; + + // Send the adjustment to the server + Packet_S_Priority.sendPriorityDelta(abDef.amount, this.player); + } catch (IndexOutOfBoundsException e) { + return; + } + } + + @Override + public void initGui() { + // Call super + super.initGui(); + + // Enable repeat keys + Keyboard.enableRepeatEvents(true); + + // Create the part switch button + this.buttonList.add(new GuiButtonAETab( + GuiPriority.PART_SWITCH_BUTTON_ID, + this.guiLeft + GuiPriority.PART_SWITCH_BUTTON_X_POSITION, + this.guiTop, + AEStateIconsEnum.WRENCH, + this.part.getUnlocalizedName())); + + // Create the adjustment buttons + int buttonXPosition = GuiPriority.ADJUSTMENT_BUTTONS_X_POSITION; + int buttonYPosition = GuiPriority.ADJUSTMENT_BUTTONS_Y_POSITION[0]; + for (int adjustmentButtonIndex = 0; + adjustmentButtonIndex < GuiPriority.ADJUSTMENT_BUTTONS.length; + adjustmentButtonIndex++) { + // Get the button def + AdjustmentButtonDef def = GuiPriority.ADJUSTMENT_BUTTONS[adjustmentButtonIndex]; + + // Calculate the ID + int ID = GuiPriority.ADJUSTMENT_BUTTONS_ID + adjustmentButtonIndex; + + // Are we moving into row 2? + if (adjustmentButtonIndex == (GuiPriority.ADJUSTMENT_BUTTONS.length / 2)) { + // Reset X + buttonXPosition = GuiPriority.ADJUSTMENT_BUTTONS_X_POSITION; + + // Set Y + buttonYPosition = GuiPriority.ADJUSTMENT_BUTTONS_Y_POSITION[1]; + } + + // Add the button + this.buttonList.add(def.makeButton(ID, this.guiLeft + buttonXPosition, this.guiTop + buttonYPosition)); + + // Increment X + buttonXPosition += def.width + GuiPriority.ADJUSTMENT_BUTTONS_X_PADDING; + } + // Create the amount field + this.amountField = new DigitTextField( + this.fontRendererObj, + GuiPriority.AMOUNT_OFFSET_X, + GuiPriority.AMOUNT_OFFSET_Y, + GuiPriority.AMOUNT_WIDTH, + GuiPriority.AMOUNT_HEIGHT); + + // Start focused + this.amountField.setFocused(true); + + // Draw in the forground + this.amountField.setEnableBackgroundDrawing(false); + + // Text color white + this.amountField.setTextColor(0xFFFFFFFF); + + // Ask for the priority from the server + Packet_S_Priority.sendPriorityRequest(this.player); + } + + /** + * Called when the gui is closing. + */ + @Override + public void onGuiClosed() { + // Disable repeat keys + Keyboard.enableRepeatEvents(false); + } + + /** + * Called when the server sends the priority. + * + * @param priority + */ + public void onServerSendPriority(final int priority) { + // Set the textbox text + this.amountField.setText(Integer.toString(priority)); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/ThEGuiHelper.java b/src/main/java/thaumicenergistics/client/gui/ThEGuiHelper.java index e9fc0df4..fa26d101 100644 --- a/src/main/java/thaumicenergistics/client/gui/ThEGuiHelper.java +++ b/src/main/java/thaumicenergistics/client/gui/ThEGuiHelper.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui; -import java.util.HashMap; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.HashMap; import net.minecraft.client.gui.FontRenderer; import net.minecraft.util.EnumChatFormatting; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; /** @@ -15,233 +15,222 @@ import thaumcraft.api.aspects.Aspect; * */ @SideOnly(Side.CLIENT) -public final class ThEGuiHelper -{ +public final class ThEGuiHelper { - /** - * Singleton - */ - public static final ThEGuiHelper INSTANCE = new ThEGuiHelper(); + /** + * Singleton + */ + public static final ThEGuiHelper INSTANCE = new ThEGuiHelper(); - /** - * Maps int -> mouse button - */ - public static final int MOUSE_BUTTON_LEFT = 0, MOUSE_BUTTON_RIGHT = 1, MOUSE_BUTTON_WHEEL = 2; + /** + * Maps int -> mouse button + */ + public static final int MOUSE_BUTTON_LEFT = 0, MOUSE_BUTTON_RIGHT = 1, MOUSE_BUTTON_WHEEL = 2; - /** - * Special case representing not a click, but a motion of the mouse wheel - */ - public static final int MOUSE_WHEEL_MOTION = -2; + /** + * Special case representing not a click, but a motion of the mouse wheel + */ + public static final int MOUSE_WHEEL_MOTION = -2; - /** - * Length of color arrays. - */ - private static final int COLOR_ARRAY_SIZE = 4; + /** + * Length of color arrays. + */ + private static final int COLOR_ARRAY_SIZE = 4; - /** - * Bitshift amounts based on byte position - */ - private final int[] COLOR_SHIFT_AMOUNT = new int[] { 0, 8, 16, 24 }; + /** + * Bitshift amounts based on byte position + */ + private final int[] COLOR_SHIFT_AMOUNT = new int[] {0, 8, 16, 24}; - /** - * Maps aspects to chat colors. - */ - private HashMap aspectChatColors = new HashMap(); + /** + * Maps aspects to chat colors. + */ + private HashMap aspectChatColors = new HashMap(); - /** - * Private constructor. - */ - private ThEGuiHelper() - { - // Add the chat colors - this.aspectChatColors.put( Aspect.AIR, EnumChatFormatting.YELLOW.toString() ); - this.aspectChatColors.put( Aspect.WATER, EnumChatFormatting.AQUA.toString() ); - this.aspectChatColors.put( Aspect.FIRE, EnumChatFormatting.RED.toString() ); - this.aspectChatColors.put( Aspect.ORDER, EnumChatFormatting.GRAY.toString() ); - this.aspectChatColors.put( Aspect.ENTROPY, EnumChatFormatting.DARK_GRAY.toString() ); - this.aspectChatColors.put( Aspect.EARTH, EnumChatFormatting.GREEN.toString() ); + /** + * Private constructor. + */ + private ThEGuiHelper() { + // Add the chat colors + this.aspectChatColors.put(Aspect.AIR, EnumChatFormatting.YELLOW.toString()); + this.aspectChatColors.put(Aspect.WATER, EnumChatFormatting.AQUA.toString()); + this.aspectChatColors.put(Aspect.FIRE, EnumChatFormatting.RED.toString()); + this.aspectChatColors.put(Aspect.ORDER, EnumChatFormatting.GRAY.toString()); + this.aspectChatColors.put(Aspect.ENTROPY, EnumChatFormatting.DARK_GRAY.toString()); + this.aspectChatColors.put(Aspect.EARTH, EnumChatFormatting.GREEN.toString()); + } - } + public static final void drawScaledText( + final FontRenderer fontRenderer, final String text, final float scale, final float posX, final float posY) { + // Disable lighting + GL11.glDisable(GL11.GL_LIGHTING); - public static final void drawScaledText( final FontRenderer fontRenderer, final String text, final float scale, final float posX, - final float posY ) - { - // Disable lighting - GL11.glDisable( GL11.GL_LIGHTING ); + // Disable depth testing + GL11.glDisable(GL11.GL_DEPTH_TEST); - // Disable depth testing - GL11.glDisable( GL11.GL_DEPTH_TEST ); + // Push the current matrix + GL11.glPushMatrix(); - // Push the current matrix - GL11.glPushMatrix(); + // Scale the GUI + GL11.glScaled(scale, scale, scale); - // Scale the GUI - GL11.glScaled( scale, scale, scale ); + // Calculate inverse scale + float inverseScale = 1.0f / scale; - // Calculate inverse scale - float inverseScale = 1.0f / scale; + // Calculate final X position + final int X = (int) ((posX - (fontRenderer.getStringWidth(text) * scale)) * inverseScale); - // Calculate final X position - final int X = (int)( ( posX - ( fontRenderer.getStringWidth( text ) * scale ) ) * inverseScale ); + // Calculate final Y position + final int Y = (int) ((posY - (7.0f * scale)) * inverseScale); - // Calculate final Y position - final int Y = (int)( ( posY - ( 7.0f * scale ) ) * inverseScale ); + // Render + fontRenderer.drawStringWithShadow(text, X, Y, 16777215); - // Render - fontRenderer.drawStringWithShadow( text, X, Y, 16777215 ); + // Pop the matrix + GL11.glPopMatrix(); - // Pop the matrix - GL11.glPopMatrix(); + // Enable lighting + GL11.glEnable(GL11.GL_LIGHTING); - // Enable lighting - GL11.glEnable( GL11.GL_LIGHTING ); + // Enable depth testing + GL11.glEnable(GL11.GL_DEPTH_TEST); + } - // Enable depth testing - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } + public final byte[] convertPackedColorToARGBb(final int color) { + byte[] colorBytes = new byte[COLOR_ARRAY_SIZE]; - public final byte[] convertPackedColorToARGBb( final int color ) - { - byte[] colorBytes = new byte[COLOR_ARRAY_SIZE]; + // Extract bytes + for (int i = 0; i < COLOR_ARRAY_SIZE; i++) { + // Get byte + colorBytes[COLOR_ARRAY_SIZE - 1 - i] = (byte) ((color >> this.COLOR_SHIFT_AMOUNT[i]) & 0xFF); + } - // Extract bytes - for( int i = 0; i < COLOR_ARRAY_SIZE; i++ ) - { - // Get byte - colorBytes[COLOR_ARRAY_SIZE - 1 - i] = (byte)( ( color >> this.COLOR_SHIFT_AMOUNT[i] ) & 0xFF ); - } + return colorBytes; + } - return colorBytes; - } + public final float[] convertPackedColorToARGBf(final int color) { + float[] colorFloats = new float[COLOR_ARRAY_SIZE]; - public final float[] convertPackedColorToARGBf( final int color ) - { - float[] colorFloats = new float[COLOR_ARRAY_SIZE]; + // Extract bytes + for (int i = 0; i < COLOR_ARRAY_SIZE; i++) { + // Get floats + colorFloats[COLOR_ARRAY_SIZE - 1 - i] = ((color >> this.COLOR_SHIFT_AMOUNT[i]) & 0xFF) / 255.0f; + } - // Extract bytes - for( int i = 0; i < COLOR_ARRAY_SIZE; i++ ) - { - // Get floats - colorFloats[COLOR_ARRAY_SIZE - 1 - i] = ( ( color >> this.COLOR_SHIFT_AMOUNT[i] ) & 0xFF ) / 255.0f; - } + return colorFloats; + } - return colorFloats; - } + public final int[] createColorGradient(final int fromColor, final int toColor, final int iterations) { + // Is there enough iterations to create a gradient? + if (iterations < 3) { + return new int[] {fromColor, toColor}; + } - public final int[] createColorGradient( final int fromColor, final int toColor, final int iterations ) - { - // Is there enough iterations to create a gradient? - if( iterations < 3 ) - { - return new int[] { fromColor, toColor }; - } + // Holds the A,R,G,B bytes of each color + int[] fromColorBytes = new int[COLOR_ARRAY_SIZE]; + int[] toColorBytes = new int[COLOR_ARRAY_SIZE]; - // Holds the A,R,G,B bytes of each color - int[] fromColorBytes = new int[COLOR_ARRAY_SIZE]; - int[] toColorBytes = new int[COLOR_ARRAY_SIZE]; + // Holds how much to change the color amount by for each iteration + float[] stepAmount = new float[COLOR_ARRAY_SIZE]; - // Holds how much to change the color amount by for each iteration - float[] stepAmount = new float[COLOR_ARRAY_SIZE]; + // Holds the color 'bytes' as they change + float[] currentColor = new float[COLOR_ARRAY_SIZE]; - // Holds the color 'bytes' as they change - float[] currentColor = new float[COLOR_ARRAY_SIZE]; + // Holds the final list of colors + int[] gradient = new int[iterations]; - // Holds the final list of colors - int[] gradient = new int[iterations]; + // Extract bytes + for (int i = 0; i < COLOR_ARRAY_SIZE; i++) { + // Get fromColor byte + fromColorBytes[i] = (fromColor >> this.COLOR_SHIFT_AMOUNT[i]) & 0xFF; - // Extract bytes - for( int i = 0; i < COLOR_ARRAY_SIZE; i++ ) - { - // Get fromColor byte - fromColorBytes[i] = ( fromColor >> this.COLOR_SHIFT_AMOUNT[i] ) & 0xFF; + // Get toColor byte + toColorBytes[i] = ((toColor >> this.COLOR_SHIFT_AMOUNT[i]) & 0xFF); - // Get toColor byte - toColorBytes[i] = ( ( toColor >> this.COLOR_SHIFT_AMOUNT[i] ) & 0xFF ); + // Calculate step amount + stepAmount[i] = (toColorBytes[i] - fromColorBytes[i]) / (float) iterations; - // Calculate step amount - stepAmount[i] = ( toColorBytes[i] - fromColorBytes[i] ) / (float)iterations; + // Init the current color + currentColor[i] = fromColorBytes[i]; + } - // Init the current color - currentColor[i] = fromColorBytes[i]; - } + // Set the first color + gradient[0] = fromColor; - // Set the first color - gradient[0] = fromColor; + for (int iteration = 1; iteration < iterations; iteration++) { + int result = 0; - for( int iteration = 1; iteration < iterations; iteration++ ) - { - int result = 0; + // Add the step amounts to the current color and incorporate into the result color + for (int i = 0; i < COLOR_ARRAY_SIZE; i++) { + // Add the step amount + currentColor[i] += stepAmount[i]; - // Add the step amounts to the current color and incorporate into the result color - for( int i = 0; i < COLOR_ARRAY_SIZE; i++ ) - { - // Add the step amount - currentColor[i] += stepAmount[i]; + // Add to result color + result += ((Math.round(currentColor[i]) & 0xFF) << this.COLOR_SHIFT_AMOUNT[i]); + } - // Add to result color - result += ( ( Math.round( currentColor[i] ) & 0xFF ) << this.COLOR_SHIFT_AMOUNT[i] ); + // Set gradient + gradient[iteration] = result; + } - } + // Set the last color + gradient[iterations - 1] = toColor; - // Set gradient - gradient[iteration] = result; + return gradient; + } - } + /** + * Gets the chat color associated with the specified aspect. + * + * @param aspect + * @return + */ + public final String getAspectChatColor(final Aspect aspect) { + if (this.aspectChatColors.containsKey(aspect)) { + return this.aspectChatColors.get(aspect); + } + return EnumChatFormatting.WHITE.toString(); + } - // Set the last color - gradient[iterations - 1] = toColor; + /** + * Checks if the specified point is within or on the bounds of a rectangle. + * This version localizes the rectangle to the confounds of the current gui. + * + * @param top + * @param left + * @param height + * @param width + * @param pointX + * @param pointY + * @param guiLeft + * @param guiTop + * @return + */ + public final boolean isPointInGuiRegion( + final int top, + final int left, + final int height, + final int width, + final int pointX, + final int pointY, + final int guiLeft, + final int guiTop) { + return this.isPointInRegion(top, left, height, width, pointX - guiLeft, pointY - guiTop); + } - return gradient; - } - - /** - * Gets the chat color associated with the specified aspect. - * - * @param aspect - * @return - */ - public final String getAspectChatColor( final Aspect aspect ) - { - if( this.aspectChatColors.containsKey( aspect ) ) - { - return this.aspectChatColors.get( aspect ); - } - return EnumChatFormatting.WHITE.toString(); - } - - /** - * Checks if the specified point is within or on the bounds of a rectangle. - * This version localizes the rectangle to the confounds of the current gui. - * - * @param top - * @param left - * @param height - * @param width - * @param pointX - * @param pointY - * @param guiLeft - * @param guiTop - * @return - */ - public final boolean isPointInGuiRegion( final int top, final int left, final int height, final int width, final int pointX, final int pointY, - final int guiLeft, final int guiTop ) - { - return this.isPointInRegion( top, left, height, width, pointX - guiLeft, pointY - guiTop ); - } - - /** - * Checks if the specified point is within or on the bounds of a rectangle - * - * @param top - * @param left - * @param height - * @param width - * @param pointX - * @param pointY - * @return - */ - public final boolean isPointInRegion( final int top, final int left, final int height, final int width, final int pointX, final int pointY ) - { - return ( pointX >= left ) && ( pointX <= ( left + width ) ) && ( pointY >= top ) && ( pointY <= ( top + height ) ); - } + /** + * Checks if the specified point is within or on the bounds of a rectangle + * + * @param top + * @param left + * @param height + * @param width + * @param pointX + * @param pointY + * @return + */ + public final boolean isPointInRegion( + final int top, final int left, final int height, final int width, final int pointX, final int pointY) { + return (pointX >= left) && (pointX <= (left + width)) && (pointY >= top) && (pointY <= (top + height)); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ACT.java b/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ACT.java index a899e743..4bed07f1 100644 --- a/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ACT.java +++ b/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ACT.java @@ -12,217 +12,217 @@ import thaumicenergistics.client.gui.GuiArcaneCraftingTerminal; * */ @SideOnly(Side.CLIENT) -public abstract class GuiConstants_ACT - extends ThEScrollbarGui -{ +public abstract class GuiConstants_ACT extends ThEScrollbarGui { - /** - * Starting X position for craft aspects - */ - protected static final int ASPECT_COST_POS_X = 136; + /** + * Starting X position for craft aspects + */ + protected static final int ASPECT_COST_POS_X = 136; - /** - * Starting Y position for craft aspects - */ - protected static final int ASPECT_COST_POS_Y = 90; + /** + * Starting Y position for craft aspects + */ + protected static final int ASPECT_COST_POS_Y = 90; - /** - * Distance between aspect icons - */ - protected static final int ASPECT_COST_SPACING = 18; + /** + * Distance between aspect icons + */ + protected static final int ASPECT_COST_SPACING = 18; - /** - * Rate at which to blink the aspect if there is not enough in the wand. - */ - protected static final double ASPECT_COST_BLINK_SPEED = 0.5D; + /** + * Rate at which to blink the aspect if there is not enough in the wand. + */ + protected static final double ASPECT_COST_BLINK_SPEED = 0.5D; - /** - * Minimum transparency of the aspect if there is not enough in the wand. - */ - protected static final float ASPECT_COST_MIN_ALPHA = 0.25F; + /** + * Minimum transparency of the aspect if there is not enough in the wand. + */ + protected static final float ASPECT_COST_MIN_ALPHA = 0.25F; - /** - * Minimum transparency of the aspect if there is not enough in the wand. - */ - protected static final float ASPECT_COST_MAX_ALPHA = 0.75F; + /** + * Minimum transparency of the aspect if there is not enough in the wand. + */ + protected static final float ASPECT_COST_MAX_ALPHA = 0.75F; - /** - * Clear grid button - */ - protected static final int BUTTON_CLEAR_GRID_ID = 0, BUTTON_CLEAR_GRID_POS_X = 98, BUTTON_CLEAR_GRID_POS_Y = 89; + /** + * Clear grid button + */ + protected static final int BUTTON_CLEAR_GRID_ID = 0, BUTTON_CLEAR_GRID_POS_X = 98, BUTTON_CLEAR_GRID_POS_Y = 89; - /** - * Sort mode button - */ - protected static final int BUTTON_SORT_MODE_ID = 1, BUTTON_SORT_MODE_POS_X = -18, BUTTON_SORT_MODE_POS_Y = 8; + /** + * Sort mode button + */ + protected static final int BUTTON_SORT_MODE_ID = 1, BUTTON_SORT_MODE_POS_X = -18, BUTTON_SORT_MODE_POS_Y = 8; - /** - * Sort direction button - */ - protected static final int BUTTON_SORT_DIR_ID = 2, BUTTON_SORT_DIR_POS_X = BUTTON_SORT_MODE_POS_X, - BUTTON_SORT_DIR_POS_Y = BUTTON_SORT_MODE_POS_Y + 20; + /** + * Sort direction button + */ + protected static final int BUTTON_SORT_DIR_ID = 2, + BUTTON_SORT_DIR_POS_X = BUTTON_SORT_MODE_POS_X, + BUTTON_SORT_DIR_POS_Y = BUTTON_SORT_MODE_POS_Y + 20; - /** - * View type button - */ - protected static final int BUTTON_VIEW_TYPE_ID = 3, BUTTON_VIEW_TYPE_POS_X = BUTTON_SORT_MODE_POS_X, - BUTTON_VIEW_TYPE_POS_Y = BUTTON_SORT_DIR_POS_Y + 20; + /** + * View type button + */ + protected static final int BUTTON_VIEW_TYPE_ID = 3, + BUTTON_VIEW_TYPE_POS_X = BUTTON_SORT_MODE_POS_X, + BUTTON_VIEW_TYPE_POS_Y = BUTTON_SORT_DIR_POS_Y + 20; - /** - * Swap armor button - */ - protected static final int BUTTON_SWAP_ARMOR_ID = 4, BUTTON_SWAP_ARMOR_POS_X = 26, BUTTON_SWAP_ARMOR_POS_Y = 112; + /** + * Swap armor button + */ + protected static final int BUTTON_SWAP_ARMOR_ID = 4, BUTTON_SWAP_ARMOR_POS_X = 26, BUTTON_SWAP_ARMOR_POS_Y = 112; - /** - * Search mode - */ - protected static final int BUTTON_SEARCH_MODE_ID = 5, BUTTON_SEARCH_MODE_POS_X = BUTTON_SORT_MODE_POS_X, - BUTTON_SEARCH_MODE_POS_Y = BUTTON_VIEW_TYPE_POS_Y + 20; + /** + * Search mode + */ + protected static final int BUTTON_SEARCH_MODE_ID = 5, + BUTTON_SEARCH_MODE_POS_X = BUTTON_SORT_MODE_POS_X, + BUTTON_SEARCH_MODE_POS_Y = BUTTON_VIEW_TYPE_POS_Y + 20; - /** - * Terminal style button - */ - protected static final int BUTTON_TERM_STYLE_ID = 6, BUTTON_TERM_STYLE_POS_X = BUTTON_SORT_MODE_POS_X, - BUTTON_TERM_STYLE_POS_Y = BUTTON_SEARCH_MODE_POS_Y + 20; + /** + * Terminal style button + */ + protected static final int BUTTON_TERM_STYLE_ID = 6, + BUTTON_TERM_STYLE_POS_X = BUTTON_SORT_MODE_POS_X, + BUTTON_TERM_STYLE_POS_Y = BUTTON_SEARCH_MODE_POS_Y + 20; - /** - * Size of the AE buttons - */ - protected static final int BUTTON_AE_SIZE = 16; + /** + * Size of the AE buttons + */ + protected static final int BUTTON_AE_SIZE = 16; - /** - * Size of the tiny buttons. - */ - protected static final int BUTTON_TINY_SIZE = 8; + /** + * Size of the tiny buttons. + */ + protected static final int BUTTON_TINY_SIZE = 8; - /** - * The width of the gui - */ - protected static final int GUI_WIDTH = 230; + /** + * The width of the gui + */ + protected static final int GUI_WIDTH = 230; - /** - * The height of the gui - */ - protected static final int GUI_HEIGHT = 243; + /** + * The height of the gui + */ + protected static final int GUI_HEIGHT = 243; - /** - * Width of the view cell texture - */ - protected static final int GUI_VIEW_CELL_TEXTURE_WIDTH = 35; + /** + * Width of the view cell texture + */ + protected static final int GUI_VIEW_CELL_TEXTURE_WIDTH = 35; - /** - * Height of the view cell texture - */ - protected static final int GUI_VIEW_CELL_TEXTURE_HEIGHT = 104; + /** + * Height of the view cell texture + */ + protected static final int GUI_VIEW_CELL_TEXTURE_HEIGHT = 104; - /** - * Size of the upper portion of the GUI - */ - protected static final int GUI_UPPER_TEXTURE_HEIGHT = 35; + /** + * Size of the upper portion of the GUI + */ + protected static final int GUI_UPPER_TEXTURE_HEIGHT = 35; - /** - * The V(y) location in the GUI texture to draw extra rows from. - */ - protected static final int GUI_TEXTURE_ROW_V = 35; + /** + * The V(y) location in the GUI texture to draw extra rows from. + */ + protected static final int GUI_TEXTURE_ROW_V = 35; - /** - * Width of the main body of the texture. - */ - protected static final int GUI_MAIN_BODY_WIDTH = GUI_WIDTH - GUI_VIEW_CELL_TEXTURE_WIDTH; + /** + * Width of the main body of the texture. + */ + protected static final int GUI_MAIN_BODY_WIDTH = GUI_WIDTH - GUI_VIEW_CELL_TEXTURE_WIDTH; - /** - * Default number of rows in the ME inventory grid. - */ - protected static final int ME_DEFAULT_ROWS = 3; + /** + * Default number of rows in the ME inventory grid. + */ + protected static final int ME_DEFAULT_ROWS = 3; - /** - * Number of columns in the ME inventory grid. - */ - protected static final int ME_COLUMNS = 9; + /** + * Number of columns in the ME inventory grid. + */ + protected static final int ME_COLUMNS = 9; - /** - * Starting X position of the items. - */ - protected static final int ME_ITEM_POS_X = 7; + /** + * Starting X position of the items. + */ + protected static final int ME_ITEM_POS_X = 7; - /** - * Starting Y position of the items. - */ - protected static final int ME_ITEM_POS_Y = 17; + /** + * Starting Y position of the items. + */ + protected static final int ME_ITEM_POS_Y = 17; - /** - * Total width of the ME item grid. - */ - protected static final int ME_GRID_WIDTH = 161; + /** + * Total width of the ME item grid. + */ + protected static final int ME_GRID_WIDTH = 161; - /** - * Height of the extra row texture. - */ - protected static final int ME_ROW_HEIGHT = 18; + /** + * Height of the extra row texture. + */ + protected static final int ME_ROW_HEIGHT = 18; - /** - * Height of the lower portion of the texture. - */ - protected static final int GUI_TEXTURE_LOWER_HEIGHT = GUI_HEIGHT - ME_ROW_HEIGHT - GUI_UPPER_TEXTURE_HEIGHT; + /** + * Height of the lower portion of the texture. + */ + protected static final int GUI_TEXTURE_LOWER_HEIGHT = GUI_HEIGHT - ME_ROW_HEIGHT - GUI_UPPER_TEXTURE_HEIGHT; - /** - * X position of the scroll bar - */ - protected static final int SCROLLBAR_POS_X = 175; + /** + * X position of the scroll bar + */ + protected static final int SCROLLBAR_POS_X = 175; - /** - * Y position of the scroll bar - */ - protected static final int SCROLLBAR_POS_Y = 18; + /** + * Y position of the scroll bar + */ + protected static final int SCROLLBAR_POS_Y = 18; - /** - * Height of the scroll bar - */ - protected static final int SCROLLBAR_HEIGHT = 52; + /** + * Height of the scroll bar + */ + protected static final int SCROLLBAR_HEIGHT = 52; - /** - * X offset to draw the search field. - */ - protected static final int SEARCH_POS_X = 98; + /** + * X offset to draw the search field. + */ + protected static final int SEARCH_POS_X = 98; - /** - * Y offset to draw the search field. - */ - protected static final int SEARCH_POS_Y = 6; + /** + * Y offset to draw the search field. + */ + protected static final int SEARCH_POS_Y = 6; - /** - * Width of the search field. - */ - protected static final int SEARCH_WIDTH = 65; + /** + * Width of the search field. + */ + protected static final int SEARCH_WIDTH = 65; - /** - * Height of the search field. - */ - protected static final int SEARCH_HEIGHT = 10; + /** + * Height of the search field. + */ + protected static final int SEARCH_HEIGHT = 10; - /** - * The maximum number of characters that can be typed in. - */ - protected static final int SEARCH_MAX_CHARS = 15; + /** + * The maximum number of characters that can be typed in. + */ + protected static final int SEARCH_MAX_CHARS = 15; - /** - * X position of the title string - */ - protected static final int TITLE_POS_X = 8; + /** + * X position of the title string + */ + protected static final int TITLE_POS_X = 8; - /** - * Y position of the title string - */ - protected static final int TITLE_POS_Y = 6; + /** + * Y position of the title string + */ + protected static final int TITLE_POS_Y = 6; - /** - * Determines how often to update the tooltip when the mouse is not moving. - */ - protected static final long WIDGET_TOOLTIP_UPDATE_INTERVAL = 3000L; - - public GuiConstants_ACT( final Container container ) - { - super( container ); - } + /** + * Determines how often to update the tooltip when the mouse is not moving. + */ + protected static final long WIDGET_TOOLTIP_UPDATE_INTERVAL = 3000L; + public GuiConstants_ACT(final Container container) { + super(container); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ECT.java b/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ECT.java index b5e27770..0f44b320 100644 --- a/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ECT.java +++ b/src/main/java/thaumicenergistics/client/gui/abstraction/GuiConstants_ECT.java @@ -12,77 +12,77 @@ import thaumicenergistics.client.gui.GuiEssentiaCellTerminal; * */ @SideOnly(Side.CLIENT) -public abstract class GuiConstants_ECT - extends ThEScrollbarGui -{ - /** - * Sort mode button position. - */ - protected static final int BUTTON_SORT_MODE_POS_X = -18, BUTTON_SORT_MODE_POS_Y = 9; +public abstract class GuiConstants_ECT extends ThEScrollbarGui { + /** + * Sort mode button position. + */ + protected static final int BUTTON_SORT_MODE_POS_X = -18, BUTTON_SORT_MODE_POS_Y = 9; - /** - * View mode button. - */ - protected static final int BUTTON_VIEW_MODE_POS_X = -18, BUTTON_VIEW_MODE_POS_Y = GuiConstants_ECT.BUTTON_SORT_MODE_POS_Y + 20; + /** + * View mode button. + */ + protected static final int BUTTON_VIEW_MODE_POS_X = -18, + BUTTON_VIEW_MODE_POS_Y = GuiConstants_ECT.BUTTON_SORT_MODE_POS_Y + 20; - /** - * Size of the gui. - */ - protected static final int GUI_WIDTH = 195, GUI_HEIGHT = 204; + /** + * Size of the gui. + */ + protected static final int GUI_WIDTH = 195, GUI_HEIGHT = 204; - /** - * Width and height of the mode buttons. - */ - protected static final int MODE_BUTTON_SIZE = 16; + /** + * Width and height of the mode buttons. + */ + protected static final int MODE_BUTTON_SIZE = 16; - /** - * Search bar. - */ - protected static final int SEARCH_X_OFFSET = 98, SEARCH_Y_OFFSET = 6, SEARCH_WIDTH = 69, SEARCH_HEIGHT = 10; + /** + * Search bar. + */ + protected static final int SEARCH_X_OFFSET = 98, SEARCH_Y_OFFSET = 6, SEARCH_WIDTH = 69, SEARCH_HEIGHT = 10; - /** - * The maximum number of displayable characters. - */ - protected static final int SEARCH_MAX_CHARS = 14; + /** + * The maximum number of displayable characters. + */ + protected static final int SEARCH_MAX_CHARS = 14; - /** - * Scroll bar. - */ - protected static final int SCROLLBAR_POS_X = 175, SCROLLBAR_POS_Y = 18, SCROLLBAR_HEIGHT = 70; + /** + * Scroll bar. + */ + protected static final int SCROLLBAR_POS_X = 175, SCROLLBAR_POS_Y = 18, SCROLLBAR_HEIGHT = 70; - /** - * Selected aspect info positions. - */ - protected static final int SELECTED_INFO_POS_X = 45, SELECTED_INFO_NAME_POS_Y = 91, SELECTED_INFO_AMOUNT_POS_Y = 101; + /** + * Selected aspect info positions. + */ + protected static final int SELECTED_INFO_POS_X = 45, + SELECTED_INFO_NAME_POS_Y = 91, + SELECTED_INFO_AMOUNT_POS_Y = 101; - /** - * Position of the title. - */ - protected static final int TITLE_POS_X = 7, TITLE_POS_Y = 6; + /** + * Position of the title. + */ + protected static final int TITLE_POS_X = 7, TITLE_POS_Y = 6; - /** - * Widget offsets. - */ - protected static final int WIDGET_OFFSET_X = 7, WIDGET_OFFSET_Y = 17; + /** + * Widget offsets. + */ + protected static final int WIDGET_OFFSET_X = 7, WIDGET_OFFSET_Y = 17; - /** - * Number of widgets per row. - */ - protected static final int WIDGETS_PER_ROW = 9; + /** + * Number of widgets per row. + */ + protected static final int WIDGETS_PER_ROW = 9; - /** - * Number of rows per page. - */ - protected static final int WIDGET_ROWS_PER_PAGE = 4; + /** + * Number of rows per page. + */ + protected static final int WIDGET_ROWS_PER_PAGE = 4; - /** - * Number of widgets per page. - */ - protected static final int WIDGETS_PER_PAGE = GuiConstants_ECT.WIDGETS_PER_ROW * GuiConstants_ECT.WIDGET_ROWS_PER_PAGE; - - public GuiConstants_ECT( final Container container ) - { - super( container ); - } + /** + * Number of widgets per page. + */ + protected static final int WIDGETS_PER_PAGE = + GuiConstants_ECT.WIDGETS_PER_ROW * GuiConstants_ECT.WIDGET_ROWS_PER_PAGE; + public GuiConstants_ECT(final Container container) { + super(container); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/abstraction/ThEBaseGui.java b/src/main/java/thaumicenergistics/client/gui/abstraction/ThEBaseGui.java index d55ea759..add4d13e 100644 --- a/src/main/java/thaumicenergistics/client/gui/abstraction/ThEBaseGui.java +++ b/src/main/java/thaumicenergistics/client/gui/abstraction/ThEBaseGui.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui.abstraction; -import java.util.ArrayList; -import java.util.List; import appeng.api.AEApi; import appeng.parts.automation.UpgradeInventory; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; @@ -27,264 +27,245 @@ import thaumicenergistics.common.container.slot.SlotNetworkTool; * */ @SideOnly(Side.CLIENT) -public abstract class ThEBaseGui - extends GuiContainer - implements IWidgetHost -{ - private static final int upgradeU = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getU(); - private static final int upgradeV = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getV(); - private static final int upgradeWidth = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getWidth(); - private static final int upgradeHeight = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getHeight(); +public abstract class ThEBaseGui extends GuiContainer implements IWidgetHost { + private static final int upgradeU = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getU(); + private static final int upgradeV = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getV(); + private static final int upgradeWidth = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getWidth(); + private static final int upgradeHeight = AEStateIconsEnum.UPGRADE_CARD_BACKGROUND.getHeight(); - /** - * Lines to draw when drawTooltip is called. - */ - protected final List tooltip = new ArrayList(); - public ItemStack draggedStack; + /** + * Lines to draw when drawTooltip is called. + */ + protected final List tooltip = new ArrayList(); - public ThEBaseGui( final Container container ) - { - super( container ); - } + public ItemStack draggedStack; - /** - * Adds to the tooltip based on which button the mouse is over. - * - * @param mouseX - * @param mouseY - * @return True when a tooltip was added, false otherwise. - */ - private final boolean addTooltipFromButtons( final int mouseX, final int mouseY ) - { - // Is the mouse over any buttons? - for( Object obj : this.buttonList ) - { - // Is it a base button? - if( obj instanceof ThEGuiButtonBase ) - { - // Cast - ThEGuiButtonBase currentButton = (ThEGuiButtonBase)obj; + public ThEBaseGui(final Container container) { + super(container); + } - // Is the mouse over it? - if( currentButton.isMouseOverButton( mouseX, mouseY ) ) - { - // Get the tooltip - currentButton.getTooltip( this.tooltip ); + /** + * Adds to the tooltip based on which button the mouse is over. + * + * @param mouseX + * @param mouseY + * @return True when a tooltip was added, false otherwise. + */ + private final boolean addTooltipFromButtons(final int mouseX, final int mouseY) { + // Is the mouse over any buttons? + for (Object obj : this.buttonList) { + // Is it a base button? + if (obj instanceof ThEGuiButtonBase) { + // Cast + ThEGuiButtonBase currentButton = (ThEGuiButtonBase) obj; - // And stop searching - return true; - } - } - } + // Is the mouse over it? + if (currentButton.isMouseOverButton(mouseX, mouseY)) { + // Get the tooltip + currentButton.getTooltip(this.tooltip); - return false; - } + // And stop searching + return true; + } + } + } - /** - * Checks if the specified point is within the bounds of the specified slot. - * - * @param slot - * @param x - * @param y - * @return True if the point is within the slot, false otherwise. - */ - private final boolean isPointWithinSlot( final Slot slot, final int x, final int y ) - { - return ThEGuiHelper.INSTANCE.isPointInGuiRegion( slot.yDisplayPosition, slot.xDisplayPosition, 16, 16, x, y, this.guiLeft, this.guiTop ); - } + return false; + } - /** - * Checks if a not-left-click was on a button.
- * Left click is handled by GuiScreen.mouseClicked() - * - * @param mouseX - * @param mouseY - * @return True if click was handled. - */ - private final boolean nonLeftClickHandler_Buttons( final int mouseX, final int mouseY, final int mouseButton ) - { - if( mouseButton != ThEGuiHelper.MOUSE_BUTTON_LEFT ) - { - // Mouse over button? - for( Object buttonObj : this.buttonList ) - { - // Cast - GuiButton button = (GuiButton)buttonObj; + /** + * Checks if the specified point is within the bounds of the specified slot. + * + * @param slot + * @param x + * @param y + * @return True if the point is within the slot, false otherwise. + */ + private final boolean isPointWithinSlot(final Slot slot, final int x, final int y) { + return ThEGuiHelper.INSTANCE.isPointInGuiRegion( + slot.yDisplayPosition, slot.xDisplayPosition, 16, 16, x, y, this.guiLeft, this.guiTop); + } - // Was mouse over the button? - if( button.mousePressed( this.mc, mouseX, mouseY ) ) - { - // Play clicky sound - button.func_146113_a( this.mc.getSoundHandler() ); + /** + * Checks if a not-left-click was on a button.
+ * Left click is handled by GuiScreen.mouseClicked() + * + * @param mouseX + * @param mouseY + * @return True if click was handled. + */ + private final boolean nonLeftClickHandler_Buttons(final int mouseX, final int mouseY, final int mouseButton) { + if (mouseButton != ThEGuiHelper.MOUSE_BUTTON_LEFT) { + // Mouse over button? + for (Object buttonObj : this.buttonList) { + // Cast + GuiButton button = (GuiButton) buttonObj; - // Call button click event - this.onButtonClicked( button, mouseButton ); + // Was mouse over the button? + if (button.mousePressed(this.mc, mouseX, mouseY)) { + // Play clicky sound + button.func_146113_a(this.mc.getSoundHandler()); - // Handled - return true; - } - } - } + // Call button click event + this.onButtonClicked(button, mouseButton); - return false; - } + // Handled + return true; + } + } + } - /** - * Draws the slot backgrounds for the network tool and upgrade slots. - * - * @param alpha - * @param mouseX - * @param mouseY - */ - protected final void drawAEToolAndUpgradeSlots( final float alpha, final int mouseX, final int mouseY ) - { - Minecraft.getMinecraft().renderEngine.bindTexture( AEStateIconsEnum.AE_STATES_TEXTURE ); + return false; + } - // Locate any upgrade or network slots - for( int i = 0; i < this.inventorySlots.inventorySlots.size(); i++ ) - { - // Get the slot - Slot slot = (Slot)this.inventorySlots.inventorySlots.get( i ); + /** + * Draws the slot backgrounds for the network tool and upgrade slots. + * + * @param alpha + * @param mouseX + * @param mouseY + */ + protected final void drawAEToolAndUpgradeSlots(final float alpha, final int mouseX, final int mouseY) { + Minecraft.getMinecraft().renderEngine.bindTexture(AEStateIconsEnum.AE_STATES_TEXTURE); - // Is it network or upgrade? - if( ( slot instanceof SlotNetworkTool ) || ( slot.inventory instanceof UpgradeInventory ) ) - { - // Draw background - this.drawTexturedModalRect( this.guiLeft + slot.xDisplayPosition, this.guiTop + slot.yDisplayPosition, ThEBaseGui.upgradeU, - ThEBaseGui.upgradeV, ThEBaseGui.upgradeWidth, ThEBaseGui.upgradeHeight ); - } - } - } + // Locate any upgrade or network slots + for (int i = 0; i < this.inventorySlots.inventorySlots.size(); i++) { + // Get the slot + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(i); - /** - * Gets the slot who contains the specified point. - * - * @param x - * @param y - * @return Slot the point is within, null if point is within no slots. - */ - protected final Slot getSlotAtMousePosition( final int x, final int y ) - { - // Loop over all slots - for( int i = 0; i < this.inventorySlots.inventorySlots.size(); i++ ) - { - // Get the slot - Slot slot = (Slot)this.inventorySlots.inventorySlots.get( i ); + // Is it network or upgrade? + if ((slot instanceof SlotNetworkTool) || (slot.inventory instanceof UpgradeInventory)) { + // Draw background + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + ThEBaseGui.upgradeU, + ThEBaseGui.upgradeV, + ThEBaseGui.upgradeWidth, + ThEBaseGui.upgradeHeight); + } + } + } - // Is the point within the slot? - if( this.isPointWithinSlot( slot, x, y ) ) - { - // Return the slot - return slot; - } - } + /** + * Gets the slot who contains the specified point. + * + * @param x + * @param y + * @return Slot the point is within, null if point is within no slots. + */ + protected final Slot getSlotAtMousePosition(final int x, final int y) { + // Loop over all slots + for (int i = 0; i < this.inventorySlots.inventorySlots.size(); i++) { + // Get the slot + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(i); - // Point was not within any slot - return null; - } + // Is the point within the slot? + if (this.isPointWithinSlot(slot, x, y)) { + // Return the slot + return slot; + } + } - /** - * Called when the mouse is clicked. - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { + // Point was not within any slot + return null; + } - if( this.nonLeftClickHandler_Buttons( mouseX, mouseY, mouseButton ) ) - { - return; - } + /** + * Called when the mouse is clicked. + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { - // Is this container one that could have a network tool? - if( this.inventorySlots instanceof ContainerWithNetworkTool ) - { - // Do we have a network tool? - if( ( (ContainerWithNetworkTool)this.inventorySlots ).hasNetworkTool() ) - { - // Get the slot the mouse was clicked over - Slot slot = this.getSlotAtMousePosition( mouseX, mouseY ); + if (this.nonLeftClickHandler_Buttons(mouseX, mouseY, mouseButton)) { + return; + } - // Was the slot the network tool? - if( ( slot != null ) && ( slot.getStack() != null ) && - ( slot.getStack().isItemEqual( AEApi.instance().definitions().items().networkTool().maybeStack( 1 ).get() ) ) ) - { - // Do not allow any interaction with the network tool slot. - return; - } - } - } + // Is this container one that could have a network tool? + if (this.inventorySlots instanceof ContainerWithNetworkTool) { + // Do we have a network tool? + if (((ContainerWithNetworkTool) this.inventorySlots).hasNetworkTool()) { + // Get the slot the mouse was clicked over + Slot slot = this.getSlotAtMousePosition(mouseX, mouseY); - // Pass to super - super.mouseClicked( mouseX, mouseY, mouseButton ); - } + // Was the slot the network tool? + if ((slot != null) + && (slot.getStack() != null) + && (slot.getStack() + .isItemEqual(AEApi.instance() + .definitions() + .items() + .networkTool() + .maybeStack(1) + .get()))) { + // Do not allow any interaction with the network tool slot. + return; + } + } + } - /** - * Called when a button is clicked. Includes which button was pressed. - * - * @param button - * @param mouseButton - */ - protected void onButtonClicked( final GuiButton button, final int mouseButton ) - { - } + // Pass to super + super.mouseClicked(mouseX, mouseY, mouseButton); + } - /** - * Called when a button is left-clicked
- * Note: Do not override, use {@link #onButtonClicked(GuiButton, int) onButtonClicked} instead. - * - * @see #onButtonClicked(GuiButton, int ) - */ - @Override - public final void actionPerformed( final GuiButton button ) - { - this.onButtonClicked( button, ThEGuiHelper.MOUSE_BUTTON_LEFT ); - } + /** + * Called when a button is clicked. Includes which button was pressed. + * + * @param button + * @param mouseButton + */ + protected void onButtonClicked(final GuiButton button, final int mouseButton) {} - @Override - public void drawScreen( final int mouseX, final int mouseY, final float mouseButton ) - { - // Call super - super.drawScreen( mouseX, mouseY, mouseButton ); + /** + * Called when a button is left-clicked
+ * Note: Do not override, use {@link #onButtonClicked(GuiButton, int) onButtonClicked} instead. + * + * @see #onButtonClicked(GuiButton, int ) + */ + @Override + public final void actionPerformed(final GuiButton button) { + this.onButtonClicked(button, ThEGuiHelper.MOUSE_BUTTON_LEFT); + } - // Empty tooltip? - if( this.tooltip.isEmpty() ) - { - // Get the tooltip from the buttons - this.addTooltipFromButtons( mouseX, mouseY ); - } + @Override + public void drawScreen(final int mouseX, final int mouseY, final float mouseButton) { + // Call super + super.drawScreen(mouseX, mouseY, mouseButton); - // Draw the tooltip - if( !this.tooltip.isEmpty() ) - { - // Draw - this.drawHoveringText( this.tooltip, mouseX, mouseY, this.fontRendererObj ); + // Empty tooltip? + if (this.tooltip.isEmpty()) { + // Get the tooltip from the buttons + this.addTooltipFromButtons(mouseX, mouseY); + } - // Clear the tooltip - this.tooltip.clear(); - } - } + // Draw the tooltip + if (!this.tooltip.isEmpty()) { + // Draw + this.drawHoveringText(this.tooltip, mouseX, mouseY, this.fontRendererObj); - @Override - public final FontRenderer getFontRenderer() - { - return this.fontRendererObj; - } + // Clear the tooltip + this.tooltip.clear(); + } + } - /** - * Gets the starting X position for the Gui. - */ - @Override - public final int guiLeft() - { - return this.guiLeft; - } + @Override + public final FontRenderer getFontRenderer() { + return this.fontRendererObj; + } - /** - * Gets the starting Y position for the Gui. - */ - @Override - public final int guiTop() - { - return this.guiTop; - } + /** + * Gets the starting X position for the Gui. + */ + @Override + public final int guiLeft() { + return this.guiLeft; + } + + /** + * Gets the starting Y position for the Gui. + */ + @Override + public final int guiTop() { + return this.guiTop; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/abstraction/ThEScrollbarGui.java b/src/main/java/thaumicenergistics/client/gui/abstraction/ThEScrollbarGui.java index 51c0e426..9c8b7fc4 100644 --- a/src/main/java/thaumicenergistics/client/gui/abstraction/ThEScrollbarGui.java +++ b/src/main/java/thaumicenergistics/client/gui/abstraction/ThEScrollbarGui.java @@ -1,13 +1,13 @@ package thaumicenergistics.client.gui.abstraction; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiScrollbar; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.inventory.Container; import net.minecraft.util.ResourceLocation; +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; import thaumicenergistics.client.gui.ThEGuiHelper; /** @@ -17,339 +17,317 @@ import thaumicenergistics.client.gui.ThEGuiHelper; * */ @SideOnly(Side.CLIENT) -public abstract class ThEScrollbarGui - extends ThEBaseGui -{ - public class ScrollbarParams - { - /** - * X position of the scroll bar - */ - int scrollbarPosX; +public abstract class ThEScrollbarGui extends ThEBaseGui { + public class ScrollbarParams { + /** + * X position of the scroll bar + */ + int scrollbarPosX; - /** - * Y position of the scroll bar - */ - int scrollbarPosY; + /** + * Y position of the scroll bar + */ + int scrollbarPosY; - /** - * Height of the scroll bar - */ - int scrollbarHeight; + /** + * Height of the scroll bar + */ + int scrollbarHeight; - /** - * Position + Height of the scroll bar. - */ - int scrollbarVerticalBound; + /** + * Position + Height of the scroll bar. + */ + int scrollbarVerticalBound; - /** - * Create the parameters - * - * @param x - * @param y - * @param height - */ - public ScrollbarParams( final int x, final int y, final int height ) - { - this.scrollbarPosX = x; - this.scrollbarPosY = y; - this.setHeight( height ); - } + /** + * Create the parameters + * + * @param x + * @param y + * @param height + */ + public ScrollbarParams(final int x, final int y, final int height) { + this.scrollbarPosX = x; + this.scrollbarPosY = y; + this.setHeight(height); + } - /** - * Sets the height of the scrollbar - * - * @param height - */ - void setHeight( final int height ) - { - this.scrollbarHeight = height; - this.scrollbarVerticalBound = this.scrollbarHeight + this.scrollbarPosY; - } - } + /** + * Sets the height of the scrollbar + * + * @param height + */ + void setHeight(final int height) { + this.scrollbarHeight = height; + this.scrollbarVerticalBound = this.scrollbarHeight + this.scrollbarPosY; + } + } - /** - * Scroll bar - */ - protected final GuiScrollbar scrollBar; + /** + * Scroll bar + */ + protected final GuiScrollbar scrollBar; - /** - * Serves as a graphics call bridge for the scroll bar. - */ - private AEBaseGui aeGuiBridge; - /** - * True if the scroll bar has mouse focus. - */ - private boolean isScrollBarHeld = false; - /** - * The last Y position of the mouse when the scroll bar has mouse focus. - */ - private int scrollHeldPrevY = 0; + /** + * Serves as a graphics call bridge for the scroll bar. + */ + private AEBaseGui aeGuiBridge; + /** + * True if the scroll bar has mouse focus. + */ + private boolean isScrollBarHeld = false; + /** + * The last Y position of the mouse when the scroll bar has mouse focus. + */ + private int scrollHeldPrevY = 0; - /** - * Scrollbar parameters - */ - private ScrollbarParams scrollParams; + /** + * Scrollbar parameters + */ + private ScrollbarParams scrollParams; - public ThEScrollbarGui( final Container container ) - { - super( container ); + public ThEScrollbarGui(final Container container) { + super(container); - // Create the scrollbar - this.scrollBar = new GuiScrollbar(); - } + // Create the scrollbar + this.scrollBar = new GuiScrollbar(); + } - /** - * Draw the foreground layer. - */ - @Override - protected void drawGuiContainerForegroundLayer( final int mouseX, final int mouseY ) - { - // Call super - super.drawGuiContainerForegroundLayer( mouseX, mouseY ); + /** + * Draw the foreground layer. + */ + @Override + protected void drawGuiContainerForegroundLayer(final int mouseX, final int mouseY) { + // Call super + super.drawGuiContainerForegroundLayer(mouseX, mouseY); - // Draw the scroll bar - this.scrollBar.draw( this.aeGuiBridge ); - } + // Draw the scroll bar + this.scrollBar.draw(this.aeGuiBridge); + } - /** - * Gets the scroll bar parameters from the subclass. - * - * @return - */ - protected abstract ScrollbarParams getScrollbarParameters(); + /** + * Gets the scroll bar parameters from the subclass. + * + * @return + */ + protected abstract ScrollbarParams getScrollbarParameters(); - /** - * Called when the player types a key. - */ - @Override - protected void keyTyped( final char key, final int keyID ) - { - // Home Key - if( keyID == Keyboard.KEY_HOME ) - { - // Move the scroll all the way to home - this.scrollBar.click( this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, this.scrollParams.scrollbarPosY + 1 ); - this.scrollBar.wheel( 1 ); - this.onScrollbarMoved(); - } - // End Key - else if( keyID == Keyboard.KEY_END ) - { - // Move the scroll all the way to end - this.scrollBar.click( this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, this.scrollParams.scrollbarVerticalBound ); - this.onScrollbarMoved(); + /** + * Called when the player types a key. + */ + @Override + protected void keyTyped(final char key, final int keyID) { + // Home Key + if (keyID == Keyboard.KEY_HOME) { + // Move the scroll all the way to home + this.scrollBar.click( + this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, this.scrollParams.scrollbarPosY + 1); + this.scrollBar.wheel(1); + this.onScrollbarMoved(); + } + // End Key + else if (keyID == Keyboard.KEY_END) { + // Move the scroll all the way to end + this.scrollBar.click( + this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, this.scrollParams.scrollbarVerticalBound); + this.onScrollbarMoved(); - } - // Up Key - else if( keyID == Keyboard.KEY_UP ) - { - this.scrollBar.wheel( 1 ); - this.onScrollbarMoved(); - } - // Down Key - else if( keyID == Keyboard.KEY_DOWN ) - { - this.scrollBar.wheel( -1 ); - this.onScrollbarMoved(); - } - else - { - super.keyTyped( key, keyID ); - } + } + // Up Key + else if (keyID == Keyboard.KEY_UP) { + this.scrollBar.wheel(1); + this.onScrollbarMoved(); + } + // Down Key + else if (keyID == Keyboard.KEY_DOWN) { + this.scrollBar.wheel(-1); + this.onScrollbarMoved(); + } else { + super.keyTyped(key, keyID); + } + } - } + /** + * Called when the mouse is clicked while the gui is open + */ + @Override + protected void mouseClicked(final int mouseX, final int mouseY, final int mouseButton) { + // Is the mouse over the scroll bar area? + if (ThEGuiHelper.INSTANCE.isPointInGuiRegion( + this.scrollParams.scrollbarPosY, + this.scrollParams.scrollbarPosX, + this.scrollParams.scrollbarHeight, + this.scrollBar.getWidth(), + mouseX, + mouseY, + this.guiLeft, + this.guiTop)) { + // The scroll bar now has mouse focus + this.isScrollBarHeld = true; - /** - * Called when the mouse is clicked while the gui is open - */ - @Override - protected void mouseClicked( final int mouseX, final int mouseY, final int mouseButton ) - { - // Is the mouse over the scroll bar area? - if( ThEGuiHelper.INSTANCE.isPointInGuiRegion( this.scrollParams.scrollbarPosY, this.scrollParams.scrollbarPosX, - this.scrollParams.scrollbarHeight, this.scrollBar.getWidth(), mouseX, mouseY, this.guiLeft, this.guiTop ) ) - { - // The scroll bar now has mouse focus - this.isScrollBarHeld = true; + // Mark this Y + this.scrollHeldPrevY = mouseY; - // Mark this Y - this.scrollHeldPrevY = mouseY; + // Jump the scroll to the mouse + this.scrollBar.click(this.aeGuiBridge, mouseX - this.guiLeft, mouseY - this.guiTop); - // Jump the scroll to the mouse - this.scrollBar.click( this.aeGuiBridge, mouseX - this.guiLeft, mouseY - this.guiTop ); + // Update the subclass + this.onScrollbarMoved(); - // Update the subclass - this.onScrollbarMoved(); + // Do not pass to super + return; + } - // Do not pass to super - return; - } + // Call super + super.mouseClicked(mouseX, mouseY, mouseButton); + } - // Call super - super.mouseClicked( mouseX, mouseY, mouseButton ); - } + /** + * Called when the mouse wheel is scrolled. + * + * @param deltaZ + * @param mouseX + * @param mouseY + */ + protected abstract void onMouseWheel(int deltaZ, int mouseX, int mouseY); - /** - * Called when the mouse wheel is scrolled. - * - * @param deltaZ - * @param mouseX - * @param mouseY - */ - protected abstract void onMouseWheel( int deltaZ, int mouseX, int mouseY ); + /** + * Called when the scroll bar has moved. + */ + protected abstract void onScrollbarMoved(); - /** - * Called when the scroll bar has moved. - */ - protected abstract void onScrollbarMoved(); + /** + * Changes the height of the scroll bar. + * + * @param newHeight + */ + protected void setScrollBarHeight(final int newHeight) { + this.scrollParams.setHeight(newHeight); + this.scrollBar.setHeight(newHeight); + } - /** - * Changes the height of the scroll bar. - * - * @param newHeight - */ - protected void setScrollBarHeight( final int newHeight ) - { - this.scrollParams.setHeight( newHeight ); - this.scrollBar.setHeight( newHeight ); - } + @Override + public void drawScreen(final int mouseX, final int mouseY, final float mouseBtn) { + // Call super + super.drawScreen(mouseX, mouseY, mouseBtn); - @Override - public void drawScreen( final int mouseX, final int mouseY, final float mouseBtn ) - { - // Call super - super.drawScreen( mouseX, mouseY, mouseBtn ); + // Is the mouse holding the scroll bar? + if (this.isScrollBarHeld) { + // Is the mouse button still being held down? + if (Mouse.isButtonDown(ThEGuiHelper.MOUSE_BUTTON_LEFT)) { + // Has the Y changed? + if (mouseY == this.scrollHeldPrevY) { + return; + } - // Is the mouse holding the scroll bar? - if( this.isScrollBarHeld ) - { - // Is the mouse button still being held down? - if( Mouse.isButtonDown( ThEGuiHelper.MOUSE_BUTTON_LEFT ) ) - { - // Has the Y changed? - if( mouseY == this.scrollHeldPrevY ) - { - return; - } + boolean correctForZero = false; - boolean correctForZero = false; + // Mark the Y + this.scrollHeldPrevY = mouseY; - // Mark the Y - this.scrollHeldPrevY = mouseY; + // Calculate the Y position for the scroll bar + int repY = mouseY - this.guiTop; - // Calculate the Y position for the scroll bar - int repY = mouseY - this.guiTop; + // Has the mouse exceeded the 'upper' bound? + if (repY > this.scrollParams.scrollbarVerticalBound) { + repY = this.scrollParams.scrollbarVerticalBound; + } + // Has the mouse exceeded the 'lower' bound? + else if (repY <= this.scrollParams.scrollbarPosY) { + repY = this.scrollParams.scrollbarPosY; - // Has the mouse exceeded the 'upper' bound? - if( repY > this.scrollParams.scrollbarVerticalBound ) - { - repY = this.scrollParams.scrollbarVerticalBound; - } - // Has the mouse exceeded the 'lower' bound? - else if( repY <= this.scrollParams.scrollbarPosY ) - { - repY = this.scrollParams.scrollbarPosY; + // We will have to correct for zero + correctForZero = true; + } - // We will have to correct for zero - correctForZero = true; - } + // Update the scroll bar + this.scrollBar.click(this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, repY); - // Update the scroll bar - this.scrollBar.click( this.aeGuiBridge, this.scrollParams.scrollbarPosX + 1, repY ); + // Should we correct for zero? + if (correctForZero) { + this.scrollBar.wheel(1); + } - // Should we correct for zero? - if( correctForZero ) - { - this.scrollBar.wheel( 1 ); - } + // Inform the subclass the scrollbar has moved + this.onScrollbarMoved(); + } else { + // The scroll bar no longer has mouse focus + this.isScrollBarHeld = false; + } + } + } - // Inform the subclass the scrollbar has moved - this.onScrollbarMoved(); - } - else - { - // The scroll bar no longer has mouse focus - this.isScrollBarHeld = false; - } - } + @Override + public void handleMouseInput() { + // Call super + super.handleMouseInput(); - } + // Get the delta z for the scroll wheel + int deltaZ = Mouse.getEventDWheel(); - @Override - public void handleMouseInput() - { - // Call super - super.handleMouseInput(); + // Did it move? + if (deltaZ != 0) { + // Get the mouse position + int mouseX = (Mouse.getEventX() * this.width) / this.mc.displayWidth; + int mouseY = this.height - ((Mouse.getEventY() * this.height) / this.mc.displayHeight) - 1; - // Get the delta z for the scroll wheel - int deltaZ = Mouse.getEventDWheel(); + // Call event + this.onMouseWheel(deltaZ, mouseX, mouseY); + } + } - // Did it move? - if( deltaZ != 0 ) - { - // Get the mouse position - int mouseX = ( Mouse.getEventX() * this.width ) / this.mc.displayWidth; - int mouseY = this.height - ( ( Mouse.getEventY() * this.height ) / this.mc.displayHeight ) - 1; + /** + * Sets the gui up. + */ + @Override + public void initGui() { + // Call super + super.initGui(); - // Call event - this.onMouseWheel( deltaZ, mouseX, mouseY ); - } - } + // Get the params + this.scrollParams = this.getScrollbarParameters(); - /** - * Sets the gui up. - */ - @Override - public void initGui() - { - // Call super - super.initGui(); + // Setup the scroll bar + this.scrollBar + .setLeft(this.scrollParams.scrollbarPosX) + .setTop(this.scrollParams.scrollbarPosY) + .setHeight(this.scrollParams.scrollbarHeight); - // Get the params - this.scrollParams = this.getScrollbarParameters(); + // No scrolling yet + this.scrollBar.setRange(0, 0, 1); - // Setup the scroll bar - this.scrollBar.setLeft( this.scrollParams.scrollbarPosX ).setTop( this.scrollParams.scrollbarPosY ) - .setHeight( this.scrollParams.scrollbarHeight ); + // Create the AE bridge + this.aeGuiBridge = new AEBaseGui(this.inventorySlots) { + @Override + public void bindTexture(final String file) { + this.bindTexture("appliedenergistics2", file); + } - // No scrolling yet - this.scrollBar.setRange( 0, 0, 1 ); + @Override + public void bindTexture(final String base, final String file) { + ThEScrollbarGui.this.mc.getTextureManager().bindTexture(new ResourceLocation(base, "textures/" + file)); + } - // Create the AE bridge - this.aeGuiBridge = new AEBaseGui( this.inventorySlots ) - { - @Override - public void bindTexture( final String file ) - { - this.bindTexture( "appliedenergistics2", file ); - } + @Override + public void drawBG(final int arg0, final int arg1, final int arg2, final int arg3) { + // Ignored + } - @Override - public void bindTexture( final String base, final String file ) - { - ThEScrollbarGui.this.mc.getTextureManager().bindTexture( new ResourceLocation( base, "textures/" + file ) ); - } - - @Override - public void drawBG( final int arg0, final int arg1, final int arg2, final int arg3 ) - { - // Ignored - } - - @Override - public void drawFG( final int arg0, final int arg1, final int arg2, final int arg3 ) - { - // Ignored - } - - @Override - public void drawTexturedModalRect( final int posX, final int posY, final int sourceOffsetX, final int sourceOffsetY, final int width, - final int height ) - { - ThEScrollbarGui.this.drawTexturedModalRect( posX, posY, sourceOffsetX, sourceOffsetY, width, height ); - } - }; - } + @Override + public void drawFG(final int arg0, final int arg1, final int arg2, final int arg3) { + // Ignored + } + @Override + public void drawTexturedModalRect( + final int posX, + final int posY, + final int sourceOffsetX, + final int sourceOffsetY, + final int width, + final int height) { + ThEScrollbarGui.this.drawTexturedModalRect(posX, posY, sourceOffsetX, sourceOffsetY, width, height); + } + }; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAETab.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAETab.java index 71e49638..1227f2dd 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAETab.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAETab.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.util.StatCollector; +import org.lwjgl.opengl.GL11; import thaumicenergistics.client.textures.AEStateIconsEnum; import thaumicenergistics.client.textures.IStateIconTexture; @@ -16,65 +16,80 @@ import thaumicenergistics.client.textures.IStateIconTexture; * */ @SideOnly(Side.CLIENT) -public class GuiButtonAETab - extends ThEStateButton -{ - /** - * Height of the button - */ - private static final int BUTTON_HEIGHT = AEStateIconsEnum.TAB_BUTTON.getHeight(); +public class GuiButtonAETab extends ThEStateButton { + /** + * Height of the button + */ + private static final int BUTTON_HEIGHT = AEStateIconsEnum.TAB_BUTTON.getHeight(); - /** - * Width of the button - */ - private static final int BUTTON_WIDTH = AEStateIconsEnum.TAB_BUTTON.getWidth(); + /** + * Width of the button + */ + private static final int BUTTON_WIDTH = AEStateIconsEnum.TAB_BUTTON.getWidth(); - private static int ICON_X_POSITION = 3; + private static int ICON_X_POSITION = 3; - private static int ICON_Y_POSITION = 3; + private static int ICON_Y_POSITION = 3; - private String tooltipMessageUnlocalized; + private String tooltipMessageUnlocalized; - /** - * Icon to draw on the button - */ - protected AEStateIconsEnum icon; + /** + * Icon to draw on the button + */ + protected AEStateIconsEnum icon; - public GuiButtonAETab( final int ID, final int xPosition, final int yPosition, final IStateIconTexture icon, final String unlocalizedTooltip ) - { - // Call super - super( ID, xPosition, yPosition, GuiButtonAETab.BUTTON_WIDTH, GuiButtonAETab.BUTTON_HEIGHT, icon, GuiButtonAETab.ICON_X_POSITION, - GuiButtonAETab.ICON_Y_POSITION, AEStateIconsEnum.TAB_BUTTON ); + public GuiButtonAETab( + final int ID, + final int xPosition, + final int yPosition, + final IStateIconTexture icon, + final String unlocalizedTooltip) { + // Call super + super( + ID, + xPosition, + yPosition, + GuiButtonAETab.BUTTON_WIDTH, + GuiButtonAETab.BUTTON_HEIGHT, + icon, + GuiButtonAETab.ICON_X_POSITION, + GuiButtonAETab.ICON_Y_POSITION, + AEStateIconsEnum.TAB_BUTTON); - // Set the tooltip - this.tooltipMessageUnlocalized = unlocalizedTooltip; - } + // Set the tooltip + this.tooltipMessageUnlocalized = unlocalizedTooltip; + } - @Override - public void drawButton( final Minecraft minecraftInstance, final int x, final int y ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + @Override + public void drawButton(final Minecraft minecraftInstance, final int x, final int y) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // Draw the tab background - this.drawIcon( minecraftInstance, AEStateIconsEnum.TAB_BUTTON, this.xPosition, this.yPosition, this.width, this.height ); + // Draw the tab background + this.drawIcon( + minecraftInstance, + AEStateIconsEnum.TAB_BUTTON, + this.xPosition, + this.yPosition, + this.width, + this.height); - if( this.stateIcon != null ) - { - // Draw the overlay icon - this.drawIcon( minecraftInstance, this.stateIcon, this.xPosition, this.yPosition, - AEStateIconsEnum.STANDARD_ICON_SIZE, AEStateIconsEnum.STANDARD_ICON_SIZE ); - } - - } - - @Override - public void getTooltip( final List tooltip ) - { - if( !this.tooltipMessageUnlocalized.equals( "" ) ) - { - tooltip.add( StatCollector.translateToLocal( this.tooltipMessageUnlocalized ) ); - } - } + if (this.stateIcon != null) { + // Draw the overlay icon + this.drawIcon( + minecraftInstance, + this.stateIcon, + this.xPosition, + this.yPosition, + AEStateIconsEnum.STANDARD_ICON_SIZE, + AEStateIconsEnum.STANDARD_ICON_SIZE); + } + } + @Override + public void getTooltip(final List tooltip) { + if (!this.tooltipMessageUnlocalized.equals("")) { + tooltip.add(StatCollector.translateToLocal(this.tooltipMessageUnlocalized)); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAllowVoid.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAllowVoid.java index 9b159b2b..519c4ee9 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAllowVoid.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonAllowVoid.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.entity.RenderItem; @@ -20,111 +20,108 @@ import thaumicenergistics.common.registries.ThEStrings; * */ @SideOnly(Side.CLIENT) -public class GuiButtonAllowVoid - extends ThEGuiButtonBase -{ - /** - * Cache the render engine - */ - private static final TextureManager RENDER_ENGINE = Minecraft.getMinecraft().renderEngine; +public class GuiButtonAllowVoid extends ThEGuiButtonBase { + /** + * Cache the render engine + */ + private static final TextureManager RENDER_ENGINE = Minecraft.getMinecraft().renderEngine; - /** - * Cache the font renderer - */ - private static final FontRenderer FONT_RENDERER = Minecraft.getMinecraft().fontRenderer; + /** + * Cache the font renderer + */ + private static final FontRenderer FONT_RENDERER = Minecraft.getMinecraft().fontRenderer; - /** - * Height and width of the button - */ - private static final int BUTTON_SIZE = 18; + /** + * Height and width of the button + */ + private static final int BUTTON_SIZE = 18; - /** - * Height and width of the disabled icon. - */ - private static final int DISABLED_ICON_SIZE = 16; + /** + * Height and width of the disabled icon. + */ + private static final int DISABLED_ICON_SIZE = 16; - /** - * Create an item renderer - */ - private static RenderItem itemRenderer = new RenderItem(); + /** + * Create an item renderer + */ + private static RenderItem itemRenderer = new RenderItem(); - /** - * Void jar itemstack. - */ - private static ItemStack voidJar = null; + /** + * Void jar itemstack. + */ + private static ItemStack voidJar = null; - /** - * Disabled icon from the AE sprite sheet. - */ - private AEStateIconsEnum disabledIcon = AEStateIconsEnum.DISABLED; + /** + * Disabled icon from the AE sprite sheet. + */ + private AEStateIconsEnum disabledIcon = AEStateIconsEnum.DISABLED; - /** - * When false, draws the disabled icon over the jar - */ - private boolean isVoidAllowed = false; + /** + * When false, draws the disabled icon over the jar + */ + private boolean isVoidAllowed = false; - public GuiButtonAllowVoid( final int ID, final int xPosition, final int yPosition ) - { - super( ID, xPosition, yPosition, GuiButtonAllowVoid.BUTTON_SIZE, GuiButtonAllowVoid.BUTTON_SIZE, "" ); + public GuiButtonAllowVoid(final int ID, final int xPosition, final int yPosition) { + super(ID, xPosition, yPosition, GuiButtonAllowVoid.BUTTON_SIZE, GuiButtonAllowVoid.BUTTON_SIZE, ""); - // Ensure we have made the void jar stack - if( GuiButtonAllowVoid.voidJar == null ) - { - GuiButtonAllowVoid.voidJar = new ItemStack( ConfigBlocks.blockJar, 1, 3 ); - } - } + // Ensure we have made the void jar stack + if (GuiButtonAllowVoid.voidJar == null) { + GuiButtonAllowVoid.voidJar = new ItemStack(ConfigBlocks.blockJar, 1, 3); + } + } - @Override - public void drawButton( final Minecraft minecraftInstance, final int x, final int y ) - { - // Draw the usual button - super.drawButton( minecraftInstance, x, y ); + @Override + public void drawButton(final Minecraft minecraftInstance, final int x, final int y) { + // Draw the usual button + super.drawButton(minecraftInstance, x, y); - // Draw the void jar - GuiButtonAllowVoid.itemRenderer.renderItemIntoGUI( GuiButtonAllowVoid.FONT_RENDERER, GuiButtonAllowVoid.RENDER_ENGINE, - GuiButtonAllowVoid.voidJar, this.xPosition + 1, - this.yPosition + 1, false ); + // Draw the void jar + GuiButtonAllowVoid.itemRenderer.renderItemIntoGUI( + GuiButtonAllowVoid.FONT_RENDERER, + GuiButtonAllowVoid.RENDER_ENGINE, + GuiButtonAllowVoid.voidJar, + this.xPosition + 1, + this.yPosition + 1, + false); - // Is void not allowed? - if( !this.isVoidAllowed ) - { - // Bind the AE states texture - minecraftInstance.getTextureManager().bindTexture( AEStateIconsEnum.AE_STATES_TEXTURE ); + // Is void not allowed? + if (!this.isVoidAllowed) { + // Bind the AE states texture + minecraftInstance.getTextureManager().bindTexture(AEStateIconsEnum.AE_STATES_TEXTURE); - // Draw the disabled icon - this.drawTexturedModalRect( this.xPosition + 1, this.yPosition + 1, this.disabledIcon.getU(), this.disabledIcon.getV(), - GuiButtonAllowVoid.DISABLED_ICON_SIZE, GuiButtonAllowVoid.DISABLED_ICON_SIZE ); - } - } + // Draw the disabled icon + this.drawTexturedModalRect( + this.xPosition + 1, + this.yPosition + 1, + this.disabledIcon.getU(), + this.disabledIcon.getV(), + GuiButtonAllowVoid.DISABLED_ICON_SIZE, + GuiButtonAllowVoid.DISABLED_ICON_SIZE); + } + } - @Override - public void getTooltip( final List tooltip ) - { - // Add the title - tooltip.add( ThEStrings.TooltipButton_VoidHeader.getLocalized() ); + @Override + public void getTooltip(final List tooltip) { + // Add the title + tooltip.add(ThEStrings.TooltipButton_VoidHeader.getLocalized()); - // Add allowed/disabled - if( this.isVoidAllowed ) - { - tooltip.add( EnumChatFormatting.GRAY + ThEStrings.TooltipButton_VoidAllow.getLocalized() ); - } - else - { - tooltip.add( EnumChatFormatting.GRAY + ThEStrings.TooltipButton_VoidDisable.getLocalized() ); - } + // Add allowed/disabled + if (this.isVoidAllowed) { + tooltip.add(EnumChatFormatting.GRAY + ThEStrings.TooltipButton_VoidAllow.getLocalized()); + } else { + tooltip.add(EnumChatFormatting.GRAY + ThEStrings.TooltipButton_VoidDisable.getLocalized()); + } - // Add the note - tooltip.add( EnumChatFormatting.ITALIC + ThEStrings.TooltipButton_VoidNote.getLocalized() ); + // Add the note + tooltip.add(EnumChatFormatting.ITALIC + ThEStrings.TooltipButton_VoidNote.getLocalized()); + } - } - - /** - * Is void allowed? - * - * @param allowed - */ - public void setIsVoidAllowed( final boolean allowed ) - { - this.isVoidAllowed = allowed; - } + /** + * Is void allowed? + * + * @param allowed + */ + public void setIsVoidAllowed(final boolean allowed) { + this.isVoidAllowed = allowed; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCellPartitioning.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCellPartitioning.java index 10966f1b..3a60446f 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCellPartitioning.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCellPartitioning.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -13,34 +13,41 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonClearCellPartitioning - extends ThEStateButton -{ +public class GuiButtonClearCellPartitioning extends ThEStateButton { - /** - * Clear icon - */ - private static final AEStateIconsEnum CLEAR_ICON = AEStateIconsEnum.CLEAR_GRID; + /** + * Clear icon + */ + private static final AEStateIconsEnum CLEAR_ICON = AEStateIconsEnum.CLEAR_GRID; - /** - * Creates the button - * - * @param ID - * @param xPosition - * @param yPosition - * @param width - * @param height - */ - public GuiButtonClearCellPartitioning( final int ID, final int xPosition, final int yPosition ) - { - super( ID, xPosition, yPosition, 16, 16, GuiButtonClearCellPartitioning.CLEAR_ICON, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } + /** + * Creates the button + * + * @param ID + * @param xPosition + * @param yPosition + * @param width + * @param height + */ + public GuiButtonClearCellPartitioning(final int ID, final int xPosition, final int yPosition) { + super( + ID, + xPosition, + yPosition, + 16, + 16, + GuiButtonClearCellPartitioning.CLEAR_ICON, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + } - @Override - public void getTooltip( final List tooltip ) - { - // Add the info - this.addAboutToTooltip( tooltip, StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.Clear" ), - StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.ClearSettings" ) ); - } + @Override + public void getTooltip(final List tooltip) { + // Add the info + this.addAboutToTooltip( + tooltip, + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Clear"), + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.ClearSettings")); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCraftingGrid.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCraftingGrid.java index 682a5da2..db3e3cbb 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCraftingGrid.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonClearCraftingGrid.java @@ -1,9 +1,9 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.EnumChatFormatting; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -14,43 +14,53 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonClearCraftingGrid - extends ThEStateButton -{ - /** - * Clear grid icon - */ - private static final AEStateIconsEnum CLEAR_ICON = AEStateIconsEnum.CLEAR_GRID; +public class GuiButtonClearCraftingGrid extends ThEStateButton { + /** + * Clear grid icon + */ + private static final AEStateIconsEnum CLEAR_ICON = AEStateIconsEnum.CLEAR_GRID; - private final boolean showTooltip; + private final boolean showTooltip; - /** - * Creates the button - * - * @param ID - * @param xPosition - * @param yPosition - * @param width - * @param height - */ - public GuiButtonClearCraftingGrid( final int ID, final int xPosition, final int yPosition, final int width, final int height, - final boolean showTooltip ) - { - // Call super - super( ID, xPosition, yPosition, width, height, GuiButtonClearCraftingGrid.CLEAR_ICON, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + /** + * Creates the button + * + * @param ID + * @param xPosition + * @param yPosition + * @param width + * @param height + */ + public GuiButtonClearCraftingGrid( + final int ID, + final int xPosition, + final int yPosition, + final int width, + final int height, + final boolean showTooltip) { + // Call super + super( + ID, + xPosition, + yPosition, + width, + height, + GuiButtonClearCraftingGrid.CLEAR_ICON, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); - // Set if the tooltip is shown or not - this.showTooltip = showTooltip; - } - - @Override - public void getTooltip( final List tooltip ) - { - if( this.showTooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.Stash.getLocal(), - EnumChatFormatting.GRAY.toString() + ButtonToolTips.StashDesc.getLocal() ); - } - } + // Set if the tooltip is shown or not + this.showTooltip = showTooltip; + } + @Override + public void getTooltip(final List tooltip) { + if (this.showTooltip) { + this.addAboutToTooltip( + tooltip, + ButtonToolTips.Stash.getLocal(), + EnumChatFormatting.GRAY.toString() + ButtonToolTips.StashDesc.getLocal()); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonCraftingMode.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonCraftingMode.java index 63d5395b..d9258034 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonCraftingMode.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonCraftingMode.java @@ -2,30 +2,28 @@ package thaumicenergistics.client.gui.buttons; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; -import java.util.List; - @SideOnly(Side.CLIENT) -public class GuiButtonCraftingMode extends ThEStateButton -{ +public class GuiButtonCraftingMode extends ThEStateButton { private static final String TOOLTIP_LOC_HEADER = "gui.tooltips.appliedenergistics2."; private boolean alwaysCraft = false; - public GuiButtonCraftingMode(final int ID, final int xPos, final int yPos, final int width, final int height) - { - super( ID, xPos, yPos, width, height, AEStateIconsEnum.CRAFT_EITHER, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + + public GuiButtonCraftingMode(final int ID, final int xPos, final int yPos, final int width, final int height) { + super(ID, xPos, yPos, width, height, AEStateIconsEnum.CRAFT_EITHER, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); } + @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, - StatCollector.translateToLocal( TOOLTIP_LOC_HEADER + "Craft" ), - StatCollector.translateToLocal( - TOOLTIP_LOC_HEADER + (alwaysCraft ? "CraftOnly" : "CraftEither" )) ); + public void getTooltip(final List tooltip) { + this.addAboutToTooltip( + tooltip, + StatCollector.translateToLocal(TOOLTIP_LOC_HEADER + "Craft"), + StatCollector.translateToLocal(TOOLTIP_LOC_HEADER + (alwaysCraft ? "CraftOnly" : "CraftEither"))); } - public void setAlwaysCraft(boolean c) - { + + public void setAlwaysCraft(boolean c) { alwaysCraft = c; this.stateIcon = alwaysCraft ? AEStateIconsEnum.CRAFT_ONLY : AEStateIconsEnum.CRAFT_EITHER; } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonEncodePattern.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonEncodePattern.java index c88cbbb5..8e3a2eda 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonEncodePattern.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonEncodePattern.java @@ -1,9 +1,9 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import thaumicenergistics.client.textures.AEStateIconsEnum; /** @@ -13,20 +13,15 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonEncodePattern - extends ThEStateButton -{ +public class GuiButtonEncodePattern extends ThEStateButton { - public GuiButtonEncodePattern( final int ID, final int posX, final int posY, final int width, final int height ) - { - // Call super - super( ID, posX, posY, width, height, AEStateIconsEnum.ARROW_DOWN, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } - - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.Encode.getLocal(), ButtonToolTips.EncodeDescription.getLocal() ); - } + public GuiButtonEncodePattern(final int ID, final int posX, final int posY, final int width, final int height) { + // Call super + super(ID, posX, posY, width, height, AEStateIconsEnum.ARROW_DOWN, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); + } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip(tooltip, ButtonToolTips.Encode.getLocal(), ButtonToolTips.EncodeDescription.getLocal()); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonRedstoneModes.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonRedstoneModes.java index 92de2b20..b52c4800 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonRedstoneModes.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonRedstoneModes.java @@ -1,9 +1,9 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.RedstoneMode; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -14,123 +14,123 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonRedstoneModes - extends ThEStateButton -{ - /** - * Localization header string for tooltips - */ - private static final String TOOLTIP_LOC_HEADER = "gui.tooltips.appliedenergistics2."; +public class GuiButtonRedstoneModes extends ThEStateButton { + /** + * Localization header string for tooltips + */ + private static final String TOOLTIP_LOC_HEADER = "gui.tooltips.appliedenergistics2."; - /** - * Mode to represent - */ - private RedstoneMode redstoneMode; + /** + * Mode to represent + */ + private RedstoneMode redstoneMode; - /** - * True when this button is attached to a level emitter - */ - private boolean emitter = false; + /** + * True when this button is attached to a level emitter + */ + private boolean emitter = false; - /** - * Creates the button. - * - * @param ID - * @param xPos - * @param yPos - * @param width - * @param height - * @param mode - */ - public GuiButtonRedstoneModes( final int ID, final int xPos, final int yPos, final int width, final int height, final RedstoneMode mode ) - { - this( ID, xPos, yPos, width, height, mode, false ); - } + /** + * Creates the button. + * + * @param ID + * @param xPos + * @param yPos + * @param width + * @param height + * @param mode + */ + public GuiButtonRedstoneModes( + final int ID, final int xPos, final int yPos, final int width, final int height, final RedstoneMode mode) { + this(ID, xPos, yPos, width, height, mode, false); + } - /** - * Creates the button with argument for if this is an emitter. - * - * @param ID - * @param xPos - * @param yPos - * @param width - * @param height - * @param mode - * @param emitter - */ - public GuiButtonRedstoneModes( final int ID, final int xPos, final int yPos, final int width, final int height, final RedstoneMode mode, - final boolean emitter ) - { - // Call super - super( ID, xPos, yPos, width, height, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + /** + * Creates the button with argument for if this is an emitter. + * + * @param ID + * @param xPos + * @param yPos + * @param width + * @param height + * @param mode + * @param emitter + */ + public GuiButtonRedstoneModes( + final int ID, + final int xPos, + final int yPos, + final int width, + final int height, + final RedstoneMode mode, + final boolean emitter) { + // Call super + super(ID, xPos, yPos, width, height, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); - // Set the if we are attached to an emitter - this.emitter = emitter; + // Set the if we are attached to an emitter + this.emitter = emitter; - // Set the redstone mode - this.setRedstoneMode( mode ); - } + // Set the redstone mode + this.setRedstoneMode(mode); + } - @Override - public void getTooltip( final List tooltip ) - { - // Get the explanation based on mode - String explanation = ""; - switch ( this.redstoneMode ) - { - case HIGH_SIGNAL: - explanation = StatCollector.translateToLocal( this.emitter ? TOOLTIP_LOC_HEADER + "EmitLevelAbove" : TOOLTIP_LOC_HEADER + - "ActiveWithSignal" ); - break; + @Override + public void getTooltip(final List tooltip) { + // Get the explanation based on mode + String explanation = ""; + switch (this.redstoneMode) { + case HIGH_SIGNAL: + explanation = StatCollector.translateToLocal( + this.emitter ? TOOLTIP_LOC_HEADER + "EmitLevelAbove" : TOOLTIP_LOC_HEADER + "ActiveWithSignal"); + break; - case IGNORE: - explanation = StatCollector.translateToLocal( TOOLTIP_LOC_HEADER + "AlwaysActive" ); - break; + case IGNORE: + explanation = StatCollector.translateToLocal(TOOLTIP_LOC_HEADER + "AlwaysActive"); + break; - case LOW_SIGNAL: - explanation = StatCollector.translateToLocal( this.emitter ? TOOLTIP_LOC_HEADER + "EmitLevelsBelow" : TOOLTIP_LOC_HEADER + - "ActiveWithoutSignal" ); - break; + case LOW_SIGNAL: + explanation = StatCollector.translateToLocal( + this.emitter + ? TOOLTIP_LOC_HEADER + "EmitLevelsBelow" + : TOOLTIP_LOC_HEADER + "ActiveWithoutSignal"); + break; - case SIGNAL_PULSE: - explanation = StatCollector.translateToLocal( TOOLTIP_LOC_HEADER + "ActiveOnPulse" ); - break; + case SIGNAL_PULSE: + explanation = StatCollector.translateToLocal(TOOLTIP_LOC_HEADER + "ActiveOnPulse"); + break; + } - } + // Add info + this.addAboutToTooltip( + tooltip, StatCollector.translateToLocal(TOOLTIP_LOC_HEADER + "RedstoneMode"), explanation); + } - // Add info - this.addAboutToTooltip( tooltip, StatCollector.translateToLocal( TOOLTIP_LOC_HEADER + "RedstoneMode" ), explanation ); + /** + * Sets the redstone mode this button represents. + * + * @param mode + */ + public void setRedstoneMode(final RedstoneMode mode) { + // Set the mode + this.redstoneMode = mode; - } + // Set the icon + switch (this.redstoneMode) { + case HIGH_SIGNAL: + this.stateIcon = AEStateIconsEnum.REDSTONE_HIGH; + break; - /** - * Sets the redstone mode this button represents. - * - * @param mode - */ - public void setRedstoneMode( final RedstoneMode mode ) - { - // Set the mode - this.redstoneMode = mode; + case IGNORE: + this.stateIcon = AEStateIconsEnum.REDSTONE_IGNORE; + break; - // Set the icon - switch ( this.redstoneMode ) - { - case HIGH_SIGNAL: - this.stateIcon = AEStateIconsEnum.REDSTONE_HIGH; - break; + case LOW_SIGNAL: + this.stateIcon = AEStateIconsEnum.REDSTONE_LOW; + break; - case IGNORE: - this.stateIcon = AEStateIconsEnum.REDSTONE_IGNORE; - break; - - case LOW_SIGNAL: - this.stateIcon = AEStateIconsEnum.REDSTONE_LOW; - break; - - case SIGNAL_PULSE: - this.stateIcon = AEStateIconsEnum.REDSTONE_PULSE; - break; - } - } + case SIGNAL_PULSE: + this.stateIcon = AEStateIconsEnum.REDSTONE_PULSE; + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSaveDelete.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSaveDelete.java index 939359fc..b7cfc19e 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSaveDelete.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSaveDelete.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import thaumicenergistics.client.textures.AEStateIconsEnum; import thaumicenergistics.common.container.ContainerKnowledgeInscriber.CoreSaveState; import thaumicenergistics.common.registries.ThEStrings; @@ -14,65 +14,59 @@ import thaumicenergistics.common.registries.ThEStrings; * */ @SideOnly(Side.CLIENT) -public class GuiButtonSaveDelete - extends ThEStateButton -{ - private String cachedTooltip; +public class GuiButtonSaveDelete extends ThEStateButton { + private String cachedTooltip; - public GuiButtonSaveDelete( final int ID, final int xPosition, final int yPosition, final CoreSaveState initialState ) - { - // Call super - super( ID, xPosition, yPosition, 16, 16, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + public GuiButtonSaveDelete( + final int ID, final int xPosition, final int yPosition, final CoreSaveState initialState) { + // Call super + super(ID, xPosition, yPosition, 16, 16, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); - // Initial state - this.setSaveState( initialState ); - } + // Initial state + this.setSaveState(initialState); + } - @Override - public void getTooltip( final List tooltip ) - { - tooltip.add( this.cachedTooltip ); - } + @Override + public void getTooltip(final List tooltip) { + tooltip.add(this.cachedTooltip); + } - /** - * Sets the save state of the button. - * - * @param saveState - */ - public void setSaveState( final CoreSaveState saveState ) - { - switch ( saveState ) - { - case Disabled_InvalidRecipe: - this.enabled = false; - this.stateIcon = null; - this.cachedTooltip = ThEStrings.TooltipButton_InscriberInvalid.getLocalized(); - break; + /** + * Sets the save state of the button. + * + * @param saveState + */ + public void setSaveState(final CoreSaveState saveState) { + switch (saveState) { + case Disabled_InvalidRecipe: + this.enabled = false; + this.stateIcon = null; + this.cachedTooltip = ThEStrings.TooltipButton_InscriberInvalid.getLocalized(); + break; - case Disabled_CoreFull: - this.enabled = false; - this.stateIcon = null; - this.cachedTooltip = ThEStrings.TooltipButton_InscriberFull.getLocalized(); - break; + case Disabled_CoreFull: + this.enabled = false; + this.stateIcon = null; + this.cachedTooltip = ThEStrings.TooltipButton_InscriberFull.getLocalized(); + break; - case Enabled_Delete: - this.enabled = true; - this.stateIcon = AEStateIconsEnum.DELETE; - this.cachedTooltip = ThEStrings.TooltipButton_InscriberDelete.getLocalized(); - break; + case Enabled_Delete: + this.enabled = true; + this.stateIcon = AEStateIconsEnum.DELETE; + this.cachedTooltip = ThEStrings.TooltipButton_InscriberDelete.getLocalized(); + break; - case Enabled_Save: - this.enabled = true; - this.stateIcon = AEStateIconsEnum.SAVE; - this.cachedTooltip = ThEStrings.TooltipButton_InscriberSave.getLocalized(); - break; + case Enabled_Save: + this.enabled = true; + this.stateIcon = AEStateIconsEnum.SAVE; + this.cachedTooltip = ThEStrings.TooltipButton_InscriberSave.getLocalized(); + break; - case Disabled_MissingCore: - this.enabled = false; - this.stateIcon = null; - this.cachedTooltip = ThEStrings.TooltipButton_InscriberMissing.getLocalized(); - break; - - } - } + case Disabled_MissingCore: + this.enabled = false; + this.stateIcon = null; + this.cachedTooltip = ThEStrings.TooltipButton_InscriberMissing.getLocalized(); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSearchMode.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSearchMode.java index 52189ff7..403a0c2c 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSearchMode.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSearchMode.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.SearchBoxMode; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.EnumChatFormatting; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -15,55 +15,53 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonSearchMode - extends ThEStateButton -{ - private String tooltipMode = ""; +public class GuiButtonSearchMode extends ThEStateButton { + private String tooltipMode = ""; - public GuiButtonSearchMode( final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight, - final SearchBoxMode currentMode ) - { - super( ID, xPosition, yPosition, buttonWidth, buttonHeight, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + public GuiButtonSearchMode( + final int ID, + final int xPosition, + final int yPosition, + final int buttonWidth, + final int buttonHeight, + final SearchBoxMode currentMode) { + super(ID, xPosition, yPosition, buttonWidth, buttonHeight, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); - this.setSearchMode( currentMode ); - } + this.setSearchMode(currentMode); + } - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.SearchMode.getLocal(), EnumChatFormatting.GRAY + this.tooltipMode ); - } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip( + tooltip, ButtonToolTips.SearchMode.getLocal(), EnumChatFormatting.GRAY + this.tooltipMode); + } - /** - * Sets the icon and tooltip based on the specified mode. - * - * @param mode - */ - public void setSearchMode( final SearchBoxMode mode ) - { - switch ( mode ) - { - case AUTOSEARCH: - this.tooltipMode = ButtonToolTips.SearchMode_Auto.getLocal(); - this.stateIcon = AEStateIconsEnum.SEARCH_MODE_AUTO; - break; + /** + * Sets the icon and tooltip based on the specified mode. + * + * @param mode + */ + public void setSearchMode(final SearchBoxMode mode) { + switch (mode) { + case AUTOSEARCH: + this.tooltipMode = ButtonToolTips.SearchMode_Auto.getLocal(); + this.stateIcon = AEStateIconsEnum.SEARCH_MODE_AUTO; + break; - case MANUAL_SEARCH: - this.tooltipMode = ButtonToolTips.SearchMode_Standard.getLocal(); - this.stateIcon = AEStateIconsEnum.SEARCH_MODE_MANUAL; - break; + case MANUAL_SEARCH: + this.tooltipMode = ButtonToolTips.SearchMode_Standard.getLocal(); + this.stateIcon = AEStateIconsEnum.SEARCH_MODE_MANUAL; + break; - case NEI_AUTOSEARCH: - this.tooltipMode = ButtonToolTips.SearchMode_NEIAuto.getLocal(); - this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_AUTO; - break; - - case NEI_MANUAL_SEARCH: - this.tooltipMode = ButtonToolTips.SearchMode_NEIStandard.getLocal(); - this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_MANUAL; - break; - - } - } + case NEI_AUTOSEARCH: + this.tooltipMode = ButtonToolTips.SearchMode_NEIAuto.getLocal(); + this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_AUTO; + break; + case NEI_MANUAL_SEARCH: + this.tooltipMode = ButtonToolTips.SearchMode_NEIStandard.getLocal(); + this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_MANUAL; + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSetCellPartitioningToCurrent.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSetCellPartitioningToCurrent.java index 847aee09..5cd84b47 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSetCellPartitioningToCurrent.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSetCellPartitioningToCurrent.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -13,33 +13,40 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonSetCellPartitioningToCurrent - extends ThEStateButton -{ - /** - * Wrench icon - */ - private static final AEStateIconsEnum WRENCH_ICON = AEStateIconsEnum.WRENCH; +public class GuiButtonSetCellPartitioningToCurrent extends ThEStateButton { + /** + * Wrench icon + */ + private static final AEStateIconsEnum WRENCH_ICON = AEStateIconsEnum.WRENCH; - /** - * Creates the button - * - * @param ID - * @param xPosition - * @param yPosition - * @param width - * @param height - */ - public GuiButtonSetCellPartitioningToCurrent( final int ID, final int xPosition, final int yPosition ) - { - super( ID, xPosition, yPosition, 16, 16, GuiButtonSetCellPartitioningToCurrent.WRENCH_ICON, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } + /** + * Creates the button + * + * @param ID + * @param xPosition + * @param yPosition + * @param width + * @param height + */ + public GuiButtonSetCellPartitioningToCurrent(final int ID, final int xPosition, final int yPosition) { + super( + ID, + xPosition, + yPosition, + 16, + 16, + GuiButtonSetCellPartitioningToCurrent.WRENCH_ICON, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + } - @Override - public void getTooltip( final List tooltip ) - { - // Add the info - this.addAboutToTooltip( tooltip, StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.PartitionStorage" ), - StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.PartitionStorageHint" ) ); - } + @Override + public void getTooltip(final List tooltip) { + // Add the info + this.addAboutToTooltip( + tooltip, + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.PartitionStorage"), + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.PartitionStorageHint")); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingDirection.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingDirection.java index 5a3b8fea..c23318e0 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingDirection.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingDirection.java @@ -1,9 +1,9 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.SortDir; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -14,33 +14,39 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonSortingDirection - extends ThEStateButton -{ +public class GuiButtonSortingDirection extends ThEStateButton { - public GuiButtonSortingDirection( final int ID, final int xPosition, final int yPosition, final int width, final int height ) - { - super( ID, xPosition, yPosition, width, height, AEStateIconsEnum.SORT_DIR_ASC, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } + public GuiButtonSortingDirection( + final int ID, final int xPosition, final int yPosition, final int width, final int height) { + super( + ID, + xPosition, + yPosition, + width, + height, + AEStateIconsEnum.SORT_DIR_ASC, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + } - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.SortOrder" ), - StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.ToggleSortDirection" ) ); - } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip( + tooltip, + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.SortOrder"), + StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.ToggleSortDirection")); + } - public void setSortingDirection( final SortDir direction ) - { - switch ( direction ) - { - case ASCENDING: - this.stateIcon = AEStateIconsEnum.SORT_DIR_ASC; - break; + public void setSortingDirection(final SortDir direction) { + switch (direction) { + case ASCENDING: + this.stateIcon = AEStateIconsEnum.SORT_DIR_ASC; + break; - case DESCENDING: - this.stateIcon = AEStateIconsEnum.SORT_DIR_DEC; - break; - } - } + case DESCENDING: + this.stateIcon = AEStateIconsEnum.SORT_DIR_DEC; + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingMode.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingMode.java index 4e4282dc..fd4e7280 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingMode.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSortingMode.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.SortOrder; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -17,69 +17,68 @@ import thaumicenergistics.common.storage.AspectStackComparator.AspectStackCompar * */ @SideOnly(Side.CLIENT) -public class GuiButtonSortingMode - extends ThEStateButton -{ - private String tooltipSortBy = ""; +public class GuiButtonSortingMode extends ThEStateButton { + private String tooltipSortBy = ""; - public GuiButtonSortingMode( final int ID, final int xPosition, final int yPosition, final int width, final int height ) - { - super( ID, xPosition, yPosition, width, height, AEStateIconsEnum.SORT_MODE_ALPHABETIC, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } + public GuiButtonSortingMode( + final int ID, final int xPosition, final int yPosition, final int width, final int height) { + super( + ID, + xPosition, + yPosition, + width, + height, + AEStateIconsEnum.SORT_MODE_ALPHABETIC, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + } - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.SortBy.getLocal(), EnumChatFormatting.GRAY + this.tooltipSortBy ); - } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip(tooltip, ButtonToolTips.SortBy.getLocal(), EnumChatFormatting.GRAY + this.tooltipSortBy); + } - /** - * Sets the buttons icon based on the specified comparator mode. - * - * @param mode - */ - public void setSortMode( final AspectStackComparatorMode mode ) - { - switch ( mode ) - { - case MODE_ALPHABETIC: - this.stateIcon = AEStateIconsEnum.SORT_MODE_ALPHABETIC; - this.tooltipSortBy = ButtonToolTips.ItemName.getLocal(); - break; + /** + * Sets the buttons icon based on the specified comparator mode. + * + * @param mode + */ + public void setSortMode(final AspectStackComparatorMode mode) { + switch (mode) { + case MODE_ALPHABETIC: + this.stateIcon = AEStateIconsEnum.SORT_MODE_ALPHABETIC; + this.tooltipSortBy = ButtonToolTips.ItemName.getLocal(); + break; - case MODE_AMOUNT: - this.stateIcon = AEStateIconsEnum.SORT_MODE_AMOUNT; - this.tooltipSortBy = ButtonToolTips.NumberOfItems.getLocal(); - break; + case MODE_AMOUNT: + this.stateIcon = AEStateIconsEnum.SORT_MODE_AMOUNT; + this.tooltipSortBy = ButtonToolTips.NumberOfItems.getLocal(); + break; + } + } - } - } + public void setSortMode(final SortOrder order) { + switch (order) { + case AMOUNT: + this.stateIcon = AEStateIconsEnum.SORT_MODE_AMOUNT; + this.tooltipSortBy = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.NumberOfItems"); + break; - public void setSortMode( final SortOrder order ) - { - switch ( order ) - { - case AMOUNT: - this.stateIcon = AEStateIconsEnum.SORT_MODE_AMOUNT; - this.tooltipSortBy = StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.NumberOfItems" ); - break; + case INVTWEAKS: + this.stateIcon = AEStateIconsEnum.SORT_MODE_INVTWEAK; + this.tooltipSortBy = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.InventoryTweaks"); + break; - case INVTWEAKS: - this.stateIcon = AEStateIconsEnum.SORT_MODE_INVTWEAK; - this.tooltipSortBy = StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.InventoryTweaks" ); - break; - - case MOD: - this.stateIcon = AEStateIconsEnum.SORT_MODE_MOD; - this.tooltipSortBy = StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.Mod" ); - break; - - case NAME: - this.stateIcon = AEStateIconsEnum.SORT_MODE_ALPHABETIC; - this.tooltipSortBy = StatCollector.translateToLocal( "gui.tooltips.appliedenergistics2.ItemName" ); - break; - - } - } + case MOD: + this.stateIcon = AEStateIconsEnum.SORT_MODE_MOD; + this.tooltipSortBy = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Mod"); + break; + case NAME: + this.stateIcon = AEStateIconsEnum.SORT_MODE_ALPHABETIC; + this.tooltipSortBy = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.ItemName"); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSwapArmor.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSwapArmor.java index 0c49c2db..b09a3012 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSwapArmor.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonSwapArmor.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import thaumicenergistics.client.textures.AEStateIconsEnum; import thaumicenergistics.client.textures.ThEStateIconsEnum; import thaumicenergistics.common.registries.ThEStrings; @@ -14,19 +14,27 @@ import thaumicenergistics.common.registries.ThEStrings; * */ @SideOnly(Side.CLIENT) -public class GuiButtonSwapArmor - extends ThEStateButton -{ +public class GuiButtonSwapArmor extends ThEStateButton { - public GuiButtonSwapArmor( final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight ) - { - super( ID, xPosition, yPosition, buttonWidth, buttonHeight, ThEStateIconsEnum.SWAP, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - } - - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ThEStrings.TooltipButton_SwapArmor_Title.getLocalized(), ThEStrings.TooltipButton_SwapArmor.getLocalized() ); - } + public GuiButtonSwapArmor( + final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight) { + super( + ID, + xPosition, + yPosition, + buttonWidth, + buttonHeight, + ThEStateIconsEnum.SWAP, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip( + tooltip, + ThEStrings.TooltipButton_SwapArmor_Title.getLocalized(), + ThEStrings.TooltipButton_SwapArmor.getLocalized()); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonTerminalStyle.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonTerminalStyle.java index 3c725830..e09ac18a 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonTerminalStyle.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonTerminalStyle.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.TerminalStyle; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.EnumChatFormatting; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -15,44 +15,42 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonTerminalStyle - extends ThEStateButton -{ - private String tooltipStyle = ""; +public class GuiButtonTerminalStyle extends ThEStateButton { + private String tooltipStyle = ""; - public GuiButtonTerminalStyle( final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight, - final TerminalStyle currentStyle ) - { - super( ID, xPosition, yPosition, buttonWidth, buttonHeight, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); + public GuiButtonTerminalStyle( + final int ID, + final int xPosition, + final int yPosition, + final int buttonWidth, + final int buttonHeight, + final TerminalStyle currentStyle) { + super(ID, xPosition, yPosition, buttonWidth, buttonHeight, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON); - // Set the style - this.setTerminalStyle( currentStyle ); - } + // Set the style + this.setTerminalStyle(currentStyle); + } - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.TerminalStyle.getLocal(), EnumChatFormatting.GRAY + this.tooltipStyle ); - } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip( + tooltip, ButtonToolTips.TerminalStyle.getLocal(), EnumChatFormatting.GRAY + this.tooltipStyle); + } - public void setTerminalStyle( final TerminalStyle style ) - { - switch ( style ) - { - case SMALL: - this.stateIcon = AEStateIconsEnum.TERM_STYLE_SMALL; - this.tooltipStyle = ButtonToolTips.TerminalStyle_Small.getLocal(); - break; + public void setTerminalStyle(final TerminalStyle style) { + switch (style) { + case SMALL: + this.stateIcon = AEStateIconsEnum.TERM_STYLE_SMALL; + this.tooltipStyle = ButtonToolTips.TerminalStyle_Small.getLocal(); + break; - case TALL: - this.stateIcon = AEStateIconsEnum.TERM_STYLE_TALL; - this.tooltipStyle = ButtonToolTips.TerminalStyle_Tall.getLocal(); - break; - - default: - break; - - } - } + case TALL: + this.stateIcon = AEStateIconsEnum.TERM_STYLE_TALL; + this.tooltipStyle = ButtonToolTips.TerminalStyle_Tall.getLocal(); + break; + default: + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonViewType.java b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonViewType.java index 85907b68..7444af1a 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonViewType.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/GuiButtonViewType.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import appeng.api.config.ViewItems; import appeng.core.localization.ButtonToolTips; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.util.EnumChatFormatting; import thaumicenergistics.client.textures.AEStateIconsEnum; @@ -15,59 +15,62 @@ import thaumicenergistics.client.textures.AEStateIconsEnum; * */ @SideOnly(Side.CLIENT) -public class GuiButtonViewType - extends ThEStateButton -{ - /** - * Cached tooltip for the buttons view mode. - */ - private String tooltipViewType = ""; +public class GuiButtonViewType extends ThEStateButton { + /** + * Cached tooltip for the buttons view mode. + */ + private String tooltipViewType = ""; - /** - * Creates the view button. - * - * @param ID - * @param xPosition - * @param yPosition - * @param width - * @param height - */ - public GuiButtonViewType( final int ID, final int xPosition, final int yPosition, final int width, final int height ) - { - super( ID, xPosition, yPosition, width, height, AEStateIconsEnum.VIEW_TYPE_ALL, 0, 0, AEStateIconsEnum.REGULAR_BUTTON ); - this.setViewMode( ViewItems.ALL ); - } + /** + * Creates the view button. + * + * @param ID + * @param xPosition + * @param yPosition + * @param width + * @param height + */ + public GuiButtonViewType( + final int ID, final int xPosition, final int yPosition, final int width, final int height) { + super( + ID, + xPosition, + yPosition, + width, + height, + AEStateIconsEnum.VIEW_TYPE_ALL, + 0, + 0, + AEStateIconsEnum.REGULAR_BUTTON); + this.setViewMode(ViewItems.ALL); + } - @Override - public void getTooltip( final List tooltip ) - { - this.addAboutToTooltip( tooltip, ButtonToolTips.View.getLocal(), EnumChatFormatting.GRAY + this.tooltipViewType ); - } + @Override + public void getTooltip(final List tooltip) { + this.addAboutToTooltip(tooltip, ButtonToolTips.View.getLocal(), EnumChatFormatting.GRAY + this.tooltipViewType); + } - /** - * Sets the icon based on the view mode. - * - * @param mode - */ - public void setViewMode( final ViewItems mode ) - { - switch ( mode ) - { - case ALL: - this.tooltipViewType = ButtonToolTips.StoredCraftable.getLocal(); - this.stateIcon = AEStateIconsEnum.VIEW_TYPE_ALL; - break; + /** + * Sets the icon based on the view mode. + * + * @param mode + */ + public void setViewMode(final ViewItems mode) { + switch (mode) { + case ALL: + this.tooltipViewType = ButtonToolTips.StoredCraftable.getLocal(); + this.stateIcon = AEStateIconsEnum.VIEW_TYPE_ALL; + break; - case CRAFTABLE: - this.tooltipViewType = ButtonToolTips.Craftable.getLocal(); - this.stateIcon = AEStateIconsEnum.VIEW_TYPE_CRAFT; - break; - - case STORED: - this.tooltipViewType = ButtonToolTips.StoredItems.getLocal(); - this.stateIcon = AEStateIconsEnum.VIEW_TYPE_STORED; - break; - } - } + case CRAFTABLE: + this.tooltipViewType = ButtonToolTips.Craftable.getLocal(); + this.stateIcon = AEStateIconsEnum.VIEW_TYPE_CRAFT; + break; + case STORED: + this.tooltipViewType = ButtonToolTips.StoredItems.getLocal(); + this.stateIcon = AEStateIconsEnum.VIEW_TYPE_STORED; + break; + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/ThEGuiButtonBase.java b/src/main/java/thaumicenergistics/client/gui/buttons/ThEGuiButtonBase.java index 51c703e3..f56ede5e 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/ThEGuiButtonBase.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/ThEGuiButtonBase.java @@ -1,8 +1,8 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.gui.GuiButton; import thaumicenergistics.client.gui.ThEGuiHelper; @@ -13,37 +13,38 @@ import thaumicenergistics.client.gui.ThEGuiHelper; * */ @SideOnly(Side.CLIENT) -public abstract class ThEGuiButtonBase - extends GuiButton -{ - public ThEGuiButtonBase( final int ID, final int xPosition, final int yPosition, final int width, final int height, final String text ) - { - super( ID, xPosition, yPosition, width, height, text ); - } +public abstract class ThEGuiButtonBase extends GuiButton { + public ThEGuiButtonBase( + final int ID, + final int xPosition, + final int yPosition, + final int width, + final int height, + final String text) { + super(ID, xPosition, yPosition, width, height, text); + } - public ThEGuiButtonBase( final int ID, final int xPosition, final int yPosition, final String text ) - { - super( ID, xPosition, yPosition, text ); - } + public ThEGuiButtonBase(final int ID, final int xPosition, final int yPosition, final String text) { + super(ID, xPosition, yPosition, text); + } - /** - * Called to get the tooltip for this button. - * - * @param tooltip - * List to add tooltip string to. - */ - public abstract void getTooltip( final List tooltip ); - - /** - * Checks if the mouse is over this button. - * - * @param mouseX - * @param mouseY - * @return - */ - public boolean isMouseOverButton( final int mouseX, final int mouseY ) - { - return ThEGuiHelper.INSTANCE.isPointInRegion( this.yPosition, this.xPosition, this.height, this.width, mouseX, mouseY ); - } + /** + * Called to get the tooltip for this button. + * + * @param tooltip + * List to add tooltip string to. + */ + public abstract void getTooltip(final List tooltip); + /** + * Checks if the mouse is over this button. + * + * @param mouseX + * @param mouseY + * @return + */ + public boolean isMouseOverButton(final int mouseX, final int mouseY) { + return ThEGuiHelper.INSTANCE.isPointInRegion( + this.yPosition, this.xPosition, this.height, this.width, mouseX, mouseY); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/buttons/ThEStateButton.java b/src/main/java/thaumicenergistics/client/gui/buttons/ThEStateButton.java index aa8b6c26..31ba3922 100644 --- a/src/main/java/thaumicenergistics/client/gui/buttons/ThEStateButton.java +++ b/src/main/java/thaumicenergistics/client/gui/buttons/ThEStateButton.java @@ -1,14 +1,14 @@ package thaumicenergistics.client.gui.buttons; -import java.util.List; -import org.apache.commons.lang3.text.WordUtils; -import org.lwjgl.opengl.GL11; import com.google.common.base.Splitter; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.EnumChatFormatting; +import org.apache.commons.lang3.text.WordUtils; +import org.lwjgl.opengl.GL11; import thaumicenergistics.client.textures.IStateIconTexture; /** @@ -18,158 +18,179 @@ import thaumicenergistics.client.textures.IStateIconTexture; * */ @SideOnly(Side.CLIENT) -public abstract class ThEStateButton - extends ThEGuiButtonBase -{ - /** - * Button background - */ - private IStateIconTexture backgroundIcon; +public abstract class ThEStateButton extends ThEGuiButtonBase { + /** + * Button background + */ + private IStateIconTexture backgroundIcon; - /** - * Offset from the top-left corner of the button to draw the icon. - */ - private int iconXOffset = 0; + /** + * Offset from the top-left corner of the button to draw the icon. + */ + private int iconXOffset = 0; - /** - * Offset from the top-left corner of the button to draw the icon. - */ - private int iconYOffset = 0; + /** + * Offset from the top-left corner of the button to draw the icon. + */ + private int iconYOffset = 0; - /** - * Icon to draw on the button - */ - protected IStateIconTexture stateIcon; + /** + * Icon to draw on the button + */ + protected IStateIconTexture stateIcon; - /** - * - * @param ID - * @param xPosition - * @param yPosition - * @param buttonWidth - * @param buttonHeight - * @param icon - * @param iconXOffset - * @param iconYOffset - * @param backgroundIcon - */ - public ThEStateButton( final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight, - final IStateIconTexture icon, final int iconXOffset, final int iconYOffset, final IStateIconTexture backgroundIcon ) - { - // Call super - super( ID, xPosition, yPosition, buttonWidth, buttonHeight, "" ); + /** + * + * @param ID + * @param xPosition + * @param yPosition + * @param buttonWidth + * @param buttonHeight + * @param icon + * @param iconXOffset + * @param iconYOffset + * @param backgroundIcon + */ + public ThEStateButton( + final int ID, + final int xPosition, + final int yPosition, + final int buttonWidth, + final int buttonHeight, + final IStateIconTexture icon, + final int iconXOffset, + final int iconYOffset, + final IStateIconTexture backgroundIcon) { + // Call super + super(ID, xPosition, yPosition, buttonWidth, buttonHeight, ""); - // Set the icon - this.stateIcon = icon; + // Set the icon + this.stateIcon = icon; - // Set the offsets - this.iconXOffset = iconXOffset; - this.iconYOffset = iconYOffset; + // Set the offsets + this.iconXOffset = iconXOffset; + this.iconYOffset = iconYOffset; - // Set background - this.backgroundIcon = backgroundIcon; - } + // Set background + this.backgroundIcon = backgroundIcon; + } - /** - * Draws a textured rectangle at the stored z-value, the texture will - * be scaled to fit within the width and height - */ - private void drawScaledTexturedModalRect( final int xPosition, final int yPosition, final int u, final int v, final int width, final int height, - final int textureWidth, final int textureHeight ) - { - // No idea what this is - float magic_number = 0.00390625F; + /** + * Draws a textured rectangle at the stored z-value, the texture will + * be scaled to fit within the width and height + */ + private void drawScaledTexturedModalRect( + final int xPosition, + final int yPosition, + final int u, + final int v, + final int width, + final int height, + final int textureWidth, + final int textureHeight) { + // No idea what this is + float magic_number = 0.00390625F; - // Calculate the UV's - float minU = u * magic_number; - float maxU = ( u + textureWidth ) * magic_number; - float minV = v * magic_number; - float maxV = ( v + textureHeight ) * magic_number; - double dHeight = height; - double dWidth = width; + // Calculate the UV's + float minU = u * magic_number; + float maxU = (u + textureWidth) * magic_number; + float minV = v * magic_number; + float maxV = (v + textureHeight) * magic_number; + double dHeight = height; + double dWidth = width; - // Get the tessellator - Tessellator tessellator = Tessellator.instance; + // Get the tessellator + Tessellator tessellator = Tessellator.instance; - // Start drawing - tessellator.startDrawingQuads(); + // Start drawing + tessellator.startDrawingQuads(); - // Top left corner - tessellator.addVertexWithUV( xPosition, yPosition + dHeight, this.zLevel, minU, maxV ); + // Top left corner + tessellator.addVertexWithUV(xPosition, yPosition + dHeight, this.zLevel, minU, maxV); - // Top right corner - tessellator.addVertexWithUV( xPosition + dWidth, yPosition + dHeight, this.zLevel, maxU, maxV ); + // Top right corner + tessellator.addVertexWithUV(xPosition + dWidth, yPosition + dHeight, this.zLevel, maxU, maxV); - // Bottom right corner - tessellator.addVertexWithUV( xPosition + dWidth, yPosition, this.zLevel, maxU, minV ); + // Bottom right corner + tessellator.addVertexWithUV(xPosition + dWidth, yPosition, this.zLevel, maxU, minV); - // Bottom left corner - tessellator.addVertexWithUV( xPosition, yPosition, this.zLevel, minU, minV ); + // Bottom left corner + tessellator.addVertexWithUV(xPosition, yPosition, this.zLevel, minU, minV); - // Draw - tessellator.draw(); - } + // Draw + tessellator.draw(); + } - /** - * Adds info to the tooltip as a white header, and grey body. - * The body is broken down into lines of length 30. - * - * @param tooltip - * @param title - * @param text - */ - protected void addAboutToTooltip( final List tooltip, final String title, final String text ) - { - // Title - tooltip.add( EnumChatFormatting.WHITE + title ); + /** + * Adds info to the tooltip as a white header, and grey body. + * The body is broken down into lines of length 30. + * + * @param tooltip + * @param title + * @param text + */ + protected void addAboutToTooltip(final List tooltip, final String title, final String text) { + // Title + tooltip.add(EnumChatFormatting.WHITE + title); - // Body - for( String line : Splitter.on( "\n" ).split( WordUtils.wrap( text, 30, "\n", false ) ) ) - { - tooltip.add( EnumChatFormatting.GRAY + line.trim() ); - } - } + // Body + for (String line : Splitter.on("\n").split(WordUtils.wrap(text, 30, "\n", false))) { + tooltip.add(EnumChatFormatting.GRAY + line.trim()); + } + } - /** - * Draws an icon to the screen. - * - * @param minecraftInstance - * @param icon - * @param xPos - * @param yPos - * @param iconWidth - * @param iconHeight - */ - protected void drawIcon( final Minecraft minecraftInstance, final IStateIconTexture icon, final int xPos, final int yPos, final int iconWidth, - final int iconHeight ) - { - // Bind the sheet - minecraftInstance.getTextureManager().bindTexture( icon.getTexture() ); + /** + * Draws an icon to the screen. + * + * @param minecraftInstance + * @param icon + * @param xPos + * @param yPos + * @param iconWidth + * @param iconHeight + */ + protected void drawIcon( + final Minecraft minecraftInstance, + final IStateIconTexture icon, + final int xPos, + final int yPos, + final int iconWidth, + final int iconHeight) { + // Bind the sheet + minecraftInstance.getTextureManager().bindTexture(icon.getTexture()); - // Draw the icon - this.drawScaledTexturedModalRect( xPos + this.iconXOffset, yPos + this.iconYOffset, icon.getU(), icon.getV(), iconWidth, iconHeight, - icon.getWidth(), icon.getHeight() ); - } + // Draw the icon + this.drawScaledTexturedModalRect( + xPos + this.iconXOffset, + yPos + this.iconYOffset, + icon.getU(), + icon.getV(), + iconWidth, + iconHeight, + icon.getWidth(), + icon.getHeight()); + } - @Override - public void drawButton( final Minecraft minecraftInstance, final int x, final int y ) - { - // Full white - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + @Override + public void drawButton(final Minecraft minecraftInstance, final int x, final int y) { + // Full white + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - if( this.backgroundIcon != null ) - { - // Draw the background - this.drawIcon( minecraftInstance, this.backgroundIcon, this.xPosition, this.yPosition, this.width, this.height ); - } - - if( this.stateIcon != null ) - { - // Draw the overlay icon - this.drawIcon( minecraftInstance, this.stateIcon, this.xPosition + this.iconXOffset, this.yPosition + this.iconYOffset, this.width, - this.height ); - } - - } + if (this.backgroundIcon != null) { + // Draw the background + this.drawIcon( + minecraftInstance, this.backgroundIcon, this.xPosition, this.yPosition, this.width, this.height); + } + if (this.stateIcon != null) { + // Draw the overlay icon + this.drawIcon( + minecraftInstance, + this.stateIcon, + this.xPosition + this.iconXOffset, + this.yPosition + this.iconYOffset, + this.width, + this.height); + } + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/AspectWidgetBase.java b/src/main/java/thaumicenergistics/client/gui/widget/AspectWidgetBase.java index 983777a7..500e4a02 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/AspectWidgetBase.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/AspectWidgetBase.java @@ -1,14 +1,14 @@ package thaumicenergistics.client.gui.widget; -import java.util.List; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumcraft.client.lib.UtilsFX; import thaumicenergistics.api.gui.IWidgetHost; @@ -24,275 +24,259 @@ import thaumicenergistics.common.storage.AspectStack; * */ @SideOnly(Side.CLIENT) -public abstract class AspectWidgetBase - extends ThEWidget -{ - /** - * Icon to display if the aspect is unknown to the player - */ - private static final ResourceLocation UNKNOWN_TEXTURE = new ResourceLocation( "thaumcraft", "textures/aspects/_unknown.png" ); +public abstract class AspectWidgetBase extends ThEWidget { + /** + * Icon to display if the aspect is unknown to the player + */ + private static final ResourceLocation UNKNOWN_TEXTURE = + new ResourceLocation("thaumcraft", "textures/aspects/_unknown.png"); - /** - * Stack this widget represents. - */ - private final IAspectStack aspectStack; + /** + * Stack this widget represents. + */ + private final IAspectStack aspectStack; - /** - * True if the player has discovered the aspect. - */ - protected boolean hasDiscovered = false; + /** + * True if the player has discovered the aspect. + */ + protected boolean hasDiscovered = false; - /** - * Cached aspect name. - */ - protected String aspectName = ""; + /** + * Cached aspect name. + */ + protected String aspectName = ""; - /** - * Cached description of the aspect. - */ - protected String aspectDescription = ""; + /** + * Cached description of the aspect. + */ + protected String aspectDescription = ""; - /** - * Cached footnote of the aspect. - */ - protected String aspectFootnote = ""; + /** + * Cached footnote of the aspect. + */ + protected String aspectFootnote = ""; - /** - * The current player. - */ - private EntityPlayer player; + /** + * The current player. + */ + private EntityPlayer player; - /** - * Color of the aspect as ARGB. - */ - private byte[] aspectColorBytes; + /** + * Color of the aspect as ARGB. + */ + private byte[] aspectColorBytes; - public AspectWidgetBase( final IWidgetHost hostGui, final IAspectStack stack, final int xPos, final int yPos, final EntityPlayer player ) - { - // Call super - super( hostGui, xPos, yPos ); + public AspectWidgetBase( + final IWidgetHost hostGui, + final IAspectStack stack, + final int xPos, + final int yPos, + final EntityPlayer player) { + // Call super + super(hostGui, xPos, yPos); - // Set the player - this.player = player; + // Set the player + this.player = player; - // Create the aspect stack - this.aspectStack = new AspectStack(); + // Create the aspect stack + this.aspectStack = new AspectStack(); - // Set the aspect - this.setAspect( stack ); - } + // Set the aspect + this.setAspect(stack); + } - /** - * Clears the stack and optionally fires the on stack changed event. - * - * @param doUpdate - */ - protected void clearStack( final boolean doUpdate ) - { - this.aspectStack.setAll( null, 0, false ); - this.aspectName = ""; - this.aspectDescription = ""; - this.aspectFootnote = ""; - this.hasDiscovered = false; + /** + * Clears the stack and optionally fires the on stack changed event. + * + * @param doUpdate + */ + protected void clearStack(final boolean doUpdate) { + this.aspectStack.setAll(null, 0, false); + this.aspectName = ""; + this.aspectDescription = ""; + this.aspectFootnote = ""; + this.hasDiscovered = false; - if( doUpdate ) - { - this.onStackChanged(); - } - } + if (doUpdate) { + this.onStackChanged(); + } + } - /** - * Draws the aspect icon, or a question mark if not discovered. - */ - protected void drawAspect() - { - // Ensure there is an aspect to draw - if( !this.aspectStack.hasAspect() ) - { - return; - } + /** + * Draws the aspect icon, or a question mark if not discovered. + */ + protected void drawAspect() { + // Ensure there is an aspect to draw + if (!this.aspectStack.hasAspect()) { + return; + } - // Have they discovered this aspect? - if( this.hasDiscovered ) - { - // Ask Thaumcraft to draw the aspect - UtilsFX.drawTag( this.xPosition + 1, this.yPosition + 1, this.aspectStack.getAspect(), 0, 0, this.zLevel ); - } - // Draw the question mark - else - { - // Bind the Thaumcraft question mark texture - Minecraft.getMinecraft().renderEngine.bindTexture( AspectWidgetBase.UNKNOWN_TEXTURE ); + // Have they discovered this aspect? + if (this.hasDiscovered) { + // Ask Thaumcraft to draw the aspect + UtilsFX.drawTag(this.xPosition + 1, this.yPosition + 1, this.aspectStack.getAspect(), 0, 0, this.zLevel); + } + // Draw the question mark + else { + // Bind the Thaumcraft question mark texture + Minecraft.getMinecraft().renderEngine.bindTexture(AspectWidgetBase.UNKNOWN_TEXTURE); - // Set the color - GL11.glColor4ub( this.aspectColorBytes[1], this.aspectColorBytes[2], this.aspectColorBytes[3], this.aspectColorBytes[0] ); + // Set the color + GL11.glColor4ub( + this.aspectColorBytes[1], + this.aspectColorBytes[2], + this.aspectColorBytes[3], + this.aspectColorBytes[0]); - // Enable blending - GL11.glEnable( GL11.GL_BLEND ); + // Enable blending + GL11.glEnable(GL11.GL_BLEND); - // Set the blending mode - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + // Set the blending mode + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - // Ask Thaumcraft to draw the question texture - UtilsFX.drawTexturedQuadFull( this.xPosition + 1, this.yPosition + 1, this.zLevel ); + // Ask Thaumcraft to draw the question texture + UtilsFX.drawTexturedQuadFull(this.xPosition + 1, this.yPosition + 1, this.zLevel); - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - } - } + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + } + } - /** - * Called when the stack changes. - */ - protected void onStackChanged() - { - // Is there an aspect? - if( this.aspectStack.hasAspect() ) - { - // Get the aspect name - this.aspectName = this.aspectStack.getAspectName( this.player ); + /** + * Called when the stack changes. + */ + protected void onStackChanged() { + // Is there an aspect? + if (this.aspectStack.hasAspect()) { + // Get the aspect name + this.aspectName = this.aspectStack.getAspectName(this.player); - // Get if the player has discovered this aspect - this.hasDiscovered = this.aspectStack.hasPlayerDiscovered( this.player ); - if( this.hasDiscovered ) - { - // Get the description - this.aspectDescription = this.aspectStack.getAspectDescription(); + // Get if the player has discovered this aspect + this.hasDiscovered = this.aspectStack.hasPlayerDiscovered(this.player); + if (this.hasDiscovered) { + // Get the description + this.aspectDescription = this.aspectStack.getAspectDescription(); - // Get the mod - ModContainer mod = AspectHooks.aspectToMod.getOrDefault( this.aspectStack.getAspect(), null ); + // Get the mod + ModContainer mod = AspectHooks.aspectToMod.getOrDefault(this.aspectStack.getAspect(), null); - // Set footnote - if( mod != null ) - { - this.aspectFootnote = mod.getName(); - } - else - { - this.aspectFootnote = "Unknown"; - } - } - else - { - this.aspectDescription = this.aspectName; - this.aspectFootnote = "Unknown"; - } + // Set footnote + if (mod != null) { + this.aspectFootnote = mod.getName(); + } else { + this.aspectFootnote = "Unknown"; + } + } else { + this.aspectDescription = this.aspectName; + this.aspectFootnote = "Unknown"; + } - // Get the color bytes - this.aspectColorBytes = ThEGuiHelper.INSTANCE.convertPackedColorToARGBb( this.aspectStack.getAspect().getColor() ); + // Get the color bytes + this.aspectColorBytes = ThEGuiHelper.INSTANCE.convertPackedColorToARGBb( + this.aspectStack.getAspect().getColor()); - // Set full alpha - this.aspectColorBytes[0] = (byte)255; - } - else - { - // Clear the info - this.clearStack( false ); - } - } + // Set full alpha + this.aspectColorBytes[0] = (byte) 255; + } else { + // Clear the info + this.clearStack(false); + } + } - /** - * Clears the stack. - */ - public void clearWidget() - { - this.clearStack( true ); - } + /** + * Clears the stack. + */ + public void clearWidget() { + this.clearStack(true); + } - /** - * Gets the stack size. - * - * @return - */ - public long getAmount() - { - return this.aspectStack.getStackSize(); - } + /** + * Gets the stack size. + * + * @return + */ + public long getAmount() { + return this.aspectStack.getStackSize(); + } - /** - * Gets the aspect stack for this widget. - * - * @return - */ - public Aspect getAspect() - { - return this.aspectStack.getAspect(); - } + /** + * Gets the aspect stack for this widget. + * + * @return + */ + public Aspect getAspect() { + return this.aspectStack.getAspect(); + } - /** - * Gets whether or not the stack is craftable. - * - * @return - */ - public boolean getCraftable() - { - return this.aspectStack.getCraftable(); - } + /** + * Gets whether or not the stack is craftable. + * + * @return + */ + public boolean getCraftable() { + return this.aspectStack.getCraftable(); + } - /** - * Returns the aspect stack. - * - * @return - */ - public IAspectStack getStack() - { - return this.aspectStack; - } + /** + * Returns the aspect stack. + * + * @return + */ + public IAspectStack getStack() { + return this.aspectStack; + } - /** - * Draws the aspect name and amount - */ - @Override - public void getTooltip( final List tooltip ) - { - if( this.hasAspect() ) - { - // Add the name - tooltip.add( this.aspectName ); + /** + * Draws the aspect name and amount + */ + @Override + public void getTooltip(final List tooltip) { + if (this.hasAspect()) { + // Add the name + tooltip.add(this.aspectName); - // Add aspect info - tooltip.add( EnumChatFormatting.GRAY.toString() + this.aspectDescription ); + // Add aspect info + tooltip.add(EnumChatFormatting.GRAY.toString() + this.aspectDescription); - // Add footnote - tooltip.add( EnumChatFormatting.DARK_PURPLE.toString() + EnumChatFormatting.ITALIC.toString() + this.aspectFootnote ); - } - } + // Add footnote + tooltip.add(EnumChatFormatting.DARK_PURPLE.toString() + + EnumChatFormatting.ITALIC.toString() + + this.aspectFootnote); + } + } - /** - * Returns true if the widget has an aspect. - * - * @return - */ - public boolean hasAspect() - { - return this.aspectStack.hasAspect(); - } + /** + * Returns true if the widget has an aspect. + * + * @return + */ + public boolean hasAspect() { + return this.aspectStack.hasAspect(); + } - /** - * Set's the aspect stack based on the passed values. - * - * @param aspect - * @param amount - * @param isCraftable - */ - public void setAspect( final Aspect aspect, final long amount, final boolean isCraftable ) - { - // Set the aspect - this.aspectStack.setAll( aspect, amount, isCraftable ); + /** + * Set's the aspect stack based on the passed values. + * + * @param aspect + * @param amount + * @param isCraftable + */ + public void setAspect(final Aspect aspect, final long amount, final boolean isCraftable) { + // Set the aspect + this.aspectStack.setAll(aspect, amount, isCraftable); - this.onStackChanged(); - } + this.onStackChanged(); + } - /** - * Sets the aspect based on the stack - * - * @param stack - */ - public void setAspect( final IAspectStack stack ) - { - // Copy the values - this.aspectStack.setAll( stack ); + /** + * Sets the aspect based on the stack + * + * @param stack + */ + public void setAspect(final IAspectStack stack) { + // Copy the values + this.aspectStack.setAll(stack); - this.onStackChanged(); - } + this.onStackChanged(); + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/DigitTextField.java b/src/main/java/thaumicenergistics/client/gui/widget/DigitTextField.java index f4364447..e11b4445 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/DigitTextField.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/DigitTextField.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.widget; -import org.lwjgl.input.Keyboard; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; +import org.lwjgl.input.Keyboard; /** * Text field that only allows numeric input. @@ -13,62 +13,54 @@ import net.minecraft.client.gui.GuiTextField; * */ @SideOnly(Side.CLIENT) -public class DigitTextField - extends GuiTextField -{ +public class DigitTextField extends GuiTextField { - /** - * Creates the text field - * - * @param fontRenderer - * @param x - * @param y - * @param length - * @param height - */ - public DigitTextField( final FontRenderer fontRenderer, final int x, final int y, final int length, final int height ) - { - super( fontRenderer, x, y, length, height ); - } + /** + * Creates the text field + * + * @param fontRenderer + * @param x + * @param y + * @param length + * @param height + */ + public DigitTextField( + final FontRenderer fontRenderer, final int x, final int y, final int length, final int height) { + super(fontRenderer, x, y, length, height); + } - @Override - public boolean textboxKeyTyped( final char keyChar, final int keyID ) - { - // Ensure we have focus - if( this.isFocused() ) - { + @Override + public boolean textboxKeyTyped(final char keyChar, final int keyID) { + // Ensure we have focus + if (this.isFocused()) { - // Is the backspace key being pressed? - if( keyID == Keyboard.KEY_BACK ) - { - // Move the cursor back a character - this.deleteFromCursor( -1 ); - return true; - } + // Is the backspace key being pressed? + if (keyID == Keyboard.KEY_BACK) { + // Move the cursor back a character + this.deleteFromCursor(-1); + return true; + } - // Is the typed character a numeric digit? - if( Character.isDigit( keyChar ) ) - { - // Append to the text - this.writeText( Character.toString( keyChar ) ); - return true; - } + // Is the typed character a numeric digit? + if (Character.isDigit(keyChar)) { + // Append to the text + this.writeText(Character.toString(keyChar)); + return true; + } - // Is the text empty or the value of the text 0? - if( this.getText().isEmpty() || this.getText().equals( "0" ) ) - { - // Did the player type a minus sign? - if( ( keyChar == '-' ) ) - { - // Player intends for number to be negative - this.setText( "-" ); - return true; - } - } + // Is the text empty or the value of the text 0? + if (this.getText().isEmpty() || this.getText().equals("0")) { + // Did the player type a minus sign? + if ((keyChar == '-')) { + // Player intends for number to be negative + this.setText("-"); + return true; + } + } - return false; - } + return false; + } - return false; - } + return false; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/ThEWidget.java b/src/main/java/thaumicenergistics/client/gui/widget/ThEWidget.java index dce5f21c..7809b720 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/ThEWidget.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/ThEWidget.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.widget; -import java.util.List; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.gui.Gui; +import org.lwjgl.opengl.GL11; import thaumicenergistics.api.gui.IWidgetHost; import thaumicenergistics.client.gui.ThEGuiHelper; @@ -15,64 +15,67 @@ import thaumicenergistics.client.gui.ThEGuiHelper; * */ @SideOnly(Side.CLIENT) -public abstract class ThEWidget - extends Gui -{ - /** - * The width and height of the aspect - */ - public static final int WIDGET_SIZE = 18; +public abstract class ThEWidget extends Gui { + /** + * The width and height of the aspect + */ + public static final int WIDGET_SIZE = 18; - protected int xPosition; + protected int xPosition; - protected int yPosition; + protected int yPosition; - protected IWidgetHost hostGUI; + protected IWidgetHost hostGUI; - public ThEWidget( final IWidgetHost hostGUI, final int xPos, final int yPos ) - { - this.hostGUI = hostGUI; + public ThEWidget(final IWidgetHost hostGUI, final int xPos, final int yPos) { + this.hostGUI = hostGUI; - this.xPosition = xPos; + this.xPosition = xPos; - this.yPosition = yPos; - } + this.yPosition = yPos; + } - public void drawMouseHoverUnderlay() - { - GL11.glDisable( GL11.GL_LIGHTING ); + public void drawMouseHoverUnderlay() { + GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable( GL11.GL_DEPTH_TEST ); + GL11.glDisable(GL11.GL_DEPTH_TEST); - this.drawGradientRect( this.xPosition + 1, this.yPosition + 1, this.xPosition + 17, this.yPosition + 17, 0x80FFFFFF, 0x80FFFFFF ); + this.drawGradientRect( + this.xPosition + 1, + this.yPosition + 1, + this.xPosition + 17, + this.yPosition + 17, + 0x80FFFFFF, + 0x80FFFFFF); - GL11.glEnable( GL11.GL_LIGHTING ); + GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } + GL11.glEnable(GL11.GL_DEPTH_TEST); + } - public abstract void drawWidget(); + public abstract void drawWidget(); - public abstract void getTooltip( List tooltip ); + public abstract void getTooltip(List tooltip); - public boolean isMouseOverWidget( final int mouseX, final int mouseY ) - { - return ThEGuiHelper.INSTANCE.isPointInGuiRegion( - this.yPosition, this.xPosition, - ThEWidget.WIDGET_SIZE - 1, ThEWidget.WIDGET_SIZE - 1, - mouseX, mouseY, - this.hostGUI.guiLeft(), this.hostGUI.guiTop() ); - } + public boolean isMouseOverWidget(final int mouseX, final int mouseY) { + return ThEGuiHelper.INSTANCE.isPointInGuiRegion( + this.yPosition, + this.xPosition, + ThEWidget.WIDGET_SIZE - 1, + ThEWidget.WIDGET_SIZE - 1, + mouseX, + mouseY, + this.hostGUI.guiLeft(), + this.hostGUI.guiTop()); + } - /** - * Called when the mouse is clicked on the widget. - */ - public abstract void onMouseClicked(); - - public void setPosition( final int xPos, final int yPos ) - { - this.xPosition = xPos; - this.yPosition = yPos; - } + /** + * Called when the mouse is clicked on the widget. + */ + public abstract void onMouseClicked(); + public void setPosition(final int xPos, final int yPos) { + this.xPosition = xPos; + this.yPosition = yPos; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAEItem.java b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAEItem.java index 540ea6b7..81d5201e 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAEItem.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAEItem.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.gui.widget; -import java.util.List; import appeng.api.storage.data.IAEItemStack; import appeng.client.render.AppEngRenderItem; import appeng.util.item.AEItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.item.ItemStack; @@ -20,150 +20,139 @@ import thaumicenergistics.api.gui.IWidgetHost; * TODO: Deprecated Remove in favor of MESlots */ @SideOnly(Side.CLIENT) -public class WidgetAEItem - extends ThEWidget -{ - /** - * Cache of the minecraft instance - */ - private static final Minecraft MC = Minecraft.getMinecraft(); +public class WidgetAEItem extends ThEWidget { + /** + * Cache of the minecraft instance + */ + private static final Minecraft MC = Minecraft.getMinecraft(); - /** - * Cache of the minecraft texture manager - */ - private static final TextureManager TEXTURE_MANAGER = Minecraft.getMinecraft().getTextureManager(); + /** + * Cache of the minecraft texture manager + */ + private static final TextureManager TEXTURE_MANAGER = + Minecraft.getMinecraft().getTextureManager(); - /** - * Cache of the AE item renderer - */ - private final AppEngRenderItem aeItemRenderer; + /** + * Cache of the AE item renderer + */ + private final AppEngRenderItem aeItemRenderer; - /** - * The itemstack this widget represents - */ - private IAEItemStack aeItemStack; + /** + * The itemstack this widget represents + */ + private IAEItemStack aeItemStack; - /** - * Creates the widget - * - * @param hostGUI - * @param xPos - * @param yPos - * @param aeItemRenderer - */ - public WidgetAEItem( final IWidgetHost hostGUI, final int xPos, final int yPos, final AppEngRenderItem aeItemRenderer ) - { - super( hostGUI, xPos, yPos ); + /** + * Creates the widget + * + * @param hostGUI + * @param xPos + * @param yPos + * @param aeItemRenderer + */ + public WidgetAEItem( + final IWidgetHost hostGUI, final int xPos, final int yPos, final AppEngRenderItem aeItemRenderer) { + super(hostGUI, xPos, yPos); - this.aeItemRenderer = aeItemRenderer; - } + this.aeItemRenderer = aeItemRenderer; + } - /** - * Draws the itemstack if there is one. - */ - @Override - public void drawWidget() - { - try - { - if( this.aeItemStack != null ) - { - // Set the z level - this.zLevel = 2.0F; - this.aeItemRenderer.zLevel = 2.0F; + /** + * Draws the itemstack if there is one. + */ + @Override + public void drawWidget() { + try { + if (this.aeItemStack != null) { + // Set the z level + this.zLevel = 2.0F; + this.aeItemRenderer.zLevel = 2.0F; - // Set the item - this.aeItemRenderer.setAeStack( this.aeItemStack ); + // Set the item + this.aeItemRenderer.setAeStack(this.aeItemStack); - // Draw the item - this.aeItemRenderer.renderItemAndEffectIntoGUI( WidgetAEItem.MC.fontRenderer, WidgetAEItem.TEXTURE_MANAGER, - this.aeItemStack.getItemStack(), this.xPosition + 1, this.yPosition + 1 ); + // Draw the item + this.aeItemRenderer.renderItemAndEffectIntoGUI( + WidgetAEItem.MC.fontRenderer, + WidgetAEItem.TEXTURE_MANAGER, + this.aeItemStack.getItemStack(), + this.xPosition + 1, + this.yPosition + 1); - // Draw the amount - this.aeItemRenderer.renderItemOverlayIntoGUI( WidgetAEItem.MC.fontRenderer, WidgetAEItem.TEXTURE_MANAGER, - this.aeItemStack.getItemStack(), this.xPosition + 1, this.yPosition + 1 ); + // Draw the amount + this.aeItemRenderer.renderItemOverlayIntoGUI( + WidgetAEItem.MC.fontRenderer, + WidgetAEItem.TEXTURE_MANAGER, + this.aeItemStack.getItemStack(), + this.xPosition + 1, + this.yPosition + 1); - // Reset the z level - this.zLevel = 0.0F; - this.aeItemRenderer.zLevel = 0.0F; - } - } - catch( Exception e ) - { - // Silently ignore. - } + // Reset the z level + this.zLevel = 0.0F; + this.aeItemRenderer.zLevel = 0.0F; + } + } catch (Exception e) { + // Silently ignore. + } + } - } + /** + * Returns the itemstack this widget represents. + * + * @return IAEItemstack if the widget has one, null otherwise. + */ + public IAEItemStack getItemStack() { + return this.aeItemStack; + } - /** - * Returns the itemstack this widget represents. - * - * @return IAEItemstack if the widget has one, null otherwise. - */ - public IAEItemStack getItemStack() - { - return this.aeItemStack; - } + @Override + public void getTooltip(final List tooltip) { + if (this.aeItemStack != null) { + // Get the stack + ItemStack stack = this.aeItemStack.getItemStack(); - @Override - public void getTooltip( final List tooltip ) - { - if( this.aeItemStack != null ) - { - // Get the stack - ItemStack stack = this.aeItemStack.getItemStack(); + // Get the tooltip list + try { + List stackTooltip = + stack.getTooltip(WidgetAEItem.MC.thePlayer, WidgetAEItem.MC.gameSettings.advancedItemTooltips); - // Get the tooltip list - try - { - List stackTooltip = stack.getTooltip( WidgetAEItem.MC.thePlayer, WidgetAEItem.MC.gameSettings.advancedItemTooltips ); + // Set colors and add + for (int index = 0; index < stackTooltip.size(); index++) { + if (index == 0) { + // Item name based on rarity + stackTooltip.set(index, stack.getRarity().rarityColor + stackTooltip.get(index)); + } else { + // The rest grey + stackTooltip.set(index, EnumChatFormatting.GRAY + stackTooltip.get(index)); + } - // Set colors and add - for( int index = 0; index < stackTooltip.size(); index++ ) - { - if( index == 0 ) - { - // Item name based on rarity - stackTooltip.set( index, stack.getRarity().rarityColor + stackTooltip.get( index ) ); - } - else - { - // The rest grey - stackTooltip.set( index, EnumChatFormatting.GRAY + stackTooltip.get( index ) ); - } + // Add the item tooltip line + tooltip.add(stackTooltip.get(index)); + } + } catch (Exception e) { + tooltip.add(EnumChatFormatting.ITALIC + ""); + } - // Add the item tooltip line - tooltip.add( stackTooltip.get( index ) ); - } - } - catch( Exception e ) - { - tooltip.add( EnumChatFormatting.ITALIC + "" ); - } + // Get the mod name + String modName = ((AEItemStack) this.aeItemStack).getModID(); + modName = modName.substring(0, 1).toUpperCase() + modName.substring(1); - // Get the mod name - String modName = ( (AEItemStack)this.aeItemStack ).getModID(); - modName = modName.substring( 0, 1 ).toUpperCase() + modName.substring( 1 ); + // Add the mod name + tooltip.add(EnumChatFormatting.BLUE + "" + EnumChatFormatting.ITALIC + modName); + } + } - // Add the mod name - tooltip.add( EnumChatFormatting.BLUE + "" + EnumChatFormatting.ITALIC + modName ); - } - } - - @Override - public void onMouseClicked() - { - // Unused - } - - /** - * Set the itemstack this widget represents - * - * @param itemStack - */ - public void setItemStack( final IAEItemStack itemStack ) - { - this.aeItemStack = itemStack; - } + @Override + public void onMouseClicked() { + // Unused + } + /** + * Set the itemstack this widget represents + * + * @param itemStack + */ + public void setItemStack(final IAEItemStack itemStack) { + this.aeItemStack = itemStack; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSelector.java b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSelector.java index 67695db1..85527ade 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSelector.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSelector.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.gui.widget; -import org.lwjgl.opengl.GL11; import appeng.core.AEConfig; import appeng.util.ReadableNumberConverter; import cpw.mods.fml.relauncher.Side; @@ -8,6 +7,7 @@ import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IAspectSelectorGui; import thaumicenergistics.api.storage.IAspectStack; @@ -21,302 +21,284 @@ import thaumicenergistics.common.utils.ThEUtils; * */ @SideOnly(Side.CLIENT) -public class WidgetAspectSelector - extends AspectWidgetBase -{ - /** - * Thickness of the selector outline. - */ - private static final int borderThickness = 1; +public class WidgetAspectSelector extends AspectWidgetBase { + /** + * Thickness of the selector outline. + */ + private static final int borderThickness = 1; - /** - * The number of iterations in the gradient - */ - private static final int GRADIENT_COUNT = 15; + /** + * The number of iterations in the gradient + */ + private static final int GRADIENT_COUNT = 15; - /** - * Color of the border while aspect is selected - */ - private static final int selectorBorderColor = 0xFF00FFFF; + /** + * Color of the border while aspect is selected + */ + private static final int selectorBorderColor = 0xFF00FFFF; - /** - * Array of colors that pulse behind the aspect - */ - private int[] backgroundPulseGradient; + /** + * Array of colors that pulse behind the aspect + */ + private int[] backgroundPulseGradient; - /** - * If true the amount will not be drawn, also if the stack is craftable - * it will show the crafting text. - */ - protected boolean hideAmount = false; + /** + * If true the amount will not be drawn, also if the stack is craftable + * it will show the crafting text. + */ + protected boolean hideAmount = false; - public WidgetAspectSelector( final IAspectSelectorGui selectorGui, final IAspectStack stack, final int xPos, final int yPos, - final EntityPlayer player ) - { - // Call super - super( selectorGui, stack, xPos, yPos, player ); - } + public WidgetAspectSelector( + final IAspectSelectorGui selectorGui, + final IAspectStack stack, + final int xPos, + final int yPos, + final EntityPlayer player) { + // Call super + super(selectorGui, stack, xPos, yPos, player); + } - /** - * Draws the selector outline. - * - * @param posX - * @param posY - * @param width - * @param height - * @param color - * @param thickness - */ - private void drawHollowRectWithCorners( final int posX, final int posY, final int width, final int height, final int color, final int thickness ) - { - // Calculate points + /** + * Draws the selector outline. + * + * @param posX + * @param posY + * @param width + * @param height + * @param color + * @param thickness + */ + private void drawHollowRectWithCorners( + final int posX, final int posY, final int width, final int height, final int color, final int thickness) { + // Calculate points - // Ending X point of the right line - int rightXEnd = posX + width; + // Ending X point of the right line + int rightXEnd = posX + width; - // Beginning X point of the right line - int rightXBegin = rightXEnd - thickness; + // Beginning X point of the right line + int rightXBegin = rightXEnd - thickness; - // Ending X point of the left line - int leftXEnd = posX + thickness; + // Ending X point of the left line + int leftXEnd = posX + thickness; - // Ending Y point of the top line - int topYEnd = posY + thickness; + // Ending Y point of the top line + int topYEnd = posY + thickness; - // Ending Y point of the bottom line - int bottomYEnd = posY + height; + // Ending Y point of the bottom line + int bottomYEnd = posY + height; - // Beginning Y point of the bottom line - int bottomYBegin = bottomYEnd - thickness; + // Beginning Y point of the bottom line + int bottomYBegin = bottomYEnd - thickness; - // Draw background gradient - Gui.drawRect( posX, posY, rightXEnd, bottomYEnd, color ); + // Draw background gradient + Gui.drawRect(posX, posY, rightXEnd, bottomYEnd, color); - // Draw notches + // Draw notches - // Top-left notch - Gui.drawRect( posX, posY, leftXEnd + 1, topYEnd + 1, selectorBorderColor ); + // Top-left notch + Gui.drawRect(posX, posY, leftXEnd + 1, topYEnd + 1, selectorBorderColor); - // Top-right notch - Gui.drawRect( rightXEnd, posY, rightXBegin - 1, topYEnd + 1, selectorBorderColor ); + // Top-right notch + Gui.drawRect(rightXEnd, posY, rightXBegin - 1, topYEnd + 1, selectorBorderColor); - // Bottom-right notch - Gui.drawRect( rightXEnd, bottomYEnd, rightXBegin - 1, bottomYBegin - 1, selectorBorderColor ); + // Bottom-right notch + Gui.drawRect(rightXEnd, bottomYEnd, rightXBegin - 1, bottomYBegin - 1, selectorBorderColor); - // Bottom-left notch - Gui.drawRect( posX, bottomYEnd, leftXEnd + 1, bottomYBegin - 1, selectorBorderColor ); + // Bottom-left notch + Gui.drawRect(posX, bottomYEnd, leftXEnd + 1, bottomYBegin - 1, selectorBorderColor); - // Draw lines + // Draw lines - // Top side - Gui.drawRect( posX, posY, rightXEnd, topYEnd, selectorBorderColor ); + // Top side + Gui.drawRect(posX, posY, rightXEnd, topYEnd, selectorBorderColor); - // Bottom side - Gui.drawRect( posX, bottomYBegin, rightXEnd, bottomYEnd, selectorBorderColor ); + // Bottom side + Gui.drawRect(posX, bottomYBegin, rightXEnd, bottomYEnd, selectorBorderColor); - // Left side - Gui.drawRect( posX, posY, leftXEnd, bottomYEnd, selectorBorderColor ); + // Left side + Gui.drawRect(posX, posY, leftXEnd, bottomYEnd, selectorBorderColor); - // Right side - Gui.drawRect( rightXBegin, posY, rightXEnd, bottomYEnd, selectorBorderColor ); - } + // Right side + Gui.drawRect(rightXBegin, posY, rightXEnd, bottomYEnd, selectorBorderColor); + } - /** - * Gets the background gradient color based on the current time. - * - * @return - */ - private int getBackgroundColor() - { - // Get the current time, slowed down. - int time = (int)( System.currentTimeMillis() / 45L ); + /** + * Gets the background gradient color based on the current time. + * + * @return + */ + private int getBackgroundColor() { + // Get the current time, slowed down. + int time = (int) (System.currentTimeMillis() / 45L); - // Lerp the index - int index = Math.abs( Math.abs( time % ( GRADIENT_COUNT * 2 ) ) - GRADIENT_COUNT ); + // Lerp the index + int index = Math.abs(Math.abs(time % (GRADIENT_COUNT * 2)) - GRADIENT_COUNT); - // Return the index - return this.backgroundPulseGradient[index]; - } + // Return the index + return this.backgroundPulseGradient[index]; + } - @Override - protected void onStackChanged() - { - // Call super - super.onStackChanged(); + @Override + protected void onStackChanged() { + // Call super + super.onStackChanged(); - if( !this.hasAspect() ) - { - return; - } + if (!this.hasAspect()) { + return; + } - // Get the aspect color - int aspectColor = this.getStack().getAspect().getColor(); + // Get the aspect color + int aspectColor = this.getStack().getAspect().getColor(); - // Create the gradient using the aspect color, varying between opacities - this.backgroundPulseGradient = ThEGuiHelper.INSTANCE - .createColorGradient( 0x70000000 | aspectColor, 0x20000000 | aspectColor, GRADIENT_COUNT + 1 ); - } + // Create the gradient using the aspect color, varying between opacities + this.backgroundPulseGradient = ThEGuiHelper.INSTANCE.createColorGradient( + 0x70000000 | aspectColor, 0x20000000 | aspectColor, GRADIENT_COUNT + 1); + } - /** - * Draws the aspect icon and selector border if it is selected. - */ - @Override - public void drawWidget() - { - // Is the widget empty? - if( !this.hasAspect() ) - { - return; - } - // Disable lighting - GL11.glDisable( GL11.GL_LIGHTING ); + /** + * Draws the aspect icon and selector border if it is selected. + */ + @Override + public void drawWidget() { + // Is the widget empty? + if (!this.hasAspect()) { + return; + } + // Disable lighting + GL11.glDisable(GL11.GL_LIGHTING); - // Enable blending - GL11.glEnable( GL11.GL_BLEND ); + // Enable blending + GL11.glEnable(GL11.GL_BLEND); - // Set the blending mode to blend alpha - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + // Set the blending mode to blend alpha + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - // No tint - GL11.glColor3f( 1.0F, 1.0F, 1.0F ); + // No tint + GL11.glColor3f(1.0F, 1.0F, 1.0F); - // Get the selected aspect - Aspect selectedAspect = ( (IAspectSelectorGui)this.hostGUI ).getSelectedAspect(); + // Get the selected aspect + Aspect selectedAspect = ((IAspectSelectorGui) this.hostGUI).getSelectedAspect(); - // Does the selected aspect match the widgets? - if( selectedAspect == this.getAspect() ) - { - // Draw the selection box - this.drawHollowRectWithCorners( this.xPosition, this.yPosition, - ThEWidget.WIDGET_SIZE, ThEWidget.WIDGET_SIZE, - this.getBackgroundColor(), WidgetAspectSelector.borderThickness ); - } + // Does the selected aspect match the widgets? + if (selectedAspect == this.getAspect()) { + // Draw the selection box + this.drawHollowRectWithCorners( + this.xPosition, + this.yPosition, + ThEWidget.WIDGET_SIZE, + ThEWidget.WIDGET_SIZE, + this.getBackgroundColor(), + WidgetAspectSelector.borderThickness); + } - // Draw the aspect - this.drawAspect(); + // Draw the aspect + this.drawAspect(); - // Get the amount and crafting - long stackSize = this.getAmount(); + // Get the amount and crafting + long stackSize = this.getAmount(); - // Is there anything to draw? - if( ( ( stackSize > 0 ) && !this.hideAmount ) || this.getCraftable() ) - { - // Text to draw - String text; + // Is there anything to draw? + if (((stackSize > 0) && !this.hideAmount) || this.getCraftable()) { + // Text to draw + String text; - // Get the font renderer - final FontRenderer fontRenderer = this.hostGUI.getFontRenderer(); + // Get the font renderer + final FontRenderer fontRenderer = this.hostGUI.getFontRenderer(); - // Disable unicode if enabled - final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); - fontRenderer.setUnicodeFlag( false ); + // Disable unicode if enabled + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(false); - // Is the terminal using a large font? - boolean largeFont = AEConfig.instance.useTerminalUseLargeFont(); + // Is the terminal using a large font? + boolean largeFont = AEConfig.instance.useTerminalUseLargeFont(); - // Set the scale - float scale = largeFont ? 0.85f : 0.5f; + // Set the scale + float scale = largeFont ? 0.85f : 0.5f; - // Set the position offset - float positionOffset = largeFont ? 0 : -1.0f; + // Set the position offset + float positionOffset = largeFont ? 0 : -1.0f; - // Calculate position - float posX = this.xPosition + positionOffset + ThEWidget.WIDGET_SIZE; - float posY = ( this.yPosition + positionOffset + ThEWidget.WIDGET_SIZE ) - 1; + // Calculate position + float posX = this.xPosition + positionOffset + ThEWidget.WIDGET_SIZE; + float posY = (this.yPosition + positionOffset + ThEWidget.WIDGET_SIZE) - 1; - // Has amount to draw? - if( ( ( stackSize > 0 ) && !this.hideAmount ) ) - { - if( largeFont ) - { - text = ReadableNumberConverter.INSTANCE.toWideReadableForm( stackSize ); - } - else - { - text = ReadableNumberConverter.INSTANCE.toSlimReadableForm( stackSize ); - } - } - // Crafting - else - { - // Get the "craftable" text from AE2 - if( largeFont ) - { - text = appeng.core.localization.GuiText.LargeFontCraft.getLocal(); - } - else - { - text = appeng.core.localization.GuiText.SmallFontCraft.getLocal(); - } - } + // Has amount to draw? + if (((stackSize > 0) && !this.hideAmount)) { + if (largeFont) { + text = ReadableNumberConverter.INSTANCE.toWideReadableForm(stackSize); + } else { + text = ReadableNumberConverter.INSTANCE.toSlimReadableForm(stackSize); + } + } + // Crafting + else { + // Get the "craftable" text from AE2 + if (largeFont) { + text = appeng.core.localization.GuiText.LargeFontCraft.getLocal(); + } else { + text = appeng.core.localization.GuiText.SmallFontCraft.getLocal(); + } + } - // Draw it - ThEGuiHelper.drawScaledText( fontRenderer, text, scale, posX, posY ); + // Draw it + ThEGuiHelper.drawScaledText(fontRenderer, text, scale, posX, posY); - // Reset unicode status - fontRenderer.setUnicodeFlag( unicodeFlag ); - } + // Reset unicode status + fontRenderer.setUnicodeFlag(unicodeFlag); + } - // Enable lighting - GL11.glEnable( GL11.GL_LIGHTING ); + // Enable lighting + GL11.glEnable(GL11.GL_LIGHTING); - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - } + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + } - /** - * Called when the widget is clicked. - */ - @Override - public void onMouseClicked() - { - // Get this aspect - Aspect widgetAspect = this.getAspect(); + /** + * Called when the widget is clicked. + */ + @Override + public void onMouseClicked() { + // Get this aspect + Aspect widgetAspect = this.getAspect(); - // Get the selected aspect - Aspect selectedAspect = ( (IAspectSelectorGui)this.hostGUI ).getSelectedAspect(); + // Get the selected aspect + Aspect selectedAspect = ((IAspectSelectorGui) this.hostGUI).getSelectedAspect(); - // Did the selected aspect change? - boolean changed = false; + // Did the selected aspect change? + boolean changed = false; - // Are both aspects the same? - if( widgetAspect == selectedAspect ) - { - // Is something selected? - if( selectedAspect != null ) - { - // Unselect - selectedAspect = null; - changed = true; - } - } - else - { - // Set to the widget aspect - selectedAspect = widgetAspect; - changed = true; - } + // Are both aspects the same? + if (widgetAspect == selectedAspect) { + // Is something selected? + if (selectedAspect != null) { + // Unselect + selectedAspect = null; + changed = true; + } + } else { + // Set to the widget aspect + selectedAspect = widgetAspect; + changed = true; + } - // Was the selected aspect changed? - if( changed ) - { - // Play clicky sound - ThEUtils.playClientSound( null, "gui.button.press" ); + // Was the selected aspect changed? + if (changed) { + // Play clicky sound + ThEUtils.playClientSound(null, "gui.button.press"); - // Set the selected aspect - ( (IAspectSelectorGui)this.hostGUI ).getContainer().setSelectedAspect( selectedAspect ); - } - } - - /** - * Sets whether or not to show the amount. - * - * @param hide - * @return - */ - public void setHideAmount( final boolean hide ) - { - this.hideAmount = hide; - } + // Set the selected aspect + ((IAspectSelectorGui) this.hostGUI).getContainer().setSelectedAspect(selectedAspect); + } + } + /** + * Sets whether or not to show the amount. + * + * @param hide + * @return + */ + public void setHideAmount(final boolean hide) { + this.hideAmount = hide; + } } diff --git a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSlot.java b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSlot.java index 2978f95f..497f162c 100644 --- a/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSlot.java +++ b/src/main/java/thaumicenergistics/client/gui/widget/WidgetAspectSlot.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.gui.widget; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.gui.IWidgetHost; import thaumicenergistics.client.textures.GuiTextureManager; @@ -18,99 +18,103 @@ import thaumicenergistics.common.network.packet.server.Packet_S_AspectSlot; * */ @SideOnly(Side.CLIENT) -public class WidgetAspectSlot - extends AspectWidgetBase -{ - public static interface IConfigurable - { - public byte getConfigState(); - } +public class WidgetAspectSlot extends AspectWidgetBase { + public static interface IConfigurable { + public byte getConfigState(); + } - private int id; - private IAspectSlotPart part; - private EntityPlayer player; - private IConfigurable configurable; + private int id; + private IAspectSlotPart part; + private EntityPlayer player; + private IConfigurable configurable; - private byte configOption; + private byte configOption; - public WidgetAspectSlot( final IWidgetHost hostGui, final EntityPlayer player, final IAspectSlotPart part, final int posX, final int posY ) - { - this( hostGui, player, part, 0, posX, posY, null, (byte)0 ); - } + public WidgetAspectSlot( + final IWidgetHost hostGui, + final EntityPlayer player, + final IAspectSlotPart part, + final int posX, + final int posY) { + this(hostGui, player, part, 0, posX, posY, null, (byte) 0); + } - public WidgetAspectSlot( final IWidgetHost hostGui, final EntityPlayer player, final IAspectSlotPart part, final int id, final int posX, - final int posY ) - { - this( hostGui, player, part, id, posX, posY, null, (byte)0 ); - } + public WidgetAspectSlot( + final IWidgetHost hostGui, + final EntityPlayer player, + final IAspectSlotPart part, + final int id, + final int posX, + final int posY) { + this(hostGui, player, part, id, posX, posY, null, (byte) 0); + } - public WidgetAspectSlot( final IWidgetHost hostGui, final EntityPlayer player, final IAspectSlotPart part, final int id, final int posX, - final int posY, final IConfigurable configurable, final byte configOption ) - { - super( hostGui, null, posX, posY, player ); - this.player = player; - this.part = part; - this.id = id; - this.configurable = configurable; - this.configOption = configOption; - } + public WidgetAspectSlot( + final IWidgetHost hostGui, + final EntityPlayer player, + final IAspectSlotPart part, + final int id, + final int posX, + final int posY, + final IConfigurable configurable, + final byte configOption) { + super(hostGui, null, posX, posY, player); + this.player = player; + this.part = part; + this.id = id; + this.configurable = configurable; + this.configOption = configOption; + } - public boolean canRender() - { - return ( this.configurable == null ) || ( this.configurable.getConfigState() >= this.configOption ); - } + public boolean canRender() { + return (this.configurable == null) || (this.configurable.getConfigState() >= this.configOption); + } - @Override - public void drawWidget() - { - // Is this slot open? - if( this.canRender() ) - { - // Disable lighting - GL11.glDisable( GL11.GL_LIGHTING ); + @Override + public void drawWidget() { + // Is this slot open? + if (this.canRender()) { + // Disable lighting + GL11.glDisable(GL11.GL_LIGHTING); - // Enable blending - GL11.glEnable( GL11.GL_BLEND ); + // Enable blending + GL11.glEnable(GL11.GL_BLEND); - // Set the blend mode - GL11.glBlendFunc( 770, 771 ); + // Set the blend mode + GL11.glBlendFunc(770, 771); - // Full white - GL11.glColor3f( 1.0F, 1.0F, 1.0F ); + // Full white + GL11.glColor3f(1.0F, 1.0F, 1.0F); - // Bind to the gui texture - Minecraft.getMinecraft().renderEngine.bindTexture( GuiTextureManager.ESSENTIA_IO_BUS.getTexture() ); + // Bind to the gui texture + Minecraft.getMinecraft().renderEngine.bindTexture(GuiTextureManager.ESSENTIA_IO_BUS.getTexture()); - // Draw this slot just like the center slot of the gui - this.drawTexturedModalRect( this.xPosition, this.yPosition, 79, 39, ThEWidget.WIDGET_SIZE, ThEWidget.WIDGET_SIZE ); + // Draw this slot just like the center slot of the gui + this.drawTexturedModalRect( + this.xPosition, this.yPosition, 79, 39, ThEWidget.WIDGET_SIZE, ThEWidget.WIDGET_SIZE); - // Do we have an aspect? - if( this.getAspect() != null ) - { - // Draw the aspect - this.drawAspect(); - } + // Do we have an aspect? + if (this.getAspect() != null) { + // Draw the aspect + this.drawAspect(); + } - // Re-enable lighting - GL11.glEnable( GL11.GL_LIGHTING ); + // Re-enable lighting + GL11.glEnable(GL11.GL_LIGHTING); - // Re-disable blending - GL11.glDisable( GL11.GL_BLEND ); + // Re-disable blending + GL11.glDisable(GL11.GL_BLEND); + } + } - } + public void mouseClicked(final Aspect withAspect) { + this.setAspect(withAspect, 1, false); - } + Packet_S_AspectSlot.sendAspectChange(this.part, this.id, this.getAspect(), this.player); + } - public void mouseClicked( final Aspect withAspect ) - { - this.setAspect( withAspect, 1, false ); - - Packet_S_AspectSlot.sendAspectChange( this.part, this.id, this.getAspect(), this.player ); - } - - @Override - public void onMouseClicked() - { - // Ignored - } + @Override + public void onMouseClicked() { + // Ignored + } } diff --git a/src/main/java/thaumicenergistics/client/render/RenderBlockEssentiaProvider.java b/src/main/java/thaumicenergistics/client/render/RenderBlockEssentiaProvider.java index b0e727ab..8b50b113 100644 --- a/src/main/java/thaumicenergistics/client/render/RenderBlockEssentiaProvider.java +++ b/src/main/java/thaumicenergistics/client/render/RenderBlockEssentiaProvider.java @@ -13,19 +13,14 @@ import thaumicenergistics.common.tiles.TileEssentiaProvider; * */ @SideOnly(Side.CLIENT) -public class RenderBlockEssentiaProvider - extends RenderBlockProviderBase -{ - public RenderBlockEssentiaProvider() - { - super( BlockTextureManager.ESSENTIA_PROVIDER ); - } - - @Override - public int getRenderId() - { - // Return the ID of the essentia provider - return Renderers.EssentiaProviderRenderID; - } +public class RenderBlockEssentiaProvider extends RenderBlockProviderBase { + public RenderBlockEssentiaProvider() { + super(BlockTextureManager.ESSENTIA_PROVIDER); + } + @Override + public int getRenderId() { + // Return the ID of the essentia provider + return Renderers.EssentiaProviderRenderID; + } } diff --git a/src/main/java/thaumicenergistics/client/render/RenderBlockInfusionProvider.java b/src/main/java/thaumicenergistics/client/render/RenderBlockInfusionProvider.java index 77bb47f3..4341570c 100644 --- a/src/main/java/thaumicenergistics/client/render/RenderBlockInfusionProvider.java +++ b/src/main/java/thaumicenergistics/client/render/RenderBlockInfusionProvider.java @@ -13,19 +13,14 @@ import thaumicenergistics.common.tiles.TileInfusionProvider; * */ @SideOnly(Side.CLIENT) -public class RenderBlockInfusionProvider - extends RenderBlockProviderBase -{ +public class RenderBlockInfusionProvider extends RenderBlockProviderBase { - public RenderBlockInfusionProvider() - { - super( BlockTextureManager.INFUSION_PROVIDER ); - } - - @Override - public int getRenderId() - { - return Renderers.InfusionProviderRenderID; - } + public RenderBlockInfusionProvider() { + super(BlockTextureManager.INFUSION_PROVIDER); + } + @Override + public int getRenderId() { + return Renderers.InfusionProviderRenderID; + } } diff --git a/src/main/java/thaumicenergistics/client/render/RenderBlockProviderBase.java b/src/main/java/thaumicenergistics/client/render/RenderBlockProviderBase.java index a7b597bb..8beac697 100644 --- a/src/main/java/thaumicenergistics/client/render/RenderBlockProviderBase.java +++ b/src/main/java/thaumicenergistics/client/render/RenderBlockProviderBase.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.render; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -10,6 +9,7 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; +import org.lwjgl.opengl.GL11; import thaumicenergistics.client.textures.BlockTextureManager; import thaumicenergistics.common.registries.Renderers; import thaumicenergistics.common.tiles.abstraction.TileProviderBase; @@ -23,212 +23,211 @@ import thaumicenergistics.common.tiles.abstraction.TileProviderBase; * */ @SideOnly(Side.CLIENT) -public abstract class RenderBlockProviderBase - implements ISimpleBlockRenderingHandler -{ +public abstract class RenderBlockProviderBase implements ISimpleBlockRenderingHandler { - /** - * Side/Face array cache. - */ - private static ForgeDirection[] FACES = ForgeDirection.VALID_DIRECTIONS; + /** + * Side/Face array cache. + */ + private static ForgeDirection[] FACES = ForgeDirection.VALID_DIRECTIONS; - /** - * Textures - */ - private BlockTextureManager textureSource; + /** + * Textures + */ + private BlockTextureManager textureSource; - /** - * Creates the renderer. - * - * @param baseTexture - * @param overlayTexture - */ - public RenderBlockProviderBase( final BlockTextureManager sourceTextures ) - { - this.textureSource = sourceTextures; - } + /** + * Creates the renderer. + * + * @param baseTexture + * @param overlayTexture + */ + public RenderBlockProviderBase(final BlockTextureManager sourceTextures) { + this.textureSource = sourceTextures; + } - /** - * Renders all faces of the provider. - * - * @param world - * @param x - * @param y - * @param z - * @param texture - * @param glowAmount - */ - private void renderFaces( final IBlockAccess world, final int x, final int y, final int z, final IIcon texture, final int glowAmount ) - { - Tessellator tessellator = Tessellator.instance; + /** + * Renders all faces of the provider. + * + * @param world + * @param x + * @param y + * @param z + * @param texture + * @param glowAmount + */ + private void renderFaces( + final IBlockAccess world, + final int x, + final int y, + final int z, + final IIcon texture, + final int glowAmount) { + Tessellator tessellator = Tessellator.instance; - // Get the UV's - double minU = texture.getMinU(); - double maxU = texture.getMaxU(); - double minV = texture.getMinV(); - double maxV = texture.getMaxV(); + // Get the UV's + double minU = texture.getMinU(); + double maxU = texture.getMaxU(); + double minV = texture.getMinV(); + double maxV = texture.getMaxV(); - // Vertex +1 offsets - int x1 = x + 1, y1 = y + 1, z1 = z + 1; + // Vertex +1 offsets + int x1 = x + 1, y1 = y + 1, z1 = z + 1; - for( ForgeDirection face : FACES ) - { - // Calculate the brightness - tessellator.setBrightness( world.getLightBrightnessForSkyBlocks( x + face.offsetX, y + face.offsetY, z - face.offsetZ, glowAmount ) ); + for (ForgeDirection face : FACES) { + // Calculate the brightness + tessellator.setBrightness(world.getLightBrightnessForSkyBlocks( + x + face.offsetX, y + face.offsetY, z - face.offsetZ, glowAmount)); - switch ( face ) - { - case DOWN: - tessellator.addVertexWithUV( x, y, z, minU, maxV ); - tessellator.addVertexWithUV( x1, y, z, maxU, maxV ); - tessellator.addVertexWithUV( x1, y, z1, maxU, minV ); - tessellator.addVertexWithUV( x, y, z1, minU, minV ); - break; + switch (face) { + case DOWN: + tessellator.addVertexWithUV(x, y, z, minU, maxV); + tessellator.addVertexWithUV(x1, y, z, maxU, maxV); + tessellator.addVertexWithUV(x1, y, z1, maxU, minV); + tessellator.addVertexWithUV(x, y, z1, minU, minV); + break; - case EAST: - tessellator.addVertexWithUV( x1, y, z, maxU, maxV ); - tessellator.addVertexWithUV( x1, y1, z, maxU, minV ); - tessellator.addVertexWithUV( x1, y1, z1, minU, minV ); - tessellator.addVertexWithUV( x1, y, z1, minU, maxV ); - break; + case EAST: + tessellator.addVertexWithUV(x1, y, z, maxU, maxV); + tessellator.addVertexWithUV(x1, y1, z, maxU, minV); + tessellator.addVertexWithUV(x1, y1, z1, minU, minV); + tessellator.addVertexWithUV(x1, y, z1, minU, maxV); + break; - case NORTH: - tessellator.addVertexWithUV( x, y, z1, minU, maxV ); - tessellator.addVertexWithUV( x1, y, z1, maxU, maxV ); - tessellator.addVertexWithUV( x1, y1, z1, maxU, minV ); - tessellator.addVertexWithUV( x, y1, z1, minU, minV ); - break; + case NORTH: + tessellator.addVertexWithUV(x, y, z1, minU, maxV); + tessellator.addVertexWithUV(x1, y, z1, maxU, maxV); + tessellator.addVertexWithUV(x1, y1, z1, maxU, minV); + tessellator.addVertexWithUV(x, y1, z1, minU, minV); + break; - case SOUTH: - tessellator.addVertexWithUV( x, y1, z, maxU, minV ); - tessellator.addVertexWithUV( x1, y1, z, minU, minV ); - tessellator.addVertexWithUV( x1, y, z, minU, maxV ); - tessellator.addVertexWithUV( x, y, z, maxU, maxV ); - break; + case SOUTH: + tessellator.addVertexWithUV(x, y1, z, maxU, minV); + tessellator.addVertexWithUV(x1, y1, z, minU, minV); + tessellator.addVertexWithUV(x1, y, z, minU, maxV); + tessellator.addVertexWithUV(x, y, z, maxU, maxV); + break; - case UP: - tessellator.addVertexWithUV( x, y1, z1, maxU, minV ); - tessellator.addVertexWithUV( x1, y1, z1, minU, minV ); - tessellator.addVertexWithUV( x1, y1, z, minU, maxV ); - tessellator.addVertexWithUV( x, y1, z, maxU, maxV ); - break; + case UP: + tessellator.addVertexWithUV(x, y1, z1, maxU, minV); + tessellator.addVertexWithUV(x1, y1, z1, minU, minV); + tessellator.addVertexWithUV(x1, y1, z, minU, maxV); + tessellator.addVertexWithUV(x, y1, z, maxU, maxV); + break; - case WEST: - tessellator.addVertexWithUV( x, y, z1, maxU, maxV ); - tessellator.addVertexWithUV( x, y1, z1, maxU, minV ); - tessellator.addVertexWithUV( x, y1, z, minU, minV ); - tessellator.addVertexWithUV( x, y, z, minU, maxV ); - break; + case WEST: + tessellator.addVertexWithUV(x, y, z1, maxU, maxV); + tessellator.addVertexWithUV(x, y1, z1, maxU, minV); + tessellator.addVertexWithUV(x, y1, z, minU, minV); + tessellator.addVertexWithUV(x, y, z, minU, maxV); + break; - default: - // Invalid side. - break; - } - } - } + default: + // Invalid side. + break; + } + } + } - /** - * Renders the provider in the inventory. - */ - @Override - public final void renderInventoryBlock( final Block block, final int metadata, final int modelId, final RenderBlocks renderer ) - { - // Get the tessellator instance - Tessellator tessellator = Tessellator.instance; + /** + * Renders the provider in the inventory. + */ + @Override + public final void renderInventoryBlock( + final Block block, final int metadata, final int modelId, final RenderBlocks renderer) { + // Get the tessellator instance + Tessellator tessellator = Tessellator.instance; - IIcon texture = this.textureSource.getTextures()[0]; + IIcon texture = this.textureSource.getTextures()[0]; - GL11.glTranslatef( -0.5F, -0.5F, -0.5F ); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - tessellator.startDrawingQuads(); + tessellator.startDrawingQuads(); - // Down - tessellator.setNormal( 0.0F, -1.0F, 0.0F ); - renderer.renderFaceYNeg( block, 0.0D, 0.0D, 0.0D, texture ); + // Down + tessellator.setNormal(0.0F, -1.0F, 0.0F); + renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, texture); - // Up - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - renderer.renderFaceYPos( block, 0.0D, 0.0D, 0.0D, texture ); + // Up + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, texture); - // North - tessellator.setNormal( 0.0F, 0.0F, -1.0F ); - renderer.renderFaceZNeg( block, 0.0D, 0.0D, 0.0D, texture ); + // North + tessellator.setNormal(0.0F, 0.0F, -1.0F); + renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, texture); - // South - tessellator.setNormal( 0.0F, 0.0F, 1.0F ); - renderer.renderFaceZPos( block, 0.0D, 0.0D, 0.0D, texture ); + // South + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, texture); - // West - tessellator.setNormal( -1.0F, 0.0F, 0.0F ); - renderer.renderFaceXNeg( block, 0.0D, 0.0D, 0.0D, texture ); + // West + tessellator.setNormal(-1.0F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, texture); - // East - tessellator.setNormal( 1.0F, 0.0F, 0.0F ); - renderer.renderFaceXPos( block, 0.0D, 0.0D, 0.0D, texture ); + // East + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, texture); - tessellator.draw(); + tessellator.draw(); - GL11.glTranslatef( 0.5F, 0.5F, 0.5F ); - } + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + } - @Override - public final boolean renderWorldBlock( final IBlockAccess world, final int x, final int y, final int z, final Block block, final int modelId, - final RenderBlocks renderer ) - { - // Get the tessellator - Tessellator tessellator = Tessellator.instance; + @Override + public final boolean renderWorldBlock( + final IBlockAccess world, + final int x, + final int y, + final int z, + final Block block, + final int modelId, + final RenderBlocks renderer) { + // Get the tessellator + Tessellator tessellator = Tessellator.instance; - // Texture - IIcon texture; + // Texture + IIcon texture; - // The forced glow of the block - int glow = 0; + // The forced glow of the block + int glow = 0; - // Is this the opaque pass? - if( Renderers.currentRenderPass == Renderers.PASS_OPAQUE ) - { - // Set the texture to the base - texture = this.textureSource.getTextures()[0]; + // Is this the opaque pass? + if (Renderers.currentRenderPass == Renderers.PASS_OPAQUE) { + // Set the texture to the base + texture = this.textureSource.getTextures()[0]; - // Set the drawing color to full white - tessellator.setColorRGBA( 255, 255, 255, 255 ); + // Set the drawing color to full white + tessellator.setColorRGBA(255, 255, 255, 255); - } - // This is the alpha pass. - else - { - // Set the texture to the overlay - texture = this.textureSource.getTextures()[1]; + } + // This is the alpha pass. + else { + // Set the texture to the overlay + texture = this.textureSource.getTextures()[1]; - // Get the provider - TileProviderBase provider = (TileProviderBase)world.getTileEntity( x, y, z ); + // Get the provider + TileProviderBase provider = (TileProviderBase) world.getTileEntity(x, y, z); - // Is the provider active? - if( provider.isActive() ) - { - // Adjust overlay brightness - glow = 15; + // Is the provider active? + if (provider.isActive()) { + // Adjust overlay brightness + glow = 15; - // Set the drawing color - tessellator.setColorOpaque_I( provider.getColor().mediumVariant ); - } - else - { - // Inactive, set the drawing color to black - tessellator.setColorRGBA( 0, 0, 0, 255 ); - } - } + // Set the drawing color + tessellator.setColorOpaque_I(provider.getColor().mediumVariant); + } else { + // Inactive, set the drawing color to black + tessellator.setColorRGBA(0, 0, 0, 255); + } + } - // Render the faces - this.renderFaces( world, x, y, z, texture, glow ); + // Render the faces + this.renderFaces(world, x, y, z, texture, glow); - return true; - } - - @Override - public final boolean shouldRender3DInInventory( final int modelId ) - { - return true; - } + return true; + } + @Override + public final boolean shouldRender3DInInventory(final int modelId) { + return true; + } } diff --git a/src/main/java/thaumicenergistics/client/render/RenderTileArcaneAssembler.java b/src/main/java/thaumicenergistics/client/render/RenderTileArcaneAssembler.java index 0c25a631..901e2ff9 100644 --- a/src/main/java/thaumicenergistics/client/render/RenderTileArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/client/render/RenderTileArcaneAssembler.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.render; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; @@ -11,6 +10,7 @@ import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumicenergistics.api.ThEApi; import thaumicenergistics.client.render.model.ModelArcaneAssembler; import thaumicenergistics.common.ThaumicEnergistics; @@ -23,89 +23,85 @@ import thaumicenergistics.common.tiles.TileArcaneAssembler; * */ @SideOnly(Side.CLIENT) -public class RenderTileArcaneAssembler - extends TileEntitySpecialRenderer -{ +public class RenderTileArcaneAssembler extends TileEntitySpecialRenderer { - /** - * Assembler model. - */ - private final ModelArcaneAssembler assemblerModel = new ModelArcaneAssembler(); + /** + * Assembler model. + */ + private final ModelArcaneAssembler assemblerModel = new ModelArcaneAssembler(); - /** - * Texture - */ - private final ResourceLocation assemblerTexture = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/models/arcane.assembler.png" ); + /** + * Texture + */ + private final ResourceLocation assemblerTexture = + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/models/arcane.assembler.png"); - /** - * Cache of the assembler block. - */ - private final Block assemblerBlock = ThEApi.instance().blocks().ArcaneAssembler.getBlock(); + /** + * Cache of the assembler block. + */ + private final Block assemblerBlock = + ThEApi.instance().blocks().ArcaneAssembler.getBlock(); - private void renderAssembler( final TileArcaneAssembler assemblerTile, final World world, final int x, final int y, final int z ) - { - // Ensure there is a world object - if( world != null ) - { - // Get the block lightning - float mixedBrightness = this.assemblerBlock.getMixedBrightnessForBlock( world, x, y, z ); - int light = world.getLightBrightnessForSkyBlocks( x, y, z, 0 ); + private void renderAssembler( + final TileArcaneAssembler assemblerTile, final World world, final int x, final int y, final int z) { + // Ensure there is a world object + if (world != null) { + // Get the block lightning + float mixedBrightness = this.assemblerBlock.getMixedBrightnessForBlock(world, x, y, z); + int light = world.getLightBrightnessForSkyBlocks(x, y, z, 0); - int l1 = light % 65536; - int l2 = light / 65536; + int l1 = light % 65536; + int l2 = light / 65536; - // Set the color based on the mixed brightness - Tessellator.instance.setColorOpaque_F( mixedBrightness, mixedBrightness, mixedBrightness ); + // Set the color based on the mixed brightness + Tessellator.instance.setColorOpaque_F(mixedBrightness, mixedBrightness, mixedBrightness); - // Set the lightmap coords - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, l1, l2 ); - } - else - { - // No world object, render at full brightness - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - } + // Set the lightmap coords + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, l1, l2); + } else { + // No world object, render at full brightness + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + } - // Push the matrix - GL11.glPushMatrix(); + // Push the matrix + GL11.glPushMatrix(); - // Center the model - GL11.glTranslatef( 0.5F, 0.5F, 0.5F ); + // Center the model + GL11.glTranslatef(0.5F, 0.5F, 0.5F); - // Bind the model texture - Minecraft.getMinecraft().renderEngine.bindTexture( this.assemblerTexture ); + // Bind the model texture + Minecraft.getMinecraft().renderEngine.bindTexture(this.assemblerTexture); - // Scale down - GL11.glScalef( 0.047F, 0.047F, 0.047F ); + // Scale down + GL11.glScalef(0.047F, 0.047F, 0.047F); - // Render the assembler - this.assemblerModel.render( null, 0, 0, -0.1F, 0, 0, 0.625F ); + // Render the assembler + this.assemblerModel.render(null, 0, 0, -0.1F, 0, 0, 0.625F); - // Pop the matrix - GL11.glPopMatrix(); - } + // Pop the matrix + GL11.glPopMatrix(); + } - /** - * Called when the assembler needs to be rendered. - */ - @Override - public void renderTileEntityAt( final TileEntity tileEntity, final double d, final double d1, final double d2, final float f ) - { - // Push the GL matrix - GL11.glPushMatrix(); + /** + * Called when the assembler needs to be rendered. + */ + @Override + public void renderTileEntityAt( + final TileEntity tileEntity, final double d, final double d1, final double d2, final float f) { + // Push the GL matrix + GL11.glPushMatrix(); - // Computes the proper place to draw - GL11.glTranslatef( (float)d, (float)d1, (float)d2 ); + // Computes the proper place to draw + GL11.glTranslatef((float) d, (float) d1, (float) d2); - // Get the assembler - TileArcaneAssembler assemblerTile = (TileArcaneAssembler)tileEntity; + // Get the assembler + TileArcaneAssembler assemblerTile = (TileArcaneAssembler) tileEntity; - // Render the gearbox - this.renderAssembler( assemblerTile, tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord ); - - // Pop the GL matrix - GL11.glPopMatrix(); - - } + // Render the gearbox + this.renderAssembler( + assemblerTile, tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); + // Pop the GL matrix + GL11.glPopMatrix(); + } } diff --git a/src/main/java/thaumicenergistics/client/render/RenderTileGearbox.java b/src/main/java/thaumicenergistics/client/render/RenderTileGearbox.java index f09c1444..23404194 100644 --- a/src/main/java/thaumicenergistics/client/render/RenderTileGearbox.java +++ b/src/main/java/thaumicenergistics/client/render/RenderTileGearbox.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.render; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; @@ -11,6 +10,7 @@ import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; +import org.lwjgl.opengl.GL11; import thaumicenergistics.api.ThEApi; import thaumicenergistics.client.render.model.ModelGearbox; import thaumicenergistics.common.ThaumicEnergistics; @@ -23,113 +23,106 @@ import thaumicenergistics.common.tiles.TileGearBox; * */ @SideOnly(Side.CLIENT) -public class RenderTileGearbox - extends TileEntitySpecialRenderer -{ - /** - * Gearbox model - */ - private final ModelGearbox gearboxModel = new ModelGearbox(); +public class RenderTileGearbox extends TileEntitySpecialRenderer { + /** + * Gearbox model + */ + private final ModelGearbox gearboxModel = new ModelGearbox(); - /** - * Textures - */ - private final ResourceLocation TEX_IRON = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/models/gearbox.iron.png" ), - TEX_THAUMIUM = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/models/gearbox.thaumium.png" ); + /** + * Textures + */ + private final ResourceLocation + TEX_IRON = new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/models/gearbox.iron.png"), + TEX_THAUMIUM = new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/models/gearbox.thaumium.png"); - /** - * Cache of the gearbox block. - */ - private final Block gearboxBlock = ThEApi.instance().blocks().IronGearBox.getBlock(); + /** + * Cache of the gearbox block. + */ + private final Block gearboxBlock = ThEApi.instance().blocks().IronGearBox.getBlock(); - /** - * Renders the gearbox. - * - * @param gearboxTile - * @param world - * @param x - * @param y - * @param z - * @param block - */ - private void renderGearbox( final TileGearBox gearboxTile, final World world, final int x, final int y, final int z ) - { - // Ensure there is a world object - if( world != null ) - { - // Get the block lightning - float mixedBrightness = this.gearboxBlock.getMixedBrightnessForBlock( world, x, y, z ); - int light = world.getLightBrightnessForSkyBlocks( x, y, z, 0 ); + /** + * Renders the gearbox. + * + * @param gearboxTile + * @param world + * @param x + * @param y + * @param z + * @param block + */ + private void renderGearbox( + final TileGearBox gearboxTile, final World world, final int x, final int y, final int z) { + // Ensure there is a world object + if (world != null) { + // Get the block lightning + float mixedBrightness = this.gearboxBlock.getMixedBrightnessForBlock(world, x, y, z); + int light = world.getLightBrightnessForSkyBlocks(x, y, z, 0); - int l1 = light % 65536; - int l2 = light / 65536; + int l1 = light % 65536; + int l2 = light / 65536; - // Set the color based on the mixed brightness - Tessellator.instance.setColorOpaque_F( mixedBrightness, mixedBrightness, mixedBrightness ); + // Set the color based on the mixed brightness + Tessellator.instance.setColorOpaque_F(mixedBrightness, mixedBrightness, mixedBrightness); - // Set the lightmap coords - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, l1, l2 ); - } - else - { - // No world object, render at full brightness - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - } + // Set the lightmap coords + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, l1, l2); + } else { + // No world object, render at full brightness + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + } - // Push the matrix - GL11.glPushMatrix(); + // Push the matrix + GL11.glPushMatrix(); - // Center the model - GL11.glTranslatef( 0.5F, 0.5F, 0.5F ); + // Center the model + GL11.glTranslatef(0.5F, 0.5F, 0.5F); - // Bind the model texture - if( gearboxTile.isThaumiumGearbox() ) - { - Minecraft.getMinecraft().renderEngine.bindTexture( this.TEX_THAUMIUM ); - } - else - { - Minecraft.getMinecraft().renderEngine.bindTexture( this.TEX_IRON ); - } + // Bind the model texture + if (gearboxTile.isThaumiumGearbox()) { + Minecraft.getMinecraft().renderEngine.bindTexture(this.TEX_THAUMIUM); + } else { + Minecraft.getMinecraft().renderEngine.bindTexture(this.TEX_IRON); + } - // Scale down - GL11.glScalef( 0.12F, 0.12F, 0.12F ); + // Scale down + GL11.glScalef(0.12F, 0.12F, 0.12F); - // Update the model. - this.gearboxModel.updateToTileEntity( gearboxTile ); + // Update the model. + this.gearboxModel.updateToTileEntity(gearboxTile); - // Render the gearbox - this.gearboxModel.render( null, 0, 0, -0.1F, 0, 0, 0.625F ); + // Render the gearbox + this.gearboxModel.render(null, 0, 0, -0.1F, 0, 0, 0.625F); - // Pop the matrix - GL11.glPopMatrix(); - } + // Pop the matrix + GL11.glPopMatrix(); + } - /** - * Called when a gearbox tile entity needs to be rendered. - * - * @param tileEntity - * @param d - * @param d1 - * @param d2 - * @param f - */ - @Override - public void renderTileEntityAt( final TileEntity tileEntity, final double d, final double d1, final double d2, final float f ) - { - // Push the GL matrix - GL11.glPushMatrix(); + /** + * Called when a gearbox tile entity needs to be rendered. + * + * @param tileEntity + * @param d + * @param d1 + * @param d2 + * @param f + */ + @Override + public void renderTileEntityAt( + final TileEntity tileEntity, final double d, final double d1, final double d2, final float f) { + // Push the GL matrix + GL11.glPushMatrix(); - // Computes the proper place to draw - GL11.glTranslatef( (float)d, (float)d1, (float)d2 ); + // Computes the proper place to draw + GL11.glTranslatef((float) d, (float) d1, (float) d2); - // Get the gearbox - TileGearBox gearBox = (TileGearBox)tileEntity; + // Get the gearbox + TileGearBox gearBox = (TileGearBox) tileEntity; - // Render the gearbox - this.renderGearbox( gearBox, tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord ); + // Render the gearbox + this.renderGearbox(gearBox, tileEntity.getWorldObj(), tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - // Pop the GL matrix - GL11.glPopMatrix(); - } -} \ No newline at end of file + // Pop the GL matrix + GL11.glPopMatrix(); + } +} diff --git a/src/main/java/thaumicenergistics/client/render/RendererItemCraftingAspect.java b/src/main/java/thaumicenergistics/client/render/RendererItemCraftingAspect.java index 27cdb001..354867bb 100644 --- a/src/main/java/thaumicenergistics/client/render/RendererItemCraftingAspect.java +++ b/src/main/java/thaumicenergistics/client/render/RendererItemCraftingAspect.java @@ -1,12 +1,12 @@ package thaumicenergistics.client.render; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumcraft.client.lib.UtilsFX; import thaumicenergistics.common.items.ItemCraftingAspect; @@ -18,74 +18,65 @@ import thaumicenergistics.common.items.ItemCraftingAspect; * */ @SideOnly(Side.CLIENT) -public class RendererItemCraftingAspect - implements IItemRenderer -{ +public class RendererItemCraftingAspect implements IItemRenderer { - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - // Handle only inventory - return( type == ItemRenderType.INVENTORY ); - } + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + // Handle only inventory + return (type == ItemRenderType.INVENTORY); + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack stack, final Object ... data ) - { - boolean isKnown = false; - Aspect aspect = null; + @Override + public void renderItem(final ItemRenderType type, final ItemStack stack, final Object... data) { + boolean isKnown = false; + Aspect aspect = null; - // Is the stack setup? - if( ( stack.getItemDamage() == 0 ) && ( stack.hasTagCompound() ) ) - { - // Get the player - EntityPlayer player = Minecraft.getMinecraft().thePlayer; + // Is the stack setup? + if ((stack.getItemDamage() == 0) && (stack.hasTagCompound())) { + // Get the player + EntityPlayer player = Minecraft.getMinecraft().thePlayer; - // Get the aspect - aspect = ItemCraftingAspect.getAspect( stack ); + // Get the aspect + aspect = ItemCraftingAspect.getAspect(stack); - // Can the knowledge be checked? - if( ( player != null ) && ( aspect != null ) ) - { - isKnown = ItemCraftingAspect.canPlayerSeeAspect( player, aspect ); - } - } + // Can the knowledge be checked? + if ((player != null) && (aspect != null)) { + isKnown = ItemCraftingAspect.canPlayerSeeAspect(player, aspect); + } + } - // Is the aspect known? - if( isKnown ) - { - // Render aspect - UtilsFX.drawTag( 0, 0, aspect, 0.0F, 0, 0.0D ); - } - else - { - // Render unknown + // Is the aspect known? + if (isKnown) { + // Render aspect + UtilsFX.drawTag(0, 0, aspect, 0.0F, 0, 0.0D); + } else { + // Render unknown - // Disable standard lighting - GL11.glDisable( GL11.GL_LIGHTING ); + // Disable standard lighting + GL11.glDisable(GL11.GL_LIGHTING); - // Set the alpha function - GL11.glAlphaFunc( GL11.GL_GREATER, 0.003921569F ); + // Set the alpha function + GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F); - // Enable alpha blending - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE ); + // Enable alpha blending + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE); - // Render - UtilsFX.bindTexture( "textures/aspects/_unknown.png" ); - GL11.glColor4f( 0.5F, 0.5F, 0.5F, 0.5F ); - UtilsFX.drawTexturedQuadFull( 0, 0, 0.0D ); + // Render + UtilsFX.bindTexture("textures/aspects/_unknown.png"); + GL11.glColor4f(0.5F, 0.5F, 0.5F, 0.5F); + UtilsFX.drawTexturedQuadFull(0, 0, 0.0D); - // Restore - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_BLEND ); - } - } + // Restore + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + } + } - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - // Do not use the helper - return false; - } + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + // Do not use the helper + return false; + } } diff --git a/src/main/java/thaumicenergistics/client/render/TileAsItemRenderer.java b/src/main/java/thaumicenergistics/client/render/TileAsItemRenderer.java index ad602f48..448801b0 100644 --- a/src/main/java/thaumicenergistics/client/render/TileAsItemRenderer.java +++ b/src/main/java/thaumicenergistics/client/render/TileAsItemRenderer.java @@ -1,12 +1,12 @@ package thaumicenergistics.client.render; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.client.IItemRenderer; +import org.lwjgl.opengl.GL11; /** * Renders a tile entity as an item. @@ -15,71 +15,63 @@ import net.minecraftforge.client.IItemRenderer; * */ @SideOnly(Side.CLIENT) -public class TileAsItemRenderer - implements IItemRenderer -{ +public class TileAsItemRenderer implements IItemRenderer { - /** - * Tile entity renderer. - */ - private TileEntitySpecialRenderer tileRenderer; + /** + * Tile entity renderer. + */ + private TileEntitySpecialRenderer tileRenderer; - /** - * Fake tile entity used to render. - */ - private TileEntity fakeEntity; + /** + * Fake tile entity used to render. + */ + private TileEntity fakeEntity; - public TileAsItemRenderer( final TileEntitySpecialRenderer tileRenderer, final TileEntity fakeEntity ) - { - // Set the renderer and entity - this.tileRenderer = tileRenderer; - this.fakeEntity = fakeEntity; - } + public TileAsItemRenderer(final TileEntitySpecialRenderer tileRenderer, final TileEntity fakeEntity) { + // Set the renderer and entity + this.tileRenderer = tileRenderer; + this.fakeEntity = fakeEntity; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object ... data ) - { - // Push the matrix - GL11.glPushMatrix(); + @Override + public void renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + // Push the matrix + GL11.glPushMatrix(); - // Adjust position based on render type - switch ( type ) - { - case ENTITY: - GL11.glTranslatef( -0.5F, -0.5F, -0.5F ); - break; + // Adjust position based on render type + switch (type) { + case ENTITY: + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + break; - case EQUIPPED_FIRST_PERSON: - GL11.glTranslatef( 0.5F, 0.2F, 0.0F ); - break; + case EQUIPPED_FIRST_PERSON: + GL11.glTranslatef(0.5F, 0.2F, 0.0F); + break; - case INVENTORY: - GL11.glTranslatef( -0.5F, -0.5F, -0.5F ); - break; + case INVENTORY: + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + break; - case FIRST_PERSON_MAP: - case EQUIPPED: - break; - } + case FIRST_PERSON_MAP: + case EQUIPPED: + break; + } - // Render the entity - this.tileRenderer.renderTileEntityAt( this.fakeEntity, 0, 0, 0, 0 ); + // Render the entity + this.tileRenderer.renderTileEntityAt(this.fakeEntity, 0, 0, 0, 0); - // Pop the matrix - GL11.glPopMatrix(); - - } - - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return true; - } + // Pop the matrix + GL11.glPopMatrix(); + } + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper) { + return true; + } } diff --git a/src/main/java/thaumicenergistics/client/render/model/ModelArcaneAssembler.java b/src/main/java/thaumicenergistics/client/render/model/ModelArcaneAssembler.java index f14f0daa..5eb9c3b3 100644 --- a/src/main/java/thaumicenergistics/client/render/model/ModelArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/client/render/model/ModelArcaneAssembler.java @@ -1,11 +1,11 @@ package thaumicenergistics.client.render.model; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; +import org.lwjgl.opengl.GL11; import thaumicenergistics.common.tiles.TileArcaneAssembler; /** @@ -15,206 +15,207 @@ import thaumicenergistics.common.tiles.TileArcaneAssembler; * */ @SideOnly(Side.CLIENT) -public class ModelArcaneAssembler - extends ModelBase -{ - /** - * 90 degrees - */ - private static final float HALF_TURN = 1.570796325F, FULL_TURN = HALF_TURN + HALF_TURN; +public class ModelArcaneAssembler extends ModelBase { + /** + * 90 degrees + */ + private static final float HALF_TURN = 1.570796325F, FULL_TURN = HALF_TURN + HALF_TURN; - //fields - private ModelRenderer OuterFrameTop; - private ModelRenderer OuterFrameBottom; - private ModelRenderer OuterFrameLeft; - private ModelRenderer OuterFrameRight; - private ModelRenderer Glass; - private ModelRenderer InnerFrameTop; - private ModelRenderer InnerFrameBottom; - private ModelRenderer InnerFrameLeft; - private ModelRenderer InnerFrameRight; + // fields + private ModelRenderer OuterFrameTop; + private ModelRenderer OuterFrameBottom; + private ModelRenderer OuterFrameLeft; + private ModelRenderer OuterFrameRight; + private ModelRenderer Glass; + private ModelRenderer InnerFrameTop; + private ModelRenderer InnerFrameBottom; + private ModelRenderer InnerFrameLeft; + private ModelRenderer InnerFrameRight; - public ModelArcaneAssembler() - { - this.textureWidth = 64; - this.textureHeight = 64; + public ModelArcaneAssembler() { + this.textureWidth = 64; + this.textureHeight = 64; - this.OuterFrameTop = new ModelRenderer( this, 0, 0 ); - this.OuterFrameTop.addBox( -17F, -17F, -15F, 34, 2, 2 ); - this.OuterFrameTop.setRotationPoint( 0F, 0F, 0F ); - this.OuterFrameTop.setTextureSize( 64, 64 ); - this.OuterFrameTop.mirror = true; + this.OuterFrameTop = new ModelRenderer(this, 0, 0); + this.OuterFrameTop.addBox(-17F, -17F, -15F, 34, 2, 2); + this.OuterFrameTop.setRotationPoint(0F, 0F, 0F); + this.OuterFrameTop.setTextureSize(64, 64); + this.OuterFrameTop.mirror = true; - this.setRotation( this.OuterFrameTop, 0F, 0F, 0F ); - this.OuterFrameBottom = new ModelRenderer( this, 0, 0 ); - this.OuterFrameBottom.addBox( -17F, 15F, -15F, 34, 2, 2 ); - this.OuterFrameBottom.setRotationPoint( 0F, 0F, 0F ); - this.OuterFrameBottom.setTextureSize( 64, 64 ); - this.OuterFrameBottom.mirror = true; + this.setRotation(this.OuterFrameTop, 0F, 0F, 0F); + this.OuterFrameBottom = new ModelRenderer(this, 0, 0); + this.OuterFrameBottom.addBox(-17F, 15F, -15F, 34, 2, 2); + this.OuterFrameBottom.setRotationPoint(0F, 0F, 0F); + this.OuterFrameBottom.setTextureSize(64, 64); + this.OuterFrameBottom.mirror = true; - this.setRotation( this.OuterFrameBottom, 0F, 0F, 0F ); - this.OuterFrameLeft = new ModelRenderer( this, 0, 0 ); - this.OuterFrameLeft.addBox( -17F, -17F, -15F, 34, 2, 2 ); - this.OuterFrameLeft.setRotationPoint( 0F, 0F, 0F ); - this.OuterFrameLeft.setTextureSize( 64, 64 ); - this.OuterFrameLeft.mirror = true; - this.setRotation( this.OuterFrameLeft, 0F, 0F, -1.570796F ); + this.setRotation(this.OuterFrameBottom, 0F, 0F, 0F); + this.OuterFrameLeft = new ModelRenderer(this, 0, 0); + this.OuterFrameLeft.addBox(-17F, -17F, -15F, 34, 2, 2); + this.OuterFrameLeft.setRotationPoint(0F, 0F, 0F); + this.OuterFrameLeft.setTextureSize(64, 64); + this.OuterFrameLeft.mirror = true; + this.setRotation(this.OuterFrameLeft, 0F, 0F, -1.570796F); - this.OuterFrameRight = new ModelRenderer( this, 0, 0 ); - this.OuterFrameRight.addBox( -17F, -17F, -15F, 34, 2, 2 ); - this.OuterFrameRight.setRotationPoint( 0F, 0F, 0F ); - this.OuterFrameRight.setTextureSize( 64, 64 ); - this.OuterFrameRight.mirror = true; - this.setRotation( this.OuterFrameRight, 0F, 0F, 1.570796F ); + this.OuterFrameRight = new ModelRenderer(this, 0, 0); + this.OuterFrameRight.addBox(-17F, -17F, -15F, 34, 2, 2); + this.OuterFrameRight.setRotationPoint(0F, 0F, 0F); + this.OuterFrameRight.setTextureSize(64, 64); + this.OuterFrameRight.mirror = true; + this.setRotation(this.OuterFrameRight, 0F, 0F, 1.570796F); - this.Glass = new ModelRenderer( this, 0, 37 ); - this.Glass.addBox( -13F, -13F, -14F, 26, 26, 1 ); - this.Glass.setRotationPoint( 0F, 0F, 0F ); - this.Glass.setTextureSize( 64, 64 ); - this.Glass.mirror = true; - this.setRotation( this.Glass, 0F, 0F, 0F ); + this.Glass = new ModelRenderer(this, 0, 37); + this.Glass.addBox(-13F, -13F, -14F, 26, 26, 1); + this.Glass.setRotationPoint(0F, 0F, 0F); + this.Glass.setTextureSize(64, 64); + this.Glass.mirror = true; + this.setRotation(this.Glass, 0F, 0F, 0F); - this.InnerFrameTop = new ModelRenderer( this, 0, 4 ); - this.InnerFrameTop.addBox( -15F, -15F, -15F, 30, 2, 2 ); - this.InnerFrameTop.setRotationPoint( 0F, 0F, 0F ); - this.InnerFrameTop.setTextureSize( 64, 64 ); - this.InnerFrameTop.mirror = true; - this.setRotation( this.InnerFrameTop, 0F, 0F, 0F ); + this.InnerFrameTop = new ModelRenderer(this, 0, 4); + this.InnerFrameTop.addBox(-15F, -15F, -15F, 30, 2, 2); + this.InnerFrameTop.setRotationPoint(0F, 0F, 0F); + this.InnerFrameTop.setTextureSize(64, 64); + this.InnerFrameTop.mirror = true; + this.setRotation(this.InnerFrameTop, 0F, 0F, 0F); - this.InnerFrameBottom = new ModelRenderer( this, 0, 4 ); - this.InnerFrameBottom.addBox( -15F, 13F, -15F, 30, 2, 2 ); - this.InnerFrameBottom.setRotationPoint( 0F, 0F, 0F ); - this.InnerFrameBottom.setTextureSize( 64, 64 ); - this.InnerFrameBottom.mirror = true; - this.setRotation( this.InnerFrameBottom, 0F, 0F, 0F ); + this.InnerFrameBottom = new ModelRenderer(this, 0, 4); + this.InnerFrameBottom.addBox(-15F, 13F, -15F, 30, 2, 2); + this.InnerFrameBottom.setRotationPoint(0F, 0F, 0F); + this.InnerFrameBottom.setTextureSize(64, 64); + this.InnerFrameBottom.mirror = true; + this.setRotation(this.InnerFrameBottom, 0F, 0F, 0F); - this.InnerFrameLeft = new ModelRenderer( this, 0, 4 ); - this.InnerFrameLeft.addBox( -15F, -15F, -15F, 30, 2, 2 ); - this.InnerFrameLeft.setRotationPoint( 0F, 0F, 0F ); - this.InnerFrameLeft.setTextureSize( 64, 64 ); - this.InnerFrameLeft.mirror = true; - this.setRotation( this.InnerFrameLeft, 0F, 0F, -1.570796F ); + this.InnerFrameLeft = new ModelRenderer(this, 0, 4); + this.InnerFrameLeft.addBox(-15F, -15F, -15F, 30, 2, 2); + this.InnerFrameLeft.setRotationPoint(0F, 0F, 0F); + this.InnerFrameLeft.setTextureSize(64, 64); + this.InnerFrameLeft.mirror = true; + this.setRotation(this.InnerFrameLeft, 0F, 0F, -1.570796F); - this.InnerFrameRight = new ModelRenderer( this, 0, 4 ); - this.InnerFrameRight.addBox( -15F, -15F, -15F, 30, 2, 2 ); - this.InnerFrameRight.setRotationPoint( 0F, 0F, 0F ); - this.InnerFrameRight.setTextureSize( 64, 64 ); - this.InnerFrameRight.mirror = true; - this.setRotation( this.InnerFrameRight, 0F, 0F, 1.570796F ); - } + this.InnerFrameRight = new ModelRenderer(this, 0, 4); + this.InnerFrameRight.addBox(-15F, -15F, -15F, 30, 2, 2); + this.InnerFrameRight.setRotationPoint(0F, 0F, 0F); + this.InnerFrameRight.setTextureSize(64, 64); + this.InnerFrameRight.mirror = true; + this.setRotation(this.InnerFrameRight, 0F, 0F, 1.570796F); + } - /** - * Renders the glass on one side of the block. - * - * @param YRotation - * @param XRotation - * @param f5 - */ - private void renderGlassSide( final float YRotation, final float XRotation, final float f5 ) - { - this.Glass.rotateAngleX = XRotation; - this.Glass.rotateAngleY = YRotation; - this.Glass.render( f5 ); + /** + * Renders the glass on one side of the block. + * + * @param YRotation + * @param XRotation + * @param f5 + */ + private void renderGlassSide(final float YRotation, final float XRotation, final float f5) { + this.Glass.rotateAngleX = XRotation; + this.Glass.rotateAngleY = YRotation; + this.Glass.render(f5); + } - } + /** + * Renders the inner frame on one side of the block. + * + * @param YRotation + * @param XRotation + * @param f5 + */ + private void renderInnerFrameSide(final float YRotation, final float XRotation, final float f5) { + // Set the Y rotation + this.InnerFrameTop.rotateAngleY = YRotation; + this.InnerFrameBottom.rotateAngleY = YRotation; + this.InnerFrameLeft.rotateAngleY = YRotation; + this.InnerFrameRight.rotateAngleY = YRotation; - /** - * Renders the inner frame on one side of the block. - * - * @param YRotation - * @param XRotation - * @param f5 - */ - private void renderInnerFrameSide( final float YRotation, final float XRotation, final float f5 ) - { - // Set the Y rotation - this.InnerFrameTop.rotateAngleY = YRotation; - this.InnerFrameBottom.rotateAngleY = YRotation; - this.InnerFrameLeft.rotateAngleY = YRotation; - this.InnerFrameRight.rotateAngleY = YRotation; + // Set the X rotation + this.InnerFrameTop.rotateAngleX = XRotation; + this.InnerFrameBottom.rotateAngleX = XRotation; + this.InnerFrameLeft.rotateAngleX = XRotation; + this.InnerFrameRight.rotateAngleX = XRotation; - // Set the X rotation - this.InnerFrameTop.rotateAngleX = XRotation; - this.InnerFrameBottom.rotateAngleX = XRotation; - this.InnerFrameLeft.rotateAngleX = XRotation; - this.InnerFrameRight.rotateAngleX = XRotation; + // Render the frame + this.InnerFrameTop.render(f5); + this.InnerFrameBottom.render(f5); + this.InnerFrameLeft.render(f5); + this.InnerFrameRight.render(f5); + } - // Render the frame - this.InnerFrameTop.render( f5 ); - this.InnerFrameBottom.render( f5 ); - this.InnerFrameLeft.render( f5 ); - this.InnerFrameRight.render( f5 ); - } + /** + * Renders the outer frame on one side of the block. + * + * @param rotation + * @param f5 + */ + private void renderOuterFrameSide(final float rotation, final float f5) { + // Set the Y rotation + this.OuterFrameTop.rotateAngleY = rotation; + this.OuterFrameBottom.rotateAngleY = rotation; + this.OuterFrameLeft.rotateAngleX = -rotation; + this.OuterFrameRight.rotateAngleX = rotation; - /** - * Renders the outer frame on one side of the block. - * - * @param rotation - * @param f5 - */ - private void renderOuterFrameSide( final float rotation, final float f5 ) - { - // Set the Y rotation - this.OuterFrameTop.rotateAngleY = rotation; - this.OuterFrameBottom.rotateAngleY = rotation; - this.OuterFrameLeft.rotateAngleX = -rotation; - this.OuterFrameRight.rotateAngleX = rotation; + // Render the frame + this.OuterFrameTop.render(f5); + this.OuterFrameBottom.render(f5); + this.OuterFrameLeft.render(f5); + this.OuterFrameRight.render(f5); + } - // Render the frame - this.OuterFrameTop.render( f5 ); - this.OuterFrameBottom.render( f5 ); - this.OuterFrameLeft.render( f5 ); - this.OuterFrameRight.render( f5 ); - } + private void setRotation(final ModelRenderer model, final float x, final float y, final float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } - private void setRotation( final ModelRenderer model, final float x, final float y, final float z ) - { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } + @Override + public void render( + final Entity entity, + final float f, + final float f1, + final float f2, + final float f3, + final float f4, + final float f5) { - @Override - public void render( final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5 ) - { + // Render the outer frame - // Render the outer frame + this.renderOuterFrameSide(0, f5); + this.renderOuterFrameSide(ModelArcaneAssembler.HALF_TURN, f5); + this.renderOuterFrameSide(-ModelArcaneAssembler.HALF_TURN, f5); + this.renderOuterFrameSide(ModelArcaneAssembler.FULL_TURN, f5); - this.renderOuterFrameSide( 0, f5 ); - this.renderOuterFrameSide( ModelArcaneAssembler.HALF_TURN, f5 ); - this.renderOuterFrameSide( -ModelArcaneAssembler.HALF_TURN, f5 ); - this.renderOuterFrameSide( ModelArcaneAssembler.FULL_TURN, f5 ); + // Render the inner frame + this.renderInnerFrameSide(0, 0, f5); + this.renderInnerFrameSide(ModelArcaneAssembler.HALF_TURN, 0, f5); + this.renderInnerFrameSide(-ModelArcaneAssembler.HALF_TURN, 0, f5); + this.renderInnerFrameSide(ModelArcaneAssembler.FULL_TURN, 0, f5); + this.renderInnerFrameSide(0, ModelArcaneAssembler.HALF_TURN, f5); + this.renderInnerFrameSide(0, -ModelArcaneAssembler.HALF_TURN, f5); - // Render the inner frame - this.renderInnerFrameSide( 0, 0, f5 ); - this.renderInnerFrameSide( ModelArcaneAssembler.HALF_TURN, 0, f5 ); - this.renderInnerFrameSide( -ModelArcaneAssembler.HALF_TURN, 0, f5 ); - this.renderInnerFrameSide( ModelArcaneAssembler.FULL_TURN, 0, f5 ); - this.renderInnerFrameSide( 0, ModelArcaneAssembler.HALF_TURN, f5 ); - this.renderInnerFrameSide( 0, -ModelArcaneAssembler.HALF_TURN, f5 ); + // Enable transparency + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - // Enable transparency - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); + // Render the glass + this.renderGlassSide(0, 0, f5); + this.renderGlassSide(ModelArcaneAssembler.HALF_TURN, 0, f5); + this.renderGlassSide(-ModelArcaneAssembler.HALF_TURN, 0, f5); + this.renderGlassSide(ModelArcaneAssembler.FULL_TURN, 0, f5); + this.renderGlassSide(0, ModelArcaneAssembler.HALF_TURN, f5); + this.renderGlassSide(0, -ModelArcaneAssembler.HALF_TURN, f5); - // Render the glass - this.renderGlassSide( 0, 0, f5 ); - this.renderGlassSide( ModelArcaneAssembler.HALF_TURN, 0, f5 ); - this.renderGlassSide( -ModelArcaneAssembler.HALF_TURN, 0, f5 ); - this.renderGlassSide( ModelArcaneAssembler.FULL_TURN, 0, f5 ); - this.renderGlassSide( 0, ModelArcaneAssembler.HALF_TURN, f5 ); - this.renderGlassSide( 0, -ModelArcaneAssembler.HALF_TURN, f5 ); - - // Disable transparency - GL11.glDisable( GL11.GL_BLEND ); - - } - - @Override - public void setRotationAngles( final float f, final float f1, final float f2, final float f3, final float f4, final float f5, - final Entity entity ) - { - super.setRotationAngles( f, f1, f2, f3, f4, f5, entity ); - } + // Disable transparency + GL11.glDisable(GL11.GL_BLEND); + } + @Override + public void setRotationAngles( + final float f, + final float f1, + final float f2, + final float f3, + final float f4, + final float f5, + final Entity entity) { + super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + } } diff --git a/src/main/java/thaumicenergistics/client/render/model/ModelGearbox.java b/src/main/java/thaumicenergistics/client/render/model/ModelGearbox.java index a1ce4e70..67ce531f 100644 --- a/src/main/java/thaumicenergistics/client/render/model/ModelGearbox.java +++ b/src/main/java/thaumicenergistics/client/render/model/ModelGearbox.java @@ -15,242 +15,242 @@ import thaumicenergistics.common.tiles.TileGearBox; * */ @SideOnly(Side.CLIENT) -public class ModelGearbox - extends ModelBase -{ - private class SideTransformation - { - private static final float SPOKE_OFFSET = 1.2F; +public class ModelGearbox extends ModelBase { + private class SideTransformation { + private static final float SPOKE_OFFSET = 1.2F; - /** - * Common - */ - public final float rotateAngleY, rotateAngleZ; + /** + * Common + */ + public final float rotateAngleY, rotateAngleZ; - /** - * Shaft - */ - public final float shaftOffsetX, shaftOffsetY, shaftOffsetZ; + /** + * Shaft + */ + public final float shaftOffsetX, shaftOffsetY, shaftOffsetZ; - /** - * Spokes - */ - public final float spokeOffsetX, spokeOffsetY, spokeOffsetZ; + /** + * Spokes + */ + public final float spokeOffsetX, spokeOffsetY, spokeOffsetZ; - /** - * Does this side have a shaft? - */ - boolean hasShaft = true; + /** + * Does this side have a shaft? + */ + boolean hasShaft = true; - /* - * Does this side have a gear? - */ - boolean hasGear = false; + /* + * Does this side have a gear? + */ + boolean hasGear = false; - /** - * Creates the transformation - * - * @param rotateAngleY - * @param rotateAngleZ - * @param offsetX - * @param offsetY - * @param offsetZ - */ - public SideTransformation( final float rotateAngleY, final float rotateAngleZ, final float offsetX, final float offsetY, final float offsetZ ) - { - // Set common - this.rotateAngleY = rotateAngleY; - this.rotateAngleZ = rotateAngleZ; + /** + * Creates the transformation + * + * @param rotateAngleY + * @param rotateAngleZ + * @param offsetX + * @param offsetY + * @param offsetZ + */ + public SideTransformation( + final float rotateAngleY, + final float rotateAngleZ, + final float offsetX, + final float offsetY, + final float offsetZ) { + // Set common + this.rotateAngleY = rotateAngleY; + this.rotateAngleZ = rotateAngleZ; - // Set shaft - this.shaftOffsetX = offsetX; - this.shaftOffsetY = offsetY; - this.shaftOffsetZ = offsetZ; + // Set shaft + this.shaftOffsetX = offsetX; + this.shaftOffsetY = offsetY; + this.shaftOffsetZ = offsetZ; - // Set spoke - this.spokeOffsetX = offsetX * SideTransformation.SPOKE_OFFSET; - this.spokeOffsetY = offsetY * SideTransformation.SPOKE_OFFSET; - this.spokeOffsetZ = offsetZ * SideTransformation.SPOKE_OFFSET; + // Set spoke + this.spokeOffsetX = offsetX * SideTransformation.SPOKE_OFFSET; + this.spokeOffsetY = offsetY * SideTransformation.SPOKE_OFFSET; + this.spokeOffsetZ = offsetZ * SideTransformation.SPOKE_OFFSET; + } - } + /** + * Set what is rendered. + * + * @param shaft + * @param gear + */ + public void setIsRendered(final boolean shaft, final boolean gear) { + this.hasShaft = shaft; + this.hasGear = gear; + } + } - /** - * Set what is rendered. - * - * @param shaft - * @param gear - */ - public void setIsRendered( final boolean shaft, final boolean gear ) - { - this.hasShaft = shaft; - this.hasGear = gear; - } - } + /** + * 90 degrees + */ + private static final float HALF_TURN = 1.570796325F; - /** - * 90 degrees - */ - private static final float HALF_TURN = 1.570796325F; + /** + * 45 degrees + */ + private static final float QUARTER_TURN = 0.7853981625F; - /** - * 45 degrees - */ - private static final float QUARTER_TURN = 0.7853981625F; + /** + * Distance to the edge from the center. + */ + private static final float EDGE_DISTANCE = 3.12F; - /** - * Distance to the edge from the center. - */ - private static final float EDGE_DISTANCE = 3.12F; + /** + * Number of valid sides. + */ + private static final int SIDE_COUNT = ForgeDirection.VALID_DIRECTIONS.length; - /** - * Number of valid sides. - */ - private static final int SIDE_COUNT = ForgeDirection.VALID_DIRECTIONS.length; + /** + * Models + */ + private final ModelRenderer Transmission, Shaft, Spoke; - /** - * Models - */ - private final ModelRenderer Transmission, Shaft, Spoke; + /** + * Rotation angle of the shafts and gears. + */ + private float rotationAngle = 0.0F; - /** - * Rotation angle of the shafts and gears. - */ - private float rotationAngle = 0.0F; + /** + * Describes how to render each sides shaft and gear. + */ + private final SideTransformation[] transformations; - /** - * Describes how to render each sides shaft and gear. - */ - private final SideTransformation[] transformations; + /** + * Creates the model. + */ + public ModelGearbox() { + this.textureWidth = 32; + this.textureHeight = 32; - /** - * Creates the model. - */ - public ModelGearbox() - { - this.textureWidth = 32; - this.textureHeight = 32; + // Create the transmission box + this.Transmission = new ModelRenderer(this, 1, 0); + this.Transmission.addBox(0F, 0F, 0F, 7, 7, 7); + this.Transmission.setRotationPoint(-3.5F, -3.5F, -3.5F); + this.Transmission.setTextureSize(64, 64); + this.Transmission.mirror = true; - // Create the transmission box - this.Transmission = new ModelRenderer( this, 1, 0 ); - this.Transmission.addBox( 0F, 0F, 0F, 7, 7, 7 ); - this.Transmission.setRotationPoint( -3.5F, -3.5F, -3.5F ); - this.Transmission.setTextureSize( 64, 64 ); - this.Transmission.mirror = true; + // Create the shaft + this.Shaft = new ModelRenderer(this, 1, 15); + this.Shaft.addBox(-1.5F, -0.5F, -0.5F, 3, 1, 1); + this.Shaft.setRotationPoint(0F, 0F, 0F); + this.Shaft.setTextureSize(64, 64); + this.Shaft.mirror = true; - // Create the shaft - this.Shaft = new ModelRenderer( this, 1, 15 ); - this.Shaft.addBox( -1.5F, -0.5F, -0.5F, 3, 1, 1 ); - this.Shaft.setRotationPoint( 0F, 0F, 0F ); - this.Shaft.setTextureSize( 64, 64 ); - this.Shaft.mirror = true; + // Create the gear spoke + this.Spoke = new ModelRenderer(this, 1, 18); + this.Spoke.addBox(-0.5F, -3.5F, -0.5F, 1, 7, 1); + this.Spoke.setRotationPoint(0F, 0F, 0F); + this.Spoke.setTextureSize(64, 64); + this.Spoke.mirror = true; - // Create the gear spoke - this.Spoke = new ModelRenderer( this, 1, 18 ); - this.Spoke.addBox( -0.5F, -3.5F, -0.5F, 1, 7, 1 ); - this.Spoke.setRotationPoint( 0F, 0F, 0F ); - this.Spoke.setTextureSize( 64, 64 ); - this.Spoke.mirror = true; + // Set the shaft and spoke transformations + this.transformations = new SideTransformation[ForgeDirection.VALID_DIRECTIONS.length]; + this.transformations[ForgeDirection.EAST.ordinal()] = + new SideTransformation(0F, 0F, ModelGearbox.EDGE_DISTANCE, 0F, 0F); + this.transformations[ForgeDirection.WEST.ordinal()] = + new SideTransformation(0F, 0F, -ModelGearbox.EDGE_DISTANCE, 0F, 0F); + this.transformations[ForgeDirection.UP.ordinal()] = + new SideTransformation(0F, ModelGearbox.HALF_TURN, 0F, ModelGearbox.EDGE_DISTANCE, 0F); + this.transformations[ForgeDirection.DOWN.ordinal()] = + new SideTransformation(0F, ModelGearbox.HALF_TURN, 0F, -ModelGearbox.EDGE_DISTANCE, 0F); + this.transformations[ForgeDirection.SOUTH.ordinal()] = + new SideTransformation(ModelGearbox.HALF_TURN, 0F, 0F, 0F, ModelGearbox.EDGE_DISTANCE); + this.transformations[ForgeDirection.NORTH.ordinal()] = + new SideTransformation(ModelGearbox.HALF_TURN, 0F, 0F, 0F, -ModelGearbox.EDGE_DISTANCE); + } - // Set the shaft and spoke transformations - this.transformations = new SideTransformation[ForgeDirection.VALID_DIRECTIONS.length]; - this.transformations[ForgeDirection.EAST.ordinal()] = new SideTransformation( 0F, 0F, ModelGearbox.EDGE_DISTANCE, 0F, 0F ); - this.transformations[ForgeDirection.WEST.ordinal()] = new SideTransformation( 0F, 0F, -ModelGearbox.EDGE_DISTANCE, 0F, 0F ); - this.transformations[ForgeDirection.UP.ordinal()] = new SideTransformation( 0F, ModelGearbox.HALF_TURN, 0F, ModelGearbox.EDGE_DISTANCE, 0F ); - this.transformations[ForgeDirection.DOWN.ordinal()] = new SideTransformation( 0F, ModelGearbox.HALF_TURN, 0F, -ModelGearbox.EDGE_DISTANCE, - 0F ); - this.transformations[ForgeDirection.SOUTH.ordinal()] = new SideTransformation( ModelGearbox.HALF_TURN, 0F, 0F, 0F, - ModelGearbox.EDGE_DISTANCE ); - this.transformations[ForgeDirection.NORTH.ordinal()] = new SideTransformation( ModelGearbox.HALF_TURN, 0F, 0F, 0F, - -ModelGearbox.EDGE_DISTANCE ); - } + /** + * Renders a shaft on the specified side. + * + * @param side + * @param withGear + * @param withExtension + * @param f5 + */ + private void renderShaft(final int side, final float f5) { + // Get the transform + SideTransformation sideTransform = this.transformations[side]; - /** - * Renders a shaft on the specified side. - * - * @param side - * @param withGear - * @param withExtension - * @param f5 - */ - private void renderShaft( final int side, final float f5 ) - { - // Get the transform - SideTransformation sideTransform = this.transformations[side]; + if (sideTransform.hasShaft) { + // Set shaft orientation + this.Shaft.rotateAngleY = sideTransform.rotateAngleY; + this.Shaft.rotateAngleZ = sideTransform.rotateAngleZ; - if( sideTransform.hasShaft ) - { - // Set shaft orientation - this.Shaft.rotateAngleY = sideTransform.rotateAngleY; - this.Shaft.rotateAngleZ = sideTransform.rotateAngleZ; + // Set shaft position + this.Shaft.offsetX = sideTransform.shaftOffsetX; + this.Shaft.offsetY = sideTransform.shaftOffsetY; + this.Shaft.offsetZ = sideTransform.shaftOffsetZ; - // Set shaft position - this.Shaft.offsetX = sideTransform.shaftOffsetX; - this.Shaft.offsetY = sideTransform.shaftOffsetY; - this.Shaft.offsetZ = sideTransform.shaftOffsetZ; + // Render shaft + this.Shaft.render(f5); - // Render shaft - this.Shaft.render( f5 ); + if (sideTransform.hasGear) { + // Set spoke orientation + this.Spoke.rotateAngleY = sideTransform.rotateAngleY; + this.Spoke.rotateAngleZ = sideTransform.rotateAngleZ; - if( sideTransform.hasGear ) - { - // Set spoke orientation - this.Spoke.rotateAngleY = sideTransform.rotateAngleY; - this.Spoke.rotateAngleZ = sideTransform.rotateAngleZ; + // Set spoke position + this.Spoke.offsetX = sideTransform.spokeOffsetX; + this.Spoke.offsetY = sideTransform.spokeOffsetY; + this.Spoke.offsetZ = sideTransform.spokeOffsetZ; - // Set spoke position - this.Spoke.offsetX = sideTransform.spokeOffsetX; - this.Spoke.offsetY = sideTransform.spokeOffsetY; - this.Spoke.offsetZ = sideTransform.spokeOffsetZ; + // Render gear + this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; + this.Spoke.render(f5); + this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; + this.Spoke.render(f5); + this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; + this.Spoke.render(f5); + this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; + this.Spoke.render(f5); + } + } + } - // Render gear - this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; - this.Spoke.render( f5 ); - this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; - this.Spoke.render( f5 ); - this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; - this.Spoke.render( f5 ); - this.Spoke.rotateAngleX += ModelGearbox.QUARTER_TURN; - this.Spoke.render( f5 ); - } - } - } + /** + * Renders the gearbox. + */ + @Override + public void render( + final Entity entity, + final float f, + final float f1, + final float f2, + final float f3, + final float f4, + final float f5) { + // Render the transmission + this.Transmission.render(f5); - /** - * Renders the gearbox. - */ - @Override - public void render( final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5 ) - { - // Render the transmission - this.Transmission.render( f5 ); + // Set all the shafts and gears to the same rotation angle. + this.Shaft.rotateAngleX = this.rotationAngle; + this.Spoke.rotateAngleX = this.rotationAngle; - // Set all the shafts and gears to the same rotation angle. - this.Shaft.rotateAngleX = this.rotationAngle; - this.Spoke.rotateAngleX = this.rotationAngle; + // Render shafts + for (int side = 0; side < ModelGearbox.SIDE_COUNT; side++) { + this.renderShaft(side, f5); + } + } - // Render shafts - for( int side = 0; side < ModelGearbox.SIDE_COUNT; side++ ) - { - this.renderShaft( side, f5 ); - } + /** + * Updates the model to match the tile entity data. + * + * @param gearboxTile + */ + public void updateToTileEntity(final TileGearBox gearboxTile) { + // Set if each shaft has a gear. + for (int side = 0; side < ModelGearbox.SIDE_COUNT; side++) { + boolean withGear = !(gearboxTile.sideIsFacingCrankable[side]); + this.transformations[side].setIsRendered(true, withGear); + } - } - - /** - * Updates the model to match the tile entity data. - * - * @param gearboxTile - */ - public void updateToTileEntity( final TileGearBox gearboxTile ) - { - // Set if each shaft has a gear. - for( int side = 0; side < ModelGearbox.SIDE_COUNT; side++ ) - { - boolean withGear = !( gearboxTile.sideIsFacingCrankable[side] ); - this.transformations[side].setIsRendered( true, withGear ); - } - - // Set the rotation angle. - this.rotationAngle = gearboxTile.shaftRotation; - } + // Set the rotation angle. + this.rotationAngle = gearboxTile.shaftRotation; + } } diff --git a/src/main/java/thaumicenergistics/client/render/model/ModelGolemWifiBackpack.java b/src/main/java/thaumicenergistics/client/render/model/ModelGolemWifiBackpack.java index 5b638b9d..d04cd1b8 100644 --- a/src/main/java/thaumicenergistics/client/render/model/ModelGolemWifiBackpack.java +++ b/src/main/java/thaumicenergistics/client/render/model/ModelGolemWifiBackpack.java @@ -1,6 +1,5 @@ package thaumicenergistics.client.render.model; -import org.lwjgl.opengl.GL11; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -9,6 +8,7 @@ import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; +import org.lwjgl.opengl.GL11; import thaumicenergistics.common.items.ItemGolemWirelessBackpack; import thaumicenergistics.common.items.ItemGolemWirelessBackpack.BackpackSkins; @@ -19,184 +19,177 @@ import thaumicenergistics.common.items.ItemGolemWirelessBackpack.BackpackSkins; * */ @SideOnly(Side.CLIENT) -public class ModelGolemWifiBackpack - extends ModelBase -{ - /** - * Submodels - */ - private final ModelRenderer Antenna, PackBack, PackFront; +public class ModelGolemWifiBackpack extends ModelBase { + /** + * Submodels + */ + private final ModelRenderer Antenna, PackBack, PackFront; - /** - * Pearl UV coords. - */ - private final float pearl_MinU, pearl_MaxU, pearl_MinV, pearl_MaxV; + /** + * Pearl UV coords. + */ + private final float pearl_MinU, pearl_MaxU, pearl_MinV, pearl_MaxV; - /** - * Scale of the fluix pearls - */ - private final float pearlScale = 0.2f; + /** + * Scale of the fluix pearls + */ + private final float pearlScale = 0.2f; - /** - * Distance from edge to edge of the antenna - */ - private final float antennaWidth = 0.32f; + /** + * Distance from edge to edge of the antenna + */ + private final float antennaWidth = 0.32f; - /** - * Distance from the antenna to render the pearl faces - */ - private final float pearl_FaceDistance, pearl_2FD; + /** + * Distance from the antenna to render the pearl faces + */ + private final float pearl_FaceDistance, pearl_2FD; - /** - * True if the pearl display list is compiled - */ - private boolean isPearlCompiled = false; + /** + * True if the pearl display list is compiled + */ + private boolean isPearlCompiled = false; - /** - * ID of the pearl display list. - */ - private int pearlDispListID = -1; + /** + * ID of the pearl display list. + */ + private int pearlDispListID = -1; - public ModelGolemWifiBackpack() - { - this.textureWidth = 16; - this.textureHeight = 16; + public ModelGolemWifiBackpack() { + this.textureWidth = 16; + this.textureHeight = 16; - this.Antenna = new ModelRenderer( this, 10, 0 ); - this.Antenna.addBox( -0.5f, -6f, -0.5f, 1, 3, 1 ); - this.Antenna.setRotationPoint( 0, 0, 0f ); - this.Antenna.setTextureSize( this.textureWidth, this.textureHeight ); - this.Antenna.mirror = true; - this.setSubmodelRotation( this.Antenna, 3.14f, 0, 0 ); + this.Antenna = new ModelRenderer(this, 10, 0); + this.Antenna.addBox(-0.5f, -6f, -0.5f, 1, 3, 1); + this.Antenna.setRotationPoint(0, 0, 0f); + this.Antenna.setTextureSize(this.textureWidth, this.textureHeight); + this.Antenna.mirror = true; + this.setSubmodelRotation(this.Antenna, 3.14f, 0, 0); - this.PackBack = new ModelRenderer( this, 0, 0 ); - this.PackBack.addBox( -1f, -3f, -3f, 2, 6, 6 ); - this.PackBack.setRotationPoint( 0, 0, 0f ); - this.PackBack.setTextureSize( this.textureWidth, this.textureHeight ); - this.PackBack.mirror = true; - this.setSubmodelRotation( this.PackBack, 3.14f, 0, 0 ); + this.PackBack = new ModelRenderer(this, 0, 0); + this.PackBack.addBox(-1f, -3f, -3f, 2, 6, 6); + this.PackBack.setRotationPoint(0, 0, 0f); + this.PackBack.setTextureSize(this.textureWidth, this.textureHeight); + this.PackBack.mirror = true; + this.setSubmodelRotation(this.PackBack, 3.14f, 0, 0); - this.PackFront = new ModelRenderer( this, 2, 0 ); - this.PackFront.addBox( -1.5f, -1f, -2f, 1, 2, 4 ); - this.PackFront.setRotationPoint( 0, 0, 0f ); - this.PackFront.setTextureSize( this.textureWidth, this.textureHeight ); - this.PackFront.mirror = true; - this.setSubmodelRotation( this.PackFront, 3.14f, 0, 0 ); + this.PackFront = new ModelRenderer(this, 2, 0); + this.PackFront.addBox(-1.5f, -1f, -2f, 1, 2, 4); + this.PackFront.setRotationPoint(0, 0, 0f); + this.PackFront.setTextureSize(this.textureWidth, this.textureHeight); + this.PackFront.mirror = true; + this.setSubmodelRotation(this.PackFront, 3.14f, 0, 0); - this.pearl_MinU = 8.0f / this.textureWidth; - this.pearl_MaxU = 13.5f / this.textureWidth; - this.pearl_MinV = 6.0f / this.textureHeight; - this.pearl_MaxV = 11.5f / this.textureHeight; + this.pearl_MinU = 8.0f / this.textureWidth; + this.pearl_MaxU = 13.5f / this.textureWidth; + this.pearl_MinV = 6.0f / this.textureHeight; + this.pearl_MaxV = 11.5f / this.textureHeight; - this.pearl_FaceDistance = -0.013f / this.pearlScale; - this.pearl_2FD = this.pearl_FaceDistance + this.pearl_FaceDistance; - } + this.pearl_FaceDistance = -0.013f / this.pearlScale; + this.pearl_2FD = this.pearl_FaceDistance + this.pearl_FaceDistance; + } - private void compilePearl() - { - // Create a new list - this.pearlDispListID = GLAllocation.generateDisplayLists( 1 ); - GL11.glNewList( this.pearlDispListID, GL11.GL_COMPILE ); + private void compilePearl() { + // Create a new list + this.pearlDispListID = GLAllocation.generateDisplayLists(1); + GL11.glNewList(this.pearlDispListID, GL11.GL_COMPILE); - // Get the tesselator - Tessellator tess = Tessellator.instance; + // Get the tesselator + Tessellator tess = Tessellator.instance; - // Move to the left of the antenna - GL11.glTranslatef( -0.0955f, 0.275f, -0.045f ); + // Move to the left of the antenna + GL11.glTranslatef(-0.0955f, 0.275f, -0.045f); - // Scale down - GL11.glScalef( this.pearlScale, this.pearlScale, this.pearlScale ); + // Scale down + GL11.glScalef(this.pearlScale, this.pearlScale, this.pearlScale); - // Draw left - this.drawPearlFaces( tess, this.pearl_MinU, this.pearl_MaxU ); + // Draw left + this.drawPearlFaces(tess, this.pearl_MinU, this.pearl_MaxU); - // Move to the right of the antenna - GL11.glTranslatef( 0.0f, 0.0f, this.antennaWidth - this.pearl_2FD ); + // Move to the right of the antenna + GL11.glTranslatef(0.0f, 0.0f, this.antennaWidth - this.pearl_2FD); - // Draw right - this.drawPearlFaces( tess, this.pearl_MaxU, this.pearl_MinU ); + // Draw right + this.drawPearlFaces(tess, this.pearl_MaxU, this.pearl_MinU); - // Rotate 90 - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); + // Rotate 90 + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); - // Move to the front of the antenna - GL11.glTranslatef( -this.antennaWidth - this.pearl_FaceDistance, 0.0f, this.antennaWidth + this.pearl_FaceDistance ); + // Move to the front of the antenna + GL11.glTranslatef( + -this.antennaWidth - this.pearl_FaceDistance, 0.0f, this.antennaWidth + this.pearl_FaceDistance); - // Draw front - this.drawPearlFaces( tess, this.pearl_MaxU, this.pearl_MinU ); + // Draw front + this.drawPearlFaces(tess, this.pearl_MaxU, this.pearl_MinU); - // Move to the back of the antenna - GL11.glTranslatef( 0.0f, 0.0f, this.antennaWidth - this.pearl_2FD ); + // Move to the back of the antenna + GL11.glTranslatef(0.0f, 0.0f, this.antennaWidth - this.pearl_2FD); - // Draw back - this.drawPearlFaces( tess, this.pearl_MinU, this.pearl_MaxU ); + // Draw back + this.drawPearlFaces(tess, this.pearl_MinU, this.pearl_MaxU); - // End the list - GL11.glEndList(); - this.isPearlCompiled = true; - } + // End the list + GL11.glEndList(); + this.isPearlCompiled = true; + } - private void drawPearlFaces( final Tessellator tess, final float minU, final float maxU ) - { - tess.startDrawingQuads(); - // Face - tess.addVertexWithUV( 0.0D, 0.0D, 0.0D, maxU, this.pearl_MaxV ); - tess.addVertexWithUV( 1.0D, 0.0D, 0.0D, minU, this.pearl_MaxV ); - tess.addVertexWithUV( 1.0D, 1.0D, 0.0D, minU, this.pearl_MinV ); - tess.addVertexWithUV( 0.0D, 1.0D, 0.0D, maxU, this.pearl_MinV ); - // Back-face - tess.addVertexWithUV( 0.0D, 1.0D, 0.0D, maxU, this.pearl_MinV ); - tess.addVertexWithUV( 1.0D, 1.0D, 0.0D, minU, this.pearl_MinV ); - tess.addVertexWithUV( 1.0D, 0.0D, 0.0D, minU, this.pearl_MaxV ); - tess.addVertexWithUV( 0.0D, 0.0D, 0.0D, maxU, this.pearl_MaxV ); - tess.draw(); - } + private void drawPearlFaces(final Tessellator tess, final float minU, final float maxU) { + tess.startDrawingQuads(); + // Face + tess.addVertexWithUV(0.0D, 0.0D, 0.0D, maxU, this.pearl_MaxV); + tess.addVertexWithUV(1.0D, 0.0D, 0.0D, minU, this.pearl_MaxV); + tess.addVertexWithUV(1.0D, 1.0D, 0.0D, minU, this.pearl_MinV); + tess.addVertexWithUV(0.0D, 1.0D, 0.0D, maxU, this.pearl_MinV); + // Back-face + tess.addVertexWithUV(0.0D, 1.0D, 0.0D, maxU, this.pearl_MinV); + tess.addVertexWithUV(1.0D, 1.0D, 0.0D, minU, this.pearl_MinV); + tess.addVertexWithUV(1.0D, 0.0D, 0.0D, minU, this.pearl_MaxV); + tess.addVertexWithUV(0.0D, 0.0D, 0.0D, maxU, this.pearl_MaxV); + tess.draw(); + } - private void renderPearl( final float pearlRotation, final boolean inRange ) - { - if( !inRange ) - { - // Set red tint - GL11.glColor3f( 1.0f, 0.0f, 0.0f ); - } + private void renderPearl(final float pearlRotation, final boolean inRange) { + if (!inRange) { + // Set red tint + GL11.glColor3f(1.0f, 0.0f, 0.0f); + } - // Apply Y rotation - GL11.glRotatef( pearlRotation, 0.0f, 1.0f, 0.0f ); + // Apply Y rotation + GL11.glRotatef(pearlRotation, 0.0f, 1.0f, 0.0f); - // Is the pearl compiled? - if( !this.isPearlCompiled ) - { - // Compile the pearl - this.compilePearl(); - } + // Is the pearl compiled? + if (!this.isPearlCompiled) { + // Compile the pearl + this.compilePearl(); + } - // Draw the pearl - GL11.glCallList( this.pearlDispListID ); + // Draw the pearl + GL11.glCallList(this.pearlDispListID); + } - } + private void setSubmodelRotation(final ModelRenderer model, final float x, final float y, final float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } - private void setSubmodelRotation( final ModelRenderer model, final float x, final float y, final float z ) - { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - - @Override - public void render( final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, - final float f5 ) - { - this.render( 0.03f, f5, true, BackpackSkins.Thaumium ); - } - - public void render( final float pearlRotation, final float f5, final boolean inRange, final BackpackSkins skin ) - { - Minecraft.getMinecraft().renderEngine.bindTexture( skin.getTextureLocation() ); - this.PackBack.render( f5 ); - this.PackFront.render( f5 ); - this.Antenna.render( f5 ); - this.renderPearl( pearlRotation, inRange ); - - } + @Override + public void render( + final Entity entity, + final float f, + final float f1, + final float f2, + final float f3, + final float f4, + final float f5) { + this.render(0.03f, f5, true, BackpackSkins.Thaumium); + } + public void render(final float pearlRotation, final float f5, final boolean inRange, final BackpackSkins skin) { + Minecraft.getMinecraft().renderEngine.bindTexture(skin.getTextureLocation()); + this.PackBack.render(f5); + this.PackFront.render(f5); + this.Antenna.render(f5); + this.renderPearl(pearlRotation, inRange); + } } diff --git a/src/main/java/thaumicenergistics/client/textures/AEStateIconsEnum.java b/src/main/java/thaumicenergistics/client/textures/AEStateIconsEnum.java index f9e5d3c9..7e4f34b7 100644 --- a/src/main/java/thaumicenergistics/client/textures/AEStateIconsEnum.java +++ b/src/main/java/thaumicenergistics/client/textures/AEStateIconsEnum.java @@ -8,155 +8,145 @@ import net.minecraft.util.ResourceLocation; * @author Nividica * */ -public enum AEStateIconsEnum - implements IStateIconTexture -{ - // Redstone modes - REDSTONE_LOW (0, 0), - REDSTONE_HIGH (16, 0), - REDSTONE_PULSE (32, 0), - REDSTONE_IGNORE (48, 0), +public enum AEStateIconsEnum implements IStateIconTexture { + // Redstone modes + REDSTONE_LOW(0, 0), + REDSTONE_HIGH(16, 0), + REDSTONE_PULSE(32, 0), + REDSTONE_IGNORE(48, 0), - // Slot backgrounds - VIEW_CELL_BACKGROUND (224, 64), - UPGRADE_CARD_BACKGROUND (240, 208), - ME_CELL_BACKGROUND (240, 0), - PATTERN_CELL_BACKGROUND (240, 128), + // Slot backgrounds + VIEW_CELL_BACKGROUND(224, 64), + UPGRADE_CARD_BACKGROUND(240, 208), + ME_CELL_BACKGROUND(240, 0), + PATTERN_CELL_BACKGROUND(240, 128), - // Buttons - REGULAR_BUTTON (240, 240), - TAB_BUTTON (208, 0, 22, 22), + // Buttons + REGULAR_BUTTON(240, 240), + TAB_BUTTON(208, 0, 22, 22), - // Sorting modes - SORT_MODE_ALPHABETIC (0, 64), - SORT_MODE_AMOUNT (16, 64), - SORT_MODE_MOD (80, 64), - SORT_MODE_INVTWEAK (64, 64), + // Sorting modes + SORT_MODE_ALPHABETIC(0, 64), + SORT_MODE_AMOUNT(16, 64), + SORT_MODE_MOD(80, 64), + SORT_MODE_INVTWEAK(64, 64), - // Sorting directions - SORT_DIR_ASC (0, 48), - SORT_DIR_DEC (16, 48), + // Sorting directions + SORT_DIR_ASC(0, 48), + SORT_DIR_DEC(16, 48), - // View types - VIEW_TYPE_STORED (0, 16), - VIEW_TYPE_ALL (32, 16), - VIEW_TYPE_CRAFT (48, 16), + // View types + VIEW_TYPE_STORED(0, 16), + VIEW_TYPE_ALL(32, 16), + VIEW_TYPE_CRAFT(48, 16), - // Terminal styles - TERM_STYLE_TALL (0, 208), - TERM_STYLE_SMALL (16, 208), + // Terminal styles + TERM_STYLE_TALL(0, 208), + TERM_STYLE_SMALL(16, 208), - // Search modes - SEARCH_MODE_AUTO (48, 32), - SEARCH_MODE_MANUAL (64, 32), - SEARCH_MODE_NEI_AUTO (80, 32), - SEARCH_MODE_NEI_MANUAL (96, 32), + // Search modes + SEARCH_MODE_AUTO(48, 32), + SEARCH_MODE_MANUAL(64, 32), + SEARCH_MODE_NEI_AUTO(80, 32), + SEARCH_MODE_NEI_MANUAL(96, 32), - // Misc - WRENCH (32, 64), - DISABLED (0, 128), - ENABLED (16, 128), - SAVE (0, 176), - DELETE (0, 192), - CLEAR_GRID (96, 0), - ARROW_DOWN (128, 0), + // Misc + WRENCH(32, 64), + DISABLED(0, 128), + ENABLED(16, 128), + SAVE(0, 176), + DELETE(0, 192), + CLEAR_GRID(96, 0), + ARROW_DOWN(128, 0), - CRAFT_ONLY(48, 16), - CRAFT_EITHER(32, 16); + CRAFT_ONLY(48, 16), + CRAFT_EITHER(32, 16); - /** - * Location of the AE states texture - */ - public static final ResourceLocation AE_STATES_TEXTURE = new ResourceLocation( "appliedenergistics2", "textures/guis/states.png" ); + /** + * Location of the AE states texture + */ + public static final ResourceLocation AE_STATES_TEXTURE = + new ResourceLocation("appliedenergistics2", "textures/guis/states.png"); - /** - * Width and height of standard icons. - */ - public static final int STANDARD_ICON_SIZE = 16; + /** + * Width and height of standard icons. + */ + public static final int STANDARD_ICON_SIZE = 16; - /** - * X position in the texture this icon is located at. - */ - private int minU; + /** + * X position in the texture this icon is located at. + */ + private int minU; - /** - * Y position in the texture this icon is located at. - */ - private int minV; + /** + * Y position in the texture this icon is located at. + */ + private int minV; - /** - * Width of the icon - */ - private int width; + /** + * Width of the icon + */ + private int width; - /** - * Height of the icon - */ - private int height; + /** + * Height of the icon + */ + private int height; - /** - * Standard icon constructor - * - * @param u - * @param v - */ - private AEStateIconsEnum( final int u, final int v ) - { - this( u, v, STANDARD_ICON_SIZE, STANDARD_ICON_SIZE ); - } + /** + * Standard icon constructor + * + * @param u + * @param v + */ + private AEStateIconsEnum(final int u, final int v) { + this(u, v, STANDARD_ICON_SIZE, STANDARD_ICON_SIZE); + } - /** - * Icon constructor - * - * @param u - * @param v - * @param width - * @param height - */ - private AEStateIconsEnum( final int u, final int v, final int width, final int height ) - { - // Set the u - this.minU = u; + /** + * Icon constructor + * + * @param u + * @param v + * @param width + * @param height + */ + private AEStateIconsEnum(final int u, final int v, final int width, final int height) { + // Set the u + this.minU = u; - // Set the v - this.minV = v; + // Set the v + this.minV = v; - // Set width - this.width = width; + // Set width + this.width = width; - // Set height - this.height = height; + // Set height + this.height = height; + } - } + @Override + public int getHeight() { + return this.height; + } - @Override - public int getHeight() - { - return this.height; - } + @Override + public ResourceLocation getTexture() { + return AEStateIconsEnum.AE_STATES_TEXTURE; + } - @Override - public ResourceLocation getTexture() - { - return AEStateIconsEnum.AE_STATES_TEXTURE; - } + @Override + public int getU() { + return this.minU; + } - @Override - public int getU() - { - return this.minU; - } - - @Override - public int getV() - { - return this.minV; - } - - @Override - public int getWidth() - { - return this.width; - } + @Override + public int getV() { + return this.minV; + } + @Override + public int getWidth() { + return this.width; + } } diff --git a/src/main/java/thaumicenergistics/client/textures/BlockTextureManager.java b/src/main/java/thaumicenergistics/client/textures/BlockTextureManager.java index b2d457ca..f12bc4ba 100644 --- a/src/main/java/thaumicenergistics/client/textures/BlockTextureManager.java +++ b/src/main/java/thaumicenergistics/client/textures/BlockTextureManager.java @@ -1,10 +1,10 @@ package thaumicenergistics.client.textures; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.util.Arrays; import java.util.Collections; import java.util.List; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import thaumicenergistics.common.ThaumicEnergistics; @@ -16,101 +16,117 @@ import thaumicenergistics.common.ThaumicEnergistics; * */ @SideOnly(Side.CLIENT) -public enum BlockTextureManager -{ - BUS_COLOR (TextureTypes.Part, new String[] { "bus.color.border", "bus.color.light", "bus.color.side" }), +public enum BlockTextureManager { + BUS_COLOR(TextureTypes.Part, new String[] {"bus.color.border", "bus.color.light", "bus.color.side"}), - ESSENTIA_IMPORT_BUS (TextureTypes.Part, new String[] { "essentia.import.bus.face", "essentia.import.bus.overlay", - "essentia.import.bus.chamber", "essentia.import.bus.side" }), + ESSENTIA_IMPORT_BUS(TextureTypes.Part, new String[] { + "essentia.import.bus.face", + "essentia.import.bus.overlay", + "essentia.import.bus.chamber", + "essentia.import.bus.side" + }), - ESSENTIA_LEVEL_EMITTER (TextureTypes.Part, new String[] { "essentia.level.emitter.base", "essentia.level.emitter.active", - "essentia.level.emitter.inactive" }), + ESSENTIA_LEVEL_EMITTER(TextureTypes.Part, new String[] { + "essentia.level.emitter.base", "essentia.level.emitter.active", "essentia.level.emitter.inactive" + }), - ESSENTIA_STORAGE_BUS (TextureTypes.Part, new String[] { "essentia.storage.bus.face", "essentia.storage.bus.overlay", - "essentia.storage.bus.side" }), + ESSENTIA_STORAGE_BUS( + TextureTypes.Part, + new String[] {"essentia.storage.bus.face", "essentia.storage.bus.overlay", "essentia.storage.bus.side"}), - ESSENTIA_EXPORT_BUS (TextureTypes.Part, new String[] { "essentia.export.bus.face", "essentia.export.bus.overlay", - "essentia.export.bus.chamber", "essentia.export.bus.side" }), + ESSENTIA_EXPORT_BUS(TextureTypes.Part, new String[] { + "essentia.export.bus.face", + "essentia.export.bus.overlay", + "essentia.export.bus.chamber", + "essentia.export.bus.side" + }), - ESSENTIA_TERMINAL (TextureTypes.Part, new String[] { "essentia.terminal.overlay.dark", "essentia.terminal.overlay.medium", - "essentia.terminal.overlay.light", "essentia.terminal.side", "essentia.termina.border" }), + ESSENTIA_TERMINAL(TextureTypes.Part, new String[] { + "essentia.terminal.overlay.dark", + "essentia.terminal.overlay.medium", + "essentia.terminal.overlay.light", + "essentia.terminal.side", + "essentia.termina.border" + }), - ESSENTIA_PROVIDER (TextureTypes.Block, new String[] { "essentia.provider", "essentia.provider.overlay" }), + ESSENTIA_PROVIDER(TextureTypes.Block, new String[] {"essentia.provider", "essentia.provider.overlay"}), - INFUSION_PROVIDER (TextureTypes.Block, new String[] { "infusion.provider", "infusion.provider.overlay" }), + INFUSION_PROVIDER(TextureTypes.Block, new String[] {"infusion.provider", "infusion.provider.overlay"}), - ARCANE_CRAFTING_TERMINAL (TextureTypes.Part, new String[] { "arcane.crafting.overlay1", "arcane.crafting.overlay2", - "arcane.crafting.overlay3", "arcane.crafting.side", "arcane.crafting.overlay4" }), + ARCANE_CRAFTING_TERMINAL(TextureTypes.Part, new String[] { + "arcane.crafting.overlay1", + "arcane.crafting.overlay2", + "arcane.crafting.overlay3", + "arcane.crafting.side", + "arcane.crafting.overlay4" + }), - VIS_RELAY_INTERFACE (TextureTypes.Part, new String[] { "vis.interface", "vis.interface.runes", "vis.interface.side" }), + VIS_RELAY_INTERFACE(TextureTypes.Part, new String[] {"vis.interface", "vis.interface.runes", "vis.interface.side"}), - GEAR_BOX (TextureTypes.Block, new String[] { "gear.box.fallback", "golem.gear.box.fallback" }), + GEAR_BOX(TextureTypes.Block, new String[] {"gear.box.fallback", "golem.gear.box.fallback"}), - ESSENTIA_CELL_WORKBENCH (TextureTypes.Block, new String[] { "essentia.cell.workbench.top", "essentia.cell.workbench.bottom", - "essentia.cell.workbench.side" }), + ESSENTIA_CELL_WORKBENCH(TextureTypes.Block, new String[] { + "essentia.cell.workbench.top", "essentia.cell.workbench.bottom", "essentia.cell.workbench.side" + }), - GASEOUS_ESSENTIA (TextureTypes.Block, new String[] { "essentia.gas" }), + GASEOUS_ESSENTIA(TextureTypes.Block, new String[] {"essentia.gas"}), - ARCANE_ASSEMBLER (TextureTypes.Block, new String[] { "arcane.assembler.fallback" }), + ARCANE_ASSEMBLER(TextureTypes.Block, new String[] {"arcane.assembler.fallback"}), - KNOWLEDGE_INSCRIBER (TextureTypes.Block, - new String[] { "knowledge.inscriber.side", "knowledge.inscriber.top", "knowledge.inscriber.bottom" }), + KNOWLEDGE_INSCRIBER( + TextureTypes.Block, + new String[] {"knowledge.inscriber.side", "knowledge.inscriber.top", "knowledge.inscriber.bottom"}), - ESSENTIA_VIBRATION_CHAMBER (TextureTypes.Block, new String[] { "e.vibration.input", "e.vibration.face.off", "e.vibration.face.ignis", - "e.vibration.face.potentia" }), + ESSENTIA_VIBRATION_CHAMBER(TextureTypes.Block, new String[] { + "e.vibration.input", "e.vibration.face.off", "e.vibration.face.ignis", "e.vibration.face.potentia" + }), - DISTILLATION_ENCODER (TextureTypes.Block, - new String[] { "knowledge.inscriber.side", "distillation.encoder.face", "knowledge.inscriber.bottom" }); + DISTILLATION_ENCODER( + TextureTypes.Block, + new String[] {"knowledge.inscriber.side", "distillation.encoder.face", "knowledge.inscriber.bottom"}); - private enum TextureTypes - { - Block, - Part; - } + private enum TextureTypes { + Block, + Part; + } - /** - * Cache of the enum values - */ - public static final List ALLVALUES = Collections.unmodifiableList( Arrays.asList( BlockTextureManager.values() ) ); + /** + * Cache of the enum values + */ + public static final List ALLVALUES = + Collections.unmodifiableList(Arrays.asList(BlockTextureManager.values())); - private TextureTypes textureType; + private TextureTypes textureType; - private String[] textureNames; + private String[] textureNames; - private IIcon[] textures; + private IIcon[] textures; - private BlockTextureManager( final TextureTypes textureType, final String[] textureNames ) - { - this.textureType = textureType; - this.textureNames = textureNames; - this.textures = new IIcon[this.textureNames.length]; - } + private BlockTextureManager(final TextureTypes textureType, final String[] textureNames) { + this.textureType = textureType; + this.textureNames = textureNames; + this.textures = new IIcon[this.textureNames.length]; + } - public IIcon getTexture() - { - return this.textures[0]; - } + public IIcon getTexture() { + return this.textures[0]; + } - public IIcon[] getTextures() - { - return this.textures; - } + public IIcon[] getTextures() { + return this.textures; + } - public void registerTexture( final TextureMap textureMap ) - { - if( textureMap.getTextureType() == 0 ) - { - String header = ThaumicEnergistics.MOD_ID + ":"; + public void registerTexture(final TextureMap textureMap) { + if (textureMap.getTextureType() == 0) { + String header = ThaumicEnergistics.MOD_ID + ":"; - if( this.textureType == TextureTypes.Part ) - { - header += "parts/"; - } + if (this.textureType == TextureTypes.Part) { + header += "parts/"; + } - for( int i = 0; i < this.textureNames.length; i++ ) - { - this.textures[i] = textureMap.registerIcon( header + this.textureNames[i] ); - } - } - } + for (int i = 0; i < this.textureNames.length; i++) { + this.textures[i] = textureMap.registerIcon(header + this.textureNames[i]); + } + } + } } diff --git a/src/main/java/thaumicenergistics/client/textures/GuiTextureManager.java b/src/main/java/thaumicenergistics/client/textures/GuiTextureManager.java index 3eb00e3f..6e4b5c53 100644 --- a/src/main/java/thaumicenergistics/client/textures/GuiTextureManager.java +++ b/src/main/java/thaumicenergistics/client/textures/GuiTextureManager.java @@ -12,31 +12,27 @@ import thaumicenergistics.common.ThaumicEnergistics; * */ @SideOnly(Side.CLIENT) -public enum GuiTextureManager -{ - ESSENTIA_LEVEL_EMITTER ("essentia.level.emitter"), - ESSENTIA_STORAGE_BUS ("essentia.storage.bus"), - ESSENTIA_TERMINAL ("essentia.terminal"), - ESSENTIA_IO_BUS ("essentia.io.bus"), - ARCANE_CRAFTING_TERMINAL ("arcane.crafting"), - PRIORITY ("priority"), - CELL_WORKBENCH ("essentia.cell.workbench"), - ARCANE_ASSEMBLER ("arcane.assembler"), - KNOWLEDGE_INSCRIBER ("knowledge.inscriber"), - ESSENTIA_VIBRATION_CHAMBER ("essentia.vibration.chamber"), - DISTILLATION_ENCODER ("distillation.encoder"); +public enum GuiTextureManager { + ESSENTIA_LEVEL_EMITTER("essentia.level.emitter"), + ESSENTIA_STORAGE_BUS("essentia.storage.bus"), + ESSENTIA_TERMINAL("essentia.terminal"), + ESSENTIA_IO_BUS("essentia.io.bus"), + ARCANE_CRAFTING_TERMINAL("arcane.crafting"), + PRIORITY("priority"), + CELL_WORKBENCH("essentia.cell.workbench"), + ARCANE_ASSEMBLER("arcane.assembler"), + KNOWLEDGE_INSCRIBER("knowledge.inscriber"), + ESSENTIA_VIBRATION_CHAMBER("essentia.vibration.chamber"), + DISTILLATION_ENCODER("distillation.encoder"); - private ResourceLocation texture; + private ResourceLocation texture; - private GuiTextureManager( final String textureName ) - { - // Create the resource location - this.texture = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/gui/" + textureName + ".png" ); - } - - public ResourceLocation getTexture() - { - return this.texture; - } + private GuiTextureManager(final String textureName) { + // Create the resource location + this.texture = new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/gui/" + textureName + ".png"); + } + public ResourceLocation getTexture() { + return this.texture; + } } diff --git a/src/main/java/thaumicenergistics/client/textures/IStateIconTexture.java b/src/main/java/thaumicenergistics/client/textures/IStateIconTexture.java index a9de1048..e53a8ec9 100644 --- a/src/main/java/thaumicenergistics/client/textures/IStateIconTexture.java +++ b/src/main/java/thaumicenergistics/client/textures/IStateIconTexture.java @@ -9,41 +9,40 @@ import net.minecraft.util.ResourceLocation; * @author Nividica * */ -public interface IStateIconTexture -{ - /** - * Height of the icon. - * - * @return - */ - int getHeight(); +public interface IStateIconTexture { + /** + * Height of the icon. + * + * @return + */ + int getHeight(); - /** - * Texture the icon is in. - * - * @return - */ - @Nonnull - ResourceLocation getTexture(); + /** + * Texture the icon is in. + * + * @return + */ + @Nonnull + ResourceLocation getTexture(); - /** - * U coordinate of the icon. - * - * @return - */ - int getU(); + /** + * U coordinate of the icon. + * + * @return + */ + int getU(); - /** - * V coordinate of the icon. - * - * @return - */ - int getV(); + /** + * V coordinate of the icon. + * + * @return + */ + int getV(); - /** - * Width of the icon. - * - * @return - */ - int getWidth(); + /** + * Width of the icon. + * + * @return + */ + int getWidth(); } diff --git a/src/main/java/thaumicenergistics/client/textures/ThEStateIconsEnum.java b/src/main/java/thaumicenergistics/client/textures/ThEStateIconsEnum.java index 4f987fa9..f05b9f27 100644 --- a/src/main/java/thaumicenergistics/client/textures/ThEStateIconsEnum.java +++ b/src/main/java/thaumicenergistics/client/textures/ThEStateIconsEnum.java @@ -9,104 +9,94 @@ import thaumicenergistics.common.ThaumicEnergistics; * @author Nividica * */ -public enum ThEStateIconsEnum - implements IStateIconTexture -{ - SWAP (0, 0); +public enum ThEStateIconsEnum implements IStateIconTexture { + SWAP(0, 0); - /** - * Location of the AE states texture - */ - public static final ResourceLocation THE_STATES_TEXTURE = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/gui/states.png" ); + /** + * Location of the AE states texture + */ + public static final ResourceLocation THE_STATES_TEXTURE = + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/gui/states.png"); - /** - * Width and height of standard icons. - */ - private static final int STANDARD_ICON_SIZE = 16; + /** + * Width and height of standard icons. + */ + private static final int STANDARD_ICON_SIZE = 16; - /** - * X position in the texture this icon is located at. - */ - private int minU; + /** + * X position in the texture this icon is located at. + */ + private int minU; - /** - * Y position in the texture this icon is located at. - */ - private int minV; + /** + * Y position in the texture this icon is located at. + */ + private int minV; - /** - * Width of the icon - */ - private int width; + /** + * Width of the icon + */ + private int width; - /** - * Height of the icon - */ - private int height; + /** + * Height of the icon + */ + private int height; - /** - * Standard icon constructor - * - * @param u - * @param v - */ - private ThEStateIconsEnum( final int u, final int v ) - { - this( u, v, STANDARD_ICON_SIZE, STANDARD_ICON_SIZE ); - } + /** + * Standard icon constructor + * + * @param u + * @param v + */ + private ThEStateIconsEnum(final int u, final int v) { + this(u, v, STANDARD_ICON_SIZE, STANDARD_ICON_SIZE); + } - /** - * Icon constructor - * - * @param u - * @param v - * @param width - * @param height - */ - private ThEStateIconsEnum( final int u, final int v, final int width, final int height ) - { - // Set the u - this.minU = u; + /** + * Icon constructor + * + * @param u + * @param v + * @param width + * @param height + */ + private ThEStateIconsEnum(final int u, final int v, final int width, final int height) { + // Set the u + this.minU = u; - // Set the v - this.minV = v; + // Set the v + this.minV = v; - // Set width - this.width = width; + // Set width + this.width = width; - // Set height - this.height = height; + // Set height + this.height = height; + } - } + @Override + public int getHeight() { + return this.height; + } - @Override - public int getHeight() - { - return this.height; - } + @Override + public ResourceLocation getTexture() { + return ThEStateIconsEnum.THE_STATES_TEXTURE; + } - @Override - public ResourceLocation getTexture() - { - return ThEStateIconsEnum.THE_STATES_TEXTURE; - } + @Override + public int getU() { + return this.minU; + } - @Override - public int getU() - { - return this.minU; - } - - @Override - public int getV() - { - return this.minV; - } - - @Override - public int getWidth() - { - return this.width; - } + @Override + public int getV() { + return this.minV; + } + @Override + public int getWidth() { + return this.width; + } } diff --git a/src/main/java/thaumicenergistics/common/CommonProxy.java b/src/main/java/thaumicenergistics/common/CommonProxy.java index aacb64d1..e5d8a693 100644 --- a/src/main/java/thaumicenergistics/common/CommonProxy.java +++ b/src/main/java/thaumicenergistics/common/CommonProxy.java @@ -19,81 +19,69 @@ import thaumicenergistics.common.tiles.TileEnum; * @author Nividica * */ -public class CommonProxy -{ - /** - * Registers blocks with the game. - */ - public void registerBlocks() - { - for( BlockEnum block : BlockEnum.VALUES ) - { - GameRegistry.registerBlock( block.getBlock(), block.itemBlockClass, block.getUnlocalizedName() ); - } - } +public class CommonProxy { + /** + * Registers blocks with the game. + */ + public void registerBlocks() { + for (BlockEnum block : BlockEnum.VALUES) { + GameRegistry.registerBlock(block.getBlock(), block.itemBlockClass, block.getUnlocalizedName()); + } + } - /** - * Registers all ThE features - */ - public void registerFeatures() - { - FeatureRegistry.instance().registerFeatures(); - } + /** + * Registers all ThE features + */ + public void registerFeatures() { + FeatureRegistry.instance().registerFeatures(); + } - /** - * Registers fluids with the game. - */ - public void registerFluids() - { - GaseousEssentia.registerGases(); - } + /** + * Registers fluids with the game. + */ + public void registerFluids() { + GaseousEssentia.registerGases(); + } - /** - * Registers items with the game. - */ - public void registerItems() - { - for( ItemEnum item : ItemEnum.VALUES ) - { - GameRegistry.registerItem( item.getItem(), item.getInternalName() ); - } + /** + * Registers items with the game. + */ + public void registerItems() { + for (ItemEnum item : ItemEnum.VALUES) { + GameRegistry.registerItem(item.getItem(), item.getInternalName()); + } - // Add iron gear to the oredic - OreDictionary.registerOre( "gearIron", ItemMaterial.MaterialTypes.IRON_GEAR.getStack() ); + // Add iron gear to the oredic + OreDictionary.registerOre("gearIron", ItemMaterial.MaterialTypes.IRON_GEAR.getStack()); - // Add the shard from thaumcraft so that AE will suggest replacements. - OreDictionary.registerOre( "materialAspectShard", new ItemStack( ConfigItems.itemShard, 1, OreDictionary.WILDCARD_VALUE ) ); - } + // Add the shard from thaumcraft so that AE will suggest replacements. + OreDictionary.registerOre( + "materialAspectShard", new ItemStack(ConfigItems.itemShard, 1, OreDictionary.WILDCARD_VALUE)); + } - /** - * Used by client proxy - */ - public void registerRenderers() - { - // Ignored server side. - } + /** + * Used by client proxy + */ + public void registerRenderers() { + // Ignored server side. + } - /** - * Adds tile entities to the AppEng2 SpatialIO whitelist - */ - public void registerSpatialIOMovables() - { - IMovableRegistry movableRegistry = AEApi.instance().registries().movable(); - for( TileEnum tile : TileEnum.values() ) - { - movableRegistry.whiteListTileEntity( tile.getTileClass() ); - } - } - - /** - * Registers tile entities with the game. - */ - public void registerTileEntities() - { - for( TileEnum tile : TileEnum.values() ) - { - GameRegistry.registerTileEntity( tile.getTileClass(), tile.getTileID() ); - } - } + /** + * Adds tile entities to the AppEng2 SpatialIO whitelist + */ + public void registerSpatialIOMovables() { + IMovableRegistry movableRegistry = AEApi.instance().registries().movable(); + for (TileEnum tile : TileEnum.values()) { + movableRegistry.whiteListTileEntity(tile.getTileClass()); + } + } + /** + * Registers tile entities with the game. + */ + public void registerTileEntities() { + for (TileEnum tile : TileEnum.values()) { + GameRegistry.registerTileEntity(tile.getTileClass(), tile.getTileID()); + } + } } diff --git a/src/main/java/thaumicenergistics/common/ConfigurationHandler.java b/src/main/java/thaumicenergistics/common/ConfigurationHandler.java index e28d1fec..6f58a4f7 100644 --- a/src/main/java/thaumicenergistics/common/ConfigurationHandler.java +++ b/src/main/java/thaumicenergistics/common/ConfigurationHandler.java @@ -10,296 +10,287 @@ import thaumicenergistics.api.IThEConfig; * @author Nividica * */ -class ConfigurationHandler - implements IThEConfig -{ - private static ConfigurationHandler INSTANCE; +class ConfigurationHandler implements IThEConfig { + private static ConfigurationHandler INSTANCE; - /** - * Names of the categories. - */ - private static final String CATEGORY_CRAFTING = "crafting", - CATEGORY_CLIENT = "client", - CATEGORY_INTEGRATION = "integration"; + /** + * Names of the categories. + */ + private static final String CATEGORY_CRAFTING = "crafting", + CATEGORY_CLIENT = "client", + CATEGORY_INTEGRATION = "integration"; - /** - * Default values. - */ - private static final int DFT_CONVERSION_EXPONENT = 7; - private static final boolean DFT_CRAFT_ARCANE_ASSEMBLER = true, - DFT_CRAFT_ARCANE_CRAFTING_TERM = true, - DFT_CRAFT_DISTILLATION_PATTERN_ENCODER = true, - DFT_CRAFT_ESSENTIA_CELLS = true, - DFT_CRAFT_ESSENTIA_PROVIDER = true, - DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER = true, - DFT_CRAFT_GOLEM_BACKPACK = true, - DFT_CRAFT_INFUSION_PROVIDER = true, - DFT_CRAFT_IO_BUSES = true, - DFT_CRAFT_VIS_RELAY_INTERFACE = true, - DFT_CRAFT_WIRELESS_ESSENTIA_TERM = true, - DFT_DISABLE_GEARBOX = false, - DFT_ENABLE_QUARTZ_DUPE = true, - DFT_ENABLE_WRENCH_FOCUS = true, - DFT_EXTRACELLS_BLIST = true, - DFT_FORCE_TC_FACADES = true; + /** + * Default values. + */ + private static final int DFT_CONVERSION_EXPONENT = 7; - /** - * Mod configuration - */ - private Configuration configSettings; + private static final boolean DFT_CRAFT_ARCANE_ASSEMBLER = true, + DFT_CRAFT_ARCANE_CRAFTING_TERM = true, + DFT_CRAFT_DISTILLATION_PATTERN_ENCODER = true, + DFT_CRAFT_ESSENTIA_CELLS = true, + DFT_CRAFT_ESSENTIA_PROVIDER = true, + DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER = true, + DFT_CRAFT_GOLEM_BACKPACK = true, + DFT_CRAFT_INFUSION_PROVIDER = true, + DFT_CRAFT_IO_BUSES = true, + DFT_CRAFT_VIS_RELAY_INTERFACE = true, + DFT_CRAFT_WIRELESS_ESSENTIA_TERM = true, + DFT_DISABLE_GEARBOX = false, + DFT_ENABLE_QUARTZ_DUPE = true, + DFT_ENABLE_WRENCH_FOCUS = true, + DFT_EXTRACELLS_BLIST = true, + DFT_FORCE_TC_FACADES = true; - /** - * Controls the conversion ratio of essentia/fluid.
- * 1 essentia unit is converted to this many mb's of fluid. - */ - private int conversionMultiplier = (int)Math.pow( 2, DFT_CONVERSION_EXPONENT ); + /** + * Mod configuration + */ + private Configuration configSettings; - private boolean craft_Arcane_Assembler = DFT_CRAFT_ARCANE_ASSEMBLER, - craft_Arcane_Crafting_Term = DFT_CRAFT_ARCANE_CRAFTING_TERM, - craft_Distillation_Pattern_Encoder = DFT_CRAFT_DISTILLATION_PATTERN_ENCODER, - craft_Essentia_Cells = DFT_CRAFT_ESSENTIA_CELLS, - craft_Essentia_Provider = DFT_CRAFT_ESSENTIA_PROVIDER, - craft_Essentia_Vibration_Chamber = DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER, - craft_GolemBackpack = DFT_CRAFT_GOLEM_BACKPACK, - craft_Infusion_Provider = DFT_CRAFT_INFUSION_PROVIDER, - craft_IO_Buses = DFT_CRAFT_IO_BUSES, - craft_Vis_Relay_Interface = DFT_CRAFT_VIS_RELAY_INTERFACE, - craft_Wireless_Essentia_Term = DFT_CRAFT_WIRELESS_ESSENTIA_TERM, - disable_Gearbox = DFT_DISABLE_GEARBOX, - enable_Quartz_Dupe = DFT_ENABLE_QUARTZ_DUPE, - enable_Wrench_Focus = DFT_ENABLE_WRENCH_FOCUS, - extracells_Blist = DFT_EXTRACELLS_BLIST, - force_TC_Facades = DFT_FORCE_TC_FACADES; + /** + * Controls the conversion ratio of essentia/fluid.
+ * 1 essentia unit is converted to this many mb's of fluid. + */ + private int conversionMultiplier = (int) Math.pow(2, DFT_CONVERSION_EXPONENT); - private ConfigurationHandler( final Configuration config ) - { - this.configSettings = config; - this.synchronizeConfigFile(); - } + private boolean craft_Arcane_Assembler = DFT_CRAFT_ARCANE_ASSEMBLER, + craft_Arcane_Crafting_Term = DFT_CRAFT_ARCANE_CRAFTING_TERM, + craft_Distillation_Pattern_Encoder = DFT_CRAFT_DISTILLATION_PATTERN_ENCODER, + craft_Essentia_Cells = DFT_CRAFT_ESSENTIA_CELLS, + craft_Essentia_Provider = DFT_CRAFT_ESSENTIA_PROVIDER, + craft_Essentia_Vibration_Chamber = DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER, + craft_GolemBackpack = DFT_CRAFT_GOLEM_BACKPACK, + craft_Infusion_Provider = DFT_CRAFT_INFUSION_PROVIDER, + craft_IO_Buses = DFT_CRAFT_IO_BUSES, + craft_Vis_Relay_Interface = DFT_CRAFT_VIS_RELAY_INTERFACE, + craft_Wireless_Essentia_Term = DFT_CRAFT_WIRELESS_ESSENTIA_TERM, + disable_Gearbox = DFT_DISABLE_GEARBOX, + enable_Quartz_Dupe = DFT_ENABLE_QUARTZ_DUPE, + enable_Wrench_Focus = DFT_ENABLE_WRENCH_FOCUS, + extracells_Blist = DFT_EXTRACELLS_BLIST, + force_TC_Facades = DFT_FORCE_TC_FACADES; - /** - * Loads and synchronizes the config file. - * - * @param configFile - */ - public static IThEConfig loadAndSyncConfigFile( final File configFile ) - { - if( ConfigurationHandler.INSTANCE == null ) - { - ConfigurationHandler.INSTANCE = new ConfigurationHandler( new Configuration( configFile ) ); - } - return ConfigurationHandler.INSTANCE; - } + private ConfigurationHandler(final Configuration config) { + this.configSettings = config; + this.synchronizeConfigFile(); + } - /** - * Synchronizes the config file and the settings. - */ - private void synchronizeConfigFile() - { - // General ========================================================= - int fluidPow = this.configSettings - .getInt( - "Essentia Fluid Ratio Exponent", - Configuration.CATEGORY_GENERAL, - ConfigurationHandler.DFT_CONVERSION_EXPONENT, - 1, - 11, - "Controls the conversion ratio of essentia/fluid. 1 essentia is converted to (2^this) milibuckets of fluid. " + - "Please be aware that this value effects how much fluid is transferred through the AE system, which also effects transfer speed and power consumption. " + - "Values above 11 make it impossible to use fluid transfer devices such as the ME IO Port, or anything from EC2." ); - this.conversionMultiplier = (int)Math.pow( 2, Math.min( fluidPow, 11 ) ); + /** + * Loads and synchronizes the config file. + * + * @param configFile + */ + public static IThEConfig loadAndSyncConfigFile(final File configFile) { + if (ConfigurationHandler.INSTANCE == null) { + ConfigurationHandler.INSTANCE = new ConfigurationHandler(new Configuration(configFile)); + } + return ConfigurationHandler.INSTANCE; + } - // Crafting ======================================================== - this.craft_Arcane_Assembler = this.configSettings.getBoolean( - "Arcane Assembler", - CATEGORY_CRAFTING, DFT_CRAFT_ARCANE_ASSEMBLER, - "Controls if the Arcane Assembler can be crafted." ); + /** + * Synchronizes the config file and the settings. + */ + private void synchronizeConfigFile() { + // General ========================================================= + int fluidPow = this.configSettings.getInt( + "Essentia Fluid Ratio Exponent", + Configuration.CATEGORY_GENERAL, + ConfigurationHandler.DFT_CONVERSION_EXPONENT, + 1, + 11, + "Controls the conversion ratio of essentia/fluid. 1 essentia is converted to (2^this) milibuckets of fluid. " + + "Please be aware that this value effects how much fluid is transferred through the AE system, which also effects transfer speed and power consumption. " + + "Values above 11 make it impossible to use fluid transfer devices such as the ME IO Port, or anything from EC2."); + this.conversionMultiplier = (int) Math.pow(2, Math.min(fluidPow, 11)); - this.craft_Arcane_Crafting_Term = this.configSettings.getBoolean( - "Arcane Crafting Terminal", - CATEGORY_CRAFTING, DFT_CRAFT_ARCANE_CRAFTING_TERM, - "Controls if the Arcane Crafting Terminal can be crafted." ); + // Crafting ======================================================== + this.craft_Arcane_Assembler = this.configSettings.getBoolean( + "Arcane Assembler", + CATEGORY_CRAFTING, + DFT_CRAFT_ARCANE_ASSEMBLER, + "Controls if the Arcane Assembler can be crafted."); - this.craft_Distillation_Pattern_Encoder = this.configSettings.getBoolean( - "Distillation Pattern Encoder.", - CATEGORY_CRAFTING, DFT_CRAFT_DISTILLATION_PATTERN_ENCODER, - "Controls if the Distillation Pattern Encoder can be crafted." ); + this.craft_Arcane_Crafting_Term = this.configSettings.getBoolean( + "Arcane Crafting Terminal", + CATEGORY_CRAFTING, + DFT_CRAFT_ARCANE_CRAFTING_TERM, + "Controls if the Arcane Crafting Terminal can be crafted."); - this.craft_Essentia_Cells = this.configSettings.getBoolean( - "Essentia Cells", - CATEGORY_CRAFTING, DFT_CRAFT_ESSENTIA_CELLS, - "Controls if Essentia Cells and Components can be crafted." ); + this.craft_Distillation_Pattern_Encoder = this.configSettings.getBoolean( + "Distillation Pattern Encoder.", + CATEGORY_CRAFTING, + DFT_CRAFT_DISTILLATION_PATTERN_ENCODER, + "Controls if the Distillation Pattern Encoder can be crafted."); - this.craft_Essentia_Provider = this.configSettings.getBoolean( - "Essentia Provider", - CATEGORY_CRAFTING, DFT_CRAFT_ESSENTIA_PROVIDER, - "Controls if the Essentia Provider can be crafted." ); + this.craft_Essentia_Cells = this.configSettings.getBoolean( + "Essentia Cells", + CATEGORY_CRAFTING, + DFT_CRAFT_ESSENTIA_CELLS, + "Controls if Essentia Cells and Components can be crafted."); - this.craft_Essentia_Vibration_Chamber = this.configSettings.getBoolean( - "Essentia Vibration Chamber", - CATEGORY_CRAFTING, DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER, - "Controlls if the Essentia Vibration Chamber can be crafted." ); + this.craft_Essentia_Provider = this.configSettings.getBoolean( + "Essentia Provider", + CATEGORY_CRAFTING, + DFT_CRAFT_ESSENTIA_PROVIDER, + "Controls if the Essentia Provider can be crafted."); - this.craft_GolemBackpack = this.configSettings.getBoolean( - "Golem Wifi Backpack", - CATEGORY_CRAFTING, DFT_CRAFT_GOLEM_BACKPACK, - "Controls if the Golem Wifi Backpack can be crafted." ); + this.craft_Essentia_Vibration_Chamber = this.configSettings.getBoolean( + "Essentia Vibration Chamber", + CATEGORY_CRAFTING, + DFT_CRAFT_ESSENTIA_VIBRATION_CHAMBER, + "Controlls if the Essentia Vibration Chamber can be crafted."); - this.craft_Infusion_Provider = this.configSettings.getBoolean( - "Infusion Provider", - CATEGORY_CRAFTING, DFT_CRAFT_INFUSION_PROVIDER, - "Controls if the Infusion Provider can be crafted." ); + this.craft_GolemBackpack = this.configSettings.getBoolean( + "Golem Wifi Backpack", + CATEGORY_CRAFTING, + DFT_CRAFT_GOLEM_BACKPACK, + "Controls if the Golem Wifi Backpack can be crafted."); - this.craft_IO_Buses = this.configSettings.getBoolean( - "IO Buses", - CATEGORY_CRAFTING, DFT_CRAFT_IO_BUSES, - "Controls if the import and export buses can be crafted." ); + this.craft_Infusion_Provider = this.configSettings.getBoolean( + "Infusion Provider", + CATEGORY_CRAFTING, + DFT_CRAFT_INFUSION_PROVIDER, + "Controls if the Infusion Provider can be crafted."); - this.craft_Vis_Relay_Interface = this.configSettings.getBoolean( - "Vis Relay Interface", - CATEGORY_CRAFTING, DFT_CRAFT_VIS_RELAY_INTERFACE, - "Controls if the Vis Relay Interface can be crafted." ); + this.craft_IO_Buses = this.configSettings.getBoolean( + "IO Buses", + CATEGORY_CRAFTING, + DFT_CRAFT_IO_BUSES, + "Controls if the import and export buses can be crafted."); - this.craft_Wireless_Essentia_Term = this.configSettings.getBoolean( - "Allow Crafting Wireless Essentia Terminal", - CATEGORY_CRAFTING, DFT_CRAFT_WIRELESS_ESSENTIA_TERM, - "Controls if the Wireless Essentia Terminal can be crafted." ); + this.craft_Vis_Relay_Interface = this.configSettings.getBoolean( + "Vis Relay Interface", + CATEGORY_CRAFTING, + DFT_CRAFT_VIS_RELAY_INTERFACE, + "Controls if the Vis Relay Interface can be crafted."); - this.enable_Quartz_Dupe = this.configSettings.getBoolean( - "Certus Quartz Duplication", - CATEGORY_CRAFTING, DFT_ENABLE_QUARTZ_DUPE, - "Controls if Certus Quartz can be duplicated in the crucible." ); + this.craft_Wireless_Essentia_Term = this.configSettings.getBoolean( + "Allow Crafting Wireless Essentia Terminal", + CATEGORY_CRAFTING, + DFT_CRAFT_WIRELESS_ESSENTIA_TERM, + "Controls if the Wireless Essentia Terminal can be crafted."); - this.enable_Wrench_Focus = this.configSettings.getBoolean( - "Wrench Focus", - CATEGORY_CRAFTING, DFT_ENABLE_WRENCH_FOCUS, - "Controls if the Wrench Focus is enabled and craftable." ); + this.enable_Quartz_Dupe = this.configSettings.getBoolean( + "Certus Quartz Duplication", + CATEGORY_CRAFTING, + DFT_ENABLE_QUARTZ_DUPE, + "Controls if Certus Quartz can be duplicated in the crucible."); - this.force_TC_Facades = this.configSettings.getBoolean( - "Force TC Facades", - CATEGORY_CRAFTING, DFT_FORCE_TC_FACADES, - "When enabled, overwrites the AE2 facade settings for some Thaumcraft blocks, allowing their facades to be crafted." ); + this.enable_Wrench_Focus = this.configSettings.getBoolean( + "Wrench Focus", + CATEGORY_CRAFTING, + DFT_ENABLE_WRENCH_FOCUS, + "Controls if the Wrench Focus is enabled and craftable."); - // Client ========================================================== - this.disable_Gearbox = this.configSettings.getBoolean( - "Disable Gearbox Model", - CATEGORY_CLIENT, DFT_DISABLE_GEARBOX, - "The iron and thaumium gearboxes will be rendered as a standard block." ); + this.force_TC_Facades = this.configSettings.getBoolean( + "Force TC Facades", + CATEGORY_CRAFTING, + DFT_FORCE_TC_FACADES, + "When enabled, overwrites the AE2 facade settings for some Thaumcraft blocks, allowing their facades to be crafted."); - // Integration ===================================================== - this.extracells_Blist = this.configSettings.getBoolean( - "ExtraCells Blacklist", - CATEGORY_INTEGRATION, DFT_EXTRACELLS_BLIST, - "Prevents extra cells from interacting with essentia gas" ); + // Client ========================================================== + this.disable_Gearbox = this.configSettings.getBoolean( + "Disable Gearbox Model", + CATEGORY_CLIENT, + DFT_DISABLE_GEARBOX, + "The iron and thaumium gearboxes will be rendered as a standard block."); - // Has the config file changed? - if( this.configSettings.hasChanged() ) - { - // Save it - this.configSettings.save(); - } - } + // Integration ===================================================== + this.extracells_Blist = this.configSettings.getBoolean( + "ExtraCells Blacklist", + CATEGORY_INTEGRATION, + DFT_EXTRACELLS_BLIST, + "Prevents extra cells from interacting with essentia gas"); - @Override - public boolean blacklistEssentiaFluidInExtraCells() - { - return this.extracells_Blist; - } + // Has the config file changed? + if (this.configSettings.hasChanged()) { + // Save it + this.configSettings.save(); + } + } - @Override - public int conversionMultiplier() - { - return this.conversionMultiplier; - } + @Override + public boolean blacklistEssentiaFluidInExtraCells() { + return this.extracells_Blist; + } - @Override - public boolean craftArcaneAssembler() - { - return this.craft_Arcane_Assembler; - } + @Override + public int conversionMultiplier() { + return this.conversionMultiplier; + } - @Override - public boolean craftArcaneCraftingTerminal() - { - return this.craft_Arcane_Crafting_Term; - } + @Override + public boolean craftArcaneAssembler() { + return this.craft_Arcane_Assembler; + } - @Override - public boolean craftDistillationPatternEncoder() - { - return this.craft_Distillation_Pattern_Encoder; - } + @Override + public boolean craftArcaneCraftingTerminal() { + return this.craft_Arcane_Crafting_Term; + } - @Override - public boolean craftEssentiaCells() - { - return this.craft_Essentia_Cells; - } + @Override + public boolean craftDistillationPatternEncoder() { + return this.craft_Distillation_Pattern_Encoder; + } - @Override - public boolean craftEssentiaProvider() - { - return this.craft_Essentia_Provider; - } + @Override + public boolean craftEssentiaCells() { + return this.craft_Essentia_Cells; + } - @Override - public boolean craftEssentiaVibrationChamber() - { - return this.craft_Essentia_Vibration_Chamber; - } + @Override + public boolean craftEssentiaProvider() { + return this.craft_Essentia_Provider; + } - @Override - public boolean craftGolemWifiBackpack() - { - return this.craft_GolemBackpack; - } + @Override + public boolean craftEssentiaVibrationChamber() { + return this.craft_Essentia_Vibration_Chamber; + } - @Override - public boolean craftInfusionProvider() - { - return this.craft_Infusion_Provider; - } + @Override + public boolean craftGolemWifiBackpack() { + return this.craft_GolemBackpack; + } - @Override - public boolean craftIOBuses() - { - return this.craft_IO_Buses; - } + @Override + public boolean craftInfusionProvider() { + return this.craft_Infusion_Provider; + } - @Override - public boolean craftVisRelayInterface() - { - return this.craft_Vis_Relay_Interface; - } + @Override + public boolean craftIOBuses() { + return this.craft_IO_Buses; + } - @Override - public boolean craftWirelessEssentiaTerminal() - { - return this.craft_Wireless_Essentia_Term; - } + @Override + public boolean craftVisRelayInterface() { + return this.craft_Vis_Relay_Interface; + } - @Override - public boolean disableGearboxModel() - { - return this.disable_Gearbox; - } + @Override + public boolean craftWirelessEssentiaTerminal() { + return this.craft_Wireless_Essentia_Term; + } - @Override - public boolean enableCertusQuartzDupe() - { - return this.enable_Quartz_Dupe; - } + @Override + public boolean disableGearboxModel() { + return this.disable_Gearbox; + } - @Override - public boolean enableWrenchFocus() - { - return this.enable_Wrench_Focus; - } + @Override + public boolean enableCertusQuartzDupe() { + return this.enable_Quartz_Dupe; + } - @Override - public boolean forceTCFacades() - { - return this.force_TC_Facades; - } + @Override + public boolean enableWrenchFocus() { + return this.enable_Wrench_Focus; + } + @Override + public boolean forceTCFacades() { + return this.force_TC_Facades; + } } diff --git a/src/main/java/thaumicenergistics/common/ThEGuiHandler.java b/src/main/java/thaumicenergistics/common/ThEGuiHandler.java index 12b00892..e1b02447 100644 --- a/src/main/java/thaumicenergistics/common/ThEGuiHandler.java +++ b/src/main/java/thaumicenergistics/common/ThEGuiHandler.java @@ -23,433 +23,419 @@ import thaumicenergistics.common.parts.ThEPartBase; * @author Nividica * */ -public class ThEGuiHandler - implements IGuiHandler -{ - // ID's between 0 and this number indicate that they are AE parts - private static final int DIRECTION_OFFSET = ForgeDirection.values().length; - - // ID's must increase in values of 10 - private static final int ID_STEP_VALUE = 10; - - /** - * Singular ID of the essentia cell gui - */ - public static final int ESSENTIA_CELL_ID = ThEGuiHandler.ID_STEP_VALUE * 1; - - /** - * Base ID of the priority gui. - * Add the ForgeDirection's side ordinal to this value. - */ - public static final int PRIORITY_ID = ThEGuiHandler.ID_STEP_VALUE * 2; - - /** - * ID of the essentia cell workbench - */ - public static final int CELL_WORKBENCH_ID = ThEGuiHandler.ID_STEP_VALUE * 3; - - /** - * ID of the wireless terminal gui. - */ - public static final int WIRELESS_TERMINAL_ID = ThEGuiHandler.ID_STEP_VALUE * 4; - - /** - * ID of the arcane assembler gui. - */ - public static final int ARCANE_ASSEMBLER_ID = ThEGuiHandler.ID_STEP_VALUE * 5; - - /** - * ID of the knowledge inscriber gui. - */ - public static final int KNOWLEDGE_INSCRIBER = ThEGuiHandler.ID_STEP_VALUE * 6; - - /** - * ID of the knowledge inscriber gui. - */ - public static final int ESSENTIA_VIBRATION_CHAMBER = ThEGuiHandler.ID_STEP_VALUE * 7; - - /** - * ID of the auto crafting amount bridge. - * When calling this make sure the current container implements ICraftingIssuerContainer, - * or extends AEBaseContainer with the target set to an ICraftingIssuerHost. - */ - public static final int AUTO_CRAFTING_AMOUNT = ThEGuiHandler.ID_STEP_VALUE * 8; - - /** - * ID of the auto crafting confirm bridge. - * When calling this make sure the current container extends - * AEBaseContainer with the target set to an ICraftingIssuerHost. - */ - public static final int AUTO_CRAFTING_CONFIRM = ThEGuiHandler.ID_STEP_VALUE * 9; - - /** - * ID of the distillation encoder. - */ - public static final int DISTILLATION_ENCODER = ThEGuiHandler.ID_STEP_VALUE * 10; - - /** - * Extra data used for some GUI calls. - */ - private static Object[] extraData = null; - - /** - * Gets the crafting issuer host or null. - * - * @param player - * @return - */ - private static ICraftingIssuerHost getCraftingIssuerHost( final EntityPlayer player ) - { - // Is the currently opened container a crafting issuer container? - if( player.openContainer instanceof ICraftingIssuerContainer ) - { - // Return the issuer - return ( (ICraftingIssuerContainer)player.openContainer ).getCraftingHost(); - } - - // Is the currently opened container an AE base container? - if( player.openContainer instanceof AEBaseContainer ) - { - // Get the target - Object target = ( (AEBaseContainer)player.openContainer ).getTarget(); - - // Is the target an ICraftingIssuerHost? - if( target instanceof ICraftingIssuerHost ) - { - return (ICraftingIssuerHost)target; - } - } - - return null; - } - - /** - * Gets the AE part at the specified location. - * - * @param tileSide - * @param world - * @param x - * @param y - * @param z - * @return - */ - private static IPart getPart( final ForgeDirection tileSide, final World world, final int x, final int y, final int z ) - { - // Get the host at the specified position - IPartHost partHost = (IPartHost)( world.getTileEntity( x, y, z ) ); - - // Ensure we got a host - if( partHost == null ) - { - return null; - } - - // Get the part from the host - return( partHost.getPart( tileSide ) ); - } - - /** - * Gets the sided part for the GUI ID. - * - * @param ID - * @param world - * @param x - * @param y - * @param z - * @return - */ - private static IPart getPartFromSidedID( final int ID, final World world, final int x, final int y, final int z ) - { - ForgeDirection side = ForgeDirection.getOrientation( ID % ThEGuiHandler.ID_STEP_VALUE ); - return ThEGuiHandler.getPart( side, world, x, y, z ); - } - - /** - * Get the gui element for the AE part at the specified location - * - * @param tileSide - * @param player - * @param world - * @param x - * @param y - * @param z - * @param isServerSide - * @return - */ - private static Object getPartGuiElement( final ForgeDirection tileSide, final EntityPlayer player, final World world, final int x, final int y, - final int z, final boolean isServerSide ) - { - // Get the part - ThEPartBase part = (ThEPartBase)ThEGuiHandler.getPart( tileSide, world, x, y, z ); - - // Ensure we got the part - if( part == null ) - { - return null; - } - - // Is this server side? - if( isServerSide ) - { - // Ask the part for its server element - return part.getServerGuiElement( player ); - } - - // Ask the part for its client element - return part.getClientGuiElement( player ); - } - - /** - * Returns true if the specified ID is within the base range. - * - * @param BaseID - * @param ID - * @return - */ - private static boolean isIDInRange( final int ID, final int BaseID ) - { - return( ( ID >= BaseID ) && ( ID < ( BaseID + ThEGuiHandler.ID_STEP_VALUE ) ) ); - } - - /** - * Helper function to properly generate a GUI ID that - * includes a forge direction. - * - * @param ID - * @param side - * @return - */ - public static int generateSidedID( final int ID, final ForgeDirection side ) - { - return ID + side.ordinal(); - } - - /** - * Launches a non AE part gui. - * - * @param ID - * @param player - * @param world - * @param x - * @param y - * @param z - */ - public static void launchGui( final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - player.openGui( ThaumicEnergistics.INSTANCE, ID + ThEGuiHandler.DIRECTION_OFFSET, world, x, y, z ); - } - - /** - * Launches a non AE part gui with the specified extra data. - * - * @param ID - * @param player - * @param world - * @param x - * @param y - * @param z - * @param extraData - */ - public static void launchGui( final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z, - final Object[] extraData ) - { - ThEGuiHandler.extraData = extraData; - player.openGui( ThaumicEnergistics.INSTANCE, ID + ThEGuiHandler.DIRECTION_OFFSET, world, x, y, z ); - ThEGuiHandler.extraData = null; - } - - /** - * Launches an AE part gui - * - * @param part - * @param player - * @param world - * @param x - * @param y - * @param z - */ - public static void launchGui( final ThEPartBase part, final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Ensure the player is allowed to open the gui - if( part.isPartUseableByPlayer( player ) ) - { - player.openGui( ThaumicEnergistics.INSTANCE, part.getSide().ordinal(), world, x, y, z ); - } - } - - @Override - public Object getClientGuiElement( int ID, final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Is the ID a forge direction? - ForgeDirection side = ForgeDirection.getOrientation( ID ); - - // Do we have a world and side? - if( ( world != null ) && ( side != ForgeDirection.UNKNOWN ) ) - { - // This is an AE part, get its gui - return ThEGuiHandler.getPartGuiElement( side, player, world, x, y, z, false ); - } - - // This is not an AE part, adjust the ID - ID -= ThEGuiHandler.DIRECTION_OFFSET; - - // Check basic ID's - switch ( ID ) - { - // Is this the essentia cell? - case ThEGuiHandler.ESSENTIA_CELL_ID: - return GuiEssentiaCellTerminal.NewEssentiaCellGui( player, world, x, y, z ); - - // Is this the cell workbench? - case ThEGuiHandler.CELL_WORKBENCH_ID: - return new GuiEssentiaCellWorkbench( player, world, x, y, z ); - - // Is this the wireless gui? - case ThEGuiHandler.WIRELESS_TERMINAL_ID: - return GuiEssentiaCellTerminal.NewWirelessEssentiaTerminalGui( player ); - - // Is this the arcane assembler? - case ThEGuiHandler.ARCANE_ASSEMBLER_ID: - return new GuiArcaneAssembler( player, world, x, y, z ); - - // Is this the knowledge inscriber? - case ThEGuiHandler.KNOWLEDGE_INSCRIBER: - return new GuiKnowledgeInscriber( player, world, x, y, z ); - - // Vibration chamber? - case ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER: - return new GuiEssentiaVibrationChamber( player, world, x, y, z ); - - // Distillation encoder? - case ThEGuiHandler.DISTILLATION_ENCODER: - return new GuiDistillationPatternEncoder( player, world, x, y, z ); - - // AE2 Autocrafting Amount? - case ThEGuiHandler.AUTO_CRAFTING_AMOUNT: - ICraftingIssuerHost amountHost = ThEGuiHandler.getCraftingIssuerHost( player ); - if( amountHost != null ) - { - return new GuiCraftAmountBridge( player, amountHost ); - } - return null; - - // AE2 Autocrafting Confirm? - case ThEGuiHandler.AUTO_CRAFTING_CONFIRM: - ICraftingIssuerHost confirmHost = ThEGuiHandler.getCraftingIssuerHost( player ); - if( confirmHost != null ) - { - return new GuiCraftConfirmBridge( player, confirmHost ); - } - return null; - - } - - // Is this the priority window? - if( ThEGuiHandler.isIDInRange( ID, ThEGuiHandler.PRIORITY_ID ) ) - { - // Get the part - IPart part = ThEGuiHandler.getPartFromSidedID( ID, world, x, y, z ); - - // Ensure we got the part, and that it implements IPriortyHost - if( ( part == null ) || !( part instanceof IPriorityHost ) ) - { - return null; - } - - // Return the gui - return new GuiPriority( (IPriorityHost)part, player ); - } - - // No matching GUI element found - return null; - - } - - @Override - public Object getServerGuiElement( int ID, final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Is the ID a forge Direction? - ForgeDirection side = ForgeDirection.getOrientation( ID ); - - // Do we have a world and side? - if( ( world != null ) && ( side != ForgeDirection.UNKNOWN ) ) - { - // This is an AE part, get its gui - return ThEGuiHandler.getPartGuiElement( side, player, world, x, y, z, true ); - } - - // This is not an AE part, adjust the ID - ID -= ThEGuiHandler.DIRECTION_OFFSET; - - switch ( ID ) - { - // Is this the essentia cell? - case ThEGuiHandler.ESSENTIA_CELL_ID: - return new ContainerEssentiaCell( player, world, x, y, z ); - - // Is this the cell workbench? - case ThEGuiHandler.CELL_WORKBENCH_ID: - return new ContainerEssentiaCellWorkbench( player, world, x, y, z ); - - // Is this the wireless gui? - case ThEGuiHandler.WIRELESS_TERMINAL_ID: - HandlerWirelessEssentiaTerminal handler = (HandlerWirelessEssentiaTerminal)ThEGuiHandler.extraData[0]; - return new ContainerWirelessEssentiaTerminal( player, handler ); - - // Is this the arcane assembler? - case ThEGuiHandler.ARCANE_ASSEMBLER_ID: - return new ContainerArcaneAssembler( player, world, x, y, z ); - - // Is this the knowledge inscriber? - case ThEGuiHandler.KNOWLEDGE_INSCRIBER: - return new ContainerKnowledgeInscriber( player, world, x, y, z ); - - // Vibration chamber? - case ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER: - return new ContainerEssentiaVibrationChamber( player, world, x, y, z ); - - // Distillation encoder? - case ThEGuiHandler.DISTILLATION_ENCODER: - return new ContainerDistillationPatternEncoder( player, world, x, y, z ); - - // AE2 Autocrafting Amount? - case ThEGuiHandler.AUTO_CRAFTING_AMOUNT: - ICraftingIssuerHost amountHost = ThEGuiHandler.getCraftingIssuerHost( player ); - if( amountHost != null ) - { - return new ContainerCraftAmount( player.inventory, amountHost ); - } - return null; - - // AE2 Autocrafting Confirm? - case ThEGuiHandler.AUTO_CRAFTING_CONFIRM: - ICraftingIssuerHost confirmHost = ThEGuiHandler.getCraftingIssuerHost( player ); - if( confirmHost != null ) - { - return new ContainerCraftConfirm( player.inventory, confirmHost ); - } - return null; - - } - - // Is this the priority window? - if( ThEGuiHandler.isIDInRange( ID, ThEGuiHandler.PRIORITY_ID ) ) - { - // Get the part - IPart part = ThEGuiHandler.getPartFromSidedID( ID, world, x, y, z ); - - // Ensure we got the part, and that it implements IPriortyHost - if( ( part == null ) || !( part instanceof IPriorityHost ) ) - { - return null; - } - - // Return the container - return new ContainerPriority( (IPriorityHost)part, player ); - - } - - // No matching GUI element found - return null; - } +public class ThEGuiHandler implements IGuiHandler { + // ID's between 0 and this number indicate that they are AE parts + private static final int DIRECTION_OFFSET = ForgeDirection.values().length; + + // ID's must increase in values of 10 + private static final int ID_STEP_VALUE = 10; + + /** + * Singular ID of the essentia cell gui + */ + public static final int ESSENTIA_CELL_ID = ThEGuiHandler.ID_STEP_VALUE * 1; + + /** + * Base ID of the priority gui. + * Add the ForgeDirection's side ordinal to this value. + */ + public static final int PRIORITY_ID = ThEGuiHandler.ID_STEP_VALUE * 2; + + /** + * ID of the essentia cell workbench + */ + public static final int CELL_WORKBENCH_ID = ThEGuiHandler.ID_STEP_VALUE * 3; + + /** + * ID of the wireless terminal gui. + */ + public static final int WIRELESS_TERMINAL_ID = ThEGuiHandler.ID_STEP_VALUE * 4; + + /** + * ID of the arcane assembler gui. + */ + public static final int ARCANE_ASSEMBLER_ID = ThEGuiHandler.ID_STEP_VALUE * 5; + + /** + * ID of the knowledge inscriber gui. + */ + public static final int KNOWLEDGE_INSCRIBER = ThEGuiHandler.ID_STEP_VALUE * 6; + + /** + * ID of the knowledge inscriber gui. + */ + public static final int ESSENTIA_VIBRATION_CHAMBER = ThEGuiHandler.ID_STEP_VALUE * 7; + + /** + * ID of the auto crafting amount bridge. + * When calling this make sure the current container implements ICraftingIssuerContainer, + * or extends AEBaseContainer with the target set to an ICraftingIssuerHost. + */ + public static final int AUTO_CRAFTING_AMOUNT = ThEGuiHandler.ID_STEP_VALUE * 8; + + /** + * ID of the auto crafting confirm bridge. + * When calling this make sure the current container extends + * AEBaseContainer with the target set to an ICraftingIssuerHost. + */ + public static final int AUTO_CRAFTING_CONFIRM = ThEGuiHandler.ID_STEP_VALUE * 9; + + /** + * ID of the distillation encoder. + */ + public static final int DISTILLATION_ENCODER = ThEGuiHandler.ID_STEP_VALUE * 10; + + /** + * Extra data used for some GUI calls. + */ + private static Object[] extraData = null; + + /** + * Gets the crafting issuer host or null. + * + * @param player + * @return + */ + private static ICraftingIssuerHost getCraftingIssuerHost(final EntityPlayer player) { + // Is the currently opened container a crafting issuer container? + if (player.openContainer instanceof ICraftingIssuerContainer) { + // Return the issuer + return ((ICraftingIssuerContainer) player.openContainer).getCraftingHost(); + } + + // Is the currently opened container an AE base container? + if (player.openContainer instanceof AEBaseContainer) { + // Get the target + Object target = ((AEBaseContainer) player.openContainer).getTarget(); + + // Is the target an ICraftingIssuerHost? + if (target instanceof ICraftingIssuerHost) { + return (ICraftingIssuerHost) target; + } + } + + return null; + } + + /** + * Gets the AE part at the specified location. + * + * @param tileSide + * @param world + * @param x + * @param y + * @param z + * @return + */ + private static IPart getPart( + final ForgeDirection tileSide, final World world, final int x, final int y, final int z) { + // Get the host at the specified position + IPartHost partHost = (IPartHost) (world.getTileEntity(x, y, z)); + + // Ensure we got a host + if (partHost == null) { + return null; + } + + // Get the part from the host + return (partHost.getPart(tileSide)); + } + + /** + * Gets the sided part for the GUI ID. + * + * @param ID + * @param world + * @param x + * @param y + * @param z + * @return + */ + private static IPart getPartFromSidedID(final int ID, final World world, final int x, final int y, final int z) { + ForgeDirection side = ForgeDirection.getOrientation(ID % ThEGuiHandler.ID_STEP_VALUE); + return ThEGuiHandler.getPart(side, world, x, y, z); + } + + /** + * Get the gui element for the AE part at the specified location + * + * @param tileSide + * @param player + * @param world + * @param x + * @param y + * @param z + * @param isServerSide + * @return + */ + private static Object getPartGuiElement( + final ForgeDirection tileSide, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final boolean isServerSide) { + // Get the part + ThEPartBase part = (ThEPartBase) ThEGuiHandler.getPart(tileSide, world, x, y, z); + + // Ensure we got the part + if (part == null) { + return null; + } + + // Is this server side? + if (isServerSide) { + // Ask the part for its server element + return part.getServerGuiElement(player); + } + + // Ask the part for its client element + return part.getClientGuiElement(player); + } + + /** + * Returns true if the specified ID is within the base range. + * + * @param BaseID + * @param ID + * @return + */ + private static boolean isIDInRange(final int ID, final int BaseID) { + return ((ID >= BaseID) && (ID < (BaseID + ThEGuiHandler.ID_STEP_VALUE))); + } + + /** + * Helper function to properly generate a GUI ID that + * includes a forge direction. + * + * @param ID + * @param side + * @return + */ + public static int generateSidedID(final int ID, final ForgeDirection side) { + return ID + side.ordinal(); + } + + /** + * Launches a non AE part gui. + * + * @param ID + * @param player + * @param world + * @param x + * @param y + * @param z + */ + public static void launchGui( + final int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { + player.openGui(ThaumicEnergistics.INSTANCE, ID + ThEGuiHandler.DIRECTION_OFFSET, world, x, y, z); + } + + /** + * Launches a non AE part gui with the specified extra data. + * + * @param ID + * @param player + * @param world + * @param x + * @param y + * @param z + * @param extraData + */ + public static void launchGui( + final int ID, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final Object[] extraData) { + ThEGuiHandler.extraData = extraData; + player.openGui(ThaumicEnergistics.INSTANCE, ID + ThEGuiHandler.DIRECTION_OFFSET, world, x, y, z); + ThEGuiHandler.extraData = null; + } + + /** + * Launches an AE part gui + * + * @param part + * @param player + * @param world + * @param x + * @param y + * @param z + */ + public static void launchGui( + final ThEPartBase part, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z) { + // Ensure the player is allowed to open the gui + if (part.isPartUseableByPlayer(player)) { + player.openGui(ThaumicEnergistics.INSTANCE, part.getSide().ordinal(), world, x, y, z); + } + } + + @Override + public Object getClientGuiElement( + int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Is the ID a forge direction? + ForgeDirection side = ForgeDirection.getOrientation(ID); + + // Do we have a world and side? + if ((world != null) && (side != ForgeDirection.UNKNOWN)) { + // This is an AE part, get its gui + return ThEGuiHandler.getPartGuiElement(side, player, world, x, y, z, false); + } + + // This is not an AE part, adjust the ID + ID -= ThEGuiHandler.DIRECTION_OFFSET; + + // Check basic ID's + switch (ID) { + // Is this the essentia cell? + case ThEGuiHandler.ESSENTIA_CELL_ID: + return GuiEssentiaCellTerminal.NewEssentiaCellGui(player, world, x, y, z); + + // Is this the cell workbench? + case ThEGuiHandler.CELL_WORKBENCH_ID: + return new GuiEssentiaCellWorkbench(player, world, x, y, z); + + // Is this the wireless gui? + case ThEGuiHandler.WIRELESS_TERMINAL_ID: + return GuiEssentiaCellTerminal.NewWirelessEssentiaTerminalGui(player); + + // Is this the arcane assembler? + case ThEGuiHandler.ARCANE_ASSEMBLER_ID: + return new GuiArcaneAssembler(player, world, x, y, z); + + // Is this the knowledge inscriber? + case ThEGuiHandler.KNOWLEDGE_INSCRIBER: + return new GuiKnowledgeInscriber(player, world, x, y, z); + + // Vibration chamber? + case ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER: + return new GuiEssentiaVibrationChamber(player, world, x, y, z); + + // Distillation encoder? + case ThEGuiHandler.DISTILLATION_ENCODER: + return new GuiDistillationPatternEncoder(player, world, x, y, z); + + // AE2 Autocrafting Amount? + case ThEGuiHandler.AUTO_CRAFTING_AMOUNT: + ICraftingIssuerHost amountHost = ThEGuiHandler.getCraftingIssuerHost(player); + if (amountHost != null) { + return new GuiCraftAmountBridge(player, amountHost); + } + return null; + + // AE2 Autocrafting Confirm? + case ThEGuiHandler.AUTO_CRAFTING_CONFIRM: + ICraftingIssuerHost confirmHost = ThEGuiHandler.getCraftingIssuerHost(player); + if (confirmHost != null) { + return new GuiCraftConfirmBridge(player, confirmHost); + } + return null; + } + + // Is this the priority window? + if (ThEGuiHandler.isIDInRange(ID, ThEGuiHandler.PRIORITY_ID)) { + // Get the part + IPart part = ThEGuiHandler.getPartFromSidedID(ID, world, x, y, z); + + // Ensure we got the part, and that it implements IPriortyHost + if ((part == null) || !(part instanceof IPriorityHost)) { + return null; + } + + // Return the gui + return new GuiPriority((IPriorityHost) part, player); + } + + // No matching GUI element found + return null; + } + + @Override + public Object getServerGuiElement( + int ID, final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Is the ID a forge Direction? + ForgeDirection side = ForgeDirection.getOrientation(ID); + + // Do we have a world and side? + if ((world != null) && (side != ForgeDirection.UNKNOWN)) { + // This is an AE part, get its gui + return ThEGuiHandler.getPartGuiElement(side, player, world, x, y, z, true); + } + + // This is not an AE part, adjust the ID + ID -= ThEGuiHandler.DIRECTION_OFFSET; + + switch (ID) { + // Is this the essentia cell? + case ThEGuiHandler.ESSENTIA_CELL_ID: + return new ContainerEssentiaCell(player, world, x, y, z); + + // Is this the cell workbench? + case ThEGuiHandler.CELL_WORKBENCH_ID: + return new ContainerEssentiaCellWorkbench(player, world, x, y, z); + + // Is this the wireless gui? + case ThEGuiHandler.WIRELESS_TERMINAL_ID: + HandlerWirelessEssentiaTerminal handler = (HandlerWirelessEssentiaTerminal) ThEGuiHandler.extraData[0]; + return new ContainerWirelessEssentiaTerminal(player, handler); + + // Is this the arcane assembler? + case ThEGuiHandler.ARCANE_ASSEMBLER_ID: + return new ContainerArcaneAssembler(player, world, x, y, z); + + // Is this the knowledge inscriber? + case ThEGuiHandler.KNOWLEDGE_INSCRIBER: + return new ContainerKnowledgeInscriber(player, world, x, y, z); + + // Vibration chamber? + case ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER: + return new ContainerEssentiaVibrationChamber(player, world, x, y, z); + + // Distillation encoder? + case ThEGuiHandler.DISTILLATION_ENCODER: + return new ContainerDistillationPatternEncoder(player, world, x, y, z); + + // AE2 Autocrafting Amount? + case ThEGuiHandler.AUTO_CRAFTING_AMOUNT: + ICraftingIssuerHost amountHost = ThEGuiHandler.getCraftingIssuerHost(player); + if (amountHost != null) { + return new ContainerCraftAmount(player.inventory, amountHost); + } + return null; + + // AE2 Autocrafting Confirm? + case ThEGuiHandler.AUTO_CRAFTING_CONFIRM: + ICraftingIssuerHost confirmHost = ThEGuiHandler.getCraftingIssuerHost(player); + if (confirmHost != null) { + return new ContainerCraftConfirm(player.inventory, confirmHost); + } + return null; + } + + // Is this the priority window? + if (ThEGuiHandler.isIDInRange(ID, ThEGuiHandler.PRIORITY_ID)) { + // Get the part + IPart part = ThEGuiHandler.getPartFromSidedID(ID, world, x, y, z); + + // Ensure we got the part, and that it implements IPriortyHost + if ((part == null) || !(part instanceof IPriorityHost)) { + return null; + } + + // Return the container + return new ContainerPriority((IPriorityHost) part, player); + } + + // No matching GUI element found + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/ThaumicEnergistics.java b/src/main/java/thaumicenergistics/common/ThaumicEnergistics.java index d13a7f1a..229cbda4 100644 --- a/src/main/java/thaumicenergistics/common/ThaumicEnergistics.java +++ b/src/main/java/thaumicenergistics/common/ThaumicEnergistics.java @@ -33,177 +33,173 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -@Mod(modid = ThaumicEnergistics.MOD_ID, name = "Thaumic Energistics", version = ThaumicEnergistics.VERSION, dependencies = "required-after:ThE-core;required-after:appliedenergistics2@[rv3-beta-116,);required-after:Thaumcraft@[4.2.3.5,);after:Waila;after:extracells") -public class ThaumicEnergistics -{ - /** - * What loading state Thaumic Energistics has completed. - */ - private static LoaderState ThEState = LoaderState.NOINIT; +@Mod( + modid = ThaumicEnergistics.MOD_ID, + name = "Thaumic Energistics", + version = ThaumicEnergistics.VERSION, + dependencies = + "required-after:ThE-core;required-after:appliedenergistics2@[rv3-beta-116,);required-after:Thaumcraft@[4.2.3.5,);after:Waila;after:extracells") +public class ThaumicEnergistics { + /** + * What loading state Thaumic Energistics has completed. + */ + private static LoaderState ThEState = LoaderState.NOINIT; - /** - * String ID of the mod. - */ - public static final String MOD_ID = "thaumicenergistics"; + /** + * String ID of the mod. + */ + public static final String MOD_ID = "thaumicenergistics"; - /** - * Current version of the mod. - */ - public static final String VERSION = "GRADLETOKEN_VERSION"; + /** + * Current version of the mod. + */ + public static final String VERSION = "GRADLETOKEN_VERSION"; - /** - * Singleton instance - */ - @Instance(value = ThaumicEnergistics.MOD_ID) - public static ThaumicEnergistics INSTANCE; + /** + * Singleton instance + */ + @Instance(value = ThaumicEnergistics.MOD_ID) + public static ThaumicEnergistics INSTANCE; - // Says where the client and server 'proxy' code is loaded. - @SidedProxy(clientSide = "thaumicenergistics.client.ClientProxy", serverSide = "thaumicenergistics.common.CommonProxy") - public static CommonProxy proxy; + // Says where the client and server 'proxy' code is loaded. + @SidedProxy( + clientSide = "thaumicenergistics.client.ClientProxy", + serverSide = "thaumicenergistics.common.CommonProxy") + public static CommonProxy proxy; - /** - * Configuration. - */ - public static IThEConfig config; + /** + * Configuration. + */ + public static IThEConfig config; - /** - * Creative tab. - */ - public static CreativeTabs ThETab = new CreativeTabs( "ThaumicEnergistics" ) - { + /** + * Creative tab. + */ + public static CreativeTabs ThETab = new CreativeTabs("ThaumicEnergistics") { - @Override - public ItemStack getIconItemStack() - { - return ThEApi.instance().blocks().InfusionProvider.getStack(); - } + @Override + public ItemStack getIconItemStack() { + return ThEApi.instance().blocks().InfusionProvider.getStack(); + } - @Override - public Item getTabIconItem() - { - return ThEApi.instance().blocks().InfusionProvider.getItem(); - } - }; + @Override + public Item getTabIconItem() { + return ThEApi.instance().blocks().InfusionProvider.getItem(); + } + }; - /** - * Gets what state/phase of loading that ThE has completed.
- * NOINIT: PreInit has not yet been called
- * PREINITIALIZATION: PreInit has finished.
- * INITIALIZATION: Load has finished.
- * POSTINITIALIZATION: PostInit has finished, ThE is fully loaded. - * - * @return - */ - public static LoaderState getLoaderState() - { - return ThaumicEnergistics.ThEState; - } + /** + * Gets what state/phase of loading that ThE has completed.
+ * NOINIT: PreInit has not yet been called
+ * PREINITIALIZATION: PreInit has finished.
+ * INITIALIZATION: Load has finished.
+ * POSTINITIALIZATION: PostInit has finished, ThE is fully loaded. + * + * @return + */ + public static LoaderState getLoaderState() { + return ThaumicEnergistics.ThEState; + } - /** - * Called after the preInit event, and before the post init event. - * - * @param event - */ - @EventHandler - public void load( final FMLInitializationEvent event ) - { - // Mark that ThE is in Init - long startTime = ThELog.beginSection( "Load" ); + /** + * Called after the preInit event, and before the post init event. + * + * @param event + */ + @EventHandler + public void load(final FMLInitializationEvent event) { + // Mark that ThE is in Init + long startTime = ThELog.beginSection("Load"); - // Register block renderers - ThaumicEnergistics.proxy.registerRenderers(); + // Register block renderers + ThaumicEnergistics.proxy.registerRenderers(); - // Register tile entities - ThaumicEnergistics.proxy.registerTileEntities(); + // Register tile entities + ThaumicEnergistics.proxy.registerTileEntities(); - // Register packets - NetworkHandler.registerPackets(); + // Register packets + NetworkHandler.registerPackets(); - // Register integration - IntegrationCore.init(); + // Register integration + IntegrationCore.init(); - // Register the essentia grid cache - AEApi.instance().registries().gridCache().registerGridCache( IEssentiaGrid.class, GridEssentiaCache.class ); + // Register the essentia grid cache + AEApi.instance().registries().gridCache().registerGridCache(IEssentiaGrid.class, GridEssentiaCache.class); - // Register the wireless golem handler - ThEApi.instance().interact().registerGolemHookHandler( WirelessGolemHandler.getInstance() ); + // Register the wireless golem handler + ThEApi.instance().interact().registerGolemHookHandler(WirelessGolemHandler.getInstance()); - // Mark that ThE has finished Init - ThELog.endSection( "Load", startTime ); - ThaumicEnergistics.ThEState = LoaderState.INITIALIZATION; - } + // Mark that ThE has finished Init + ThELog.endSection("Load", startTime); + ThaumicEnergistics.ThEState = LoaderState.INITIALIZATION; + } - /** - * Called after the load event. - * - * @param event - */ - @EventHandler - public void postInit( final FMLPostInitializationEvent event ) - { - // Mark that ThE is in PostInit - long startTime = ThELog.beginSection( "PostInit" ); + /** + * Called after the load event. + * + * @param event + */ + @EventHandler + public void postInit(final FMLPostInitializationEvent event) { + // Mark that ThE is in PostInit + long startTime = ThELog.beginSection("PostInit"); - // Register the standard thaumcraft container items and tiles - EssentiaTileContainerHelper.INSTANCE.registerDefaultContainers(); - EssentiaItemContainerHelper.INSTANCE.registerDefaultContainers(); + // Register the standard thaumcraft container items and tiles + EssentiaTileContainerHelper.INSTANCE.registerDefaultContainers(); + EssentiaItemContainerHelper.INSTANCE.registerDefaultContainers(); - // Register features - ThaumicEnergistics.proxy.registerFeatures(); + // Register features + ThaumicEnergistics.proxy.registerFeatures(); - // Register my tiles with SpatialIO - ThaumicEnergistics.proxy.registerSpatialIOMovables(); + // Register my tiles with SpatialIO + ThaumicEnergistics.proxy.registerSpatialIOMovables(); - // Register fluids - ThaumicEnergistics.proxy.registerFluids(); + // Register fluids + ThaumicEnergistics.proxy.registerFluids(); - // Give AE items aspects - try - { - AEAspectRegister.INSTANCE.registerAEAspects(); - } - catch( Exception e ) - { - ThELog.warning( "Unable to finish aspect registration due to exception:%n%s%n", e.getMessage() ); - } + // Give AE items aspects + try { + AEAspectRegister.INSTANCE.registerAEAspects(); + } catch (Exception e) { + ThELog.warning("Unable to finish aspect registration due to exception:%n%s%n", e.getMessage()); + } - // Mark that ThE has finished PostInit - ThELog.endSection( "PostInit", startTime ); - ThaumicEnergistics.ThEState = LoaderState.POSTINITIALIZATION; - } + // Mark that ThE has finished PostInit + ThELog.endSection("PostInit", startTime); + ThaumicEnergistics.ThEState = LoaderState.POSTINITIALIZATION; + } - /** - * Called before the load event. - * - * @param event - * @throws Exception - */ - @EventHandler - public void preInit( final FMLPreInitializationEvent event ) throws Exception - { - // Mark that ThE is in PreInit - long startTime = ThELog.beginSection( "PreInit" ); + /** + * Called before the load event. + * + * @param event + * @throws Exception + */ + @EventHandler + public void preInit(final FMLPreInitializationEvent event) throws Exception { + // Mark that ThE is in PreInit + long startTime = ThELog.beginSection("PreInit"); - // Set the instance - ThaumicEnergistics.INSTANCE = this; + // Set the instance + ThaumicEnergistics.INSTANCE = this; - // Sync with config - ThaumicEnergistics.config = ConfigurationHandler.loadAndSyncConfigFile( event.getSuggestedConfigurationFile() ); + // Sync with config + ThaumicEnergistics.config = ConfigurationHandler.loadAndSyncConfigFile(event.getSuggestedConfigurationFile()); - // Register the gui handler - NetworkRegistry.INSTANCE.registerGuiHandler( this, new ThEGuiHandler() ); + // Register the gui handler + NetworkRegistry.INSTANCE.registerGuiHandler(this, new ThEGuiHandler()); - // Register items - ThaumicEnergistics.proxy.registerItems(); + // Register items + ThaumicEnergistics.proxy.registerItems(); - // Register blocks - ThaumicEnergistics.proxy.registerBlocks(); + // Register blocks + ThaumicEnergistics.proxy.registerBlocks(); - // Mark that ThE has finished PreInit - ThELog.endSection( "PreInit", startTime ); - ThaumicEnergistics.ThEState = LoaderState.PREINITIALIZATION; - } + // Mark that ThE has finished PreInit + ThELog.endSection("PreInit", startTime); + ThaumicEnergistics.ThEState = LoaderState.PREINITIALIZATION; + } - // TODO: General: Sync server configs + // TODO: General: Sync server configs } diff --git a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockAEWrenchable.java b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockAEWrenchable.java index a3b352d5..a668760a 100644 --- a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockAEWrenchable.java +++ b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockAEWrenchable.java @@ -13,93 +13,89 @@ import net.minecraft.world.World; * @author Nividica * */ -public abstract class AbstractBlockAEWrenchable - extends BlockContainer -{ +public abstract class AbstractBlockAEWrenchable extends BlockContainer { - protected AbstractBlockAEWrenchable( final Material material ) - { - super( material ); - } + protected AbstractBlockAEWrenchable(final Material material) { + super(material); + } - /** - * Called when the block is right-clicked - * - * @param world - * @param x - * @param y - * @param z - * @param player - * @return - */ - protected boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return false; - } + /** + * Called when the block is right-clicked + * + * @param world + * @param x + * @param y + * @param z + * @param player + * @return + */ + protected boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + return false; + } - /** - * Called when the block is being removed via AE wrench. - * Return an itemstack that represents the block. Can be null. - */ - protected ItemStack onDismantled( final World world, final int x, final int y, final int z ) - { - return null; - } + /** + * Called when the block is being removed via AE wrench. + * Return an itemstack that represents the block. Can be null. + */ + protected ItemStack onDismantled(final World world, final int x, final int y, final int z) { + return null; + } - /** - * Returning false will cancel onBlockActivated. - * - * @return - */ - public boolean canPlayerInteract( final EntityPlayer player ) - { - return true; - } + /** + * Returning false will cancel onBlockActivated. + * + * @return + */ + public boolean canPlayerInteract(final EntityPlayer player) { + return true; + } - /** - * The block was right-clicked - */ - @Override - public final boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player, final int side, - final float hitX, final float hitY, final float hitZ ) - { - // Can the player interact with the block? - if( !this.canPlayerInteract( player ) ) - { - return false; - } + /** + * The block was right-clicked + */ + @Override + public final boolean onBlockActivated( + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + // Can the player interact with the block? + if (!this.canPlayerInteract(player)) { + return false; + } - // Is the player holding an AE wrench item? - if( Platform.isWrench( player, player.getHeldItem(), x, y, z ) ) - { - // Is the player sneaking? - if( player.isSneaking() ) - { - // Call on dismantled - ItemStack representitive = this.onDismantled( world, x, y, z ); + // Is the player holding an AE wrench item? + if (Platform.isWrench(player, player.getHeldItem(), x, y, z)) { + // Is the player sneaking? + if (player.isSneaking()) { + // Call on dismantled + ItemStack representitive = this.onDismantled(world, x, y, z); - // Call break - this.breakBlock( world, x, y, z, this, world.getBlockMetadata( x, y, z ) ); + // Call break + this.breakBlock(world, x, y, z, this, world.getBlockMetadata(x, y, z)); - // Is there an representative itemstack? - if( representitive == null ) - { - // Create a basic stack. - representitive = new ItemStack( this ); - } + // Is there an representative itemstack? + if (representitive == null) { + // Create a basic stack. + representitive = new ItemStack(this); + } - // Drop the itemstack - this.dropBlockAsItem( world, x, y, z, representitive ); + // Drop the itemstack + this.dropBlockAsItem(world, x, y, z, representitive); - // Set the block to air - world.setBlockToAir( x, y, z ); - } + // Set the block to air + world.setBlockToAir(x, y, z); + } - return true; - } - - return this.onBlockActivated( world, x, y, z, player ); - - } + return true; + } + return this.onBlockActivated(world, x, y, z, player); + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockGearBoxBase.java b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockGearBoxBase.java index cd2981d5..8d4f07a2 100644 --- a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockGearBoxBase.java +++ b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockGearBoxBase.java @@ -22,159 +22,145 @@ import thaumicenergistics.common.tiles.TileGearBox; * @author Nividica * */ -public abstract class AbstractBlockGearBoxBase - extends AbstractBlockAEWrenchable -{ - /** - * Determines if thaumcraft golems are allowed to interact with the gearbox. - */ - protected boolean allowGolemInteraction = false; +public abstract class AbstractBlockGearBoxBase extends AbstractBlockAEWrenchable { + /** + * Determines if thaumcraft golems are allowed to interact with the gearbox. + */ + protected boolean allowGolemInteraction = false; - /** - * Creates the block. - */ - public AbstractBlockGearBoxBase() - { - // Set material type - super( Material.ground ); + /** + * Creates the block. + */ + public AbstractBlockGearBoxBase() { + // Set material type + super(Material.ground); - // Set creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); + // Set creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); - // Set sound type - this.setStepSound( Block.soundTypeStone ); + // Set sound type + this.setStepSound(Block.soundTypeStone); - // Set hardness - this.setHardness( 0.6F ); + // Set hardness + this.setHardness(0.6F); - // Set bounding box - this.setBlockBounds( 0.23F, 0.23F, 0.23F, 0.77F, 0.77F, 0.77F ); - } + // Set bounding box + this.setBlockBounds(0.23F, 0.23F, 0.23F, 0.77F, 0.77F, 0.77F); + } - /** - * Crank the gearbox. - */ - @Override - protected boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { + /** + * Crank the gearbox. + */ + @Override + protected boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { - // Get the tile - TileGearBox gearBox = (TileGearBox)world.getTileEntity( x, y, z ); + // Get the tile + TileGearBox gearBox = (TileGearBox) world.getTileEntity(x, y, z); - // Crank it - return gearBox.crankGearbox(); - } + // Crank it + return gearBox.crankGearbox(); + } - @Override - public boolean canPlayerInteract( final EntityPlayer player ) - { - // Fake player? - if( player instanceof FakePlayer ) - { - // Are golems allowed to interact? - if( !this.allowGolemInteraction ) - { - // Golem interaction not allowed - return false; - } + @Override + public boolean canPlayerInteract(final EntityPlayer player) { + // Fake player? + if (player instanceof FakePlayer) { + // Are golems allowed to interact? + if (!this.allowGolemInteraction) { + // Golem interaction not allowed + return false; + } - // Is the fake player a golem? - if( !player.getGameProfile().getName().equalsIgnoreCase( "FakeThaumcraftGolem" ) ) - { - // Not a golem - return false; - } - } + // Is the fake player a golem? + if (!player.getGameProfile().getName().equalsIgnoreCase("FakeThaumcraftGolem")) { + // Not a golem + return false; + } + } - return true; - } + return true; + } - /** - * Creates the gear box tile. - */ - @Override - public TileEntity createNewTileEntity( final World w, final int meta ) - { - return new TileGearBox(); - } + /** + * Creates the gear box tile. + */ + @Override + public TileEntity createNewTileEntity(final World w, final int meta) { + return new TileGearBox(); + } - /** - * Get the icon from subclass. - */ - @SideOnly(Side.CLIENT) - @Override - public abstract IIcon getIcon( final int side, final int meta ); + /** + * Get the icon from subclass. + */ + @SideOnly(Side.CLIENT) + @Override + public abstract IIcon getIcon(final int side, final int meta); - /** - * Get the name from subclass. - */ - @Override - public abstract String getUnlocalizedName(); + /** + * Get the name from subclass. + */ + @Override + public abstract String getUnlocalizedName(); - /** - * Is not opaque. - */ - @Override - public final boolean isOpaqueCube() - { - return false; - } + /** + * Is not opaque. + */ + @Override + public final boolean isOpaqueCube() { + return false; + } - /** - * Dependent on config setting. - */ - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - return ThEApi.instance().config().disableGearboxModel(); - } + /** + * Dependent on config setting. + */ + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + return ThEApi.instance().config().disableGearboxModel(); + } - /** - * One of the adjacent blocks has changed. - */ - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block neighbor ) - { - // Get the tile - TileEntity gearBox = w.getTileEntity( x, y, z ); + /** + * One of the adjacent blocks has changed. + */ + @Override + public void onNeighborBlockChange(final World w, final int x, final int y, final int z, final Block neighbor) { + // Get the tile + TileEntity gearBox = w.getTileEntity(x, y, z); - // Update it - if( gearBox instanceof TileGearBox ) - { - ( (TileGearBox)gearBox ).updateCrankables(); + // Update it + if (gearBox instanceof TileGearBox) { + ((TileGearBox) gearBox).updateCrankables(); - // Update the client tile entity - w.markBlockForUpdate( x, y, z ); - } - } + // Update the client tile entity + w.markBlockForUpdate(x, y, z); + } + } - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } - /** - * Dependent on config setting. - */ - @Override - public final boolean renderAsNormalBlock() - { - return ThEApi.instance().config().disableGearboxModel(); - } - - /** - * Prevents MC from using the default block renderer. - * Dependent on config setting. - */ - @Override - public boolean shouldSideBeRendered( final IBlockAccess iblockaccess, final int i, final int j, final int k, final int l ) - { - return ThEApi.instance().config().disableGearboxModel(); - } + /** + * Dependent on config setting. + */ + @Override + public final boolean renderAsNormalBlock() { + return ThEApi.instance().config().disableGearboxModel(); + } + /** + * Prevents MC from using the default block renderer. + * Dependent on config setting. + */ + @Override + public boolean shouldSideBeRendered( + final IBlockAccess iblockaccess, final int i, final int j, final int k, final int l) { + return ThEApi.instance().config().disableGearboxModel(); + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockProviderBase.java b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockProviderBase.java index e21f699e..64abf01e 100644 --- a/src/main/java/thaumicenergistics/common/blocks/AbstractBlockProviderBase.java +++ b/src/main/java/thaumicenergistics/common/blocks/AbstractBlockProviderBase.java @@ -18,161 +18,159 @@ import thaumicenergistics.common.registries.EnumCache; import thaumicenergistics.common.registries.Renderers; import thaumicenergistics.common.tiles.abstraction.TileProviderBase; -public abstract class AbstractBlockProviderBase - extends AbstractBlockAEWrenchable -{ +public abstract class AbstractBlockProviderBase extends AbstractBlockAEWrenchable { - protected AbstractBlockProviderBase( final Material material ) - { - super( material ); + protected AbstractBlockProviderBase(final Material material) { + super(material); - // Place in our creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in our creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - @Override - public void breakBlock( final World world, final int x, final int y, final int z, final Block block, final int metadata ) - { - // Get tile entity - TileEntity tileProvider = world.getTileEntity( x, y, z ); + @Override + public void breakBlock( + final World world, final int x, final int y, final int z, final Block block, final int metadata) { + // Get tile entity + TileEntity tileProvider = world.getTileEntity(x, y, z); - // Is there still have a tile? - if( tileProvider instanceof TileProviderBase ) - { - // Inform it that its going away - ( (TileProviderBase)tileProvider ).onBreakBlock(); - } + // Is there still have a tile? + if (tileProvider instanceof TileProviderBase) { + // Inform it that its going away + ((TileProviderBase) tileProvider).onBreakBlock(); + } - // Pass to super - super.breakBlock( world, x, y, z, block, metadata ); - } + // Pass to super + super.breakBlock(world, x, y, z, block, metadata); + } - @Override - public final boolean canRenderInPass( final int pass ) - { - // Mark the current pass - Renderers.currentRenderPass = pass; + @Override + public final boolean canRenderInPass(final int pass) { + // Mark the current pass + Renderers.currentRenderPass = pass; - // We render during both passes - return true; - } + // We render during both passes + return true; + } - @Override - public abstract TileEntity createNewTileEntity( World world, int metaData ); + @Override + public abstract TileEntity createNewTileEntity(World world, int metaData); - @SideOnly(Side.CLIENT) - @Override - public abstract IIcon getIcon( int side, int metaData ); + @SideOnly(Side.CLIENT) + @Override + public abstract IIcon getIcon(int side, int metaData); - /* Colored Lights Core Test Code - @Override - public int getLightValue( final IBlockAccess world, final int x, final int y, final int z ) - { - // Get tile entity - TileEntity tileProvider = world.getTileEntity( x, y, z ); - - // Is there still have a tile? - if( tileProvider instanceof TileProviderBase ) - { - - float r = 0; - float g = 0; - float b = 0; - - if( ( (TileProviderBase)tileProvider ).isActive() ) - { - int mv = ( (TileProviderBase)tileProvider ).getColor().mediumVariant; - - r = ( ( mv >> 16 ) & 0xff ) / 255.0F; - g = ( ( mv >> 8 ) & 0xff ) / 255.0F; - b = ( ( mv ) & 0xff ) / 255.0F; - return CLApi.makeRGBLightValue( r, g, b ); - } - - return 0; - } - - return super.getLightValue( world, x, y, z ); - - } - */ + /* Colored Lights Core Test Code + @Override + public int getLightValue( final IBlockAccess world, final int x, final int y, final int z ) + { + // Get tile entity + TileEntity tileProvider = world.getTileEntity( x, y, z ); - @SideOnly(Side.CLIENT) - @Override - public final int getRenderBlockPass() - { - // Ensure the alpha pass is rendered - return Renderers.PASS_ALPHA; - } + // Is there still have a tile? + if( tileProvider instanceof TileProviderBase ) + { - @SideOnly(Side.CLIENT) - @Override - public abstract int getRenderType(); + float r = 0; + float g = 0; + float b = 0; - @Override - public abstract String getUnlocalizedName(); + if( ( (TileProviderBase)tileProvider ).isActive() ) + { + int mv = ( (TileProviderBase)tileProvider ).getColor().mediumVariant; - @Override - public final boolean isOpaqueCube() - { - // Occlude adjoining faces. - return true; - } + r = ( ( mv >> 16 ) & 0xff ) / 255.0F; + g = ( ( mv >> 8 ) & 0xff ) / 255.0F; + b = ( ( mv ) & 0xff ) / 255.0F; + return CLApi.makeRGBLightValue( r, g, b ); + } - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - // This is a solid cube - return true; - } + return 0; + } - // Sets the metadata for the block based on which side of the neighbor block they clicked on. - @Override - public final int onBlockPlaced( final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, - final float hitZ, final int metaData ) - { - // Get the opposite face and return it - return ForgeDirection.OPPOSITES[side]; - } + return super.getLightValue( world, x, y, z ); - @Override - public final void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase entity, - final ItemStack itemstack ) - { - // Set the owner - if( entity instanceof EntityPlayer ) - { - TileEntity tileProvider = world.getTileEntity( x, y, z ); - if( tileProvider instanceof TileProviderBase ) - { - ( (TileProviderBase)tileProvider ).setOwner( (EntityPlayer)entity ); - } - } - } + } + */ - @Override - public abstract void onNeighborBlockChange( World world, int x, int y, int z, Block neighbor ); + @SideOnly(Side.CLIENT) + @Override + public final int getRenderBlockPass() { + // Ensure the alpha pass is rendered + return Renderers.PASS_ALPHA; + } - @Override - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int color ) - { - return ( (TileProviderBase)world.getTileEntity( x, y, z ) ).recolourBlock( side, EnumCache.AE_COLOR[color], null ); + @SideOnly(Side.CLIENT) + @Override + public abstract int getRenderType(); - } + @Override + public abstract String getUnlocalizedName(); - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored + @Override + public final boolean isOpaqueCube() { + // Occlude adjoining faces. + return true; + } - } + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + // This is a solid cube + return true; + } - @Override - public final boolean renderAsNormalBlock() - { - // We have a custom renderer for this block - return false; - } + // Sets the metadata for the block based on which side of the neighbor block they clicked on. + @Override + public final int onBlockPlaced( + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ, + final int metaData) { + // Get the opposite face and return it + return ForgeDirection.OPPOSITES[side]; + } + @Override + public final void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase entity, + final ItemStack itemstack) { + // Set the owner + if (entity instanceof EntityPlayer) { + TileEntity tileProvider = world.getTileEntity(x, y, z); + if (tileProvider instanceof TileProviderBase) { + ((TileProviderBase) tileProvider).setOwner((EntityPlayer) entity); + } + } + } + + @Override + public abstract void onNeighborBlockChange(World world, int x, int y, int z, Block neighbor); + + @Override + public boolean recolourBlock( + final World world, final int x, final int y, final int z, final ForgeDirection side, final int color) { + return ((TileProviderBase) world.getTileEntity(x, y, z)).recolourBlock(side, EnumCache.AE_COLOR[color], null); + } + + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + + } + + @Override + public final boolean renderAsNormalBlock() { + // We have a custom renderer for this block + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockArcaneAssembler.java b/src/main/java/thaumicenergistics/common/blocks/BlockArcaneAssembler.java index 0cb6511e..d6d9aeb8 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockArcaneAssembler.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.blocks; -import java.util.ArrayList; import appeng.api.implementations.items.IMemoryCard; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -29,216 +29,198 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class BlockArcaneAssembler - extends AbstractBlockAEWrenchable -{ +public class BlockArcaneAssembler extends AbstractBlockAEWrenchable { - public static final int MAX_SPEED_UPGRADES = 4; + public static final int MAX_SPEED_UPGRADES = 4; - public BlockArcaneAssembler() - { - // Call super with material machine (iron) - super( Material.iron ); + public BlockArcaneAssembler() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); + // Sound of metal + this.setStepSound(Block.soundTypeMetal); - // Place in the ThE creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in the ThE creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - /** - * Called when the assembler is right-clicked - * - * @param world - * @param x - * @param y - * @param z - * @param player - * @return - */ - @Override - protected boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - // Get what the player is holding - ItemStack playerHolding = player.inventory.getCurrentItem(); + /** + * Called when the assembler is right-clicked + * + * @param world + * @param x + * @param y + * @param z + * @param player + * @return + */ + @Override + protected boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + // Get what the player is holding + ItemStack playerHolding = player.inventory.getCurrentItem(); - // Get the tile - TileEntity tileAssembler = world.getTileEntity( x, y, z ); + // Get the tile + TileEntity tileAssembler = world.getTileEntity(x, y, z); - if( tileAssembler instanceof TileArcaneAssembler ) - { - // Are they holding a memory card? - if( ( playerHolding != null ) && ( playerHolding.getItem() instanceof IMemoryCard ) ) - { - // Inform the tile of the event - ( (TileArcaneAssembler)tileAssembler ).onMemoryCardActivate( player, (IMemoryCard)playerHolding.getItem(), playerHolding ); - } - else - { - // Can the player interact with the assembler? - if( ( (TileArcaneAssembler)tileAssembler ).isUseableByPlayer( player ) ) - { - // Launch the gui. - ThEGuiHandler.launchGui( ThEGuiHandler.ARCANE_ASSEMBLER_ID, player, world, x, y, z ); - } - } - } + if (tileAssembler instanceof TileArcaneAssembler) { + // Are they holding a memory card? + if ((playerHolding != null) && (playerHolding.getItem() instanceof IMemoryCard)) { + // Inform the tile of the event + ((TileArcaneAssembler) tileAssembler) + .onMemoryCardActivate(player, (IMemoryCard) playerHolding.getItem(), playerHolding); + } else { + // Can the player interact with the assembler? + if (((TileArcaneAssembler) tileAssembler).isUseableByPlayer(player)) { + // Launch the gui. + ThEGuiHandler.launchGui(ThEGuiHandler.ARCANE_ASSEMBLER_ID, player, world, x, y, z); + } + } + } - return true; - } + return true; + } - /** - * Called when the assembler is dismantled via wrench. - */ - @Override - protected ItemStack onDismantled( final World world, final int x, final int y, final int z ) - { - // Create the itemstack - ItemStack itemStack = new ItemStack( this ); + /** + * Called when the assembler is dismantled via wrench. + */ + @Override + protected ItemStack onDismantled(final World world, final int x, final int y, final int z) { + // Create the itemstack + ItemStack itemStack = new ItemStack(this); - // Get the tile - TileEntity tileAssembler = world.getTileEntity( x, y, z ); + // Get the tile + TileEntity tileAssembler = world.getTileEntity(x, y, z); - if( tileAssembler instanceof TileArcaneAssembler ) - { - // Create a compound tag - NBTTagCompound data = new NBTTagCompound(); + if (tileAssembler instanceof TileArcaneAssembler) { + // Create a compound tag + NBTTagCompound data = new NBTTagCompound(); - // Save the vis levels - ( (TileArcaneAssembler)tileAssembler ).writeVisLevelsToNBT( data ); + // Save the vis levels + ((TileArcaneAssembler) tileAssembler).writeVisLevelsToNBT(data); - // Set the itemstack tag - if( !data.hasNoTags() ) - { - itemStack.setTagCompound( data ); - } - } + // Set the itemstack tag + if (!data.hasNoTags()) { + itemStack.setTagCompound(data); + } + } - return itemStack; - } + return itemStack; + } - /** - * Called when the block is broken. - */ - @Override - public void breakBlock( final World world, final int x, final int y, final int z, final Block block, final int metaData ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Get the tile - TileEntity tileAssembler = world.getTileEntity( x, y, z ); + /** + * Called when the block is broken. + */ + @Override + public void breakBlock( + final World world, final int x, final int y, final int z, final Block block, final int metaData) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Get the tile + TileEntity tileAssembler = world.getTileEntity(x, y, z); - if( tileAssembler instanceof TileArcaneAssembler ) - { - // Get the drops - ArrayList drops = new ArrayList(); - ( (TileArcaneAssembler)tileAssembler ).getDrops( world, x, y, z, drops ); + if (tileAssembler instanceof TileArcaneAssembler) { + // Get the drops + ArrayList drops = new ArrayList(); + ((TileArcaneAssembler) tileAssembler).getDrops(world, x, y, z, drops); - for( ItemStack drop : drops ) - { - world.spawnEntityInWorld( new EntityItem( world, 0.5 + x, 0.5 + y, 0.2 + z, drop ) ); - } + for (ItemStack drop : drops) { + world.spawnEntityInWorld(new EntityItem(world, 0.5 + x, 0.5 + y, 0.2 + z, drop)); + } - // Inform the tile it is being broken - ( (TileArcaneAssembler)tileAssembler ).onBreak(); - } - } + // Inform the tile it is being broken + ((TileArcaneAssembler) tileAssembler).onBreak(); + } + } - // Call super - super.breakBlock( world, x, y, z, block, metaData ); - } + // Call super + super.breakBlock(world, x, y, z, block, metaData); + } - /** - * Creates a new Arcane Assembler tile - */ - @Override - public TileEntity createNewTileEntity( final World world, final int metadata ) - { - return new TileArcaneAssembler(); - } + /** + * Creates a new Arcane Assembler tile + */ + @Override + public TileEntity createNewTileEntity(final World world, final int metadata) { + return new TileArcaneAssembler(); + } - /** - * Gets the standard block icon. - */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - // Sides - return BlockTextureManager.ARCANE_ASSEMBLER.getTexture(); - } + /** + * Gets the standard block icon. + */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + // Sides + return BlockTextureManager.ARCANE_ASSEMBLER.getTexture(); + } - /** - * Gets the unlocalized name of the block. - */ - @Override - public String getUnlocalizedName() - { - return BlockEnum.ARCANE_ASSEMBLER.getUnlocalizedName(); - } + /** + * Gets the unlocalized name of the block. + */ + @Override + public String getUnlocalizedName() { + return BlockEnum.ARCANE_ASSEMBLER.getUnlocalizedName(); + } - @Override - public final boolean isOpaqueCube() - { - return false; - } + @Override + public final boolean isOpaqueCube() { + return false; + } - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - return false; - } + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + return false; + } - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack itemStack ) - { - // Get the tile - TileEntity tileAssembler = world.getTileEntity( x, y, z ); + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase player, + final ItemStack itemStack) { + // Get the tile + TileEntity tileAssembler = world.getTileEntity(x, y, z); - if( tileAssembler instanceof TileArcaneAssembler ) - { - if( itemStack.hasTagCompound() ) - { - // Load the vis data - ( (TileArcaneAssembler)tileAssembler ).readVisLevelsFromNBT( itemStack.getTagCompound() ); - } + if (tileAssembler instanceof TileArcaneAssembler) { + if (itemStack.hasTagCompound()) { + // Load the vis data + ((TileArcaneAssembler) tileAssembler).readVisLevelsFromNBT(itemStack.getTagCompound()); + } - if( player instanceof EntityPlayer ) - { - // Set the owner - ( (TileArcaneAssembler)tileAssembler ).setOwner( (EntityPlayer)player ); - } - } - } + if (player instanceof EntityPlayer) { + // Set the owner + ((TileArcaneAssembler) tileAssembler).setOwner((EntityPlayer) player); + } + } + } - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } - @Override - public final boolean renderAsNormalBlock() - { - return false; - } - - /** - * Prevents MC from using the default block renderer. - */ - @Override - public boolean shouldSideBeRendered( final IBlockAccess iblockaccess, final int i, final int j, final int k, final int l ) - { - return false; - } + @Override + public final boolean renderAsNormalBlock() { + return false; + } + /** + * Prevents MC from using the default block renderer. + */ + @Override + public boolean shouldSideBeRendered( + final IBlockAccess iblockaccess, final int i, final int j, final int k, final int l) { + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockDistillationEncoder.java b/src/main/java/thaumicenergistics/common/blocks/BlockDistillationEncoder.java index dafa2495..05d08d01 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockDistillationEncoder.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockDistillationEncoder.java @@ -1,8 +1,8 @@ package thaumicenergistics.common.blocks; -import java.util.ArrayList; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -27,174 +27,161 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class BlockDistillationEncoder - extends AbstractBlockAEWrenchable -{ - public BlockDistillationEncoder() - { - // Call super with material machine (iron) - super( Material.iron ); +public class BlockDistillationEncoder extends AbstractBlockAEWrenchable { + public BlockDistillationEncoder() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); + // Sound of metal + this.setStepSound(Block.soundTypeMetal); - // Place in the ThE creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in the ThE creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - @Override - protected final boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - // Launch the gui. - ThEGuiHandler.launchGui( ThEGuiHandler.DISTILLATION_ENCODER, player, world, x, y, z ); + @Override + protected final boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + // Launch the gui. + ThEGuiHandler.launchGui(ThEGuiHandler.DISTILLATION_ENCODER, player, world, x, y, z); - return true; - } + return true; + } - /** - * Called when the block is broken. - */ - @Override - public void breakBlock( final World world, final int x, final int y, final int z, final Block block, final int metaData ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Get the tile - TileEntity tile = world.getTileEntity( x, y, z ); + /** + * Called when the block is broken. + */ + @Override + public void breakBlock( + final World world, final int x, final int y, final int z, final Block block, final int metaData) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Get the tile + TileEntity tile = world.getTileEntity(x, y, z); - if( tile instanceof TileDistillationPatternEncoder ) - { - // Cast - TileDistillationPatternEncoder tileDE = (TileDistillationPatternEncoder)tile; + if (tile instanceof TileDistillationPatternEncoder) { + // Cast + TileDistillationPatternEncoder tileDE = (TileDistillationPatternEncoder) tile; - // Does it have patterns? - if( tileDE.hasPatterns() ) - { - // Get the drops - ArrayList drops = tileDE.getDrops( new ArrayList() ); - for( ItemStack drop : drops ) - { - // Spawn in the world - world.spawnEntityInWorld( new EntityItem( world, 0.5 + x, 0.5 + y, 0.2 + z, drop ) ); - } - } - } - } + // Does it have patterns? + if (tileDE.hasPatterns()) { + // Get the drops + ArrayList drops = tileDE.getDrops(new ArrayList()); + for (ItemStack drop : drops) { + // Spawn in the world + world.spawnEntityInWorld(new EntityItem(world, 0.5 + x, 0.5 + y, 0.2 + z, drop)); + } + } + } + } - // Call super - super.breakBlock( world, x, y, z, block, metaData ); - } + // Call super + super.breakBlock(world, x, y, z, block, metaData); + } - /** - * Creates the tile entity associated with the block. - */ - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - return new TileDistillationPatternEncoder(); - } + /** + * Creates the tile entity associated with the block. + */ + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + return new TileDistillationPatternEncoder(); + } - /** - * Gets the standard block icon. - */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - // Face? - if( side == ForgeDirection.OPPOSITES[meta] ) - { - // Face texture - return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[1]; - } + /** + * Gets the standard block icon. + */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + // Face? + if (side == ForgeDirection.OPPOSITES[meta]) { + // Face texture + return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[1]; + } - // Top or bottom? - if( ( ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.UP ) || ( ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.DOWN ) ) - { - // Bottom texture - return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[2]; + // Top or bottom? + if ((ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.UP) + || (ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.DOWN)) { + // Bottom texture + return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[2]; + } - } + // Sides + return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[0]; + } - // Sides - return BlockTextureManager.DISTILLATION_ENCODER.getTextures()[0]; - } + /** + * Gets the unlocalized name of the block. + */ + @Override + public String getUnlocalizedName() { + return BlockEnum.DISTILLATION_ENCODER.getUnlocalizedName(); + } - /** - * Gets the unlocalized name of the block. - */ - @Override - public String getUnlocalizedName() - { - return BlockEnum.DISTILLATION_ENCODER.getUnlocalizedName(); - } + /** + * Is opaque. + */ + @Override + public final boolean isOpaqueCube() { + // Occlude adjoining faces. + return true; + } - /** - * Is opaque. - */ - @Override - public final boolean isOpaqueCube() - { - // Occlude adjoining faces. - return true; - } + /** + * Is solid. + */ + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + // This is a solid cube + return true; + } - /** - * Is solid. - */ - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - // This is a solid cube - return true; - } + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase player, + final ItemStack itemStack) { + // Set the metadata to up + world.setBlockMetadataWithNotify(x, y, z, 0, 2); + } - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack itemStack ) - { - // Set the metadata to up - world.setBlockMetadataWithNotify( x, y, z, 0, 2 ); - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } + /** + * Normal renderer. + */ + @Override + public final boolean renderAsNormalBlock() { + return true; + } - /** - * Normal renderer. - */ - @Override - public final boolean renderAsNormalBlock() - { - return true; - } + @Override + public boolean rotateBlock(final World world, final int x, final int y, final int z, final ForgeDirection side) { + // Get and increment the meta data + int metaData = world.getBlockMetadata(x, y, z) + 1; - @Override - public boolean rotateBlock( final World world, final int x, final int y, final int z, final ForgeDirection side ) - { - // Get and increment the meta data - int metaData = world.getBlockMetadata( x, y, z ) + 1; + // Bounds check + if (metaData >= ForgeDirection.VALID_DIRECTIONS.length) { + metaData = 0; + } - // Bounds check - if( metaData >= ForgeDirection.VALID_DIRECTIONS.length ) - { - metaData = 0; - } - - // Set the meta data - world.setBlockMetadataWithNotify( x, y, z, metaData, 3 ); - - return true; - } + // Set the meta data + world.setBlockMetadataWithNotify(x, y, z, metaData, 3); + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockEnum.java b/src/main/java/thaumicenergistics/common/blocks/BlockEnum.java index b06495b4..13251c71 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockEnum.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockEnum.java @@ -12,81 +12,79 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public enum BlockEnum -{ - ESSENTIA_PROVIDER (ThEStrings.Block_EssentiaProvider, new BlockEssentiaProvider()), - INFUSION_PROVIDER (ThEStrings.Block_InfusionProvider, new BlockInfusionProvider()), - IRON_GEAR_BOX (ThEStrings.Block_IronGearbox, new BlockGearBox()), - THAUMIUM_GEAR_BOX (ThEStrings.Block_ThaumiumGearbox, new BlockGolemGearBox()), - ESSENTIA_CELL_WORKBENCH (ThEStrings.Block_EssentiaCellWorkbench, new BlockEssentiaCellWorkbench()), - ARCANE_ASSEMBLER (ThEStrings.Block_ArcaneAssembler, new BlockArcaneAssembler(), ItemBlockArcaneAssembler.class), - KNOWLEDGE_INSCRIBER (ThEStrings.Block_KnowledgeInscriber, new BlockKnowledgeInscriber()), - ESSENTIA_VIBRATION_CHAMBER (ThEStrings.Block_EssentiaVibrationChamber, new BlockEssentiaVibrationChamber(), - ItemBlockEssentiaVibrationChamber.class), - DISTILLATION_ENCODER (ThEStrings.Block_DistillationEncoder, new BlockDistillationEncoder()); +public enum BlockEnum { + ESSENTIA_PROVIDER(ThEStrings.Block_EssentiaProvider, new BlockEssentiaProvider()), + INFUSION_PROVIDER(ThEStrings.Block_InfusionProvider, new BlockInfusionProvider()), + IRON_GEAR_BOX(ThEStrings.Block_IronGearbox, new BlockGearBox()), + THAUMIUM_GEAR_BOX(ThEStrings.Block_ThaumiumGearbox, new BlockGolemGearBox()), + ESSENTIA_CELL_WORKBENCH(ThEStrings.Block_EssentiaCellWorkbench, new BlockEssentiaCellWorkbench()), + ARCANE_ASSEMBLER(ThEStrings.Block_ArcaneAssembler, new BlockArcaneAssembler(), ItemBlockArcaneAssembler.class), + KNOWLEDGE_INSCRIBER(ThEStrings.Block_KnowledgeInscriber, new BlockKnowledgeInscriber()), + ESSENTIA_VIBRATION_CHAMBER( + ThEStrings.Block_EssentiaVibrationChamber, + new BlockEssentiaVibrationChamber(), + ItemBlockEssentiaVibrationChamber.class), + DISTILLATION_ENCODER(ThEStrings.Block_DistillationEncoder, new BlockDistillationEncoder()); - /** - * Cache of the enum values - */ - public static final BlockEnum[] VALUES = BlockEnum.values(); + /** + * Cache of the enum values + */ + public static final BlockEnum[] VALUES = BlockEnum.values(); - /** - * The block object. - */ - private final Block block; + /** + * The block object. + */ + private final Block block; - /** - * Unlocalized name of the block. - */ - private final ThEStrings unlocalizedName; + /** + * Unlocalized name of the block. + */ + private final ThEStrings unlocalizedName; - /** - * Custom item - */ - public final Class itemBlockClass; + /** + * Custom item + */ + public final Class itemBlockClass; - /** - * Constructs the block with the default itemblock. - * - * @param unlocalizedName - * @param block - */ - private BlockEnum( final ThEStrings unlocalizedName, final Block block ) - { - this( unlocalizedName, block, ItemBlock.class ); - } + /** + * Constructs the block with the default itemblock. + * + * @param unlocalizedName + * @param block + */ + private BlockEnum(final ThEStrings unlocalizedName, final Block block) { + this(unlocalizedName, block, ItemBlock.class); + } - /** - * Constructs the block with the specified itemBlock. - * - * @param unlocalizedName - * @param block - * @param itemBlockClass - */ - private BlockEnum( final ThEStrings unlocalizedName, final Block block, final Class itemBlockClass ) - { - // Set the block - this.block = block; + /** + * Constructs the block with the specified itemBlock. + * + * @param unlocalizedName + * @param block + * @param itemBlockClass + */ + private BlockEnum( + final ThEStrings unlocalizedName, final Block block, final Class itemBlockClass) { + // Set the block + this.block = block; - // Set the unlocalized name - this.unlocalizedName = unlocalizedName; + // Set the unlocalized name + this.unlocalizedName = unlocalizedName; - // Set the block's name - block.setBlockName( this.unlocalizedName.getUnlocalized() ); + // Set the block's name + block.setBlockName(this.unlocalizedName.getUnlocalized()); - // Set item - this.itemBlockClass = itemBlockClass; - } + // Set item + this.itemBlockClass = itemBlockClass; + } - // Return the block - public Block getBlock() - { - return this.block; - } + // Return the block + public Block getBlock() { + return this.block; + } - // Return the name - public String getUnlocalizedName() - { - return this.unlocalizedName.getUnlocalized(); - } + // Return the name + public String getUnlocalizedName() { + return this.unlocalizedName.getUnlocalized(); + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaCellWorkbench.java b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaCellWorkbench.java index 6a6c8528..d38bc06c 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaCellWorkbench.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaCellWorkbench.java @@ -25,154 +25,143 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class BlockEssentiaCellWorkbench - extends AbstractBlockAEWrenchable -{ - /** - * Cached values of the top and bottom side indexes - */ - private static final int SIDE_TOP = ForgeDirection.UP.ordinal(), SIDE_BOTTOM = ForgeDirection.DOWN.ordinal(); +public class BlockEssentiaCellWorkbench extends AbstractBlockAEWrenchable { + /** + * Cached values of the top and bottom side indexes + */ + private static final int SIDE_TOP = ForgeDirection.UP.ordinal(), SIDE_BOTTOM = ForgeDirection.DOWN.ordinal(); - public BlockEssentiaCellWorkbench() - { - // Call super with material machine (iron) - super( Material.iron ); + public BlockEssentiaCellWorkbench() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); + // Sound of metal + this.setStepSound(Block.soundTypeMetal); - // Place in the ThE creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in the ThE creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - /** - * Called when the workbench is right-clicked - * - * @param world - * @param x - * @param y - * @param z - * @param player - * @return - */ - @Override - protected boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - // Launch the gui. - ThEGuiHandler.launchGui( ThEGuiHandler.CELL_WORKBENCH_ID, player, world, x, y, z ); + /** + * Called when the workbench is right-clicked + * + * @param world + * @param x + * @param y + * @param z + * @param player + * @return + */ + @Override + protected boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + // Launch the gui. + ThEGuiHandler.launchGui(ThEGuiHandler.CELL_WORKBENCH_ID, player, world, x, y, z); - return true; - } + return true; + } - /** - * Called when the block is broken. - */ - @Override - public void breakBlock( final World world, final int x, final int y, final int z, final Block block, final int metaData ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Get the tile - TileEntity tileWorkBench = world.getTileEntity( x, y, z ); + /** + * Called when the block is broken. + */ + @Override + public void breakBlock( + final World world, final int x, final int y, final int z, final Block block, final int metaData) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Get the tile + TileEntity tileWorkBench = world.getTileEntity(x, y, z); - // Does the workbench have a cell? - if( ( tileWorkBench instanceof TileEssentiaCellWorkbench ) && ( ( (TileEssentiaCellWorkbench)tileWorkBench ).hasEssentiaCell() ) ) - { - // Spawn the cell as an item entity. - world.spawnEntityInWorld( new EntityItem( world, 0.5 + x, 0.5 + y, 0.2 + z, ( (TileEssentiaCellWorkbench)tileWorkBench ) - .getStackInSlot( 0 ) ) ); - } - } + // Does the workbench have a cell? + if ((tileWorkBench instanceof TileEssentiaCellWorkbench) + && (((TileEssentiaCellWorkbench) tileWorkBench).hasEssentiaCell())) { + // Spawn the cell as an item entity. + world.spawnEntityInWorld(new EntityItem( + world, + 0.5 + x, + 0.5 + y, + 0.2 + z, + ((TileEssentiaCellWorkbench) tileWorkBench).getStackInSlot(0))); + } + } - // Call super - super.breakBlock( world, x, y, z, block, metaData ); - } + // Call super + super.breakBlock(world, x, y, z, block, metaData); + } - @Override - public boolean canPlayerInteract( final EntityPlayer player ) - { - return !( player instanceof FakePlayer ); - } + @Override + public boolean canPlayerInteract(final EntityPlayer player) { + return !(player instanceof FakePlayer); + } - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - return new TileEssentiaCellWorkbench(); - } + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + return new TileEssentiaCellWorkbench(); + } - /** - * Gets the blocks icons. - */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - // Is top? - if( side == BlockEssentiaCellWorkbench.SIDE_TOP ) - { - return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[0]; - } - // Is bottom? - else if( side == BlockEssentiaCellWorkbench.SIDE_BOTTOM ) - { - return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[1]; + /** + * Gets the blocks icons. + */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + // Is top? + if (side == BlockEssentiaCellWorkbench.SIDE_TOP) { + return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[0]; + } + // Is bottom? + else if (side == BlockEssentiaCellWorkbench.SIDE_BOTTOM) { + return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[1]; + } - } + // Sides + return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[2]; + } - // Sides - return BlockTextureManager.ESSENTIA_CELL_WORKBENCH.getTextures()[2]; - } + /** + * Gets the unlocalized name of the block. + */ + @Override + public String getUnlocalizedName() { + return BlockEnum.ESSENTIA_CELL_WORKBENCH.getUnlocalizedName(); + } - /** - * Gets the unlocalized name of the block. - */ - @Override - public String getUnlocalizedName() - { - return BlockEnum.ESSENTIA_CELL_WORKBENCH.getUnlocalizedName(); - } + /** + * Is opaque. + */ + @Override + public final boolean isOpaqueCube() { + // Occlude adjoining faces. + return true; + } - /** - * Is opaque. - */ - @Override - public final boolean isOpaqueCube() - { - // Occlude adjoining faces. - return true; - } + /** + * Is solid. + */ + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + // This is a solid cube + return true; + } - /** - * Is solid. - */ - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - // This is a solid cube - return true; - } - - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } - - /** - * Normal renderer. - */ - @Override - public final boolean renderAsNormalBlock() - { - return true; - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } + /** + * Normal renderer. + */ + @Override + public final boolean renderAsNormalBlock() { + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaProvider.java b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaProvider.java index d5b9b375..946b244f 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaProvider.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaProvider.java @@ -17,65 +17,55 @@ import thaumicenergistics.common.tiles.TileEssentiaProvider; * @author Nividica * */ -public class BlockEssentiaProvider - extends AbstractBlockProviderBase -{ +public class BlockEssentiaProvider extends AbstractBlockProviderBase { - public BlockEssentiaProvider() - { - // Call super with material machine (iron) - super( Material.iron ); + public BlockEssentiaProvider() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); - } + // Sound of metal + this.setStepSound(Block.soundTypeMetal); + } - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - // Create a new provider tile, passing the side to attach to - TileEssentiaProvider tile = new TileEssentiaProvider(); + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + // Create a new provider tile, passing the side to attach to + TileEssentiaProvider tile = new TileEssentiaProvider(); - // Setup the essentia provider - tile.setupProvider( metaData ); + // Setup the essentia provider + tile.setupProvider(metaData); - // Return the tile - return tile; - } + // Return the tile + return tile; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int metaData ) - { - return BlockTextureManager.ESSENTIA_PROVIDER.getTexture(); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int metaData) { + return BlockTextureManager.ESSENTIA_PROVIDER.getTexture(); + } - @SideOnly(Side.CLIENT) - @Override - public int getRenderType() - { - // Provide our custom ID - return Renderers.EssentiaProviderRenderID; - } + @SideOnly(Side.CLIENT) + @Override + public int getRenderType() { + // Provide our custom ID + return Renderers.EssentiaProviderRenderID; + } - @Override - public String getUnlocalizedName() - { - return BlockEnum.ESSENTIA_PROVIDER.getUnlocalizedName(); - } - - @Override - public void onNeighborBlockChange( final World world, final int x, final int y, final int z, final Block neighbor ) - { - TileEntity te = world.getTileEntity( x, y, z ); - if( te instanceof TileEssentiaProvider ) - { - // Inform our tile entity a neighbor has changed - ( (TileEssentiaProvider)te ).checkGridConnectionColor(); - } - } + @Override + public String getUnlocalizedName() { + return BlockEnum.ESSENTIA_PROVIDER.getUnlocalizedName(); + } + @Override + public void onNeighborBlockChange(final World world, final int x, final int y, final int z, final Block neighbor) { + TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof TileEssentiaProvider) { + // Inform our tile entity a neighbor has changed + ((TileEssentiaProvider) te).checkGridConnectionColor(); + } + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaVibrationChamber.java index 73a4a545..a81166b3 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockEssentiaVibrationChamber.java @@ -29,317 +29,282 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class BlockEssentiaVibrationChamber - extends AbstractBlockAEWrenchable -{ +public class BlockEssentiaVibrationChamber extends AbstractBlockAEWrenchable { - public BlockEssentiaVibrationChamber() - { - // Call super with material machine (iron) - super( Material.iron ); + public BlockEssentiaVibrationChamber() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); + // Sound of metal + this.setStepSound(Block.soundTypeMetal); - // Place in the ThE creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in the ThE creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - /** - * Returns the EVC tile entity, if found and is valid. - * - * @param world - * @param x - * @param y - * @param z - * @return - */ - private TileEssentiaVibrationChamber getEVCTile( final IBlockAccess world, final int x, final int y, final int z ) - { - // Ensure the world is not null - if( world != null ) - { - // Get the tile entity - TileEntity te = world.getTileEntity( x, y, z ); + /** + * Returns the EVC tile entity, if found and is valid. + * + * @param world + * @param x + * @param y + * @param z + * @return + */ + private TileEssentiaVibrationChamber getEVCTile(final IBlockAccess world, final int x, final int y, final int z) { + // Ensure the world is not null + if (world != null) { + // Get the tile entity + TileEntity te = world.getTileEntity(x, y, z); - // Ensure it is an EVC - if( te instanceof TileEssentiaVibrationChamber ) - { - return (TileEssentiaVibrationChamber)te; - } - } + // Ensure it is an EVC + if (te instanceof TileEssentiaVibrationChamber) { + return (TileEssentiaVibrationChamber) te; + } + } - return null; - } + return null; + } - @Override - protected boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - // Ignore if player is sneaking - if( player.isSneaking() ) - { - return false; - } + @Override + protected boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + // Ignore if player is sneaking + if (player.isSneaking()) { + return false; + } - // Server side? - if( EffectiveSide.isServerSide() ) - { - // Is the tile valid? - if( this.getEVCTile( world, x, y, z ) != null ) - { - // Launch the GUI - ThEGuiHandler.launchGui( ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER, player, world, x, y, z ); - } - } + // Server side? + if (EffectiveSide.isServerSide()) { + // Is the tile valid? + if (this.getEVCTile(world, x, y, z) != null) { + // Launch the GUI + ThEGuiHandler.launchGui(ThEGuiHandler.ESSENTIA_VIBRATION_CHAMBER, player, world, x, y, z); + } + } - return true; - } + return true; + } - @Override - protected ItemStack onDismantled( final World world, final int x, final int y, final int z ) - { - // Ignore client side. - if( EffectiveSide.isClientSide() ) - { - return null; - } + @Override + protected ItemStack onDismantled(final World world, final int x, final int y, final int z) { + // Ignore client side. + if (EffectiveSide.isClientSide()) { + return null; + } - // Get the chamber - TileEssentiaVibrationChamber chamber = this.getEVCTile( world, x, y, z ); + // Get the chamber + TileEssentiaVibrationChamber chamber = this.getEVCTile(world, x, y, z); - // Validate - if( chamber == null ) - { - // Invalid EVC tile - return null; - } + // Validate + if (chamber == null) { + // Invalid EVC tile + return null; + } - // Anything to save? - if( !chamber.hasSaveDataForDismanle() ) - { - // Nothing unique to save - return null; - } + // Anything to save? + if (!chamber.hasSaveDataForDismanle()) { + // Nothing unique to save + return null; + } - // Reset processing speed - chamber.resetForDismantle(); + // Reset processing speed + chamber.resetForDismantle(); - // Create the tag - NBTTagCompound tag = new NBTTagCompound(); + // Create the tag + NBTTagCompound tag = new NBTTagCompound(); - // Save into the tag - chamber.onNBTSave( tag ); + // Save into the tag + chamber.onNBTSave(tag); - // Create the stack - ItemStack representive = new ItemStack( this ); + // Create the stack + ItemStack representive = new ItemStack(this); - // Set the tag - representive.setTagCompound( tag ); + // Set the tag + representive.setTagCompound(tag); - return representive; - } + return representive; + } - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - return new TileEssentiaVibrationChamber(); - } + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + return new TileEssentiaVibrationChamber(); + } - /** - * Gets the world icons - * - * @param world - * @param x - * @param y - * @param z - * @param side - * @return - */ - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon( final IBlockAccess world, final int x, final int y, final int z, final int side ) - { - // Get the chamber - TileEssentiaVibrationChamber chamber = this.getEVCTile( world, x, y, z ); + /** + * Gets the world icons + * + * @param world + * @param x + * @param y + * @param z + * @param side + * @return + */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final IBlockAccess world, final int x, final int y, final int z, final int side) { + // Get the chamber + TileEssentiaVibrationChamber chamber = this.getEVCTile(world, x, y, z); - // Is the tile valid? - if( chamber == null ) - { - return this.getIcon( side, 0 ); - } + // Is the tile valid? + if (chamber == null) { + return this.getIcon(side, 0); + } - // Is this side the face? - if( ( chamber.getForward() != null ) && ( side == chamber.getForward().ordinal() ) ) - { - // Get the aspect in the chamber - Aspect aspect = chamber.getProcessingAspect(); + // Is this side the face? + if ((chamber.getForward() != null) && (side == chamber.getForward().ordinal())) { + // Get the aspect in the chamber + Aspect aspect = chamber.getProcessingAspect(); - if( aspect == Aspect.ENERGY ) - { - // On: Potentia - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[3]; - } - else if( aspect == Aspect.FIRE ) - { - // On: Ignis - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[2]; - } + if (aspect == Aspect.ENERGY) { + // On: Potentia + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[3]; + } else if (aspect == Aspect.FIRE) { + // On: Ignis + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[2]; + } - // Off - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[1]; - } + // Off + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[1]; + } - // Input - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[0]; - } + // Input + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[0]; + } - /** - * Gets the inventory icons. - */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - // Inventory icons - if( side == 4 ) - { - // Face off - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[1]; - } + /** + * Gets the inventory icons. + */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + // Inventory icons + if (side == 4) { + // Face off + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[1]; + } - // Sides - return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[0]; + // Sides + return BlockTextureManager.ESSENTIA_VIBRATION_CHAMBER.getTextures()[0]; + } - } + /** + * Bright when active, dark when not. + */ + @Override + public int getLightValue(final IBlockAccess world, final int x, final int y, final int z) { + // Get the chamber + TileEssentiaVibrationChamber chamber = this.getEVCTile(world, x, y, z); + if (chamber != null) { + // Return bright if chamber + return (chamber.getProcessingAspect() != null ? 12 : 0); + } - /** - * Bright when active, dark when not. - */ - @Override - public int getLightValue( final IBlockAccess world, final int x, final int y, final int z ) - { - // Get the chamber - TileEssentiaVibrationChamber chamber = this.getEVCTile( world, x, y, z ); - if( chamber != null ) - { - // Return bright if chamber - return( chamber.getProcessingAspect() != null ? 12 : 0 ); - } + return 0; + } - return 0; - } + /** + * Gets the unlocalized name of the block. + */ + @Override + public String getUnlocalizedName() { + return BlockEnum.ESSENTIA_VIBRATION_CHAMBER.getUnlocalizedName(); + } - /** - * Gets the unlocalized name of the block. - */ - @Override - public String getUnlocalizedName() - { - return BlockEnum.ESSENTIA_VIBRATION_CHAMBER.getUnlocalizedName(); - } + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase player, + final ItemStack itemStack) { + // Get the chamber tile + TileEssentiaVibrationChamber chamber = this.getEVCTile(world, x, y, z); - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack itemStack ) - { - // Get the chamber tile - TileEssentiaVibrationChamber chamber = this.getEVCTile( world, x, y, z ); + // Is the tile valid? + if (chamber == null) { + // Invalid tile + return; + } - // Is the tile valid? - if( chamber == null ) - { - // Invalid tile - return; - } + if ((itemStack.getTagCompound() != null) && (EffectiveSide.isServerSide())) { + // Load the saved data + chamber.onNBTLoad(itemStack.getTagCompound()); + } - if( ( itemStack.getTagCompound() != null ) && ( EffectiveSide.isServerSide() ) ) - { - // Load the saved data - chamber.onNBTLoad( itemStack.getTagCompound() ); - } + if (player instanceof EntityPlayer) { + // Set the owner + chamber.setOwner((EntityPlayer) player); + } - if( player instanceof EntityPlayer ) - { - // Set the owner - chamber.setOwner( (EntityPlayer)player ); - } + ForgeDirection face = ForgeDirection.NORTH; - ForgeDirection face = ForgeDirection.NORTH; + // Is the player looking down? + if (player.rotationPitch > 50) { + face = ForgeDirection.UP; + } + // Is the player looking up? + else if (player.rotationPitch < -50) { + face = ForgeDirection.DOWN; + } else { + // Get the side index based on which direction the player is turned + int sideIndex = MathHelper.floor_double(((player.rotationYaw * 4.0F) / 360.0F) + 0.5D) & 3; - // Is the player looking down? - if( player.rotationPitch > 50 ) - { - face = ForgeDirection.UP; - } - // Is the player looking up? - else if( player.rotationPitch < -50 ) - { - face = ForgeDirection.DOWN; - } + switch (sideIndex) { + case 0: + face = ForgeDirection.NORTH; + break; + case 1: + face = ForgeDirection.EAST; + break; + case 2: + face = ForgeDirection.SOUTH; + break; + case 3: + face = ForgeDirection.WEST; + break; + } + } - else - { - // Get the side index based on which direction the player is turned - int sideIndex = MathHelper.floor_double( ( ( player.rotationYaw * 4.0F ) / 360.0F ) + 0.5D ) & 3; + // Set the orientation + chamber.setOrientation(face, ForgeDirection.UP); + } - switch ( sideIndex ) - { - case 0: - face = ForgeDirection.NORTH; - break; - case 1: - face = ForgeDirection.EAST; - break; - case 2: - face = ForgeDirection.SOUTH; - break; - case 3: - face = ForgeDirection.WEST; - break; - } - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } - // Set the orientation - chamber.setOrientation( face, ForgeDirection.UP ); + @Override + public boolean rotateBlock(final World world, final int x, final int y, final int z, final ForgeDirection axis) { + // Cast + TileEssentiaVibrationChamber chamber = this.getEVCTile(world, x, y, z); - } + // Validate + if (chamber == null) { + return false; + } - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } + // Get the current facing + ForgeDirection forward = chamber.getForward(); + ForgeDirection up = chamber.getUp(); - @Override - public boolean rotateBlock( final World world, final int x, final int y, final int z, final ForgeDirection axis ) - { - // Cast - TileEssentiaVibrationChamber chamber = this.getEVCTile( world, x, y, z ); + // Rotate + forward = Platform.rotateAround(forward, axis); + up = Platform.rotateAround(up, axis); - // Validate - if( chamber == null ) - { - return false; - } - - // Get the current facing - ForgeDirection forward = chamber.getForward(); - ForgeDirection up = chamber.getUp(); - - // Rotate - forward = Platform.rotateAround( forward, axis ); - up = Platform.rotateAround( up, axis ); - - // Apply rotation - chamber.setOrientation( forward, up ); - - return true; - } + // Apply rotation + chamber.setOrientation(forward, up); + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockGearBox.java b/src/main/java/thaumicenergistics/common/blocks/BlockGearBox.java index 38620335..de2f2638 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockGearBox.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockGearBox.java @@ -12,20 +12,15 @@ import thaumicenergistics.common.tiles.TileGearBox; * @author Nividica * */ -public class BlockGearBox - extends AbstractBlockGearBoxBase -{ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - return BlockTextureManager.GEAR_BOX.getTextures()[0]; - } - - @Override - public String getUnlocalizedName() - { - return BlockEnum.IRON_GEAR_BOX.getUnlocalizedName(); - } +public class BlockGearBox extends AbstractBlockGearBoxBase { + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + return BlockTextureManager.GEAR_BOX.getTextures()[0]; + } + @Override + public String getUnlocalizedName() { + return BlockEnum.IRON_GEAR_BOX.getUnlocalizedName(); + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockGolemGearBox.java b/src/main/java/thaumicenergistics/common/blocks/BlockGolemGearBox.java index 4876bcb6..e8b7d378 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockGolemGearBox.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockGolemGearBox.java @@ -12,27 +12,21 @@ import thaumicenergistics.common.tiles.TileGearBox; * @author Nividica * */ -public class BlockGolemGearBox - extends AbstractBlockGearBoxBase -{ +public class BlockGolemGearBox extends AbstractBlockGearBoxBase { - public BlockGolemGearBox() - { - // Set that golems are allowed to interact with the gearbox. - this.allowGolemInteraction = true; - } + public BlockGolemGearBox() { + // Set that golems are allowed to interact with the gearbox. + this.allowGolemInteraction = true; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - return BlockTextureManager.GEAR_BOX.getTextures()[1]; - } - - @Override - public String getUnlocalizedName() - { - return BlockEnum.THAUMIUM_GEAR_BOX.getUnlocalizedName(); - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + return BlockTextureManager.GEAR_BOX.getTextures()[1]; + } + @Override + public String getUnlocalizedName() { + return BlockEnum.THAUMIUM_GEAR_BOX.getUnlocalizedName(); + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockInfusionProvider.java b/src/main/java/thaumicenergistics/common/blocks/BlockInfusionProvider.java index 873e4a18..1179ad24 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockInfusionProvider.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockInfusionProvider.java @@ -17,67 +17,56 @@ import thaumicenergistics.common.tiles.TileInfusionProvider; * @author Nividica * */ -public class BlockInfusionProvider - extends AbstractBlockProviderBase -{ +public class BlockInfusionProvider extends AbstractBlockProviderBase { - public BlockInfusionProvider() - { - // Call super with material machine (iron) - super( Material.iron ); + public BlockInfusionProvider() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); - } + // Sound of metal + this.setStepSound(Block.soundTypeMetal); + } - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - // Create a new provider tile, passing the side to attach to - TileInfusionProvider tile = new TileInfusionProvider(); + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + // Create a new provider tile, passing the side to attach to + TileInfusionProvider tile = new TileInfusionProvider(); - // Setup the infusion provider - tile.setupProvider( metaData ); + // Setup the infusion provider + tile.setupProvider(metaData); - // Return the tile - return tile; - } + // Return the tile + return tile; + } - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int metaData ) - { - return BlockTextureManager.INFUSION_PROVIDER.getTextures()[1]; - } + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int metaData) { + return BlockTextureManager.INFUSION_PROVIDER.getTextures()[1]; + } - @SideOnly(Side.CLIENT) - @Override - public int getRenderType() - { - // Provide our custom ID - return Renderers.InfusionProviderRenderID; - } + @SideOnly(Side.CLIENT) + @Override + public int getRenderType() { + // Provide our custom ID + return Renderers.InfusionProviderRenderID; + } - @Override - public String getUnlocalizedName() - { - return BlockEnum.INFUSION_PROVIDER.getUnlocalizedName(); - } - - @Override - public void onNeighborBlockChange( final World world, final int x, final int y, final int z, final Block neighbor ) - { - // Get tile entity - TileEntity tileProvider = world.getTileEntity( x, y, z ); - if( tileProvider instanceof TileInfusionProvider ) - { - // Inform our tile entity a neighbor has changed - ( (TileInfusionProvider)tileProvider ).checkGridConnectionColor(); - } - - } + @Override + public String getUnlocalizedName() { + return BlockEnum.INFUSION_PROVIDER.getUnlocalizedName(); + } + @Override + public void onNeighborBlockChange(final World world, final int x, final int y, final int z, final Block neighbor) { + // Get tile entity + TileEntity tileProvider = world.getTileEntity(x, y, z); + if (tileProvider instanceof TileInfusionProvider) { + // Inform our tile entity a neighbor has changed + ((TileInfusionProvider) tileProvider).checkGridConnectionColor(); + } + } } diff --git a/src/main/java/thaumicenergistics/common/blocks/BlockKnowledgeInscriber.java b/src/main/java/thaumicenergistics/common/blocks/BlockKnowledgeInscriber.java index b9437b7a..97aa9017 100644 --- a/src/main/java/thaumicenergistics/common/blocks/BlockKnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/common/blocks/BlockKnowledgeInscriber.java @@ -26,165 +26,157 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class BlockKnowledgeInscriber - extends AbstractBlockAEWrenchable -{ - public BlockKnowledgeInscriber() - { - // Call super with material machine (iron) - super( Material.iron ); +public class BlockKnowledgeInscriber extends AbstractBlockAEWrenchable { + public BlockKnowledgeInscriber() { + // Call super with material machine (iron) + super(Material.iron); - // Basic hardness - this.setHardness( 1.0f ); + // Basic hardness + this.setHardness(1.0f); - // Sound of metal - this.setStepSound( Block.soundTypeMetal ); + // Sound of metal + this.setStepSound(Block.soundTypeMetal); - // Place in the ThE creative tab - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Place in the ThE creative tab + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - @Override - protected final boolean onBlockActivated( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - // Launch the gui. - ThEGuiHandler.launchGui( ThEGuiHandler.KNOWLEDGE_INSCRIBER, player, world, x, y, z ); + @Override + protected final boolean onBlockActivated( + final World world, final int x, final int y, final int z, final EntityPlayer player) { + // Launch the gui. + ThEGuiHandler.launchGui(ThEGuiHandler.KNOWLEDGE_INSCRIBER, player, world, x, y, z); - return true; - } + return true; + } - /** - * Called when the block is broken. - */ - @Override - public void breakBlock( final World world, final int x, final int y, final int z, final Block block, final int metaData ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Get the tile - TileEntity tile = world.getTileEntity( x, y, z ); + /** + * Called when the block is broken. + */ + @Override + public void breakBlock( + final World world, final int x, final int y, final int z, final Block block, final int metaData) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Get the tile + TileEntity tile = world.getTileEntity(x, y, z); - if( tile instanceof TileKnowledgeInscriber ) - { - TileKnowledgeInscriber tileKI = (TileKnowledgeInscriber)tile; - // Does the inscriber have a cell? - if( tileKI.hasKCore() ) - { - // Spawn the core as an item entity. - world.spawnEntityInWorld( new EntityItem( world, 0.5 + x, 0.5 + y, 0.2 + z, tileKI.getStackInSlot( - TileKnowledgeInscriber.KCORE_SLOT ) ) ); - } - } - } + if (tile instanceof TileKnowledgeInscriber) { + TileKnowledgeInscriber tileKI = (TileKnowledgeInscriber) tile; + // Does the inscriber have a cell? + if (tileKI.hasKCore()) { + // Spawn the core as an item entity. + world.spawnEntityInWorld(new EntityItem( + world, + 0.5 + x, + 0.5 + y, + 0.2 + z, + tileKI.getStackInSlot(TileKnowledgeInscriber.KCORE_SLOT))); + } + } + } - // Call super - super.breakBlock( world, x, y, z, block, metaData ); - } + // Call super + super.breakBlock(world, x, y, z, block, metaData); + } - @Override - public TileEntity createNewTileEntity( final World world, final int metaData ) - { - return new TileKnowledgeInscriber(); - } + @Override + public TileEntity createNewTileEntity(final World world, final int metaData) { + return new TileKnowledgeInscriber(); + } - /** - * Gets the standard block icon. - */ - @SideOnly(Side.CLIENT) - @Override - public IIcon getIcon( final int side, final int meta ) - { - // Face? - if( side == ForgeDirection.OPPOSITES[meta] ) - { - // Face texture - return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[1]; - } + /** + * Gets the standard block icon. + */ + @SideOnly(Side.CLIENT) + @Override + public IIcon getIcon(final int side, final int meta) { + // Face? + if (side == ForgeDirection.OPPOSITES[meta]) { + // Face texture + return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[1]; + } - // Top or bottom? - if( ( ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.UP ) || ( ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.DOWN ) ) - { - // Bottom texture - return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[2]; + // Top or bottom? + if ((ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.UP) + || (ForgeDirection.VALID_DIRECTIONS[side] == ForgeDirection.DOWN)) { + // Bottom texture + return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[2]; + } - } + // Sides + return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[0]; + } - // Sides - return BlockTextureManager.KNOWLEDGE_INSCRIBER.getTextures()[0]; - } + /** + * Gets the unlocalized name of the block. + */ + @Override + public String getUnlocalizedName() { + return BlockEnum.KNOWLEDGE_INSCRIBER.getUnlocalizedName(); + } - /** - * Gets the unlocalized name of the block. - */ - @Override - public String getUnlocalizedName() - { - return BlockEnum.KNOWLEDGE_INSCRIBER.getUnlocalizedName(); - } + /** + * Is opaque. + */ + @Override + public final boolean isOpaqueCube() { + // Occlude adjoining faces. + return true; + } - /** - * Is opaque. - */ - @Override - public final boolean isOpaqueCube() - { - // Occlude adjoining faces. - return true; - } + /** + * Is solid. + */ + @Override + public final boolean isSideSolid( + final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side) { + // This is a solid cube + return true; + } - /** - * Is solid. - */ - @Override - public final boolean isSideSolid( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side ) - { - // This is a solid cube - return true; - } + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase player, + final ItemStack itemStack) { + // Set the metadata to up + world.setBlockMetadataWithNotify(x, y, z, 0, 2); + } - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack itemStack ) - { - // Set the metadata to up - world.setBlockMetadataWithNotify( x, y, z, 0, 2 ); - } + /** + * Taken care of by texture manager + */ + @SideOnly(Side.CLIENT) + @Override + public final void registerBlockIcons(final IIconRegister register) { + // Ignored + } - /** - * Taken care of by texture manager - */ - @SideOnly(Side.CLIENT) - @Override - public final void registerBlockIcons( final IIconRegister register ) - { - // Ignored - } + /** + * Normal renderer. + */ + @Override + public final boolean renderAsNormalBlock() { + return true; + } - /** - * Normal renderer. - */ - @Override - public final boolean renderAsNormalBlock() - { - return true; - } + @Override + public boolean rotateBlock(final World world, final int x, final int y, final int z, final ForgeDirection side) { + // Get and increment the meta data + int metaData = world.getBlockMetadata(x, y, z) + 1; - @Override - public boolean rotateBlock( final World world, final int x, final int y, final int z, final ForgeDirection side ) - { - // Get and increment the meta data - int metaData = world.getBlockMetadata( x, y, z ) + 1; + // Bounds check + if (metaData >= ForgeDirection.VALID_DIRECTIONS.length) { + metaData = 0; + } - // Bounds check - if( metaData >= ForgeDirection.VALID_DIRECTIONS.length ) - { - metaData = 0; - } - - // Set the meta data - world.setBlockMetadataWithNotify( x, y, z, metaData, 3 ); - - return true; - } + // Set the meta data + world.setBlockMetadataWithNotify(x, y, z, metaData, 3); + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerArcaneAssembler.java b/src/main/java/thaumicenergistics/common/container/ContainerArcaneAssembler.java index 5b1ed424..84f57ade 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerArcaneAssembler.java @@ -20,262 +20,258 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class ContainerArcaneAssembler - extends ContainerWithNetworkTool -{ +public class ContainerArcaneAssembler extends ContainerWithNetworkTool { - /** - * Y position for the player inventory. - */ - private static final int PLAYER_INV_POSITION_Y = 115; + /** + * Y position for the player inventory. + */ + private static final int PLAYER_INV_POSITION_Y = 115; - /** - * Y position for the hotbar inventory. - */ - private static final int HOTBAR_INV_POSITION_Y = PLAYER_INV_POSITION_Y + 58; + /** + * Y position for the hotbar inventory. + */ + private static final int HOTBAR_INV_POSITION_Y = PLAYER_INV_POSITION_Y + 58; - /** - * Starting position of the pattern slots. - */ - private static final int PATTERN_SLOT_X = 26, PATTERN_SLOT_Y = 25; + /** + * Starting position of the pattern slots. + */ + private static final int PATTERN_SLOT_X = 26, PATTERN_SLOT_Y = 25; - /** - * Number of rows and columns of the pattern slots. - */ - private static final int PATTERN_ROWS = 3, PATTERN_COLS = 7; + /** + * Number of rows and columns of the pattern slots. + */ + private static final int PATTERN_ROWS = 3, PATTERN_COLS = 7; - /** - * Position of the kcore slot. - */ - private static final int KCORE_SLOT_X = 187, KCORE_SLOT_Y = 8; + /** + * Position of the kcore slot. + */ + private static final int KCORE_SLOT_X = 187, KCORE_SLOT_Y = 8; - /** - * Upgrade slots. - */ - private static final int UPGRADE_SLOT_COUNT = BlockArcaneAssembler.MAX_SPEED_UPGRADES, UPGRADE_SLOT_X = 187, UPGRADE_SLOT_Y = 26; + /** + * Upgrade slots. + */ + private static final int UPGRADE_SLOT_COUNT = BlockArcaneAssembler.MAX_SPEED_UPGRADES, + UPGRADE_SLOT_X = 187, + UPGRADE_SLOT_Y = 26; - /** - * Target slot. - */ - private static final int TARGET_SLOT_X = 14, TARGET_SLOT_Y = 87; + /** + * Target slot. + */ + private static final int TARGET_SLOT_X = 14, TARGET_SLOT_Y = 87; - /** - * Discount armor slots. - */ - private static final int DISCOUNT_ARMOR_SLOT_X = 210, DISCOUNT_ARMOR_SLOT_Y = 26, DISCOUNT_ARMOR_COUNT = 4; + /** + * Discount armor slots. + */ + private static final int DISCOUNT_ARMOR_SLOT_X = 210, DISCOUNT_ARMOR_SLOT_Y = 26, DISCOUNT_ARMOR_COUNT = 4; - /** - * Reference to the arcane assembler - */ - public final TileArcaneAssembler assembler; + /** + * Reference to the arcane assembler + */ + public final TileArcaneAssembler assembler; - /** - * Knowledge Core slot. - */ - private final SlotRestrictive kCoreSlot; + /** + * Knowledge Core slot. + */ + private final SlotRestrictive kCoreSlot; - /** - * Discount armor slots. - */ - private final SlotArmor[] discountSlots = new SlotArmor[4]; + /** + * Discount armor slots. + */ + private final SlotArmor[] discountSlots = new SlotArmor[4]; - /** - * Pattern slots - */ - private final SlotInaccessible[] patternSlots = new SlotInaccessible[PATTERN_ROWS * PATTERN_COLS]; + /** + * Pattern slots + */ + private final SlotInaccessible[] patternSlots = new SlotInaccessible[PATTERN_ROWS * PATTERN_COLS]; - public ContainerArcaneAssembler( final EntityPlayer player, final World world, final int X, final int Y, final int Z ) - { - // Call super - super( player ); + public ContainerArcaneAssembler( + final EntityPlayer player, final World world, final int X, final int Y, final int Z) { + // Call super + super(player); - // Get the assembler - this.assembler = (TileArcaneAssembler)world.getTileEntity( X, Y, Z ); + // Get the assembler + this.assembler = (TileArcaneAssembler) world.getTileEntity(X, Y, Z); - // Get the assemblers inventory - IInventory assemblerInventory = this.assembler.getInternalInventory(); + // Get the assemblers inventory + IInventory assemblerInventory = this.assembler.getInternalInventory(); - // Bind to the players inventory - this.bindPlayerInventory( player.inventory, ContainerArcaneAssembler.PLAYER_INV_POSITION_Y, ContainerArcaneAssembler.HOTBAR_INV_POSITION_Y ); + // Bind to the players inventory + this.bindPlayerInventory( + player.inventory, + ContainerArcaneAssembler.PLAYER_INV_POSITION_Y, + ContainerArcaneAssembler.HOTBAR_INV_POSITION_Y); - // Bind to network tool - this.bindToNetworkTool( player.inventory, this.assembler.getLocation(), 0, 35 ); + // Bind to network tool + this.bindToNetworkTool(player.inventory, this.assembler.getLocation(), 0, 35); - // Add the kcore slot - this.kCoreSlot = new SlotRestrictive( assemblerInventory, TileArcaneAssembler.KCORE_SLOT_INDEX, ContainerArcaneAssembler.KCORE_SLOT_X, - ContainerArcaneAssembler.KCORE_SLOT_Y ); - this.addSlotToContainer( this.kCoreSlot ); + // Add the kcore slot + this.kCoreSlot = new SlotRestrictive( + assemblerInventory, + TileArcaneAssembler.KCORE_SLOT_INDEX, + ContainerArcaneAssembler.KCORE_SLOT_X, + ContainerArcaneAssembler.KCORE_SLOT_Y); + this.addSlotToContainer(this.kCoreSlot); - // Create the pattern slots - for( int row = 0; row < ContainerArcaneAssembler.PATTERN_ROWS; row++ ) - { - for( int col = 0; col < ContainerArcaneAssembler.PATTERN_COLS; col++ ) - { - // Calculate the index - int index = ( row * ContainerArcaneAssembler.PATTERN_COLS ) + col; - int invIndex = TileArcaneAssembler.PATTERN_SLOT_INDEX + index; + // Create the pattern slots + for (int row = 0; row < ContainerArcaneAssembler.PATTERN_ROWS; row++) { + for (int col = 0; col < ContainerArcaneAssembler.PATTERN_COLS; col++) { + // Calculate the index + int index = (row * ContainerArcaneAssembler.PATTERN_COLS) + col; + int invIndex = TileArcaneAssembler.PATTERN_SLOT_INDEX + index; - // Add the slot - this.addSlotToContainer( this.patternSlots[index] = new SlotInaccessible( assemblerInventory, invIndex, - ContainerArcaneAssembler.PATTERN_SLOT_X + ( 18 * col ), - ContainerArcaneAssembler.PATTERN_SLOT_Y + ( 18 * row ) ) ); - } - } + // Add the slot + this.addSlotToContainer( + this.patternSlots[index] = new SlotInaccessible( + assemblerInventory, + invIndex, + ContainerArcaneAssembler.PATTERN_SLOT_X + (18 * col), + ContainerArcaneAssembler.PATTERN_SLOT_Y + (18 * row))); + } + } - // Create the upgrade slots - this.addUpgradeSlots( this.assembler.getUpgradeInventory(), ContainerArcaneAssembler.UPGRADE_SLOT_COUNT, - ContainerArcaneAssembler.UPGRADE_SLOT_X, ContainerArcaneAssembler.UPGRADE_SLOT_Y ); + // Create the upgrade slots + this.addUpgradeSlots( + this.assembler.getUpgradeInventory(), + ContainerArcaneAssembler.UPGRADE_SLOT_COUNT, + ContainerArcaneAssembler.UPGRADE_SLOT_X, + ContainerArcaneAssembler.UPGRADE_SLOT_Y); - // Create the target slot - this.addSlotToContainer( new SlotInaccessible( assemblerInventory, TileArcaneAssembler.TARGET_SLOT_INDEX, - ContainerArcaneAssembler.TARGET_SLOT_X, ContainerArcaneAssembler.TARGET_SLOT_Y ) ); + // Create the target slot + this.addSlotToContainer(new SlotInaccessible( + assemblerInventory, + TileArcaneAssembler.TARGET_SLOT_INDEX, + ContainerArcaneAssembler.TARGET_SLOT_X, + ContainerArcaneAssembler.TARGET_SLOT_Y)); - // Add armor slots - for( int index = 0; index < ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT; index++ ) - { - this.discountSlots[index] = new SlotArmor( assemblerInventory, TileArcaneAssembler.DISCOUNT_ARMOR_INDEX + index, - ContainerArcaneAssembler.DISCOUNT_ARMOR_SLOT_X, - ContainerArcaneAssembler.DISCOUNT_ARMOR_SLOT_Y + ( index * 18 ), - index, true ); + // Add armor slots + for (int index = 0; index < ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT; index++) { + this.discountSlots[index] = new SlotArmor( + assemblerInventory, + TileArcaneAssembler.DISCOUNT_ARMOR_INDEX + index, + ContainerArcaneAssembler.DISCOUNT_ARMOR_SLOT_X, + ContainerArcaneAssembler.DISCOUNT_ARMOR_SLOT_Y + (index * 18), + index, + true); - this.addSlotToContainer( this.discountSlots[index] ); - } + this.addSlotToContainer(this.discountSlots[index]); + } + } - } + /** + * Attempts to merge the itemstack with the armor slots. + * + * @param slotStack + * @return + */ + private boolean mergeWithArmorSlots(final ItemStack slotStack) { + // Check each armor slot + for (int index = 0; index < ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT; index++) { + // Is the item for the slot? + if (this.discountSlots[index].isItemValid(slotStack)) { + // Is the slot empty? + if (!this.discountSlots[index].getHasStack()) { + // Place the item + this.discountSlots[index].putStack(slotStack.copy()); - /** - * Attempts to merge the itemstack with the armor slots. - * - * @param slotStack - * @return - */ - private boolean mergeWithArmorSlots( final ItemStack slotStack ) - { - // Check each armor slot - for( int index = 0; index < ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT; index++ ) - { - // Is the item for the slot? - if( this.discountSlots[index].isItemValid( slotStack ) ) - { - // Is the slot empty? - if( !this.discountSlots[index].getHasStack() ) - { - // Place the item - this.discountSlots[index].putStack( slotStack.copy() ); + // Clear the input stack + slotStack.stackSize = 0; - // Clear the input stack - slotStack.stackSize = 0; + return true; + } + break; + } + } - return true; - } - break; - } - } + return false; + } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + // Ensure there is an assembler + if (this.assembler != null) { + // Ask it if this player can interact + return this.assembler.isUseableByPlayer(player); + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - // Ensure there is an assembler - if( this.assembler != null ) - { - // Ask it if this player can interact - return this.assembler.isUseableByPlayer( player ); - } + return false; + } - return false; - } + /** + * Called when the player shift+clicks on a slot + */ + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Is this client side? + if (EffectiveSide.isClientSide()) { + // Do nothing. + return null; + } - /** - * Called when the player shift+clicks on a slot - */ - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Is this client side? - if( EffectiveSide.isClientSide() ) - { - // Do nothing. - return null; - } + // Get the slot that was shift-clicked + Slot slot = this.getSlotOrNull(slotNumber); - // Get the slot that was shift-clicked - Slot slot = this.getSlotOrNull( slotNumber ); + // Is there a valid slot with and item? + if ((slot != null) && (slot.getHasStack())) { + boolean didMerge = false; - // Is there a valid slot with and item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - boolean didMerge = false; + // Get the itemstack in the slot + ItemStack slotStack = slot.getStack(); - // Get the itemstack in the slot - ItemStack slotStack = slot.getStack(); + // Was the slot clicked in the player or hotbar inventory? + if (this.slotClickedWasInPlayerInventory(slotNumber) || this.slotClickedWasInHotbarInventory(slotNumber)) { + // Skip upgrade cards, let the super class handle them + if (!(slotStack.getItem() instanceof IUpgradeModule)) { + // Attempt to merge with kcore slot + if (this.kCoreSlot.isItemValid(slotStack)) { + didMerge = this.mergeItemStack( + slotStack, this.kCoreSlot.slotNumber, this.kCoreSlot.slotNumber + 1, false); + } else if (slotStack.getItem() instanceof IVisDiscountGear) { + didMerge = this.mergeWithArmorSlots(slotStack); + } - // Was the slot clicked in the player or hotbar inventory? - if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Skip upgrade cards, let the super class handle them - if( !( slotStack.getItem() instanceof IUpgradeModule ) ) - { - // Attempt to merge with kcore slot - if( this.kCoreSlot.isItemValid( slotStack ) ) - { - didMerge = this.mergeItemStack( slotStack, this.kCoreSlot.slotNumber, this.kCoreSlot.slotNumber + 1, false ); - } - else if( slotStack.getItem() instanceof IVisDiscountGear ) - { - didMerge = this.mergeWithArmorSlots( slotStack ); - } + // Was the stack merged? + if (!didMerge) { + // Attempt to merge with player inventory + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + } + // Was the slot clicked the KCore slot or armor slots? + else if ((this.kCoreSlot.slotNumber == slotNumber) + || ((slotNumber >= this.discountSlots[0].slotNumber) + && (slotNumber + <= this.discountSlots[ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT - 1] + .slotNumber))) { + // Attempt to merge with player hotbar + didMerge = this.mergeSlotWithHotbarInventory(slotStack); - // Was the stack merged? - if( !didMerge ) - { - // Attempt to merge with player inventory - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - } - } - // Was the slot clicked the KCore slot or armor slots? - else if( ( this.kCoreSlot.slotNumber == slotNumber ) || - ( ( slotNumber >= this.discountSlots[0].slotNumber ) && - ( slotNumber <= this.discountSlots[ContainerArcaneAssembler.DISCOUNT_ARMOR_COUNT - 1].slotNumber ) ) ) - { - // Attempt to merge with player hotbar - didMerge = this.mergeSlotWithHotbarInventory( slotStack ); + // Was the stack merged? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } - // Was the stack merged? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } + // Was the stack merged? + if (didMerge) { - // Was the stack merged? - if( didMerge ) - { + // Did the merger drain the stack? + if ((slotStack == null) || (slotStack.stackSize == 0)) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } - // Did the merger drain the stack? - if( ( slotStack == null ) || ( slotStack.stackSize == 0 ) ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } + // Send changes + this.detectAndSendChanges(); - // Send changes - this.detectAndSendChanges(); + return null; + } + } - return null; - } - } - - // Call super - return super.transferStackInSlot( player, slotNumber ); - } + // Call super + return super.transferStackInSlot(player, slotNumber); + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerDistillationPatternEncoder.java b/src/main/java/thaumicenergistics/common/container/ContainerDistillationPatternEncoder.java index 983ed990..fa66dfae 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerDistillationPatternEncoder.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerDistillationPatternEncoder.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.container; -import java.util.List; -import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.container.slot.SlotFake; +import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; @@ -29,575 +29,536 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class ContainerDistillationPatternEncoder - extends ContainerWithPlayerInventory -{ - /** - * Y position for the player and hotbar inventory. - */ - private static final int PLAYER_INV_POSITION_Y = 152, HOTBAR_INV_POSITION_Y = ContainerDistillationPatternEncoder.PLAYER_INV_POSITION_Y + 58; - - /** - * Position of the source item slot - */ - public static final int SLOT_SOURCE_ITEM_POS_X = 15, SLOT_SOURCE_ITEM_POS_Y = 69; - - /** - * Starting position of the source aspect slots - */ - private static final int SLOT_SOURCE_ASPECTS_POS_X = 65, SLOT_SOURCE_ASPECTS_POS_Y = 24, SLOT_SOURCE_ASPECTS_COUNT = 6; - - /** - * Position of the save aspect. - */ - private static final int SLOT_SELECTED_ASPECT_POS_X = 116, SLOT_SELECTED_ASPECT_POS_Y = 69; - - /** - * Position of the blank patterns. - */ - private static final int SLOT_PATTERNS_BLANK_POS_X = 146, SLOT_PATTERNS_BLANK_POS_Y = 75; - - /** - * Position of the encoded pattern. - */ - private static final int SLOT_PATTERN_ENCODED_POS_X = 146, SLOT_PATTERN_ENCODED_POS_Y = 113; - - /** - * Host encoder. - */ - private final TileDistillationPatternEncoder encoder; - - /** - * Slot holding the selected aspect. - */ - private final SlotFake slotSelectedAspect; - - /** - * Blank patterns slot. - */ - private final SlotRestrictive slotPatternsBlank; - - /** - * Encoded pattern slot. - */ - private final SlotRestrictive slotPatternEncoded; - - /** - * Pattern helper - */ - private final HandlerDistillationPattern patternHelper; - - /** - * Stores the aspects for the source item. - */ - private final TheInternalInventory internalInventory; - - /** - * Cached versions of the source and pattern. - */ - private ItemStack cachedSource, cachedPattern; - - /** - * Slot holding the source item. - */ - public final SlotFake slotSourceItem; - - /** - * Slots holding the source item's aspects. - */ - public final SlotFake[] slotSourceAspects = new SlotFake[ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT]; - - /** - * Gui to send updates to when slots change. - */ - public IInventoryUpdateReceiver slotUpdateReceiver; - - /** - * Constructor. - * - * @param player - * @param world - * @param x - * @param y - * @param z - */ - public ContainerDistillationPatternEncoder( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( player ); - - // Get the encoder - this.encoder = (TileDistillationPatternEncoder)world.getTileEntity( x, y, z ); - - // Create the internal inventory - this.internalInventory = new TheInternalInventory( "dpeAspects", 7, 64 ) - { - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack itemStack ) - { - return( ( itemStack == null ) || ( itemStack.getItem() instanceof ItemCraftingAspect ) ); - } - }; - - // Add the source aspect slots - for( int index = 0; index < ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT; ++index ) - { - // Calculate Y - int posY = ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_POS_Y + ( index * 18 ); - - // Create the slot - this.slotSourceAspects[index] = new SlotFake( this.internalInventory, index, - ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_POS_X, posY ); - this.addSlotToContainer( this.slotSourceAspects[index] ); - } - - // Add the selected aspect slot - this.slotSelectedAspect = new SlotFake( this.internalInventory, ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT, - ContainerDistillationPatternEncoder.SLOT_SELECTED_ASPECT_POS_X, - ContainerDistillationPatternEncoder.SLOT_SELECTED_ASPECT_POS_Y ); - this.addSlotToContainer( this.slotSelectedAspect ); - - // Add the source item slot - this.slotSourceItem = new SlotFake( this.encoder, TileDistillationPatternEncoder.SLOT_SOURCE_ITEM, - ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_X, - ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_Y ); - this.addSlotToContainer( this.slotSourceItem ); - - // Add blank pattern slot - this.slotPatternsBlank = new SlotRestrictive( this.encoder, TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS, - ContainerDistillationPatternEncoder.SLOT_PATTERNS_BLANK_POS_X, - ContainerDistillationPatternEncoder.SLOT_PATTERNS_BLANK_POS_Y ); - this.addSlotToContainer( this.slotPatternsBlank ); - - // Add encoded pattern slot - this.slotPatternEncoded = new SlotRestrictive( this.encoder, TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN, - ContainerDistillationPatternEncoder.SLOT_PATTERN_ENCODED_POS_X, - ContainerDistillationPatternEncoder.SLOT_PATTERN_ENCODED_POS_Y ); - this.addSlotToContainer( this.slotPatternEncoded ); - - // Bind to the players inventory - this.bindPlayerInventory( player.inventory, ContainerDistillationPatternEncoder.PLAYER_INV_POSITION_Y, - ContainerDistillationPatternEncoder.HOTBAR_INV_POSITION_Y ); - - // Create the helper - this.patternHelper = new HandlerDistillationPattern(); - - } - - /** - * Clears all aspect slots. - */ - private void clearAspectSlots() - { - this.slotSelectedAspect.clearStack(); - for( int index = 0; index < this.slotSourceAspects.length; ++index ) - { - this.slotSourceAspects[index].clearStack(); - } - } - - /** - * Returns true if the transfer was handled. - * Assumes that clickedslot has an itemstack. - * - * @param clickedSlot - * @return - */ - private boolean handleSlotTransfer( @Nonnull final Slot clickedSlot ) - { - // Get the stack - ItemStack slotStack = clickedSlot.getStack(); - - // Is the slot in the player inventory? - if( clickedSlot.inventory == this.player.inventory ) - { - // Will the blank pattern slot take this? - if( this.slotPatternsBlank.isItemValid( slotStack ) ) - { - return this.mergeItemStack( slotStack, this.slotPatternsBlank.slotNumber, this.slotPatternsBlank.slotNumber + 1, false ); - } - - // Will the encoded pattern take this? - if( this.slotPatternEncoded.isItemValid( slotStack ) ) - { - return this.mergeItemStack( slotStack, this.slotPatternEncoded.slotNumber, this.slotPatternEncoded.slotNumber + 1, false ); - } - // Set the source slot - ItemStack copy = slotStack.copy(); - copy.stackSize = 1; - this.slotSourceItem.putStack( copy ); - return true; - - } - - // Pattern slot? - if( ( ( this.slotPatternsBlank == clickedSlot ) || ( this.slotPatternEncoded == clickedSlot ) ) ) - { - // Merge with the hotbar? - if( !this.mergeSlotWithHotbarInventory( slotStack ) ) - { - // Merge with the player inventory - return this.mergeSlotWithPlayerInventory( slotStack ); - } - // Merged with hotbar - return true; - } - - return false; - } - - /** - * Attempts to load a pattern in the encoded slot. - */ - private void loadPattern() - { - // Read the pattern - this.cachedPattern = this.slotPatternEncoded.getStack(); - this.patternHelper.readPattern( this.cachedPattern ); - - // Is the pattern valid? - if( this.patternHelper.isValid() ) - { - // Set the source item - this.slotSourceItem.putStack( this.patternHelper.getInput() ); - this.scanSourceItem( false ); - - // Set the selected aspect - this.setSelectedAspect( this.patternHelper.getOutput() ); - } - } - - /** - * Called when the source item has changed. - * - * @param setSelectedAspect - */ - private void scanSourceItem( final boolean setSelectedAspect ) - { - - this.cachedSource = this.slotSourceItem.getStack(); - - // Clear aspect slots - this.clearAspectSlots(); - - // Null? - if( this.cachedSource == null ) - { - // Done - return; - } - - // Get the aspects - AspectList itemAspects = ThaumcraftApiHelper.getObjectAspects( this.cachedSource ); - itemAspects = ThaumcraftApiHelper.getBonusObjectTags( this.cachedSource, itemAspects ); - Aspect[] sortedAspects = null; - - // Does the item have any aspects? - if( ( itemAspects == null ) || ( itemAspects.size() == 0 ) ) - { - // Done - return; - } - - // Generate hash - int hash = ScanManager.generateItemHash( this.cachedSource.getItem(), this.cachedSource.getItemDamage() ); - - // Get the list of scanned objects - List list = Thaumcraft.proxy.getScannedObjects().get( this.player.getCommandSenderName() ); - - // Assume all slot will have an aspect - int numOfAspects = this.slotSourceAspects.length; - - // Has the player scanned the item? - boolean playerScanned = ( ( list != null ) && ( ( list.contains( "@" + hash ) ) || ( list.contains( "#" + hash ) ) ) ); - if( playerScanned ) - { - // Get sorted - sortedAspects = itemAspects.getAspectsSortedAmount(); - - // Set number to display - numOfAspects = Math.min( numOfAspects, sortedAspects.length ); - } - - // Add each aspect - Aspect aspect; - for( int i = 0; i < numOfAspects; ++i ) - { - // Create an itemstack - ItemStack aspectItem = ItemEnum.CRAFTING_ASPECT.getStack(); - - if( sortedAspects != null ) - { - // Get the aspect - aspect = sortedAspects[i]; - - // Set the aspect - ItemCraftingAspect.setAspect( aspectItem, aspect ); - - // Set the size - aspectItem.stackSize = itemAspects.getAmount( aspect ); - } - - // Put into slot - this.slotSourceAspects[i].putStack( aspectItem ); - - // Selected aspect empty? - if( setSelectedAspect && playerScanned && !this.slotSelectedAspect.getHasStack() ) - { - // Set selected - this.setSelectedAspect( aspectItem ); - } - } - } - - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - // Does the pattern slot need to be sync'd? - if( this.slotPatternEncoded.getStack() != this.cachedPattern ) - { - // Load the pattern - this.loadPattern(); - return true; - } - // Does the source item need to be sync'd? - else if( this.slotSourceItem.getStack() != this.cachedSource ) - { - // Scan the source item - this.scanSourceItem( true ); - return true; - } - - return false; - } - - /** - * Set's the selected aspect stack. - * - * @param aspectStack - */ - protected void setSelectedAspect( final ItemStack aspectStack ) - { - // Clear the stack - this.slotSelectedAspect.clearStack(); - - // Is there anything to put? - if( aspectStack == null ) - { - return; - } - - // Does the stack have an aspect? - Aspect aspect = ItemCraftingAspect.getAspect( aspectStack ); - if( aspect == null ) - { - return; - } - - // Has the player discovered this aspect? - if( !ItemCraftingAspect.canPlayerSeeAspect( this.player, aspect ) ) - { - // Set the selected aspect to unknown - this.slotSelectedAspect.putStack( ItemEnum.CRAFTING_ASPECT.getStack() ); - return; - } - - // Set the aspect - this.slotSelectedAspect.putStack( aspectStack.copy() ); - } - - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.encoder != null ) - { - return this.encoder.isUseableByPlayer( player ); - } - return false; - } - - /** - * Returns the player for this container. - * - * @return - */ - public EntityPlayer getPlayer() - { - return this.player; - } - - /** - * Called when a pattern is to be encoded. - */ - public void onEncodePattern() - { - ItemStack pattern = null; - boolean takeBlank = false; - - // Is there anything in the encoded pattern slot? - if( this.slotPatternEncoded.getHasStack() ) - { - // Set the pattern to it - pattern = this.slotPatternEncoded.getStack(); - } - // Is there a blank pattern to draw from? - else if( this.slotPatternsBlank.getHasStack() ) - { - // Create a new encoded pattern - pattern = AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).orNull(); - if( pattern == null ) - { - // Patterns are disabled? - // How did you even get here?! - return; - } - takeBlank = true; - } - else - { - // Nothing to save to - return; - } - - // Set the pattern items - if( !this.patternHelper.setPatternItems( this.slotSourceItem.getDisplayStack(), this.slotSelectedAspect.getDisplayStack() ) ) - { - // Nothing to save - return; - } - - // Encode! - this.patternHelper.encodePattern( pattern ); - - // Set the pattern slot - this.slotPatternEncoded.putStack( pattern ); - - if( takeBlank ) - { - // Decrement the blank patterns - this.slotPatternsBlank.decrStackSize( 1 ); - } - } - - @Override - public void putStackInSlot( final int slotNumber, final ItemStack stack ) - { - // Call super - super.putStackInSlot( slotNumber, stack ); - - // Source item changed? - if( ( this.slotUpdateReceiver != null ) && ( this.slotSourceItem.slotNumber == slotNumber ) ) - { - this.slotUpdateReceiver.onInventoryChanged( this.slotSourceItem.inventory ); - } - } - - @Override - public ItemStack slotClick( final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player ) - { - // Selected aspect? - if( this.slotSelectedAspect.slotNumber == slotNumber ) - { - // No interaction - return null; - } - - // If true detect will be called, and null returned. - boolean handled = false; - - // Source item slot? - if( this.slotSourceItem.slotNumber == slotNumber ) - { - // Get the item the player is dragging - ItemStack heldItem = player.inventory.getItemStack(); - - // Set the source slot - if( heldItem != null ) - { - ItemStack copy = heldItem.copy(); - copy.stackSize = 1; - this.slotSourceItem.putStack( copy ); - } - else - { - this.slotSourceItem.putStack( null ); - } - - handled = true; - } - - // One of the source aspect slots? - if( !handled ) - { - for( int index = 0; index < this.slotSourceAspects.length; ++index ) - { - if( this.slotSourceAspects[index].slotNumber == slotNumber ) - { - if( this.slotSourceAspects[index].getHasStack() ) - { - // Place it into the selected - this.setSelectedAspect( this.slotSourceAspects[index].getStack() ); - } - - // Done - handled = true; - break; - } - } - } - - // Was the click handled? - if( handled ) - { - // Detect any changes - this.detectAndSendChanges(); - - // Done - return null; - } - - // Call super - return super.slotClick( slotNumber, buttonPressed, flag, player ); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - if( EffectiveSide.isClientSide() ) - { - // Ignored client side - return null; - } - - // Get the slot - Slot clickedSlot = this.getSlotOrNull( slotNumber ); - - // Slot empty? - if( ( clickedSlot == null ) || !clickedSlot.getHasStack() ) - { - // Done - return null; - } - - // Was this handled? - if( this.handleSlotTransfer( clickedSlot ) ) - { - // Was the itemstack in the slot drained? - if( clickedSlot.getHasStack() && ( clickedSlot.getStack().stackSize <= 0 ) ) - { - // Set to null - clickedSlot.putStack( null ); - } - else - { - // Let the slot know it has changed. - clickedSlot.onSlotChanged(); - } - - // Update - this.detectAndSendChanges(); - } - - return null; - } +public class ContainerDistillationPatternEncoder extends ContainerWithPlayerInventory { + /** + * Y position for the player and hotbar inventory. + */ + private static final int PLAYER_INV_POSITION_Y = 152, + HOTBAR_INV_POSITION_Y = ContainerDistillationPatternEncoder.PLAYER_INV_POSITION_Y + 58; + + /** + * Position of the source item slot + */ + public static final int SLOT_SOURCE_ITEM_POS_X = 15, SLOT_SOURCE_ITEM_POS_Y = 69; + + /** + * Starting position of the source aspect slots + */ + private static final int SLOT_SOURCE_ASPECTS_POS_X = 65, + SLOT_SOURCE_ASPECTS_POS_Y = 24, + SLOT_SOURCE_ASPECTS_COUNT = 6; + + /** + * Position of the save aspect. + */ + private static final int SLOT_SELECTED_ASPECT_POS_X = 116, SLOT_SELECTED_ASPECT_POS_Y = 69; + + /** + * Position of the blank patterns. + */ + private static final int SLOT_PATTERNS_BLANK_POS_X = 146, SLOT_PATTERNS_BLANK_POS_Y = 75; + + /** + * Position of the encoded pattern. + */ + private static final int SLOT_PATTERN_ENCODED_POS_X = 146, SLOT_PATTERN_ENCODED_POS_Y = 113; + + /** + * Host encoder. + */ + private final TileDistillationPatternEncoder encoder; + + /** + * Slot holding the selected aspect. + */ + private final SlotFake slotSelectedAspect; + + /** + * Blank patterns slot. + */ + private final SlotRestrictive slotPatternsBlank; + + /** + * Encoded pattern slot. + */ + private final SlotRestrictive slotPatternEncoded; + + /** + * Pattern helper + */ + private final HandlerDistillationPattern patternHelper; + + /** + * Stores the aspects for the source item. + */ + private final TheInternalInventory internalInventory; + + /** + * Cached versions of the source and pattern. + */ + private ItemStack cachedSource, cachedPattern; + + /** + * Slot holding the source item. + */ + public final SlotFake slotSourceItem; + + /** + * Slots holding the source item's aspects. + */ + public final SlotFake[] slotSourceAspects = + new SlotFake[ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT]; + + /** + * Gui to send updates to when slots change. + */ + public IInventoryUpdateReceiver slotUpdateReceiver; + + /** + * Constructor. + * + * @param player + * @param world + * @param x + * @param y + * @param z + */ + public ContainerDistillationPatternEncoder( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(player); + + // Get the encoder + this.encoder = (TileDistillationPatternEncoder) world.getTileEntity(x, y, z); + + // Create the internal inventory + this.internalInventory = new TheInternalInventory("dpeAspects", 7, 64) { + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack itemStack) { + return ((itemStack == null) || (itemStack.getItem() instanceof ItemCraftingAspect)); + } + }; + + // Add the source aspect slots + for (int index = 0; index < ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT; ++index) { + // Calculate Y + int posY = ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_POS_Y + (index * 18); + + // Create the slot + this.slotSourceAspects[index] = new SlotFake( + this.internalInventory, index, ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_POS_X, posY); + this.addSlotToContainer(this.slotSourceAspects[index]); + } + + // Add the selected aspect slot + this.slotSelectedAspect = new SlotFake( + this.internalInventory, + ContainerDistillationPatternEncoder.SLOT_SOURCE_ASPECTS_COUNT, + ContainerDistillationPatternEncoder.SLOT_SELECTED_ASPECT_POS_X, + ContainerDistillationPatternEncoder.SLOT_SELECTED_ASPECT_POS_Y); + this.addSlotToContainer(this.slotSelectedAspect); + + // Add the source item slot + this.slotSourceItem = new SlotFake( + this.encoder, + TileDistillationPatternEncoder.SLOT_SOURCE_ITEM, + ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_X, + ContainerDistillationPatternEncoder.SLOT_SOURCE_ITEM_POS_Y); + this.addSlotToContainer(this.slotSourceItem); + + // Add blank pattern slot + this.slotPatternsBlank = new SlotRestrictive( + this.encoder, + TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS, + ContainerDistillationPatternEncoder.SLOT_PATTERNS_BLANK_POS_X, + ContainerDistillationPatternEncoder.SLOT_PATTERNS_BLANK_POS_Y); + this.addSlotToContainer(this.slotPatternsBlank); + + // Add encoded pattern slot + this.slotPatternEncoded = new SlotRestrictive( + this.encoder, + TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN, + ContainerDistillationPatternEncoder.SLOT_PATTERN_ENCODED_POS_X, + ContainerDistillationPatternEncoder.SLOT_PATTERN_ENCODED_POS_Y); + this.addSlotToContainer(this.slotPatternEncoded); + + // Bind to the players inventory + this.bindPlayerInventory( + player.inventory, + ContainerDistillationPatternEncoder.PLAYER_INV_POSITION_Y, + ContainerDistillationPatternEncoder.HOTBAR_INV_POSITION_Y); + + // Create the helper + this.patternHelper = new HandlerDistillationPattern(); + } + + /** + * Clears all aspect slots. + */ + private void clearAspectSlots() { + this.slotSelectedAspect.clearStack(); + for (int index = 0; index < this.slotSourceAspects.length; ++index) { + this.slotSourceAspects[index].clearStack(); + } + } + + /** + * Returns true if the transfer was handled. + * Assumes that clickedslot has an itemstack. + * + * @param clickedSlot + * @return + */ + private boolean handleSlotTransfer(@Nonnull final Slot clickedSlot) { + // Get the stack + ItemStack slotStack = clickedSlot.getStack(); + + // Is the slot in the player inventory? + if (clickedSlot.inventory == this.player.inventory) { + // Will the blank pattern slot take this? + if (this.slotPatternsBlank.isItemValid(slotStack)) { + return this.mergeItemStack( + slotStack, this.slotPatternsBlank.slotNumber, this.slotPatternsBlank.slotNumber + 1, false); + } + + // Will the encoded pattern take this? + if (this.slotPatternEncoded.isItemValid(slotStack)) { + return this.mergeItemStack( + slotStack, this.slotPatternEncoded.slotNumber, this.slotPatternEncoded.slotNumber + 1, false); + } + // Set the source slot + ItemStack copy = slotStack.copy(); + copy.stackSize = 1; + this.slotSourceItem.putStack(copy); + return true; + } + + // Pattern slot? + if (((this.slotPatternsBlank == clickedSlot) || (this.slotPatternEncoded == clickedSlot))) { + // Merge with the hotbar? + if (!this.mergeSlotWithHotbarInventory(slotStack)) { + // Merge with the player inventory + return this.mergeSlotWithPlayerInventory(slotStack); + } + // Merged with hotbar + return true; + } + + return false; + } + + /** + * Attempts to load a pattern in the encoded slot. + */ + private void loadPattern() { + // Read the pattern + this.cachedPattern = this.slotPatternEncoded.getStack(); + this.patternHelper.readPattern(this.cachedPattern); + + // Is the pattern valid? + if (this.patternHelper.isValid()) { + // Set the source item + this.slotSourceItem.putStack(this.patternHelper.getInput()); + this.scanSourceItem(false); + + // Set the selected aspect + this.setSelectedAspect(this.patternHelper.getOutput()); + } + } + + /** + * Called when the source item has changed. + * + * @param setSelectedAspect + */ + private void scanSourceItem(final boolean setSelectedAspect) { + + this.cachedSource = this.slotSourceItem.getStack(); + + // Clear aspect slots + this.clearAspectSlots(); + + // Null? + if (this.cachedSource == null) { + // Done + return; + } + + // Get the aspects + AspectList itemAspects = ThaumcraftApiHelper.getObjectAspects(this.cachedSource); + itemAspects = ThaumcraftApiHelper.getBonusObjectTags(this.cachedSource, itemAspects); + Aspect[] sortedAspects = null; + + // Does the item have any aspects? + if ((itemAspects == null) || (itemAspects.size() == 0)) { + // Done + return; + } + + // Generate hash + int hash = ScanManager.generateItemHash(this.cachedSource.getItem(), this.cachedSource.getItemDamage()); + + // Get the list of scanned objects + List list = Thaumcraft.proxy.getScannedObjects().get(this.player.getCommandSenderName()); + + // Assume all slot will have an aspect + int numOfAspects = this.slotSourceAspects.length; + + // Has the player scanned the item? + boolean playerScanned = ((list != null) && ((list.contains("@" + hash)) || (list.contains("#" + hash)))); + if (playerScanned) { + // Get sorted + sortedAspects = itemAspects.getAspectsSortedAmount(); + + // Set number to display + numOfAspects = Math.min(numOfAspects, sortedAspects.length); + } + + // Add each aspect + Aspect aspect; + for (int i = 0; i < numOfAspects; ++i) { + // Create an itemstack + ItemStack aspectItem = ItemEnum.CRAFTING_ASPECT.getStack(); + + if (sortedAspects != null) { + // Get the aspect + aspect = sortedAspects[i]; + + // Set the aspect + ItemCraftingAspect.setAspect(aspectItem, aspect); + + // Set the size + aspectItem.stackSize = itemAspects.getAmount(aspect); + } + + // Put into slot + this.slotSourceAspects[i].putStack(aspectItem); + + // Selected aspect empty? + if (setSelectedAspect && playerScanned && !this.slotSelectedAspect.getHasStack()) { + // Set selected + this.setSelectedAspect(aspectItem); + } + } + } + + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Does the pattern slot need to be sync'd? + if (this.slotPatternEncoded.getStack() != this.cachedPattern) { + // Load the pattern + this.loadPattern(); + return true; + } + // Does the source item need to be sync'd? + else if (this.slotSourceItem.getStack() != this.cachedSource) { + // Scan the source item + this.scanSourceItem(true); + return true; + } + + return false; + } + + /** + * Set's the selected aspect stack. + * + * @param aspectStack + */ + protected void setSelectedAspect(final ItemStack aspectStack) { + // Clear the stack + this.slotSelectedAspect.clearStack(); + + // Is there anything to put? + if (aspectStack == null) { + return; + } + + // Does the stack have an aspect? + Aspect aspect = ItemCraftingAspect.getAspect(aspectStack); + if (aspect == null) { + return; + } + + // Has the player discovered this aspect? + if (!ItemCraftingAspect.canPlayerSeeAspect(this.player, aspect)) { + // Set the selected aspect to unknown + this.slotSelectedAspect.putStack(ItemEnum.CRAFTING_ASPECT.getStack()); + return; + } + + // Set the aspect + this.slotSelectedAspect.putStack(aspectStack.copy()); + } + + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.encoder != null) { + return this.encoder.isUseableByPlayer(player); + } + return false; + } + + /** + * Returns the player for this container. + * + * @return + */ + public EntityPlayer getPlayer() { + return this.player; + } + + /** + * Called when a pattern is to be encoded. + */ + public void onEncodePattern() { + ItemStack pattern = null; + boolean takeBlank = false; + + // Is there anything in the encoded pattern slot? + if (this.slotPatternEncoded.getHasStack()) { + // Set the pattern to it + pattern = this.slotPatternEncoded.getStack(); + } + // Is there a blank pattern to draw from? + else if (this.slotPatternsBlank.getHasStack()) { + // Create a new encoded pattern + pattern = AEApi.instance() + .definitions() + .items() + .encodedPattern() + .maybeStack(1) + .orNull(); + if (pattern == null) { + // Patterns are disabled? + // How did you even get here?! + return; + } + takeBlank = true; + } else { + // Nothing to save to + return; + } + + // Set the pattern items + if (!this.patternHelper.setPatternItems( + this.slotSourceItem.getDisplayStack(), this.slotSelectedAspect.getDisplayStack())) { + // Nothing to save + return; + } + + // Encode! + this.patternHelper.encodePattern(pattern); + + // Set the pattern slot + this.slotPatternEncoded.putStack(pattern); + + if (takeBlank) { + // Decrement the blank patterns + this.slotPatternsBlank.decrStackSize(1); + } + } + + @Override + public void putStackInSlot(final int slotNumber, final ItemStack stack) { + // Call super + super.putStackInSlot(slotNumber, stack); + + // Source item changed? + if ((this.slotUpdateReceiver != null) && (this.slotSourceItem.slotNumber == slotNumber)) { + this.slotUpdateReceiver.onInventoryChanged(this.slotSourceItem.inventory); + } + } + + @Override + public ItemStack slotClick( + final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player) { + // Selected aspect? + if (this.slotSelectedAspect.slotNumber == slotNumber) { + // No interaction + return null; + } + + // If true detect will be called, and null returned. + boolean handled = false; + + // Source item slot? + if (this.slotSourceItem.slotNumber == slotNumber) { + // Get the item the player is dragging + ItemStack heldItem = player.inventory.getItemStack(); + + // Set the source slot + if (heldItem != null) { + ItemStack copy = heldItem.copy(); + copy.stackSize = 1; + this.slotSourceItem.putStack(copy); + } else { + this.slotSourceItem.putStack(null); + } + + handled = true; + } + + // One of the source aspect slots? + if (!handled) { + for (int index = 0; index < this.slotSourceAspects.length; ++index) { + if (this.slotSourceAspects[index].slotNumber == slotNumber) { + if (this.slotSourceAspects[index].getHasStack()) { + // Place it into the selected + this.setSelectedAspect(this.slotSourceAspects[index].getStack()); + } + + // Done + handled = true; + break; + } + } + } + + // Was the click handled? + if (handled) { + // Detect any changes + this.detectAndSendChanges(); + + // Done + return null; + } + + // Call super + return super.slotClick(slotNumber, buttonPressed, flag, player); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + if (EffectiveSide.isClientSide()) { + // Ignored client side + return null; + } + + // Get the slot + Slot clickedSlot = this.getSlotOrNull(slotNumber); + + // Slot empty? + if ((clickedSlot == null) || !clickedSlot.getHasStack()) { + // Done + return null; + } + + // Was this handled? + if (this.handleSlotTransfer(clickedSlot)) { + // Was the itemstack in the slot drained? + if (clickedSlot.getHasStack() && (clickedSlot.getStack().stackSize <= 0)) { + // Set to null + clickedSlot.putStack(null); + } else { + // Let the slot know it has changed. + clickedSlot.onSlotChanged(); + } + + // Update + this.detectAndSendChanges(); + } + + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCell.java b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCell.java index 027f524a..45b5e73b 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCell.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCell.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.container; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.Settings; import appeng.api.config.ViewItems; import appeng.api.networking.IGrid; @@ -15,6 +13,9 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.tile.storage.TileChest; import appeng.util.Platform; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; @@ -35,308 +36,266 @@ import thaumicenergistics.common.network.packet.server.Packet_S_EssentiaCellTerm import thaumicenergistics.common.storage.AspectStackComparator.AspectStackComparatorMode; import thaumicenergistics.common.utils.EffectiveSide; -import javax.annotation.Nonnull; - /** * Inventory container for essentia cells in a ME chest. * * @author Nividica * */ -public class ContainerEssentiaCell - extends ContainerEssentiaCellTerminalBase -{ - /** - * The ME chest the cell is stored in. - */ - private final TileChest hostChest; +public class ContainerEssentiaCell extends ContainerEssentiaCellTerminalBase { + /** + * The ME chest the cell is stored in. + */ + private final TileChest hostChest; - /** - * Network source representing the player who is interacting with the - * container. - */ - private PlayerSource playerSource = null; + /** + * Network source representing the player who is interacting with the + * container. + */ + private PlayerSource playerSource = null; - /** - * Compiler safe reference to the TileChest when using the - * ISaveProvider interface. - */ - private ISaveProvider chestSaveProvider; + /** + * Compiler safe reference to the TileChest when using the + * ISaveProvider interface. + */ + private ISaveProvider chestSaveProvider; - private Aspect tmpSelectedAspect; + private Aspect tmpSelectedAspect; - /** - * Import and export inventory slots. - */ - private TheInternalInventory privateInventory = new TheInternalInventory( ThaumicEnergistics.MOD_ID + ".item.essentia.cell.inventory", 2, 64 ) - { - @Override - public boolean isItemValidForSlot( final int slotID, final ItemStack itemStack ) - { - // Get the type - AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType( itemStack ); + /** + * Import and export inventory slots. + */ + private TheInternalInventory privateInventory = + new TheInternalInventory(ThaumicEnergistics.MOD_ID + ".item.essentia.cell.inventory", 2, 64) { + @Override + public boolean isItemValidForSlot(final int slotID, final ItemStack itemStack) { + // Get the type + AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType(itemStack); - // True if jar or jar label - return ( iType == AspectItemType.EssentiaContainer ) || ( iType == AspectItemType.JarLabel ); - } - }; + // True if jar or jar label + return (iType == AspectItemType.EssentiaContainer) || (iType == AspectItemType.JarLabel); + } + }; - /** - * Creates the container. - * - * @param player - * The player that owns this container. - * @param world - * The world the ME chest is in. - * @param x - * X position of the ME chest. - * @param y - * Y position of the ME chest. - * @param z - * Z position of the ME chest. - */ - public ContainerEssentiaCell( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call the super-constructor - super( player ); + /** + * Creates the container. + * + * @param player + * The player that owns this container. + * @param world + * The world the ME chest is in. + * @param x + * X position of the ME chest. + * @param y + * Y position of the ME chest. + * @param z + * Z position of the ME chest. + */ + public ContainerEssentiaCell(final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call the super-constructor + super(player); - // Get the tile entity for the chest - this.hostChest = (TileChest)world.getTileEntity( x, y, z ); + // Get the tile entity for the chest + this.hostChest = (TileChest) world.getTileEntity(x, y, z); - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - /* - * Note: Casting the hostChest to an object is required to prevent the compiler - * from seeing the soft-dependencies of AE2, such a buildcraft, which it attempts - * to resolve at compile time. - * */ - Object hostObject = this.hostChest; - this.chestSaveProvider = ( (ISaveProvider)hostObject ); + // Is this server side? + if (EffectiveSide.isServerSide()) { + /* + * Note: Casting the hostChest to an object is required to prevent the compiler + * from seeing the soft-dependencies of AE2, such a buildcraft, which it attempts + * to resolve at compile time. + * */ + Object hostObject = this.hostChest; + this.chestSaveProvider = ((ISaveProvider) hostObject); - // Create the action source - this.playerSource = new PlayerSource( this.player, (IActionHost)hostObject ); - } - else - { - // Request a full update from the server - Packet_S_EssentiaCellTerminal.sendFullUpdateRequest( player ); - } + // Create the action source + this.playerSource = new PlayerSource(this.player, (IActionHost) hostObject); + } else { + // Request a full update from the server + Packet_S_EssentiaCellTerminal.sendFullUpdateRequest(player); + } - // Bind our inventory - this.bindToInventory( this.privateInventory ); + // Bind our inventory + this.bindToInventory(this.privateInventory); + } - } + /** + * Gets a handler for the essentia cell. + * + * @return + */ + private HandlerItemEssentiaCell getCellHandler() { + // Ensure we have a host + if (this.hostChest == null) { + return null; + } - /** - * Gets a handler for the essentia cell. - * - * @return - */ - private HandlerItemEssentiaCell getCellHandler() - { - // Ensure we have a host - if( this.hostChest == null ) - { - return null; - } + // Get the cell + ItemStack essentiaCell = this.hostChest.getStackInSlot(1); - // Get the cell - ItemStack essentiaCell = this.hostChest.getStackInSlot( 1 ); + // Ensure we have the cell + if ((essentiaCell == null) || !(essentiaCell.getItem() instanceof ItemEssentiaCell)) { + return null; + } - // Ensure we have the cell - if( ( essentiaCell == null ) || !( essentiaCell.getItem() instanceof ItemEssentiaCell ) ) - { - return null; - } + // Get the handler + return new HandlerItemEssentiaCell(essentiaCell, this.chestSaveProvider); + } - // Get the handler - return new HandlerItemEssentiaCell( essentiaCell, this.chestSaveProvider ); - } + @Override + protected BaseActionSource getActionSource() { + return this.playerSource; + } - @Override - protected BaseActionSource getActionSource() - { - return this.playerSource; - } + @Override + protected IGrid getHostGrid() { + try { + return this.hostChest.getActionableNode().getGrid(); + } catch (Exception e) { + return null; + } + } - @Override - protected IGrid getHostGrid() - { - try - { - return this.hostChest.getActionableNode().getGrid(); - } - catch( Exception e ) - { - return null; - } - } + @Override + protected Aspect getHostSelectedAspect() { + return this.tmpSelectedAspect; + } - @Override - protected Aspect getHostSelectedAspect() - { - return this.tmpSelectedAspect; - } + @Override + protected IMEEssentiaMonitor getNewMonitor() { + try { + IMEInventoryHandler handler = null; - @Override - protected IMEEssentiaMonitor getNewMonitor() - { - try - { - IMEInventoryHandler handler = null; + // Get the chest handler + List hostCellArray = this.hostChest.getCellArray(StorageChannel.FLUIDS); + if (hostCellArray.size() > 0) { + handler = hostCellArray.get(0); + } - // Get the chest handler - List hostCellArray = this.hostChest.getCellArray( StorageChannel.FLUIDS ); - if( hostCellArray.size() > 0 ) - { - handler = hostCellArray.get( 0 ); - } + // Get the monitor + if (handler != null) { + // Create the essentia monitor + return new EssentiaMonitor( + (IMEMonitor) handler, + this.hostChest.getProxy().getEnergy(), + this); + } + } catch (Exception e) { + e.printStackTrace(); + } - // Get the monitor - if( handler != null ) - { - // Create the essentia monitor - return new EssentiaMonitor( (IMEMonitor)handler, this.hostChest.getProxy().getEnergy(), this ); - } - } - catch( Exception e ) - { - e.printStackTrace(); - } + return null; + } - return null; - } + @Override + protected void setHostSelectedAspect(final Aspect aspect) { + this.tmpSelectedAspect = aspect; + } - @Override - protected void setHostSelectedAspect( final Aspect aspect ) - { - this.tmpSelectedAspect = aspect; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.hostChest != null) { + return this.hostChest.isUseableByPlayer(player); + } + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.hostChest != null ) - { - return this.hostChest.isUseableByPlayer( player ); - } - return false; - } + /** + * Transfers essentia. + */ + @Override + public void doWork(final int elapsedTicks) { + // Transfer essentia if needed. + this.transferEssentiaFromWorkSlots(); + } - /** - * Transfers essentia. - */ - @Override - public void doWork( final int elapsedTicks ) - { - // Transfer essentia if needed. - this.transferEssentiaFromWorkSlots(); - } + @Override + public ICraftingIssuerHost getCraftingHost() { + // Can't craft. + return null; + } - @Override - public ICraftingIssuerHost getCraftingHost() - { - // Can't craft. - return null; - } + @Override + public void onClientRequestAutoCraft(final EntityPlayer player, final Aspect aspect) { + // Ignored, can't issue, or even see, craftable essentia from here. + } - @Override - public void onClientRequestAutoCraft( final EntityPlayer player, final Aspect aspect ) - { - // Ignored, can't issue, or even see, craftable essentia from here. - } + /** + * Gets the current list from the AE monitor and sends + * it to the client. + */ + @Override + public void onClientRequestFullUpdate() { + // Get the handler + HandlerItemEssentiaCell cellHandler = this.getCellHandler(); - /** - * Gets the current list from the AE monitor and sends - * it to the client. - */ - @Override - public void onClientRequestFullUpdate() - { - // Get the handler - HandlerItemEssentiaCell cellHandler = this.getCellHandler(); + // Did we get the handler? + if (cellHandler != null) { + // Send the viewing mode + Packet_C_EssentiaCellTerminal.sendViewingModes( + this.player, cellHandler.getSortingMode(), cellHandler.getViewMode()); + } - // Did we get the handler? - if( cellHandler != null ) - { - // Send the viewing mode - Packet_C_EssentiaCellTerminal.sendViewingModes( this.player, cellHandler.getSortingMode(), cellHandler.getViewMode() ); - } + // Send the list + if (this.hostChest.isPowered()) { + Packet_C_EssentiaCellTerminal.sendFullList(this.player, this.repo.getAll()); + } else { + Packet_C_EssentiaCellTerminal.sendFullList(this.player, new ArrayList()); + } + } - // Send the list - if( this.hostChest.isPowered() ) - { - Packet_C_EssentiaCellTerminal.sendFullList( this.player, this.repo.getAll() ); - } - else - { - Packet_C_EssentiaCellTerminal.sendFullList( this.player, new ArrayList() ); + @Override + public void onClientRequestSortModeChange(final EntityPlayer player, final boolean backwards) { + // Get the handler + HandlerItemEssentiaCell cellHandler = this.getCellHandler(); + if (cellHandler != null) { + // Change the sorting mode + AspectStackComparatorMode sortingMode; + if (backwards) { + sortingMode = cellHandler.getSortingMode().previousMode(); + } else { + sortingMode = cellHandler.getSortingMode().nextMode(); + } - } - } + // Inform the handler of the change + cellHandler.setSortingMode(sortingMode); - @Override - public void onClientRequestSortModeChange( final EntityPlayer player, final boolean backwards ) - { - // Get the handler - HandlerItemEssentiaCell cellHandler = this.getCellHandler(); - if( cellHandler != null ) - { - // Change the sorting mode - AspectStackComparatorMode sortingMode; - if( backwards ) - { - sortingMode = cellHandler.getSortingMode().previousMode(); - } - else - { - sortingMode = cellHandler.getSortingMode().nextMode(); - } + // Send confirmation back to client + Packet_C_EssentiaCellTerminal.sendViewingModes(player, sortingMode, cellHandler.getViewMode()); + } + } - // Inform the handler of the change - cellHandler.setSortingMode( sortingMode ); + @Override + public void onClientRequestViewModeChange(final EntityPlayer player, final boolean backwards) { + // Get the handler + HandlerItemEssentiaCell cellHandler = this.getCellHandler(); + if (cellHandler != null) { - // Send confirmation back to client - Packet_C_EssentiaCellTerminal.sendViewingModes( player, sortingMode, cellHandler.getViewMode() ); - } - } + // Change the view mode + ViewItems viewMode = + Platform.rotateEnum(cellHandler.getViewMode(), backwards, Settings.VIEW_MODE.getPossibleValues()); - @Override - public void onClientRequestViewModeChange( final EntityPlayer player, final boolean backwards ) - { - // Get the handler - HandlerItemEssentiaCell cellHandler = this.getCellHandler(); - if( cellHandler != null ) - { + // Inform the handler of the change + cellHandler.setViewMode(viewMode); - // Change the view mode - ViewItems viewMode = Platform.rotateEnum( cellHandler.getViewMode(), backwards, Settings.VIEW_MODE.getPossibleValues() ); + // Send confirmation back to client + Packet_C_EssentiaCellTerminal.sendViewingModes(player, cellHandler.getSortingMode(), viewMode); + } + } - // Inform the handler of the change - cellHandler.setViewMode( viewMode ); + /** + * Drops any items in the import and export inventory. + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Drop anything in the work slots. + if (EffectiveSide.isServerSide()) { + for (int i = 0; i < 2; i++) { + this.player.dropPlayerItemWithRandomChoice(((Slot) this.inventorySlots.get(i)).getStack(), false); + } + } - // Send confirmation back to client - Packet_C_EssentiaCellTerminal.sendViewingModes( player, cellHandler.getSortingMode(), viewMode ); - } - } - - /** - * Drops any items in the import and export inventory. - */ - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - // Drop anything in the work slots. - if( EffectiveSide.isServerSide() ) - { - for( int i = 0; i < 2; i++ ) - { - this.player.dropPlayerItemWithRandomChoice( ( (Slot)this.inventorySlots.get( i ) ).getStack(), false ); - } - } - - // Call super - super.onContainerClosed( player ); - } + // Call super + super.onContainerClosed(player); + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellTerminalBase.java b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellTerminalBase.java index 8eb6699e..cc20778b 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellTerminalBase.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellTerminalBase.java @@ -1,9 +1,5 @@ package thaumicenergistics.common.container; -import java.util.Collection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.apache.commons.lang3.tuple.ImmutablePair; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; @@ -12,12 +8,16 @@ import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.security.ISecurityGrid; import appeng.api.networking.security.MachineSource; import appeng.api.networking.security.PlayerSource; +import java.util.Collection; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.inventory.SlotFurnace; import net.minecraft.item.ItemStack; +import org.apache.commons.lang3.tuple.ImmutablePair; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.ICraftingIssuerHost; import thaumicenergistics.api.grid.IMEEssentiaMonitor; @@ -43,1082 +43,977 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public abstract class ContainerEssentiaCellTerminalBase - extends ContainerWithPlayerInventory - implements IMEEssentiaMonitorReceiver, IAspectSelectorContainer, ICraftingIssuerContainer -{ - /** - * X position for the output slot - */ - private static final int OUTPUT_POSITION_X = 26; - - /** - * Y position for the output slot - */ - private static final int OUTPUT_POSITION_Y = 92; - - /** - * X position for the input slot - */ - private static final int INPUT_POSITION_X = 8; - - /** - * Y position for the input slot - */ - private static final int INPUT_POSITION_Y = ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_Y; - - /** - * Y position for the player inventory - */ - private static final int PLAYER_INV_POSITION_Y = 122; - - /** - * Y position for the hotbar inventory - */ - private static final int HOTBAR_INV_POSITION_Y = 180; - - /** - * The minimum amount of time to wait before playing - * sounds again. In ms. - */ - private static final int MINIMUM_SOUND_WAIT = 900; - - /** - * The number of ticks required to pass before doWork is called. - */ - private static final int WORK_TICK_RATE = 3; - - /** - * The maximum amount of essentia to try and transfer each time - * the transfer method is called. - * This is a soft-cap. - */ - private static final int ESSENTIA_TRANSFER_PER_WORK_CYCLE = 64; - - /** - * Inventory indices for the input and output - */ - private static int OUTPUT_INV_INDEX = 1, INPUT_INV_INDEX = 0; - - /** - * Location of the splash sound - */ - private final String soundLocation_Splash = "game.neutral.swim"; - - /** - * Location of the paper sound - */ - private final String soundLocation_Paper = "thaumcraft:page"; - - /** - * The last known stack size stored in the export slot - */ - private int audioStackSizeTracker = 0; - - /** - * Work slots - */ - private Slot inputSlot; - - /** - * Import and export inventory - */ - private IInventory inventory; - - /** - * The last time, in ms, the transfer sound played - */ - private long lastSoundPlaytime = 0; - - /** - * Work slots - */ - private Slot outputSlot; - - /** - * The aspect the user has selected. - */ - private Aspect selectedAspect; - - /** - * Tracks the number of ticks - */ - private int tickCounter = 0; - - /** - * Tracks the amount of work performed. - */ - private int workCounter = 0; - - /** - * List of aspects on the network - */ - protected final IEssentiaRepo repo; - - /** - * Essentia network monitor - */ - private IMEEssentiaMonitor essentiaMonitor; - - /** - * Create the container and register the owner - * - * @param player - */ - public ContainerEssentiaCellTerminalBase( final EntityPlayer player ) - { - // Call super - super( player ); - - if( EffectiveSide.isClientSide() ) - { - // Set the sound time - this.lastSoundPlaytime = System.currentTimeMillis(); - } - - // Create the reop - this.repo = new EssentiaRepo(); - } - - /** - * Attach this container to the Essentia monitor - * - * @param essentiaMonitor - */ - private boolean attachToMonitor( final IMEEssentiaMonitor eMonitor ) - { - if( ( EffectiveSide.isServerSide() ) && ( eMonitor != null ) ) - { - // Get the grid - IGrid grid = this.getHostGrid(); - if( grid == null ) - { - return false; - } - - // Detach from any current monitor - if( this.essentiaMonitor != null ) - { - this.detachFromMonitor(); - } - - // Set the monitor - this.essentiaMonitor = eMonitor; - - // Listen - this.essentiaMonitor.addListener( this, grid.hashCode() ); - - // Update our cached list of aspects - this.repo.copyFrom( this.essentiaMonitor.getEssentiaList() ); - return true; - } - - return false; - } - - /** - * Returns true if the specified stack can be merged into the output slot. - * - * @param stackToMerge - * @return True if the slot is empty, - * or if can be merged by increasing the slots stacksize by the specified stacks stacksize. - */ - private boolean canMergeWithOutputSlot( final ItemStack stackToMerge ) - { - // Ensure the stack is not null. - if( stackToMerge == null ) - { - // Invalid itemstack - return false; - } - - // Is the slot empty? - if( !this.outputSlot.getHasStack() ) - { - return true; - } - - // Get the slot stack - ItemStack slotStack = this.outputSlot.getStack(); - - // Get the stack size - int slotStackSize = slotStack.stackSize; - - // Is the slot full? - if( slotStack.getMaxStackSize() == slotStackSize ) - { - return false; - } - - // Will adding the stack cause the slot to be over full? - if( ( slotStackSize + stackToMerge.stackSize ) > slotStack.getMaxStackSize() ) - { - return false; - } - - // Do the stacks match? - // Compare ignoring stack size - ItemStack o = slotStack.copy(); - ItemStack n = stackToMerge.copy(); - o.stackSize = 1; - n.stackSize = 1; - return ItemStack.areItemStacksEqual( o, n ); - } - - /** - * Returns if the player has the requested permission or not. - * - * @param perm - * @param actionSource - * @return - */ - private boolean checkSecurityPermission( final SecurityPermissions perm, final BaseActionSource actionSource ) - { - - // Ensure there is an action source. - if( actionSource == null ) - { - return false; - } - - // Get the source node - IGridNode sourceNode = null; - if( actionSource instanceof MachineSource ) - { - sourceNode = ( (MachineSource)actionSource ).via.getActionableNode(); - } - else if( actionSource instanceof PlayerSource ) - { - sourceNode = ( (PlayerSource)actionSource ).via.getActionableNode(); - } - - // Ensure there is a node - if( sourceNode == null ) - { - return false; - } - - // Get the security grid for the node. - ISecurityGrid sGrid = sourceNode.getGrid().getCache( ISecurityGrid.class ); - - // Return the permission. - return sGrid.hasPermission( this.player, perm ); - } - - /** - * Drains an essentia container item. - * - * @param container - * @param actionSource - * @param mode - * @return The result of the drain. - */ - @Nullable - private ImmutablePair drainContainer( final ItemStack container, final BaseActionSource actionSource, - final Actionable mode ) - { - // Ensure there is a container - if( container == null ) - { - return null; - } - - // Get the fluid stack from the item - IAspectStack containerEssentia = EssentiaItemContainerHelper.INSTANCE.getAspectStackFromContainer( container ); - - // Ensure there is something to drain - if( ( containerEssentia == null ) || containerEssentia.isEmpty() ) - { - // Nothing to drain - return null; - } - - // Get the proposed drain amount. - int proposedDrainAmount = (int)containerEssentia.getStackSize(); - - // Do a network injection - long rejectedAmount = this.essentiaMonitor.injectEssentia( containerEssentia.getAspect(), proposedDrainAmount, mode, actionSource, - true ); - - // Was any rejected? - if( rejectedAmount > 0 ) - { - // Decrease the proposed amount - proposedDrainAmount -= (int)rejectedAmount; - - // Can the network accept any? - if( proposedDrainAmount <= 0 ) - { - // Network is full - return null; - } - } - - // Adjust work counter - if( mode == Actionable.MODULATE ) - { - this.workCounter += proposedDrainAmount; - } - - // Attempt to drain the container - return EssentiaItemContainerHelper.INSTANCE.extractFromContainer( container, proposedDrainAmount ); - } - - /** - * Fills an essentia container item. - * - * @param withAspect - * @param container - * @param actionSource - * @param mode - * @return The result of the fill. - */ - @Nullable - private ImmutablePair fillContainer( final Aspect withAspect, final ItemStack container, - final BaseActionSource actionSource, final Actionable mode ) - { - // Ensure there is an aspect - if( withAspect == null ) - { - return null; - } - - // Get the capacity of the container - int containerCapacity = EssentiaItemContainerHelper.INSTANCE.getContainerCapacity( container ); - - // Can the container hold essentia? - if( containerCapacity == 0 ) - { - // Invalid container - return null; - } - - // Do an extraction from the network - long extractedAmount = this.essentiaMonitor.extractEssentia( withAspect, containerCapacity, mode, actionSource, true ); - - // Was anything extracted? - if( extractedAmount <= 0 ) - { - // Gas is not present on network. - return null; - } - - // Calculate the proposed amount, based on how much we need and how much - // is available - int proposedFillAmount = (int)Math.min( containerCapacity, extractedAmount ); - - // Adjust work counter - if( mode == Actionable.MODULATE ) - { - this.workCounter += proposedFillAmount; - } - - // Create a new container filled to the proposed amount - return EssentiaItemContainerHelper.INSTANCE.injectIntoContainer( container, - new AspectStack( withAspect, proposedFillAmount ) ); - } - - /** - * Binds the container to the specified inventory and the players inventory. - * - * @param inventory - */ - protected void bindToInventory( final IInventory inventory ) - { - // Set the inventory - this.inventory = inventory; - - // Create the input slot - this.inputSlot = new SlotRestrictive( inventory, ContainerEssentiaCellTerminalBase.INPUT_INV_INDEX, - ContainerEssentiaCellTerminalBase.INPUT_POSITION_X, ContainerEssentiaCellTerminalBase.INPUT_POSITION_Y ); - this.addSlotToContainer( this.inputSlot ); - - // Create the output slot - this.outputSlot = new SlotFurnace( this.player, inventory, ContainerEssentiaCellTerminalBase.OUTPUT_INV_INDEX, - ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_X, ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_Y ); - this.addSlotToContainer( this.outputSlot ); - - // Bind to the player's inventory - this.bindPlayerInventory( this.player.inventory, ContainerEssentiaCellTerminalBase.PLAYER_INV_POSITION_Y, - ContainerEssentiaCellTerminalBase.HOTBAR_INV_POSITION_Y ); - - } - - /** - * Detaches from the monitor if attached. - */ - protected void detachFromMonitor() - { - if( EffectiveSide.isServerSide() ) - { - if( this.essentiaMonitor != null ) - { - // Stop listening - this.essentiaMonitor.removeListener( this ); - - // Null the monitor - this.essentiaMonitor = null; - - // Clear the repo - this.repo.clear(); - } - } - } - - /** - * Checks if there is any work to perform. - * If there is it does so. - */ - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - // Compare selected aspects - if( this.getHostSelectedAspect() != this.selectedAspect ) - { - // Update the selected aspect - this.selectedAspect = this.getHostSelectedAspect(); - - // Send the change back to the client - Packet_C_EssentiaCellTerminal.setSelectedAspect( this.player, this.selectedAspect ); - } - - // Is there a monitor? - if( this.essentiaMonitor != null ) - { - // Inc tick tracker - this.tickCounter += 1; - - if( this.tickCounter > ContainerEssentiaCellTerminalBase.WORK_TICK_RATE ) - { - // Do work - this.doWork( this.tickCounter ); - - // Reset the tick counter - this.tickCounter = 0; - - return true; - } - } - else - { - // Attempt to attach to a monitor - if( this.attachToMonitor( this.getNewMonitor() ) ) - { - // Send update - this.onClientRequestFullUpdate(); - } - - } - - return false; - } - - /** - * Called periodically so that the container can perform work. - */ - protected abstract void doWork( int elapsedTicks ); - - /** - * Gets the action source. - * - * @return - */ - protected abstract BaseActionSource getActionSource(); - - /** - * Gets the grid for the host. - * - * @return - */ - @Nullable - protected abstract IGrid getHostGrid(); - - /** - * Return the selected aspect stored in the host. - * - * @return - */ - @Nullable - protected abstract Aspect getHostSelectedAspect(); - - /** - * Attempts to get a new essentia monitor. - * - * @return - */ - @Nullable - protected abstract IMEEssentiaMonitor getNewMonitor(); - - /** - * Sets the hosts selected aspect. - * - * @param aspect - */ - protected abstract void setHostSelectedAspect( @Nullable Aspect aspect ); - - /** - * Fills, drains, or sets label aspect. - * - * @param stack - * This is not modified during the course of this function. - * @param aspect - * Ignored when draining - * @param actionSource - * @param mode - * @return The new stack if changes made, the original stack otherwise. - */ - protected ItemStack transferEssentia( final ItemStack stack, final Aspect aspect, final BaseActionSource actionSource, final Actionable mode ) - { - // Ensure the stack & monitor are not null - if( ( stack == null ) || ( this.essentiaMonitor == null ) ) - { - return stack; - } - - // Get the item type - AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType( stack ); - - // Label? - if( iType == AspectItemType.JarLabel ) - { - // Copy the stack - ItemStack label = stack.copy(); - - // Set the label - EssentiaItemContainerHelper.INSTANCE.setLabelAspect( label, aspect ); - - // Update work performed - ++this.workCounter; - - // Return the label - return label; - } - - // Valid container? - if( iType != AspectItemType.EssentiaContainer ) - { - // Invalid container - return stack; - } - - // Result of the operation - ImmutablePair result = null; - - // Filling? - if( EssentiaItemContainerHelper.INSTANCE.isContainerEmpty( stack ) ) - { - // Check extract permission - if( this.checkSecurityPermission( SecurityPermissions.EXTRACT, actionSource ) ) - { - // Attempt to fill the container - result = this.fillContainer( aspect, stack, actionSource, mode ); - } - } - // Draining - else - { - // Check inject permission - if( this.checkSecurityPermission( SecurityPermissions.INJECT, actionSource ) ) - { - // Attempt to drain the container - result = this.drainContainer( stack, actionSource, mode ); - } - } - - // Is there any result? - if( result != null ) - { - // Return the new stack. - return result.right; - } - - // No result - return stack; - } - - /** - * Transfers essentia in or out of the system using the input and output slots. - */ - protected void transferEssentiaFromWorkSlots() - { - // Ensure the inventory is valid - if( this.inventory == null ) - { - return; - } - - // Get the input stack - final ItemStack inputStack = this.inventory.getStackInSlot( ContainerEssentiaCellTerminalBase.INPUT_INV_INDEX ); - - // Ensure the input stack is not empty - if( ( inputStack == null ) ) - { - // Nothing in input slot. - return; - } - - // Is the output slot full? - if( this.outputSlot.getHasStack() ) - { - ItemStack outputStack = this.outputSlot.getStack(); - if( outputStack.stackSize >= outputStack.getMaxStackSize() ) - { - // Output slot is full. - return; - } - } - - // Reset the work counter - this.workCounter = 0; - - // Get the action source - final BaseActionSource actionSource = this.getActionSource(); - - // Copy the input - final ItemStack container = inputStack.copy(); - container.stackSize = 1; - - // Loop while maximum work has not been performed, there is input, and the operation did not fail. - ItemStack result; - do - { - // Simulate the work - result = this.transferEssentia( container, this.selectedAspect, actionSource, Actionable.SIMULATE ); - - // Did anything change? - if( ( result == null ) || ( result == container ) ) - { - // No work to perform - break; - } - - // Can the result not be merged with the output stack? - if( !this.canMergeWithOutputSlot( result ) ) - { - // Unable to merge - break; - } - - // Perform the work - result = this.transferEssentia( container, this.selectedAspect, actionSource, Actionable.MODULATE ); - - // Merge the result - if( this.outputSlot.getHasStack() ) - { - // Can just increment here because canMergeWithOutputSlot explicitly checks that - ++this.outputSlot.getStack().stackSize; - } - else - { - this.outputSlot.putStack( result ); - } - - // Is the input drained? - if( ( --inputStack.stackSize ) == 0 ) - { - this.inputSlot.putStack( null ); - break; - } - } - while( this.workCounter < ContainerEssentiaCellTerminalBase.ESSENTIA_TRANSFER_PER_WORK_CYCLE ); - } - - /** - * Gets the list of aspect stacks in the container. - * - * @return - */ - public Collection getAspectStackList() - { - return this.repo.getAll(); - } - - @Override - public abstract ICraftingIssuerHost getCraftingHost(); - - /** - * Get the player that owns this container - * - * @return - */ - public EntityPlayer getPlayer() - { - return this.player; - } - - /** - * Gets the aspect that the player has selected. - * - * @return - */ - public Aspect getSelectedAspect() - { - return this.selectedAspect; - } - - /** - * Is this container still valid for receiving updates - * from the AE monitor? - */ - @Override - public final boolean isValid( final Object verificationToken ) - { - // Get the grid - IGrid grid = this.getHostGrid(); - if( grid != null ) - { - // Do the hash codes match? - if( grid.hashCode() == (Integer)verificationToken ) - { - return true; - } - } - - // No longer valid (Do not call detach, this will happen automatically) - this.essentiaMonitor = null; - this.repo.clear(); - - // Update the client - this.onClientRequestFullUpdate(); - - return false; - } - - /** - * Called when a client has clicked on a craftable aspect. - * - * @param player - * @param result - */ - public abstract void onClientRequestAutoCraft( final EntityPlayer player, final Aspect aspect ); - - /** - * Called when a client requests the state of the container. - * Updates our cached list of aspects - */ - public abstract void onClientRequestFullUpdate(); - - /** - * Called when a client sends a sorting mode change request. - * - * @param sortingMode - */ - public abstract void onClientRequestSortModeChange( final EntityPlayer player, boolean backwards ); - - /** - * Called when a client sends a view mode change request. - * - * @param player - */ - public abstract void onClientRequestViewModeChange( final EntityPlayer player, boolean backwards ); - - /** - * Unregister this container from the monitor. - */ - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - // Call super - super.onContainerClosed( player ); - - // Detach from the monitor - this.detachFromMonitor(); - } - - /** - * Called when a player clicked on an aspect while holding an item. - * - * @param player - * @param aspect - */ - public void onInteractWithHeldItem( final EntityPlayer player, final Aspect aspect ) - { - // Sanity check - if( ( ( player == null ) || ( player.inventory.getItemStack() == null ) ) ) - { - return; - } - - // Get the item - ItemStack sourceStack = player.inventory.getItemStack(); - - // Create a new stack - final ItemStack takeFrom = sourceStack.copy(); - takeFrom.stackSize = 1; - - // Get the action source - final BaseActionSource actionSource = this.getActionSource(); - - // Simulate the transfer - ItemStack resultStack = this.transferEssentia( takeFrom, aspect, actionSource, Actionable.SIMULATE ); - - // Was any work performed? - if( ( resultStack == null ) || ( resultStack == takeFrom ) ) - { - // Nothing to do. - return; - } - - // If the source stack size is > 1, the result will need to be put into the player inventory - if( sourceStack.stackSize > 1 ) - { - // Attempt to merge - if( !this.mergeSlotWithHotbarInventory( resultStack ) ) - { - if( !this.mergeSlotWithPlayerInventory( resultStack ) ) - { - // Could not merge - return; - } - } - - // Decrement the source stack - --sourceStack.stackSize; - } - else - { - // Set the source stack to the result - sourceStack = resultStack; - } - - // Perform the work - this.transferEssentia( takeFrom, aspect, actionSource, Actionable.MODULATE ); - - // Set what the player is holding - player.inventory.setItemStack( sourceStack ); - - // Update - Packet_C_Sync.sendPlayerHeldItem( player, sourceStack ); - if( player instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP)player ).isChangingQuantityOnly = false; - } - this.detectAndSendChanges(); - this.playTransferSound( player, false, - ( EssentiaItemContainerHelper.INSTANCE.getItemType( sourceStack ) == AspectItemType.JarLabel ? 1 : 0 ) ); - - } - - /** - * Called by the gui when the aspect list arrives. - * - * @param aspectStackList - */ - public void onReceivedAspectList( final Collection aspectStackList ) - { - // Set the aspect list - this.repo.copyFrom( aspectStackList ); - } - - /** - * Called by the gui when a change arrives. - * - * @param change - */ - public void onReceivedAspectListChange( final IAspectStack change ) - { - // Ignored server side - if( EffectiveSide.isServerSide() ) - { - return; - } - - // Ensure the change is not null - if( change == null ) - { - return; - } - - // Post the change - this.repo.postChange( change ); - } - - /** - * Called when the the selected aspect has changed. - * - * @param selectedAspect - */ - public void onReceivedSelectedAspect( final Aspect selectedAspect ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - this.setHostSelectedAspect( selectedAspect ); - } - else - { - this.selectedAspect = selectedAspect; - } - } - - /** - * Checks if the transfer sound should play. - * if checkWorkSlots is true the type will be automatically determined. - * - * @param player - * @param checkWorkSlots - * @param type - * 0 = splash, 1 = paper - */ - - public void playTransferSound( final EntityPlayer player, final boolean checkWorkSlots, int type ) - { - if( checkWorkSlots ) - { - // Get the itemstack in the output slot - ItemStack itemStack = this.outputSlot.getStack(); - - // Is there anything in the second slot? - if( itemStack != null ) - { - - // Is the item a label? - if( EssentiaItemContainerHelper.INSTANCE.getItemType( itemStack ) == AspectItemType.JarLabel ) - { - type = 1; - } - else - { - type = 0; - } - - // Has the count changed? - if( this.audioStackSizeTracker == itemStack.stackSize ) - { - // Nothing changed - return; - } - - // Set the count - this.audioStackSizeTracker = itemStack.stackSize; - - } - else - { - // Reset the count - this.audioStackSizeTracker = 0; - return; - } - - } - - // Has enough time passed to play the sound again? - if( ( System.currentTimeMillis() - this.lastSoundPlaytime ) > ContainerEssentiaCellTerminalBase.MINIMUM_SOUND_WAIT ) - { - if( type == 0 ) - { - ThEUtils.playClientSound( this.player, this.soundLocation_Splash ); - } - else if( type == 1 ) - { - ThEUtils.playClientSound( this.player, this.soundLocation_Paper ); - } - - // Set the playtime - this.lastSoundPlaytime = System.currentTimeMillis(); - } - } - - /** - * Called by the Essentia monitor when the network changes. - */ - - @Override - public final void postChange( final IMEEssentiaMonitor fromMonitor, final Iterable changes ) - { - // Ensure there was a change - if( changes == null ) - { - return; - } - - // Loop over the changes - for( IAspectStack change : changes ) - { - // Update the client - Packet_C_EssentiaCellTerminal.setAspectAmount( this.player, change ); - } - } - - @Override - public void putStackInSlot( final int slotNumber, final ItemStack stack ) - { - // Call super - super.putStackInSlot( slotNumber, stack ); - - // Is this client side? - if( ( this.outputSlot.slotNumber == slotNumber ) && EffectiveSide.isClientSide() ) - { - this.playTransferSound( null, true, 0 ); - } - } - - /** - * Called when the user has clicked on an aspect. - * Sends that change to the server for validation. - */ - @Override - public void setSelectedAspect( final Aspect selectedAspect ) - { - Packet_S_EssentiaCellTerminal.sendSelectedAspect( this.player, selectedAspect ); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Get the slot that was shift-clicked - Slot slot = this.getSlotOrNull( slotNumber ); - - // Is there a valid slot with and item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - boolean didMerge = false; - - // Get the itemstack in the slot - ItemStack slotStack = slot.getStack(); - - // Was the slot clicked the input slot or output slot? - if( ( slot == this.inputSlot ) || ( slot == this.outputSlot ) ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - // Was the slot clicked in the player or hotbar inventory? - else if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Is the item valid for the input slot? - if( this.inputSlot.isItemValid( slotStack ) ) - { - // Attempt to merge with the input slot - didMerge = this.mergeItemStack( slotStack, this.inputSlot.slotNumber, this.inputSlot.slotNumber + 1, false ); - } - - // Did we merge? - if( !didMerge ) - { - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - - } - - if( didMerge ) - { - // Did the merger drain the stack? - if( slotStack.stackSize == 0 ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - this.detectAndSendChanges(); - } - - } - - return null; - } +public abstract class ContainerEssentiaCellTerminalBase extends ContainerWithPlayerInventory + implements IMEEssentiaMonitorReceiver, IAspectSelectorContainer, ICraftingIssuerContainer { + /** + * X position for the output slot + */ + private static final int OUTPUT_POSITION_X = 26; + + /** + * Y position for the output slot + */ + private static final int OUTPUT_POSITION_Y = 92; + + /** + * X position for the input slot + */ + private static final int INPUT_POSITION_X = 8; + + /** + * Y position for the input slot + */ + private static final int INPUT_POSITION_Y = ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_Y; + + /** + * Y position for the player inventory + */ + private static final int PLAYER_INV_POSITION_Y = 122; + + /** + * Y position for the hotbar inventory + */ + private static final int HOTBAR_INV_POSITION_Y = 180; + + /** + * The minimum amount of time to wait before playing + * sounds again. In ms. + */ + private static final int MINIMUM_SOUND_WAIT = 900; + + /** + * The number of ticks required to pass before doWork is called. + */ + private static final int WORK_TICK_RATE = 3; + + /** + * The maximum amount of essentia to try and transfer each time + * the transfer method is called. + * This is a soft-cap. + */ + private static final int ESSENTIA_TRANSFER_PER_WORK_CYCLE = 64; + + /** + * Inventory indices for the input and output + */ + private static int OUTPUT_INV_INDEX = 1, INPUT_INV_INDEX = 0; + + /** + * Location of the splash sound + */ + private final String soundLocation_Splash = "game.neutral.swim"; + + /** + * Location of the paper sound + */ + private final String soundLocation_Paper = "thaumcraft:page"; + + /** + * The last known stack size stored in the export slot + */ + private int audioStackSizeTracker = 0; + + /** + * Work slots + */ + private Slot inputSlot; + + /** + * Import and export inventory + */ + private IInventory inventory; + + /** + * The last time, in ms, the transfer sound played + */ + private long lastSoundPlaytime = 0; + + /** + * Work slots + */ + private Slot outputSlot; + + /** + * The aspect the user has selected. + */ + private Aspect selectedAspect; + + /** + * Tracks the number of ticks + */ + private int tickCounter = 0; + + /** + * Tracks the amount of work performed. + */ + private int workCounter = 0; + + /** + * List of aspects on the network + */ + protected final IEssentiaRepo repo; + + /** + * Essentia network monitor + */ + private IMEEssentiaMonitor essentiaMonitor; + + /** + * Create the container and register the owner + * + * @param player + */ + public ContainerEssentiaCellTerminalBase(final EntityPlayer player) { + // Call super + super(player); + + if (EffectiveSide.isClientSide()) { + // Set the sound time + this.lastSoundPlaytime = System.currentTimeMillis(); + } + + // Create the reop + this.repo = new EssentiaRepo(); + } + + /** + * Attach this container to the Essentia monitor + * + * @param essentiaMonitor + */ + private boolean attachToMonitor(final IMEEssentiaMonitor eMonitor) { + if ((EffectiveSide.isServerSide()) && (eMonitor != null)) { + // Get the grid + IGrid grid = this.getHostGrid(); + if (grid == null) { + return false; + } + + // Detach from any current monitor + if (this.essentiaMonitor != null) { + this.detachFromMonitor(); + } + + // Set the monitor + this.essentiaMonitor = eMonitor; + + // Listen + this.essentiaMonitor.addListener(this, grid.hashCode()); + + // Update our cached list of aspects + this.repo.copyFrom(this.essentiaMonitor.getEssentiaList()); + return true; + } + + return false; + } + + /** + * Returns true if the specified stack can be merged into the output slot. + * + * @param stackToMerge + * @return True if the slot is empty, + * or if can be merged by increasing the slots stacksize by the specified stacks stacksize. + */ + private boolean canMergeWithOutputSlot(final ItemStack stackToMerge) { + // Ensure the stack is not null. + if (stackToMerge == null) { + // Invalid itemstack + return false; + } + + // Is the slot empty? + if (!this.outputSlot.getHasStack()) { + return true; + } + + // Get the slot stack + ItemStack slotStack = this.outputSlot.getStack(); + + // Get the stack size + int slotStackSize = slotStack.stackSize; + + // Is the slot full? + if (slotStack.getMaxStackSize() == slotStackSize) { + return false; + } + + // Will adding the stack cause the slot to be over full? + if ((slotStackSize + stackToMerge.stackSize) > slotStack.getMaxStackSize()) { + return false; + } + + // Do the stacks match? + // Compare ignoring stack size + ItemStack o = slotStack.copy(); + ItemStack n = stackToMerge.copy(); + o.stackSize = 1; + n.stackSize = 1; + return ItemStack.areItemStacksEqual(o, n); + } + + /** + * Returns if the player has the requested permission or not. + * + * @param perm + * @param actionSource + * @return + */ + private boolean checkSecurityPermission(final SecurityPermissions perm, final BaseActionSource actionSource) { + + // Ensure there is an action source. + if (actionSource == null) { + return false; + } + + // Get the source node + IGridNode sourceNode = null; + if (actionSource instanceof MachineSource) { + sourceNode = ((MachineSource) actionSource).via.getActionableNode(); + } else if (actionSource instanceof PlayerSource) { + sourceNode = ((PlayerSource) actionSource).via.getActionableNode(); + } + + // Ensure there is a node + if (sourceNode == null) { + return false; + } + + // Get the security grid for the node. + ISecurityGrid sGrid = sourceNode.getGrid().getCache(ISecurityGrid.class); + + // Return the permission. + return sGrid.hasPermission(this.player, perm); + } + + /** + * Drains an essentia container item. + * + * @param container + * @param actionSource + * @param mode + * @return The result of the drain. + */ + @Nullable + private ImmutablePair drainContainer( + final ItemStack container, final BaseActionSource actionSource, final Actionable mode) { + // Ensure there is a container + if (container == null) { + return null; + } + + // Get the fluid stack from the item + IAspectStack containerEssentia = EssentiaItemContainerHelper.INSTANCE.getAspectStackFromContainer(container); + + // Ensure there is something to drain + if ((containerEssentia == null) || containerEssentia.isEmpty()) { + // Nothing to drain + return null; + } + + // Get the proposed drain amount. + int proposedDrainAmount = (int) containerEssentia.getStackSize(); + + // Do a network injection + long rejectedAmount = this.essentiaMonitor.injectEssentia( + containerEssentia.getAspect(), proposedDrainAmount, mode, actionSource, true); + + // Was any rejected? + if (rejectedAmount > 0) { + // Decrease the proposed amount + proposedDrainAmount -= (int) rejectedAmount; + + // Can the network accept any? + if (proposedDrainAmount <= 0) { + // Network is full + return null; + } + } + + // Adjust work counter + if (mode == Actionable.MODULATE) { + this.workCounter += proposedDrainAmount; + } + + // Attempt to drain the container + return EssentiaItemContainerHelper.INSTANCE.extractFromContainer(container, proposedDrainAmount); + } + + /** + * Fills an essentia container item. + * + * @param withAspect + * @param container + * @param actionSource + * @param mode + * @return The result of the fill. + */ + @Nullable + private ImmutablePair fillContainer( + final Aspect withAspect, + final ItemStack container, + final BaseActionSource actionSource, + final Actionable mode) { + // Ensure there is an aspect + if (withAspect == null) { + return null; + } + + // Get the capacity of the container + int containerCapacity = EssentiaItemContainerHelper.INSTANCE.getContainerCapacity(container); + + // Can the container hold essentia? + if (containerCapacity == 0) { + // Invalid container + return null; + } + + // Do an extraction from the network + long extractedAmount = + this.essentiaMonitor.extractEssentia(withAspect, containerCapacity, mode, actionSource, true); + + // Was anything extracted? + if (extractedAmount <= 0) { + // Gas is not present on network. + return null; + } + + // Calculate the proposed amount, based on how much we need and how much + // is available + int proposedFillAmount = (int) Math.min(containerCapacity, extractedAmount); + + // Adjust work counter + if (mode == Actionable.MODULATE) { + this.workCounter += proposedFillAmount; + } + + // Create a new container filled to the proposed amount + return EssentiaItemContainerHelper.INSTANCE.injectIntoContainer( + container, new AspectStack(withAspect, proposedFillAmount)); + } + + /** + * Binds the container to the specified inventory and the players inventory. + * + * @param inventory + */ + protected void bindToInventory(final IInventory inventory) { + // Set the inventory + this.inventory = inventory; + + // Create the input slot + this.inputSlot = new SlotRestrictive( + inventory, + ContainerEssentiaCellTerminalBase.INPUT_INV_INDEX, + ContainerEssentiaCellTerminalBase.INPUT_POSITION_X, + ContainerEssentiaCellTerminalBase.INPUT_POSITION_Y); + this.addSlotToContainer(this.inputSlot); + + // Create the output slot + this.outputSlot = new SlotFurnace( + this.player, + inventory, + ContainerEssentiaCellTerminalBase.OUTPUT_INV_INDEX, + ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_X, + ContainerEssentiaCellTerminalBase.OUTPUT_POSITION_Y); + this.addSlotToContainer(this.outputSlot); + + // Bind to the player's inventory + this.bindPlayerInventory( + this.player.inventory, + ContainerEssentiaCellTerminalBase.PLAYER_INV_POSITION_Y, + ContainerEssentiaCellTerminalBase.HOTBAR_INV_POSITION_Y); + } + + /** + * Detaches from the monitor if attached. + */ + protected void detachFromMonitor() { + if (EffectiveSide.isServerSide()) { + if (this.essentiaMonitor != null) { + // Stop listening + this.essentiaMonitor.removeListener(this); + + // Null the monitor + this.essentiaMonitor = null; + + // Clear the repo + this.repo.clear(); + } + } + } + + /** + * Checks if there is any work to perform. + * If there is it does so. + */ + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Compare selected aspects + if (this.getHostSelectedAspect() != this.selectedAspect) { + // Update the selected aspect + this.selectedAspect = this.getHostSelectedAspect(); + + // Send the change back to the client + Packet_C_EssentiaCellTerminal.setSelectedAspect(this.player, this.selectedAspect); + } + + // Is there a monitor? + if (this.essentiaMonitor != null) { + // Inc tick tracker + this.tickCounter += 1; + + if (this.tickCounter > ContainerEssentiaCellTerminalBase.WORK_TICK_RATE) { + // Do work + this.doWork(this.tickCounter); + + // Reset the tick counter + this.tickCounter = 0; + + return true; + } + } else { + // Attempt to attach to a monitor + if (this.attachToMonitor(this.getNewMonitor())) { + // Send update + this.onClientRequestFullUpdate(); + } + } + + return false; + } + + /** + * Called periodically so that the container can perform work. + */ + protected abstract void doWork(int elapsedTicks); + + /** + * Gets the action source. + * + * @return + */ + protected abstract BaseActionSource getActionSource(); + + /** + * Gets the grid for the host. + * + * @return + */ + @Nullable + protected abstract IGrid getHostGrid(); + + /** + * Return the selected aspect stored in the host. + * + * @return + */ + @Nullable + protected abstract Aspect getHostSelectedAspect(); + + /** + * Attempts to get a new essentia monitor. + * + * @return + */ + @Nullable + protected abstract IMEEssentiaMonitor getNewMonitor(); + + /** + * Sets the hosts selected aspect. + * + * @param aspect + */ + protected abstract void setHostSelectedAspect(@Nullable Aspect aspect); + + /** + * Fills, drains, or sets label aspect. + * + * @param stack + * This is not modified during the course of this function. + * @param aspect + * Ignored when draining + * @param actionSource + * @param mode + * @return The new stack if changes made, the original stack otherwise. + */ + protected ItemStack transferEssentia( + final ItemStack stack, final Aspect aspect, final BaseActionSource actionSource, final Actionable mode) { + // Ensure the stack & monitor are not null + if ((stack == null) || (this.essentiaMonitor == null)) { + return stack; + } + + // Get the item type + AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType(stack); + + // Label? + if (iType == AspectItemType.JarLabel) { + // Copy the stack + ItemStack label = stack.copy(); + + // Set the label + EssentiaItemContainerHelper.INSTANCE.setLabelAspect(label, aspect); + + // Update work performed + ++this.workCounter; + + // Return the label + return label; + } + + // Valid container? + if (iType != AspectItemType.EssentiaContainer) { + // Invalid container + return stack; + } + + // Result of the operation + ImmutablePair result = null; + + // Filling? + if (EssentiaItemContainerHelper.INSTANCE.isContainerEmpty(stack)) { + // Check extract permission + if (this.checkSecurityPermission(SecurityPermissions.EXTRACT, actionSource)) { + // Attempt to fill the container + result = this.fillContainer(aspect, stack, actionSource, mode); + } + } + // Draining + else { + // Check inject permission + if (this.checkSecurityPermission(SecurityPermissions.INJECT, actionSource)) { + // Attempt to drain the container + result = this.drainContainer(stack, actionSource, mode); + } + } + + // Is there any result? + if (result != null) { + // Return the new stack. + return result.right; + } + + // No result + return stack; + } + + /** + * Transfers essentia in or out of the system using the input and output slots. + */ + protected void transferEssentiaFromWorkSlots() { + // Ensure the inventory is valid + if (this.inventory == null) { + return; + } + + // Get the input stack + final ItemStack inputStack = this.inventory.getStackInSlot(ContainerEssentiaCellTerminalBase.INPUT_INV_INDEX); + + // Ensure the input stack is not empty + if ((inputStack == null)) { + // Nothing in input slot. + return; + } + + // Is the output slot full? + if (this.outputSlot.getHasStack()) { + ItemStack outputStack = this.outputSlot.getStack(); + if (outputStack.stackSize >= outputStack.getMaxStackSize()) { + // Output slot is full. + return; + } + } + + // Reset the work counter + this.workCounter = 0; + + // Get the action source + final BaseActionSource actionSource = this.getActionSource(); + + // Copy the input + final ItemStack container = inputStack.copy(); + container.stackSize = 1; + + // Loop while maximum work has not been performed, there is input, and the operation did not fail. + ItemStack result; + do { + // Simulate the work + result = this.transferEssentia(container, this.selectedAspect, actionSource, Actionable.SIMULATE); + + // Did anything change? + if ((result == null) || (result == container)) { + // No work to perform + break; + } + + // Can the result not be merged with the output stack? + if (!this.canMergeWithOutputSlot(result)) { + // Unable to merge + break; + } + + // Perform the work + result = this.transferEssentia(container, this.selectedAspect, actionSource, Actionable.MODULATE); + + // Merge the result + if (this.outputSlot.getHasStack()) { + // Can just increment here because canMergeWithOutputSlot explicitly checks that + ++this.outputSlot.getStack().stackSize; + } else { + this.outputSlot.putStack(result); + } + + // Is the input drained? + if ((--inputStack.stackSize) == 0) { + this.inputSlot.putStack(null); + break; + } + } while (this.workCounter < ContainerEssentiaCellTerminalBase.ESSENTIA_TRANSFER_PER_WORK_CYCLE); + } + + /** + * Gets the list of aspect stacks in the container. + * + * @return + */ + public Collection getAspectStackList() { + return this.repo.getAll(); + } + + @Override + public abstract ICraftingIssuerHost getCraftingHost(); + + /** + * Get the player that owns this container + * + * @return + */ + public EntityPlayer getPlayer() { + return this.player; + } + + /** + * Gets the aspect that the player has selected. + * + * @return + */ + public Aspect getSelectedAspect() { + return this.selectedAspect; + } + + /** + * Is this container still valid for receiving updates + * from the AE monitor? + */ + @Override + public final boolean isValid(final Object verificationToken) { + // Get the grid + IGrid grid = this.getHostGrid(); + if (grid != null) { + // Do the hash codes match? + if (grid.hashCode() == (Integer) verificationToken) { + return true; + } + } + + // No longer valid (Do not call detach, this will happen automatically) + this.essentiaMonitor = null; + this.repo.clear(); + + // Update the client + this.onClientRequestFullUpdate(); + + return false; + } + + /** + * Called when a client has clicked on a craftable aspect. + * + * @param player + * @param result + */ + public abstract void onClientRequestAutoCraft(final EntityPlayer player, final Aspect aspect); + + /** + * Called when a client requests the state of the container. + * Updates our cached list of aspects + */ + public abstract void onClientRequestFullUpdate(); + + /** + * Called when a client sends a sorting mode change request. + * + * @param sortingMode + */ + public abstract void onClientRequestSortModeChange(final EntityPlayer player, boolean backwards); + + /** + * Called when a client sends a view mode change request. + * + * @param player + */ + public abstract void onClientRequestViewModeChange(final EntityPlayer player, boolean backwards); + + /** + * Unregister this container from the monitor. + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Call super + super.onContainerClosed(player); + + // Detach from the monitor + this.detachFromMonitor(); + } + + /** + * Called when a player clicked on an aspect while holding an item. + * + * @param player + * @param aspect + */ + public void onInteractWithHeldItem(final EntityPlayer player, final Aspect aspect) { + // Sanity check + if (((player == null) || (player.inventory.getItemStack() == null))) { + return; + } + + // Get the item + ItemStack sourceStack = player.inventory.getItemStack(); + + // Create a new stack + final ItemStack takeFrom = sourceStack.copy(); + takeFrom.stackSize = 1; + + // Get the action source + final BaseActionSource actionSource = this.getActionSource(); + + // Simulate the transfer + ItemStack resultStack = this.transferEssentia(takeFrom, aspect, actionSource, Actionable.SIMULATE); + + // Was any work performed? + if ((resultStack == null) || (resultStack == takeFrom)) { + // Nothing to do. + return; + } + + // If the source stack size is > 1, the result will need to be put into the player inventory + if (sourceStack.stackSize > 1) { + // Attempt to merge + if (!this.mergeSlotWithHotbarInventory(resultStack)) { + if (!this.mergeSlotWithPlayerInventory(resultStack)) { + // Could not merge + return; + } + } + + // Decrement the source stack + --sourceStack.stackSize; + } else { + // Set the source stack to the result + sourceStack = resultStack; + } + + // Perform the work + this.transferEssentia(takeFrom, aspect, actionSource, Actionable.MODULATE); + + // Set what the player is holding + player.inventory.setItemStack(sourceStack); + + // Update + Packet_C_Sync.sendPlayerHeldItem(player, sourceStack); + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).isChangingQuantityOnly = false; + } + this.detectAndSendChanges(); + this.playTransferSound( + player, + false, + (EssentiaItemContainerHelper.INSTANCE.getItemType(sourceStack) == AspectItemType.JarLabel ? 1 : 0)); + } + + /** + * Called by the gui when the aspect list arrives. + * + * @param aspectStackList + */ + public void onReceivedAspectList(final Collection aspectStackList) { + // Set the aspect list + this.repo.copyFrom(aspectStackList); + } + + /** + * Called by the gui when a change arrives. + * + * @param change + */ + public void onReceivedAspectListChange(final IAspectStack change) { + // Ignored server side + if (EffectiveSide.isServerSide()) { + return; + } + + // Ensure the change is not null + if (change == null) { + return; + } + + // Post the change + this.repo.postChange(change); + } + + /** + * Called when the the selected aspect has changed. + * + * @param selectedAspect + */ + public void onReceivedSelectedAspect(final Aspect selectedAspect) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + this.setHostSelectedAspect(selectedAspect); + } else { + this.selectedAspect = selectedAspect; + } + } + + /** + * Checks if the transfer sound should play. + * if checkWorkSlots is true the type will be automatically determined. + * + * @param player + * @param checkWorkSlots + * @param type + * 0 = splash, 1 = paper + */ + public void playTransferSound(final EntityPlayer player, final boolean checkWorkSlots, int type) { + if (checkWorkSlots) { + // Get the itemstack in the output slot + ItemStack itemStack = this.outputSlot.getStack(); + + // Is there anything in the second slot? + if (itemStack != null) { + + // Is the item a label? + if (EssentiaItemContainerHelper.INSTANCE.getItemType(itemStack) == AspectItemType.JarLabel) { + type = 1; + } else { + type = 0; + } + + // Has the count changed? + if (this.audioStackSizeTracker == itemStack.stackSize) { + // Nothing changed + return; + } + + // Set the count + this.audioStackSizeTracker = itemStack.stackSize; + + } else { + // Reset the count + this.audioStackSizeTracker = 0; + return; + } + } + + // Has enough time passed to play the sound again? + if ((System.currentTimeMillis() - this.lastSoundPlaytime) + > ContainerEssentiaCellTerminalBase.MINIMUM_SOUND_WAIT) { + if (type == 0) { + ThEUtils.playClientSound(this.player, this.soundLocation_Splash); + } else if (type == 1) { + ThEUtils.playClientSound(this.player, this.soundLocation_Paper); + } + + // Set the playtime + this.lastSoundPlaytime = System.currentTimeMillis(); + } + } + + /** + * Called by the Essentia monitor when the network changes. + */ + @Override + public final void postChange(final IMEEssentiaMonitor fromMonitor, final Iterable changes) { + // Ensure there was a change + if (changes == null) { + return; + } + + // Loop over the changes + for (IAspectStack change : changes) { + // Update the client + Packet_C_EssentiaCellTerminal.setAspectAmount(this.player, change); + } + } + + @Override + public void putStackInSlot(final int slotNumber, final ItemStack stack) { + // Call super + super.putStackInSlot(slotNumber, stack); + + // Is this client side? + if ((this.outputSlot.slotNumber == slotNumber) && EffectiveSide.isClientSide()) { + this.playTransferSound(null, true, 0); + } + } + + /** + * Called when the user has clicked on an aspect. + * Sends that change to the server for validation. + */ + @Override + public void setSelectedAspect(final Aspect selectedAspect) { + Packet_S_EssentiaCellTerminal.sendSelectedAspect(this.player, selectedAspect); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Get the slot that was shift-clicked + Slot slot = this.getSlotOrNull(slotNumber); + + // Is there a valid slot with and item? + if ((slot != null) && (slot.getHasStack())) { + boolean didMerge = false; + + // Get the itemstack in the slot + ItemStack slotStack = slot.getStack(); + + // Was the slot clicked the input slot or output slot? + if ((slot == this.inputSlot) || (slot == this.outputSlot)) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + // Was the slot clicked in the player or hotbar inventory? + else if (this.slotClickedWasInPlayerInventory(slotNumber) + || this.slotClickedWasInHotbarInventory(slotNumber)) { + // Is the item valid for the input slot? + if (this.inputSlot.isItemValid(slotStack)) { + // Attempt to merge with the input slot + didMerge = this.mergeItemStack( + slotStack, this.inputSlot.slotNumber, this.inputSlot.slotNumber + 1, false); + } + + // Did we merge? + if (!didMerge) { + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + + if (didMerge) { + // Did the merger drain the stack? + if (slotStack.stackSize == 0) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + this.detectAndSendChanges(); + } + } + + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellWorkbench.java b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellWorkbench.java index 5702ad30..30cdf4f4 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellWorkbench.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaCellWorkbench.java @@ -1,6 +1,7 @@ package thaumicenergistics.common.container; import java.util.ArrayList; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; @@ -12,194 +13,173 @@ import thaumicenergistics.common.network.packet.client.Packet_C_AspectSlot; import thaumicenergistics.common.tiles.TileEssentiaCellWorkbench; import thaumicenergistics.common.utils.EffectiveSide; -import javax.annotation.Nonnull; - /** * {@link TileEssentiaCellWorkbench} container. * * @author Nividica * */ -public class ContainerEssentiaCellWorkbench - extends ContainerWithPlayerInventory -{ +public class ContainerEssentiaCellWorkbench extends ContainerWithPlayerInventory { - /** - * Y position for the player inventory - */ - private static int PLAYER_INV_POSITION_Y = 169; + /** + * Y position for the player inventory + */ + private static int PLAYER_INV_POSITION_Y = 169; - /** - * Y position for the hotbar inventory - */ - private static int HOTBAR_INV_POSITION_Y = PLAYER_INV_POSITION_Y + 58; + /** + * Y position for the hotbar inventory + */ + private static int HOTBAR_INV_POSITION_Y = PLAYER_INV_POSITION_Y + 58; - /** - * Position of the cell slot. - */ - public static int CELL_SLOT_X = 152, CELL_SLOT_Y = 8; + /** + * Position of the cell slot. + */ + public static int CELL_SLOT_X = 152, CELL_SLOT_Y = 8; - /** - * Cell Workbench. - */ - public final TileEssentiaCellWorkbench workbench; + /** + * Cell Workbench. + */ + public final TileEssentiaCellWorkbench workbench; - /** - * The cell slot. - */ - private final Slot cellSlot; + /** + * The cell slot. + */ + private final Slot cellSlot; - public ContainerEssentiaCellWorkbench( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( player ); + public ContainerEssentiaCellWorkbench( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(player); - // Get the workbench - this.workbench = (TileEssentiaCellWorkbench)world.getTileEntity( x, y, z ); + // Get the workbench + this.workbench = (TileEssentiaCellWorkbench) world.getTileEntity(x, y, z); - // Create the cell slot - this.cellSlot = new SlotRestrictive( this.workbench, 0, ContainerEssentiaCellWorkbench.CELL_SLOT_X, - ContainerEssentiaCellWorkbench.CELL_SLOT_Y ); - this.addSlotToContainer( this.cellSlot ); + // Create the cell slot + this.cellSlot = new SlotRestrictive( + this.workbench, + 0, + ContainerEssentiaCellWorkbench.CELL_SLOT_X, + ContainerEssentiaCellWorkbench.CELL_SLOT_Y); + this.addSlotToContainer(this.cellSlot); - // Bind to the player's inventory - this.bindPlayerInventory( this.player.inventory, ContainerEssentiaCellWorkbench.PLAYER_INV_POSITION_Y, - ContainerEssentiaCellWorkbench.HOTBAR_INV_POSITION_Y ); + // Bind to the player's inventory + this.bindPlayerInventory( + this.player.inventory, + ContainerEssentiaCellWorkbench.PLAYER_INV_POSITION_Y, + ContainerEssentiaCellWorkbench.HOTBAR_INV_POSITION_Y); - // Register with the workbench - if( EffectiveSide.isServerSide() ) - { - this.workbench.registerListener( this ); - } - } + // Register with the workbench + if (EffectiveSide.isServerSide()) { + this.workbench.registerListener(this); + } + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.workbench != null ) - { - return this.workbench.isUseableByPlayer( player ); - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.workbench != null) { + return this.workbench.isUseableByPlayer(player); + } - return false; - } + return false; + } - /** - * Called when a client has requested the full list. - */ - public void onClientRequestPartitionList() - { - this.onPartitionChanged( this.workbench.getPartitionList() ); - } + /** + * Called when a client has requested the full list. + */ + public void onClientRequestPartitionList() { + this.onPartitionChanged(this.workbench.getPartitionList()); + } - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - // Call super - super.onContainerClosed( player ); + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Call super + super.onContainerClosed(player); - if( EffectiveSide.isServerSide() ) - { - this.workbench.removeListener( this ); - } - } + if (EffectiveSide.isServerSide()) { + this.workbench.removeListener(this); + } + } - /** - * Called when the partition list changes. - */ - public void onPartitionChanged( final ArrayList partitionList ) - { - // Send to client - Packet_C_AspectSlot.setFilterList( partitionList, this.player ); - } + /** + * Called when the partition list changes. + */ + public void onPartitionChanged(final ArrayList partitionList) { + // Send to client + Packet_C_AspectSlot.setFilterList(partitionList, this.player); + } - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Is this client side? - if( EffectiveSide.isClientSide() ) - { - // Do nothing. - return null; - } + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Is this client side? + if (EffectiveSide.isClientSide()) { + // Do nothing. + return null; + } - // Get the slot that was shift-clicked - Slot slot = this.getSlotOrNull( slotNumber ); + // Get the slot that was shift-clicked + Slot slot = this.getSlotOrNull(slotNumber); - // Is there a valid slot with and item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - boolean didMerge = false; + // Is there a valid slot with and item? + if ((slot != null) && (slot.getHasStack())) { + boolean didMerge = false; - // Get the itemstack in the slot - ItemStack slotStack = slot.getStack(); + // Get the itemstack in the slot + ItemStack slotStack = slot.getStack(); - // Was the slot clicked the cell slot - if( ( slot == this.cellSlot ) ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - // Was the slot clicked in the player or hotbar inventory? - else if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Is the cell slot empty? - if( !this.cellSlot.getHasStack() ) - { - // Is the item in the clicked slot a valid cell? - if( this.cellSlot.isItemValid( slotStack ) ) - { - // Set the slot - this.cellSlot.putStack( slotStack.copy() ); + // Was the slot clicked the cell slot + if ((slot == this.cellSlot)) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + // Was the slot clicked in the player or hotbar inventory? + else if (this.slotClickedWasInPlayerInventory(slotNumber) + || this.slotClickedWasInHotbarInventory(slotNumber)) { + // Is the cell slot empty? + if (!this.cellSlot.getHasStack()) { + // Is the item in the clicked slot a valid cell? + if (this.cellSlot.isItemValid(slotStack)) { + // Set the slot + this.cellSlot.putStack(slotStack.copy()); - // Clear the clicked slot - slotStack.stackSize = 0; + // Clear the clicked slot + slotStack.stackSize = 0; - // Set that we merged - didMerge = true; - } - } + // Set that we merged + didMerge = true; + } + } - // Did we merge? - if( !didMerge ) - { - // Is the stack an aspect container? - Aspect slotAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( slotStack ); - if( slotAspect != null ) - { - // Attempt to add the aspect to the cell partition list - didMerge = this.workbench.addAspectToPartition( slotAspect ); - } + // Did we merge? + if (!didMerge) { + // Is the stack an aspect container? + Aspect slotAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(slotStack); + if (slotAspect != null) { + // Attempt to add the aspect to the cell partition list + didMerge = this.workbench.addAspectToPartition(slotAspect); + } - // Did we merge? - if( !didMerge ) - { - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - } + // Did we merge? + if (!didMerge) { + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + } - } + if (didMerge) { + // Did the merger drain the stack? + if (slotStack.stackSize == 0) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } - if( didMerge ) - { - // Did the merger drain the stack? - if( slotStack.stackSize == 0 ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - - // Send changes - this.detectAndSendChanges(); - } - } - - return null; - } + // Send changes + this.detectAndSendChanges(); + } + } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaTerminal.java b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaTerminal.java index 2e0d61b2..f3f7af58 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaTerminal.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.container; -import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.ViewItems; import appeng.api.networking.IGrid; @@ -9,6 +8,7 @@ import appeng.api.networking.security.PlayerSource; import appeng.api.storage.data.IAEItemStack; import appeng.container.ContainerOpenContext; import appeng.container.implementations.ContainerCraftAmount; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; @@ -29,201 +29,176 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class ContainerEssentiaTerminal - extends ContainerEssentiaCellTerminalBase -{ - /** - * The terminal this is associated with. - */ - @Nonnull - private final PartEssentiaTerminal terminal; +public class ContainerEssentiaTerminal extends ContainerEssentiaCellTerminalBase { + /** + * The terminal this is associated with. + */ + @Nonnull + private final PartEssentiaTerminal terminal; - /** - * Network source representing the player who is interacting with the - * container. - */ - private final PlayerSource playerSource; + /** + * Network source representing the player who is interacting with the + * container. + */ + private final PlayerSource playerSource; - /** - * Creates the container - * - * @param terminal - * Parent terminal. - * @param player - * Player that owns this container. - */ - public ContainerEssentiaTerminal( @Nonnull final PartEssentiaTerminal terminal, final EntityPlayer player ) - { - // Call the super - super( player ); + /** + * Creates the container + * + * @param terminal + * Parent terminal. + * @param player + * Player that owns this container. + */ + public ContainerEssentiaTerminal(@Nonnull final PartEssentiaTerminal terminal, final EntityPlayer player) { + // Call the super + super(player); - // Set the terminal - this.terminal = terminal; + // Set the terminal + this.terminal = terminal; - // Get and set the machine source - this.playerSource = new PlayerSource( player, this.terminal ); + // Get and set the machine source + this.playerSource = new PlayerSource(player, this.terminal); - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Add this container to the terminal's list - terminal.addListener( this ); - } - else - { - // Ask for a list update - Packet_S_EssentiaCellTerminal.sendFullUpdateRequest( this.player ); - } + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Add this container to the terminal's list + terminal.addListener(this); + } else { + // Ask for a list update + Packet_S_EssentiaCellTerminal.sendFullUpdateRequest(this.player); + } - // Bind our inventory - this.bindToInventory( terminal.getInventory() ); - } + // Bind our inventory + this.bindToInventory(terminal.getInventory()); + } - @Override - protected BaseActionSource getActionSource() - { - return this.playerSource; - } + @Override + protected BaseActionSource getActionSource() { + return this.playerSource; + } - @Override - protected IGrid getHostGrid() - { - try - { - return this.terminal.getGridBlock().getGrid(); - } - catch( Exception e ) - { - return null; - } - } + @Override + protected IGrid getHostGrid() { + try { + return this.terminal.getGridBlock().getGrid(); + } catch (Exception e) { + return null; + } + } - @Override - protected Aspect getHostSelectedAspect() - { - return this.terminal.selectedAspect; - } + @Override + protected Aspect getHostSelectedAspect() { + return this.terminal.selectedAspect; + } - @Override - protected IMEEssentiaMonitor getNewMonitor() - { - return this.terminal.getGridBlock().getEssentiaMonitor(); - } + @Override + protected IMEEssentiaMonitor getNewMonitor() { + return this.terminal.getGridBlock().getEssentiaMonitor(); + } - @Override - protected void setHostSelectedAspect( final Aspect aspect ) - { - this.terminal.selectedAspect = aspect; - } + @Override + protected void setHostSelectedAspect(final Aspect aspect) { + this.terminal.selectedAspect = aspect; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - return this.terminal.isPartUseableByPlayer( player ); - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + return this.terminal.isPartUseableByPlayer(player); + } - /** - * Transfers essentia. - */ - @Override - public void doWork( final int elapsedTicks ) - { - // Transfer essentia if needed. - this.transferEssentiaFromWorkSlots(); - } + /** + * Transfers essentia. + */ + @Override + public void doWork(final int elapsedTicks) { + // Transfer essentia if needed. + this.transferEssentiaFromWorkSlots(); + } - @Override - public ICraftingIssuerHost getCraftingHost() - { - return this.terminal; - } + @Override + public ICraftingIssuerHost getCraftingHost() { + return this.terminal; + } - @Override - public void onClientRequestAutoCraft( final EntityPlayer player, final Aspect aspect ) - { - // Get the host tile - TileEntity te = this.terminal.getHostTile(); + @Override + public void onClientRequestAutoCraft(final EntityPlayer player, final Aspect aspect) { + // Get the host tile + TileEntity te = this.terminal.getHostTile(); - // Launch the GUI - ThEGuiHandler.launchGui( ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); + // Launch the GUI + ThEGuiHandler.launchGui( + ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); - // Setup the amount container - if( player.openContainer instanceof ContainerCraftAmount ) - { - // Get the container - ContainerCraftAmount cca = (ContainerCraftAmount)this.player.openContainer; + // Setup the amount container + if (player.openContainer instanceof ContainerCraftAmount) { + // Get the container + ContainerCraftAmount cca = (ContainerCraftAmount) this.player.openContainer; - // Create the open context - cca.setOpenContext( new ContainerOpenContext( te ) ); - cca.getOpenContext().setWorld( te.getWorldObj() ); - cca.getOpenContext().setX( te.xCoord ); - cca.getOpenContext().setY( te.yCoord ); - cca.getOpenContext().setZ( te.zCoord ); - cca.getOpenContext().setSide( this.terminal.getSide() ); + // Create the open context + cca.setOpenContext(new ContainerOpenContext(te)); + cca.getOpenContext().setWorld(te.getWorldObj()); + cca.getOpenContext().setX(te.xCoord); + cca.getOpenContext().setY(te.yCoord); + cca.getOpenContext().setZ(te.zCoord); + cca.getOpenContext().setSide(this.terminal.getSide()); - // Create the result item - IAEItemStack result = AEApi.instance().storage().createItemStack( ItemCraftingAspect.createStackForAspect( aspect, 1 ) ); + // Create the result item + IAEItemStack result = + AEApi.instance().storage().createItemStack(ItemCraftingAspect.createStackForAspect(aspect, 1)); - // Set the item - cca.getCraftingItem().putStack( result.getItemStack() ); - cca.setItemToCraft( result ); + // Set the item + cca.getCraftingItem().putStack(result.getItemStack()); + cca.setItemToCraft(result); - // Issue update - if( player instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP)player ).isChangingQuantityOnly = false; - } - cca.detectAndSendChanges(); - } - } + // Issue update + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).isChangingQuantityOnly = false; + } + cca.detectAndSendChanges(); + } + } - /** - * Gets the current list from the AE monitor, as well as the current - * sorting mode, and sends it to the client. - */ - @Override - public void onClientRequestFullUpdate() - { - // Send the sorting mode - this.onModeChanged( this.terminal.getSortingMode(), this.terminal.getViewMode() ); + /** + * Gets the current list from the AE monitor, as well as the current + * sorting mode, and sends it to the client. + */ + @Override + public void onClientRequestFullUpdate() { + // Send the sorting mode + this.onModeChanged(this.terminal.getSortingMode(), this.terminal.getViewMode()); - // Send the aspect list - Packet_C_EssentiaCellTerminal.sendFullList( this.player, this.repo.getAll() ); - } + // Send the aspect list + Packet_C_EssentiaCellTerminal.sendFullList(this.player, this.repo.getAll()); + } - @Override - public void onClientRequestSortModeChange( final EntityPlayer player, final boolean backwards ) - { - this.terminal.onClientRequestSortingModeChange( backwards ); - } + @Override + public void onClientRequestSortModeChange(final EntityPlayer player, final boolean backwards) { + this.terminal.onClientRequestSortingModeChange(backwards); + } - @Override - public void onClientRequestViewModeChange( final EntityPlayer player, final boolean backwards ) - { - this.terminal.onClientRequestViewModeChange( backwards ); - } + @Override + public void onClientRequestViewModeChange(final EntityPlayer player, final boolean backwards) { + this.terminal.onClientRequestViewModeChange(backwards); + } - /** - * Removes this container from the terminal. - */ - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - super.onContainerClosed( player ); + /** + * Removes this container from the terminal. + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + super.onContainerClosed(player); - if( EffectiveSide.isServerSide() ) - { - this.terminal.removeListener( this ); - } - } - - /** - * Called from the terminal when it's mode has changed - */ - public void onModeChanged( final AspectStackComparatorMode sortingMode, final ViewItems viewMode ) - { - // Inform the client - Packet_C_EssentiaCellTerminal.sendViewingModes( this.player, sortingMode, viewMode ); - } + if (EffectiveSide.isServerSide()) { + this.terminal.removeListener(this); + } + } + /** + * Called from the terminal when it's mode has changed + */ + public void onModeChanged(final AspectStackComparatorMode sortingMode, final ViewItems viewMode) { + // Inform the client + Packet_C_EssentiaCellTerminal.sendViewingModes(this.player, sortingMode, viewMode); + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaVibrationChamber.java index 6c301305..fdcc1d7e 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerEssentiaVibrationChamber.java @@ -1,6 +1,7 @@ package thaumicenergistics.common.container; import appeng.tile.misc.TileVibrationChamber; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -11,231 +12,200 @@ import thaumicenergistics.common.tiles.abstraction.TileEVCBase; import thaumicenergistics.common.utils.EffectiveSide; import thaumicenergistics.common.utils.ThEUtils; -import javax.annotation.Nonnull; - /** * {@link TileVibrationChamber} container. * * @author Nividica * */ -public class ContainerEssentiaVibrationChamber - extends TheContainerBase -{ - /** - * The number of items to average. - */ - private static final int TICK_AVG_COUNT = 4; +public class ContainerEssentiaVibrationChamber extends TheContainerBase { + /** + * The number of items to average. + */ + private static final int TICK_AVG_COUNT = 4; - /** - * The essentia vibration chamber. - */ - private final TileEssentiaVibrationChamber chamber; + /** + * The essentia vibration chamber. + */ + private final TileEssentiaVibrationChamber chamber; - private float powerPerTick = 0, powerPercent = 1.0F, ticksPercent = 1.0F, ticksRemaningMovingAverage = 0.0F; - private int averageTicksRemaning; + private float powerPerTick = 0, powerPercent = 1.0F, ticksPercent = 1.0F, ticksRemaningMovingAverage = 0.0F; + private int averageTicksRemaning; - public ContainerEssentiaVibrationChamber( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( player ); + public ContainerEssentiaVibrationChamber( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(player); - // Get the tile entity - TileEntity te = world.getTileEntity( x, y, z ); + // Get the tile entity + TileEntity te = world.getTileEntity(x, y, z); - // Ensure it is an E.V.C - if( te instanceof TileEssentiaVibrationChamber ) - { - // Set the chamber - this.chamber = (TileEssentiaVibrationChamber)te; - } - else - { - // Invalid tile entity - this.chamber = null; - return; - } + // Ensure it is an E.V.C + if (te instanceof TileEssentiaVibrationChamber) { + // Set the chamber + this.chamber = (TileEssentiaVibrationChamber) te; + } else { + // Invalid tile entity + this.chamber = null; + return; + } - // Client side? - if( EffectiveSide.isClientSide() ) - { - // Nothing to do client side. - return; - } + // Client side? + if (EffectiveSide.isClientSide()) { + // Nothing to do client side. + return; + } - // Register for updates - this.chamber.registerListener( this ); + // Register for updates + this.chamber.registerListener(this); + } - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.chamber != null) { + return ThEUtils.canPlayerInteractWith(player, this.chamber); + } + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.chamber != null ) - { - return ThEUtils.canPlayerInteractWith( player, this.chamber ); - } - return false; - } + /** + * Gets the power level as a percentage. + * + * @return + */ + public float getPowerPercent() { + return this.powerPercent; + } - /** - * Gets the power level as a percentage. - * - * @return - */ - public float getPowerPercent() - { - return this.powerPercent; - } + /** + * Gets the power produced per tick. + * + * @return + */ + public float getPowerPerTick() { + return this.powerPerTick; + } - /** - * Gets the power produced per tick. - * - * @return - */ - public float getPowerPerTick() - { - return this.powerPerTick; - } + /** + * Gets the aspect being processed by the EVC, can be null. + * + * @return + */ + public Aspect getProcessingAspect() { + if (this.chamber != null) { + return this.chamber.getProcessingAspect(); + } - /** - * Gets the aspect being processed by the EVC, can be null. - * - * @return - */ - public Aspect getProcessingAspect() - { - if( this.chamber != null ) - { - return this.chamber.getProcessingAspect(); - } + return null; + } - return null; - } + /** + * Gets the amount of essentia stored in the EVC. + * + * @return + */ + public int getStoredEssentiaAmount() { + if (this.chamber != null) { + return this.chamber.getEssentiaAmount(null); + } - /** - * Gets the amount of essentia stored in the EVC. - * - * @return - */ - public int getStoredEssentiaAmount() - { - if( this.chamber != null ) - { - return this.chamber.getEssentiaAmount( null ); - } + return 0; + } - return 0; - } + /** + * Gets the aspect stored in the EVC, can be null. + * + * @return + */ + public Aspect getStoredEssentiaAspect() { + if (this.chamber != null) { + return this.chamber.getEssentiaType(null); + } - /** - * Gets the aspect stored in the EVC, can be null. - * - * @return - */ - public Aspect getStoredEssentiaAspect() - { - if( this.chamber != null ) - { - return this.chamber.getEssentiaType( null ); - } + return null; + } - return null; - } + /** + * Gets the amount of essentia stored in the EVC as a percentage. + * + * @return + */ + public float getStoredEssentiaPercent() { + return 1.0F - (this.getStoredEssentiaAmount() / (float) TileEVCBase.MAX_ESSENTIA_STORED); + } - /** - * Gets the amount of essentia stored in the EVC as a percentage. - * - * @return - */ - public float getStoredEssentiaPercent() - { - return 1.0F - ( this.getStoredEssentiaAmount() / (float)TileEVCBase.MAX_ESSENTIA_STORED ); - } + /** + * Gets the number of ticks left for processing. + * + * @return + */ + public int getTicksRemaining() { + return this.averageTicksRemaning; + } - /** - * Gets the number of ticks left for processing. - * - * @return - */ - public int getTicksRemaining() - { - return this.averageTicksRemaning; - } + /** + * Gets the time remaining as a percentage. + * + * @return + */ + public float getTicksRemainingPercent() { + return this.ticksPercent; + } - /** - * Gets the time remaining as a percentage. - * - * @return - */ - public float getTicksRemainingPercent() - { - return this.ticksPercent; - } + /** + * Called server side when the EVC updates; client side when an update packet arrives. + * + * @param powerPerTick + * @param ticksRemaining + * @param totalTicks + */ + public void onChamberUpdate( + final float powerPerTick, final float maxPowerPerTick, final int ticksRemaining, final int totalTicks) { + // Server side? + if (EffectiveSide.isServerSide()) { + // Send update packet + Packet_C_EssentiaVibrationChamber.sendUpdate( + this.player, powerPerTick, maxPowerPerTick, ticksRemaining, totalTicks); + } else { + // Set power per tick + this.powerPerTick = powerPerTick; - /** - * Called server side when the EVC updates; client side when an update packet arrives. - * - * @param powerPerTick - * @param ticksRemaining - * @param totalTicks - */ - public void onChamberUpdate( final float powerPerTick, final float maxPowerPerTick, final int ticksRemaining, final int totalTicks ) - { - // Server side? - if( EffectiveSide.isServerSide() ) - { - // Send update packet - Packet_C_EssentiaVibrationChamber.sendUpdate( - this.player, powerPerTick, - maxPowerPerTick, ticksRemaining, totalTicks ); - } - else - { - // Set power per tick - this.powerPerTick = powerPerTick; + // Calculate power percent + this.powerPercent = 1.0F - (maxPowerPerTick > 0 ? (powerPerTick / maxPowerPerTick) : 0); - // Calculate power percent - this.powerPercent = 1.0F - ( maxPowerPerTick > 0 ? ( powerPerTick / maxPowerPerTick ) : 0 ); + // First tick? + if (this.ticksRemaningMovingAverage == 0) { + this.ticksRemaningMovingAverage = ticksRemaining; + } + // Update tick average + else { + float invertedWeight = 1; + if (ticksRemaining > this.ticksRemaningMovingAverage) { + invertedWeight = 0.3F; + } - // First tick? - if( this.ticksRemaningMovingAverage == 0 ) - { - this.ticksRemaningMovingAverage = ticksRemaining; - } - // Update tick average - else - { - float invertedWeight = 1; - if( ticksRemaining > this.ticksRemaningMovingAverage ) - { - invertedWeight = 0.3F; - } + this.ticksRemaningMovingAverage -= this.ticksRemaningMovingAverage + / (ContainerEssentiaVibrationChamber.TICK_AVG_COUNT * invertedWeight); + this.ticksRemaningMovingAverage += + ticksRemaining / (ContainerEssentiaVibrationChamber.TICK_AVG_COUNT * invertedWeight); + } - this.ticksRemaningMovingAverage -= this.ticksRemaningMovingAverage / - ( ContainerEssentiaVibrationChamber.TICK_AVG_COUNT * invertedWeight ); - this.ticksRemaningMovingAverage += ticksRemaining / ( ContainerEssentiaVibrationChamber.TICK_AVG_COUNT * invertedWeight ); - } + // Cast to int + this.averageTicksRemaning = (int) this.ticksRemaningMovingAverage; - // Cast to int - this.averageTicksRemaning = (int)this.ticksRemaningMovingAverage; + // Calculate time percent + this.ticksPercent = 1.0F - (totalTicks > 0 ? (ticksRemaining / (float) totalTicks) : 0); + } + } - // Calculate time percent - this.ticksPercent = 1.0F - ( totalTicks > 0 ? ( ticksRemaining / (float)totalTicks ) : 0 ); - } - } - - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - // Call super - super.onContainerClosed( player ); - - // Server side? - if( EffectiveSide.isServerSide() && ( this.chamber != null ) ) - { - this.chamber.removeListener( this ); - } - } + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Call super + super.onContainerClosed(player); + // Server side? + if (EffectiveSide.isServerSide() && (this.chamber != null)) { + this.chamber.removeListener(this); + } + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerInternalCrafting.java b/src/main/java/thaumicenergistics/common/container/ContainerInternalCrafting.java index cf67783f..bcb5dc0d 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerInternalCrafting.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerInternalCrafting.java @@ -9,18 +9,12 @@ import net.minecraft.inventory.Container; * @author Nividica * */ -public class ContainerInternalCrafting - extends Container -{ +public class ContainerInternalCrafting extends Container { - public ContainerInternalCrafting() - { - } - - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - return false; - } + public ContainerInternalCrafting() {} + @Override + public boolean canInteractWith(final EntityPlayer player) { + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerKnowledgeInscriber.java b/src/main/java/thaumicenergistics/common/container/ContainerKnowledgeInscriber.java index 5117a229..2c41e091 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerKnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerKnowledgeInscriber.java @@ -1,11 +1,12 @@ package thaumicenergistics.common.container; -import java.util.ArrayList; -import java.util.Iterator; import appeng.api.storage.data.IAEItemStack; import appeng.container.slot.SlotFake; import appeng.container.slot.SlotFakeCraftingMatrix; import appeng.container.slot.SlotInaccessible; +import java.util.ArrayList; +import java.util.Iterator; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.ICrafting; @@ -28,727 +29,671 @@ import thaumicenergistics.common.network.packet.client.Packet_C_KnowledgeInscrib import thaumicenergistics.common.tiles.TileKnowledgeInscriber; import thaumicenergistics.common.utils.EffectiveSide; -import javax.annotation.Nonnull; - /** * {@link TileKnowledgeInscriber} container. * * @author Nividica * */ -public class ContainerKnowledgeInscriber - extends ContainerWithPlayerInventory -{ - /** - * What state the save/delete button should be in. - * - * @author Nividica - * - */ - public enum CoreSaveState - { - Disabled_InvalidRecipe, - Disabled_CoreFull, - Disabled_MissingCore, - Enabled_Save, - Enabled_Delete - } - - /** - * Maximum number of patterns. - */ - private static final int MAXIMUM_PATTERNS = HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS; - - /** - * Y position for the player and hotbar inventory. - */ - private static final int PLAYER_INV_POSITION_Y = 162, HOTBAR_INV_POSITION_Y = ContainerKnowledgeInscriber.PLAYER_INV_POSITION_Y + 58; - - /** - * Knowledge core slot. - */ - public static final int KCORE_SLOT_X = 186, KCORE_SLOT_Y = 8; - - /** - * Pattern slots. - */ - private static final int PATTERN_SLOT = 0, PATTERN_SLOT_X = 26, PATTERN_SLOT_Y = 18, - PATTERN_ROWS = 3, PATTERN_COLS = 7, PATTERN_SLOT_SPACING = 18; - - /** - * Crafting slots - */ - public static final int CRAFTING_MATRIX_SLOT = ContainerKnowledgeInscriber.MAXIMUM_PATTERNS + ContainerKnowledgeInscriber.PATTERN_SLOT, - CRAFTING_SLOT_X = 26, - CRAFTING_SLOT_Y = 90, CRAFTING_ROWS = 3, CRAFTING_COLS = 3, - CRAFTING_GRID_SIZE = ContainerKnowledgeInscriber.CRAFTING_ROWS * ContainerKnowledgeInscriber.CRAFTING_COLS, - CRAFTING_SLOT_SPACING = 18, - CRAFTING_RESULT_SLOT = ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE; - - /** - * Handles interaction with the knowledge core. - */ - private final HandlerKnowledgeCore kCoreHandler; - - /** - * Slots - */ - private final SlotRestrictive kCoreSlot; - private final SlotFake resultSlot; - private final SlotInaccessible[] patternSlots = new SlotInaccessible[ContainerKnowledgeInscriber.MAXIMUM_PATTERNS]; - private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE]; - - /** - * The current recipe, if any. - */ - private IArcaneRecipe activeRecipe = null; - - /** - * Inscriber tile entity. - */ - private TileKnowledgeInscriber inscriber; - - /** - * Inventory for the patterns and crafting matrix - */ - private final TheInternalInventory internalInventory; - - public ContainerKnowledgeInscriber( final EntityPlayer player, final World world, final int x, final int y, final int z ) - { - // Call super - super( player ); - - // Bind to the players inventory - this.bindPlayerInventory( player.inventory, ContainerKnowledgeInscriber.PLAYER_INV_POSITION_Y, - ContainerKnowledgeInscriber.HOTBAR_INV_POSITION_Y ); - - // Get the inscriber - this.inscriber = (TileKnowledgeInscriber)world.getTileEntity( x, y, z ); - - // Create the Kcore slot - this.kCoreSlot = new SlotRestrictive( this.inscriber, TileKnowledgeInscriber.KCORE_SLOT, ContainerKnowledgeInscriber.KCORE_SLOT_X, - ContainerKnowledgeInscriber.KCORE_SLOT_Y ); - this.addSlotToContainer( this.kCoreSlot ); - - // Setup the internal inventory - this.internalInventory = new TheInternalInventory( "cki", ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT + 1, 64 ); - - // Create pattern slots - this.initPatternSlots(); - - // Create crafting slots - this.initCraftingSlots(); - - // Create the result slot - this.resultSlot = new SlotFake( this.internalInventory, ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT, 116, 108 ); - this.addSlotToContainer( this.resultSlot ); - - // Create the handler - this.kCoreHandler = new HandlerKnowledgeCore(); - } - - /** - * Determines the current save state. - * - * @return - */ - private CoreSaveState getSaveState() - { - CoreSaveState saveState; - - // Is there a core handler? - if( !this.kCoreHandler.hasCore() ) - { - saveState = CoreSaveState.Disabled_MissingCore; - } - // Is there a valid recipe? - else if( this.activeRecipe == null ) - { - saveState = CoreSaveState.Disabled_InvalidRecipe; - } - else - { - // Get the recipe output - ItemStack recipeOutput = ArcaneRecipeHelper.INSTANCE.getRecipeOutput( this.internalInventory, - ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, this.activeRecipe ); - - // Ensure there is an output - if( recipeOutput == null ) - { - saveState = CoreSaveState.Disabled_InvalidRecipe; - } - else - { - // Does the core already have this recipe, or one that produces the same result, stored? - boolean isNew = !this.kCoreHandler.hasPatternFor( recipeOutput ); - - // Would the recipe be a new pattern? - if( isNew ) - { - // Is there room for the recipe? - if( this.kCoreHandler.hasRoomToStorePattern() ) - { - // Enable saving - saveState = CoreSaveState.Enabled_Save; - } - else - { - // Core is full - saveState = CoreSaveState.Disabled_CoreFull; - } - } - else - { - // Enable deleting - saveState = CoreSaveState.Enabled_Delete; - } - } - } - - return saveState; - } - - private void initCraftingSlots() - { - int slotIndex; - // Create the crafting slots - slotIndex = ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT; - for( int row = 0; row < ContainerKnowledgeInscriber.CRAFTING_ROWS; row++ ) - { - for( int column = 0; column < ContainerKnowledgeInscriber.CRAFTING_COLS; column++ ) - { - // Calculate the array index - int index = ( row * ContainerKnowledgeInscriber.CRAFTING_COLS ) + column; - - // Calculate the position - int posX = ContainerKnowledgeInscriber.CRAFTING_SLOT_X + ( ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING * column ); - int posY = ContainerKnowledgeInscriber.CRAFTING_SLOT_Y + ( ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING * row ); - - // Add the slot - this.addSlotToContainer( this.craftingSlots[index] = new SlotFakeCraftingMatrix( this.internalInventory, slotIndex++ , posX, posY ) ); - - } - } - } - - private void initPatternSlots() - { - int slotIndex; - // Create the pattern slots - slotIndex = ContainerKnowledgeInscriber.PATTERN_SLOT; - for( int row = 0; row < ContainerKnowledgeInscriber.PATTERN_ROWS; row++ ) - { - for( int column = 0; column < ContainerKnowledgeInscriber.PATTERN_COLS; column++ ) - { - // Calculate the array index - int index = ( row * ContainerKnowledgeInscriber.PATTERN_COLS ) + column; - - // Calculate the position - int posX = ContainerKnowledgeInscriber.PATTERN_SLOT_X + ( ContainerKnowledgeInscriber.PATTERN_SLOT_SPACING * column ); - int posY = ContainerKnowledgeInscriber.PATTERN_SLOT_Y + ( ContainerKnowledgeInscriber.PATTERN_SLOT_SPACING * row ); - - // Add to the array - this.patternSlots[index] = new SlotInaccessible( this.internalInventory, slotIndex++ , posX, posY ); - - // Add the slot - this.addSlotToContainer( this.patternSlots[index] ); - } - } - } - - private void loadPattern( final ArcaneCraftingPattern pattern ) - { - if( ( pattern == null ) || ( !pattern.isPatternValid() ) ) - { - return; - } - // Set the slots - for( int index = 0; index < this.craftingSlots.length; index++ ) - { - IAEItemStack ingStack = pattern.getInputs()[index]; - if( ingStack != null ) - { - this.craftingSlots[index].putStack( ingStack.getItemStack() ); - } - else - { - this.craftingSlots[index].putStack( null ); - } - } - } - - /** - * Prepares input to a pattern from the current recipe - * - * @param input - * @param slotNumber - * @return - */ - private Object preparePatternInput( final Object input, final int slotNumber ) - { - if( input instanceof ArrayList ) - { - // Get the prefered item - ItemStack preferedItem = this.craftingSlots[slotNumber].getStack(); - - // Create the list - ArrayList ingList = new ArrayList(); - - // Add the prefered item first - if( preferedItem != null ) - { - ingList.add( preferedItem ); - } - - // Add the rest - ArrayList inputList = (ArrayList)input; - for( ItemStack item : inputList ) - { - if( ( item == null ) || ( ItemStack.areItemStacksEqual( preferedItem, item ) ) ) - { - continue; - } - ingList.add( item ); - } - - return ingList; - } - // Is this a wildcard item? - else if( ( input instanceof ItemStack ) && ( ( (ItemStack)input ).getItemDamage() == OreDictionary.WILDCARD_VALUE ) ) - { - // Create a list to hold the users preferred item, and the wildcard item - ArrayList ingList = new ArrayList(); - ingList.add( this.craftingSlots[slotNumber].getStack() ); - ingList.add( (ItemStack)input ); - return ingList; - } - - return input; - } - - private boolean prepareShapless( final Object[] inputs ) - { - // Get the recipe - ShapelessArcaneRecipe recipe = (ShapelessArcaneRecipe)this.activeRecipe; - - ArrayList ings = recipe.getInput(); - - // Check each crafting grid slot - for( int slotIndex = 0; slotIndex < ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE; ++slotIndex ) - { - // Get the stack - - ItemStack slotStack = this.craftingSlots[slotIndex].getStack(); - if( slotStack == null ) - { - continue; - } - - // Locate it in the ingredients. - Object matchingIng = null; - int ingIndex = 0; - for( ; ingIndex < ings.size(); ++ingIndex ) - { - if (inputs[ingIndex] != null) // if there already was such ingredient - continue; - Object ing = ings.get( ingIndex ); - - if( ArcaneCraftingPattern.canSubstitueFor( ing, slotStack ) ) - { - matchingIng = ing; - break; - } - } - - // If no match found, do not encode. - if( matchingIng == null ) - { - return false; - } - - // Add to the inputs - inputs[ingIndex] = this.preparePatternInput( matchingIng, slotIndex ); - } - - // Finished prep - return true; - } - - /** - * Updates the slots to reflect the stored patterns. - */ - private void updatePatternSlots() - { - Iterator iterator = null; - - // Get the list of stored pattern results - if( this.kCoreHandler.hasCore() ) - { - ArrayList storedResults = this.kCoreHandler.getStoredOutputs(); - iterator = storedResults.iterator(); - } - - // Loop over all pattern slots - for( Slot patternSlot : this.patternSlots ) - { - // Is there an itemstack to put? - if( ( iterator != null ) && ( iterator.hasNext() ) ) - { - // Put the result - patternSlot.putStack( iterator.next() ); - } - else - { - // Clear the slot - patternSlot.putStack( null ); - } - - // Update clients with change - for( int cIndex = 0; cIndex < this.crafters.size(); ++cIndex ) - { - ( (ICrafting)this.crafters.get( cIndex ) ).sendSlotContents( this, patternSlot.slotNumber, patternSlot.getStack() ); - } - } - } - - /** - * Checks for core insertion or removal. - * - * @param playerMP - * @return - */ - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - // Has a core changed? - if( !this.kCoreHandler.isHandlingCore( this.kCoreSlot.getStack() ) ) - { - if( this.kCoreSlot.getHasStack() ) - { - // Setup the handler - this.kCoreHandler.open( this.kCoreSlot.getStack() ); - } - else - { - // Close the handler - this.kCoreHandler.close(); - } - - // Update the slots - this.updatePatternSlots(); - - // Update the save state - this.sendSaveState( false ); - - return true; - } - - return false; - } - - /** - * Can interact with anyone - * - * @param player - * @return - */ - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.inscriber != null ) - { - return this.inscriber.isUseableByPlayer( player ); - } - return false; - } - - public void onClientRequestClearGrid() - { - // Clear the grid - for( int index = ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT; index < ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT; ++index ) - { - this.internalInventory.setInventorySlotContents( index, null ); - } - - // Update the matrix - this.onCraftMatrixChanged( this.internalInventory ); - } - - /** - * Attempts to save or delete the active pattern from the kcore. - * - * @param player - */ - public void onClientRequestSaveOrDelete( final EntityPlayer player ) - { - // Get the current save state - CoreSaveState saveState = this.getSaveState(); - - Object[] inputs = new Object[ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE]; - - if( saveState == CoreSaveState.Enabled_Save ) - { - // Build the ingredient list - - // Is the recipe shaped? - if( this.activeRecipe instanceof ShapedArcaneRecipe ) - { - ShapedArcaneRecipe recipe = (ShapedArcaneRecipe)this.activeRecipe; - for( int slotNumber = 0; slotNumber < recipe.input.length; ++slotNumber ) - { - inputs[slotNumber] = this.preparePatternInput( recipe.input[slotNumber], slotNumber ); - } - } - // Is the recipe shapeless? - else if( this.activeRecipe instanceof ShapelessArcaneRecipe ) - { - if( !this.prepareShapless( inputs ) ) - { - // Could not prep shapeless - return; - } - } - else - { - // Unknown recipe type. - return; - } - - // Get the aspect cost - AspectList recipeAspects = ArcaneRecipeHelper.INSTANCE.getRecipeAspectCost( this.internalInventory, - ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, this.activeRecipe ); - - // Create the pattern - ArcaneCraftingPattern pattern = new ArcaneCraftingPattern( this.kCoreSlot.getStack(), recipeAspects, this.resultSlot.getStack(), inputs ); - - // Add the pattern - this.kCoreHandler.addPattern( pattern ); - - // Update the slots - this.updatePatternSlots(); - this.loadPattern( pattern ); - - // Update the save state - this.sendSaveState( true ); - - // Mark the inscriber as dirty - this.inscriber.markDirty(); - } - else if( saveState == CoreSaveState.Enabled_Delete ) - { - // Get the pattern for the result item - ArcaneCraftingPattern pattern = this.kCoreHandler.getPatternForItem( this.resultSlot.getStack() ); - - // Ensure there is a pattern for it - if( pattern != null ) - { - // Remove it - this.kCoreHandler.removePattern( pattern ); - - // Update the slots - this.updatePatternSlots(); - - // Update the save state - this.sendSaveState( false ); - - // Mark the inscriber as dirty - this.inscriber.markDirty(); - } - } - } - - /** - * A client has requested the save state. - * - */ - public void onClientRequestSaveState() - { - // Update the client - this.sendSaveState( false ); - } - - /** - * Updates the arcane recipe. - * - * @param inv - */ - @Override - public void onCraftMatrixChanged( final IInventory inv ) - { - // Set the active recipe - this.activeRecipe = ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult( inv, ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, - ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, - this.player ); - - ItemStack craftResult = null; - - // Set the result slot - if( this.activeRecipe != null ) - { - craftResult = ArcaneRecipeHelper.INSTANCE.getRecipeOutput( inv, ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, - ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, this.activeRecipe ); - } - - this.resultSlot.putStack( craftResult ); - - // Update the save state - if( EffectiveSide.isServerSide() ) - { - this.sendSaveState( false ); - } - - // Sync - this.detectAndSendChanges(); - } - - /** - * Sends the save-state to the client. - */ - public void sendSaveState( final boolean justSaved ) - { - Packet_C_KnowledgeInscriber.sendSaveState( this.player, this.getSaveState(), justSaved ); - } - - /** - * Creates 'ghost' items when a crafting slot is clicked. - * - * @param slotNumber - * @param buttonPressed - * @param flag - * @param player - * @return - */ - @Override - public ItemStack slotClick( final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player ) - { - // Get the itemstack the player is holding with the mouse - ItemStack draggingStack = player.inventory.getItemStack(); - - // Was the clicked slot a crafting slot? - for( Slot slot : this.craftingSlots ) - { - if( slot.slotNumber == slotNumber ) - { - // Is the player holding anything? - if( draggingStack != null ) - { - ItemStack copiedStack = draggingStack.copy(); - copiedStack.stackSize = 1; - - // Place a copy of the stack into the clicked slot - slot.putStack( copiedStack ); - } - else - { - // Clear the slot - slot.putStack( null ); - } - - // Update the matrix - this.onCraftMatrixChanged( slot.inventory ); - - return draggingStack; - } - } - - // Was the clicked slot a pattern slot? - for( Slot slot : this.patternSlots ) - { - if( slot.slotNumber == slotNumber ) - { - // Does the slot correspond to a stored pattern? - if( slot.getHasStack() ) - { - // Load the pattern - this.loadPattern( this.kCoreHandler.getPatternForItem( slot.getStack() ) ); - - // Update the matrix - this.onCraftMatrixChanged( slot.inventory ); - } - - return draggingStack; - } - } - - // Pass to super - return super.slotClick( slotNumber, buttonPressed, flag, player ); - - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Is this client side? - if( EffectiveSide.isClientSide() ) - { - // Do nothing. - return null; - } - - // Get the slot that was shift-clicked - Slot slot = this.getSlotOrNull( slotNumber ); - - // Is there a valid slot with and item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - boolean didMerge = false; - - // Get the itemstack in the slot - ItemStack slotStack = slot.getStack(); - - // Was the slot clicked in the player or hotbar inventory? - if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Attempt to merge with kcore slot - if( slotStack.getItem() instanceof ItemKnowledgeCore ) - { - didMerge = this.mergeItemStack( slotStack, this.kCoreSlot.slotNumber, this.kCoreSlot.slotNumber + 1, false ); - } - - // Was the stack merged? - if( !didMerge ) - { - // Attempt to merge with player inventory - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - } - // Was the slot clicked the KCore slot? - else if( this.kCoreSlot.slotNumber == slotNumber ) - { - // Attempt to merge with player hotbar - didMerge = this.mergeSlotWithHotbarInventory( slotStack ); - - // Was the stack merged? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } - - // Was the stack merged? - if( didMerge ) - { - - // Did the merger drain the stack? - if( ( slotStack == null ) || ( slotStack.stackSize == 0 ) ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - - // Send changes - this.detectAndSendChanges(); - } - } - - // All done. - return null; - - } +public class ContainerKnowledgeInscriber extends ContainerWithPlayerInventory { + /** + * What state the save/delete button should be in. + * + * @author Nividica + * + */ + public enum CoreSaveState { + Disabled_InvalidRecipe, + Disabled_CoreFull, + Disabled_MissingCore, + Enabled_Save, + Enabled_Delete + } + + /** + * Maximum number of patterns. + */ + private static final int MAXIMUM_PATTERNS = HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS; + + /** + * Y position for the player and hotbar inventory. + */ + private static final int PLAYER_INV_POSITION_Y = 162, + HOTBAR_INV_POSITION_Y = ContainerKnowledgeInscriber.PLAYER_INV_POSITION_Y + 58; + + /** + * Knowledge core slot. + */ + public static final int KCORE_SLOT_X = 186, KCORE_SLOT_Y = 8; + + /** + * Pattern slots. + */ + private static final int PATTERN_SLOT = 0, + PATTERN_SLOT_X = 26, + PATTERN_SLOT_Y = 18, + PATTERN_ROWS = 3, + PATTERN_COLS = 7, + PATTERN_SLOT_SPACING = 18; + + /** + * Crafting slots + */ + public static final int + CRAFTING_MATRIX_SLOT = + ContainerKnowledgeInscriber.MAXIMUM_PATTERNS + ContainerKnowledgeInscriber.PATTERN_SLOT, + CRAFTING_SLOT_X = 26, + CRAFTING_SLOT_Y = 90, + CRAFTING_ROWS = 3, + CRAFTING_COLS = 3, + CRAFTING_GRID_SIZE = ContainerKnowledgeInscriber.CRAFTING_ROWS * ContainerKnowledgeInscriber.CRAFTING_COLS, + CRAFTING_SLOT_SPACING = 18, + CRAFTING_RESULT_SLOT = + ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE; + + /** + * Handles interaction with the knowledge core. + */ + private final HandlerKnowledgeCore kCoreHandler; + + /** + * Slots + */ + private final SlotRestrictive kCoreSlot; + + private final SlotFake resultSlot; + private final SlotInaccessible[] patternSlots = new SlotInaccessible[ContainerKnowledgeInscriber.MAXIMUM_PATTERNS]; + private final SlotFakeCraftingMatrix[] craftingSlots = + new SlotFakeCraftingMatrix[ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE]; + + /** + * The current recipe, if any. + */ + private IArcaneRecipe activeRecipe = null; + + /** + * Inscriber tile entity. + */ + private TileKnowledgeInscriber inscriber; + + /** + * Inventory for the patterns and crafting matrix + */ + private final TheInternalInventory internalInventory; + + public ContainerKnowledgeInscriber( + final EntityPlayer player, final World world, final int x, final int y, final int z) { + // Call super + super(player); + + // Bind to the players inventory + this.bindPlayerInventory( + player.inventory, + ContainerKnowledgeInscriber.PLAYER_INV_POSITION_Y, + ContainerKnowledgeInscriber.HOTBAR_INV_POSITION_Y); + + // Get the inscriber + this.inscriber = (TileKnowledgeInscriber) world.getTileEntity(x, y, z); + + // Create the Kcore slot + this.kCoreSlot = new SlotRestrictive( + this.inscriber, + TileKnowledgeInscriber.KCORE_SLOT, + ContainerKnowledgeInscriber.KCORE_SLOT_X, + ContainerKnowledgeInscriber.KCORE_SLOT_Y); + this.addSlotToContainer(this.kCoreSlot); + + // Setup the internal inventory + this.internalInventory = + new TheInternalInventory("cki", ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT + 1, 64); + + // Create pattern slots + this.initPatternSlots(); + + // Create crafting slots + this.initCraftingSlots(); + + // Create the result slot + this.resultSlot = + new SlotFake(this.internalInventory, ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT, 116, 108); + this.addSlotToContainer(this.resultSlot); + + // Create the handler + this.kCoreHandler = new HandlerKnowledgeCore(); + } + + /** + * Determines the current save state. + * + * @return + */ + private CoreSaveState getSaveState() { + CoreSaveState saveState; + + // Is there a core handler? + if (!this.kCoreHandler.hasCore()) { + saveState = CoreSaveState.Disabled_MissingCore; + } + // Is there a valid recipe? + else if (this.activeRecipe == null) { + saveState = CoreSaveState.Disabled_InvalidRecipe; + } else { + // Get the recipe output + ItemStack recipeOutput = ArcaneRecipeHelper.INSTANCE.getRecipeOutput( + this.internalInventory, + ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, + this.activeRecipe); + + // Ensure there is an output + if (recipeOutput == null) { + saveState = CoreSaveState.Disabled_InvalidRecipe; + } else { + // Does the core already have this recipe, or one that produces the same result, stored? + boolean isNew = !this.kCoreHandler.hasPatternFor(recipeOutput); + + // Would the recipe be a new pattern? + if (isNew) { + // Is there room for the recipe? + if (this.kCoreHandler.hasRoomToStorePattern()) { + // Enable saving + saveState = CoreSaveState.Enabled_Save; + } else { + // Core is full + saveState = CoreSaveState.Disabled_CoreFull; + } + } else { + // Enable deleting + saveState = CoreSaveState.Enabled_Delete; + } + } + } + + return saveState; + } + + private void initCraftingSlots() { + int slotIndex; + // Create the crafting slots + slotIndex = ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT; + for (int row = 0; row < ContainerKnowledgeInscriber.CRAFTING_ROWS; row++) { + for (int column = 0; column < ContainerKnowledgeInscriber.CRAFTING_COLS; column++) { + // Calculate the array index + int index = (row * ContainerKnowledgeInscriber.CRAFTING_COLS) + column; + + // Calculate the position + int posX = ContainerKnowledgeInscriber.CRAFTING_SLOT_X + + (ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING * column); + int posY = ContainerKnowledgeInscriber.CRAFTING_SLOT_Y + + (ContainerKnowledgeInscriber.CRAFTING_SLOT_SPACING * row); + + // Add the slot + this.addSlotToContainer( + this.craftingSlots[index] = + new SlotFakeCraftingMatrix(this.internalInventory, slotIndex++, posX, posY)); + } + } + } + + private void initPatternSlots() { + int slotIndex; + // Create the pattern slots + slotIndex = ContainerKnowledgeInscriber.PATTERN_SLOT; + for (int row = 0; row < ContainerKnowledgeInscriber.PATTERN_ROWS; row++) { + for (int column = 0; column < ContainerKnowledgeInscriber.PATTERN_COLS; column++) { + // Calculate the array index + int index = (row * ContainerKnowledgeInscriber.PATTERN_COLS) + column; + + // Calculate the position + int posX = ContainerKnowledgeInscriber.PATTERN_SLOT_X + + (ContainerKnowledgeInscriber.PATTERN_SLOT_SPACING * column); + int posY = ContainerKnowledgeInscriber.PATTERN_SLOT_Y + + (ContainerKnowledgeInscriber.PATTERN_SLOT_SPACING * row); + + // Add to the array + this.patternSlots[index] = new SlotInaccessible(this.internalInventory, slotIndex++, posX, posY); + + // Add the slot + this.addSlotToContainer(this.patternSlots[index]); + } + } + } + + private void loadPattern(final ArcaneCraftingPattern pattern) { + if ((pattern == null) || (!pattern.isPatternValid())) { + return; + } + // Set the slots + for (int index = 0; index < this.craftingSlots.length; index++) { + IAEItemStack ingStack = pattern.getInputs()[index]; + if (ingStack != null) { + this.craftingSlots[index].putStack(ingStack.getItemStack()); + } else { + this.craftingSlots[index].putStack(null); + } + } + } + + /** + * Prepares input to a pattern from the current recipe + * + * @param input + * @param slotNumber + * @return + */ + private Object preparePatternInput(final Object input, final int slotNumber) { + if (input instanceof ArrayList) { + // Get the prefered item + ItemStack preferedItem = this.craftingSlots[slotNumber].getStack(); + + // Create the list + ArrayList ingList = new ArrayList(); + + // Add the prefered item first + if (preferedItem != null) { + ingList.add(preferedItem); + } + + // Add the rest + ArrayList inputList = (ArrayList) input; + for (ItemStack item : inputList) { + if ((item == null) || (ItemStack.areItemStacksEqual(preferedItem, item))) { + continue; + } + ingList.add(item); + } + + return ingList; + } + // Is this a wildcard item? + else if ((input instanceof ItemStack) + && (((ItemStack) input).getItemDamage() == OreDictionary.WILDCARD_VALUE)) { + // Create a list to hold the users preferred item, and the wildcard item + ArrayList ingList = new ArrayList(); + ingList.add(this.craftingSlots[slotNumber].getStack()); + ingList.add((ItemStack) input); + return ingList; + } + + return input; + } + + private boolean prepareShapless(final Object[] inputs) { + // Get the recipe + ShapelessArcaneRecipe recipe = (ShapelessArcaneRecipe) this.activeRecipe; + + ArrayList ings = recipe.getInput(); + + // Check each crafting grid slot + for (int slotIndex = 0; slotIndex < ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE; ++slotIndex) { + // Get the stack + + ItemStack slotStack = this.craftingSlots[slotIndex].getStack(); + if (slotStack == null) { + continue; + } + + // Locate it in the ingredients. + Object matchingIng = null; + int ingIndex = 0; + for (; ingIndex < ings.size(); ++ingIndex) { + if (inputs[ingIndex] != null) // if there already was such ingredient + continue; + Object ing = ings.get(ingIndex); + + if (ArcaneCraftingPattern.canSubstitueFor(ing, slotStack)) { + matchingIng = ing; + break; + } + } + + // If no match found, do not encode. + if (matchingIng == null) { + return false; + } + + // Add to the inputs + inputs[ingIndex] = this.preparePatternInput(matchingIng, slotIndex); + } + + // Finished prep + return true; + } + + /** + * Updates the slots to reflect the stored patterns. + */ + private void updatePatternSlots() { + Iterator iterator = null; + + // Get the list of stored pattern results + if (this.kCoreHandler.hasCore()) { + ArrayList storedResults = this.kCoreHandler.getStoredOutputs(); + iterator = storedResults.iterator(); + } + + // Loop over all pattern slots + for (Slot patternSlot : this.patternSlots) { + // Is there an itemstack to put? + if ((iterator != null) && (iterator.hasNext())) { + // Put the result + patternSlot.putStack(iterator.next()); + } else { + // Clear the slot + patternSlot.putStack(null); + } + + // Update clients with change + for (int cIndex = 0; cIndex < this.crafters.size(); ++cIndex) { + ((ICrafting) this.crafters.get(cIndex)) + .sendSlotContents(this, patternSlot.slotNumber, patternSlot.getStack()); + } + } + } + + /** + * Checks for core insertion or removal. + * + * @param playerMP + * @return + */ + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Has a core changed? + if (!this.kCoreHandler.isHandlingCore(this.kCoreSlot.getStack())) { + if (this.kCoreSlot.getHasStack()) { + // Setup the handler + this.kCoreHandler.open(this.kCoreSlot.getStack()); + } else { + // Close the handler + this.kCoreHandler.close(); + } + + // Update the slots + this.updatePatternSlots(); + + // Update the save state + this.sendSaveState(false); + + return true; + } + + return false; + } + + /** + * Can interact with anyone + * + * @param player + * @return + */ + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.inscriber != null) { + return this.inscriber.isUseableByPlayer(player); + } + return false; + } + + public void onClientRequestClearGrid() { + // Clear the grid + for (int index = ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT; + index < ContainerKnowledgeInscriber.CRAFTING_RESULT_SLOT; + ++index) { + this.internalInventory.setInventorySlotContents(index, null); + } + + // Update the matrix + this.onCraftMatrixChanged(this.internalInventory); + } + + /** + * Attempts to save or delete the active pattern from the kcore. + * + * @param player + */ + public void onClientRequestSaveOrDelete(final EntityPlayer player) { + // Get the current save state + CoreSaveState saveState = this.getSaveState(); + + Object[] inputs = new Object[ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE]; + + if (saveState == CoreSaveState.Enabled_Save) { + // Build the ingredient list + + // Is the recipe shaped? + if (this.activeRecipe instanceof ShapedArcaneRecipe) { + ShapedArcaneRecipe recipe = (ShapedArcaneRecipe) this.activeRecipe; + for (int slotNumber = 0; slotNumber < recipe.input.length; ++slotNumber) { + inputs[slotNumber] = this.preparePatternInput(recipe.input[slotNumber], slotNumber); + } + } + // Is the recipe shapeless? + else if (this.activeRecipe instanceof ShapelessArcaneRecipe) { + if (!this.prepareShapless(inputs)) { + // Could not prep shapeless + return; + } + } else { + // Unknown recipe type. + return; + } + + // Get the aspect cost + AspectList recipeAspects = ArcaneRecipeHelper.INSTANCE.getRecipeAspectCost( + this.internalInventory, + ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, + this.activeRecipe); + + // Create the pattern + ArcaneCraftingPattern pattern = new ArcaneCraftingPattern( + this.kCoreSlot.getStack(), recipeAspects, this.resultSlot.getStack(), inputs); + + // Add the pattern + this.kCoreHandler.addPattern(pattern); + + // Update the slots + this.updatePatternSlots(); + this.loadPattern(pattern); + + // Update the save state + this.sendSaveState(true); + + // Mark the inscriber as dirty + this.inscriber.markDirty(); + } else if (saveState == CoreSaveState.Enabled_Delete) { + // Get the pattern for the result item + ArcaneCraftingPattern pattern = this.kCoreHandler.getPatternForItem(this.resultSlot.getStack()); + + // Ensure there is a pattern for it + if (pattern != null) { + // Remove it + this.kCoreHandler.removePattern(pattern); + + // Update the slots + this.updatePatternSlots(); + + // Update the save state + this.sendSaveState(false); + + // Mark the inscriber as dirty + this.inscriber.markDirty(); + } + } + } + + /** + * A client has requested the save state. + * + */ + public void onClientRequestSaveState() { + // Update the client + this.sendSaveState(false); + } + + /** + * Updates the arcane recipe. + * + * @param inv + */ + @Override + public void onCraftMatrixChanged(final IInventory inv) { + // Set the active recipe + this.activeRecipe = ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult( + inv, + ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, + this.player); + + ItemStack craftResult = null; + + // Set the result slot + if (this.activeRecipe != null) { + craftResult = ArcaneRecipeHelper.INSTANCE.getRecipeOutput( + inv, + ContainerKnowledgeInscriber.CRAFTING_MATRIX_SLOT, + ContainerKnowledgeInscriber.CRAFTING_GRID_SIZE, + this.activeRecipe); + } + + this.resultSlot.putStack(craftResult); + + // Update the save state + if (EffectiveSide.isServerSide()) { + this.sendSaveState(false); + } + + // Sync + this.detectAndSendChanges(); + } + + /** + * Sends the save-state to the client. + */ + public void sendSaveState(final boolean justSaved) { + Packet_C_KnowledgeInscriber.sendSaveState(this.player, this.getSaveState(), justSaved); + } + + /** + * Creates 'ghost' items when a crafting slot is clicked. + * + * @param slotNumber + * @param buttonPressed + * @param flag + * @param player + * @return + */ + @Override + public ItemStack slotClick( + final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player) { + // Get the itemstack the player is holding with the mouse + ItemStack draggingStack = player.inventory.getItemStack(); + + // Was the clicked slot a crafting slot? + for (Slot slot : this.craftingSlots) { + if (slot.slotNumber == slotNumber) { + // Is the player holding anything? + if (draggingStack != null) { + ItemStack copiedStack = draggingStack.copy(); + copiedStack.stackSize = 1; + + // Place a copy of the stack into the clicked slot + slot.putStack(copiedStack); + } else { + // Clear the slot + slot.putStack(null); + } + + // Update the matrix + this.onCraftMatrixChanged(slot.inventory); + + return draggingStack; + } + } + + // Was the clicked slot a pattern slot? + for (Slot slot : this.patternSlots) { + if (slot.slotNumber == slotNumber) { + // Does the slot correspond to a stored pattern? + if (slot.getHasStack()) { + // Load the pattern + this.loadPattern(this.kCoreHandler.getPatternForItem(slot.getStack())); + + // Update the matrix + this.onCraftMatrixChanged(slot.inventory); + } + + return draggingStack; + } + } + + // Pass to super + return super.slotClick(slotNumber, buttonPressed, flag, player); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Is this client side? + if (EffectiveSide.isClientSide()) { + // Do nothing. + return null; + } + + // Get the slot that was shift-clicked + Slot slot = this.getSlotOrNull(slotNumber); + + // Is there a valid slot with and item? + if ((slot != null) && (slot.getHasStack())) { + boolean didMerge = false; + + // Get the itemstack in the slot + ItemStack slotStack = slot.getStack(); + + // Was the slot clicked in the player or hotbar inventory? + if (this.slotClickedWasInPlayerInventory(slotNumber) || this.slotClickedWasInHotbarInventory(slotNumber)) { + // Attempt to merge with kcore slot + if (slotStack.getItem() instanceof ItemKnowledgeCore) { + didMerge = this.mergeItemStack( + slotStack, this.kCoreSlot.slotNumber, this.kCoreSlot.slotNumber + 1, false); + } + + // Was the stack merged? + if (!didMerge) { + // Attempt to merge with player inventory + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + // Was the slot clicked the KCore slot? + else if (this.kCoreSlot.slotNumber == slotNumber) { + // Attempt to merge with player hotbar + didMerge = this.mergeSlotWithHotbarInventory(slotStack); + + // Was the stack merged? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } + + // Was the stack merged? + if (didMerge) { + + // Did the merger drain the stack? + if ((slotStack == null) || (slotStack.stackSize == 0)) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + + // Send changes + this.detectAndSendChanges(); + } + } + + // All done. + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerPartArcaneCraftingTerminal.java b/src/main/java/thaumicenergistics/common/container/ContainerPartArcaneCraftingTerminal.java index 6f6a231a..69e38dae 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerPartArcaneCraftingTerminal.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerPartArcaneCraftingTerminal.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.container; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SortDir; @@ -20,6 +17,10 @@ import appeng.container.ContainerOpenContext; import appeng.container.implementations.ContainerCraftAmount; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; @@ -30,7 +31,6 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.oredict.OreDictionary; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.api.crafting.IArcaneRecipe; @@ -50,1722 +50,1563 @@ import thaumicenergistics.common.parts.PartArcaneCraftingTerminal; import thaumicenergistics.common.utils.EffectiveSide; import thaumicenergistics.common.utils.ThEUtils; -import javax.annotation.Nonnull; - /** * {@link PartArcaneCraftingTerminal} container. * * @author Nividica * */ -public class ContainerPartArcaneCraftingTerminal - extends ContainerWithPlayerInventory - implements IMEMonitorHandlerReceiver, ICraftingIssuerContainer -{ - /** - * Holds a single aspect cost for the current recipe. - * - * @author Nividica - * - */ - public class ArcaneCrafingCost - { - /** - * How much vis does the recipe require? - */ - public final float visCost; - - /** - * Which aspect? - */ - public final Aspect primal; - - /** - * Do we have enough of this aspect in the wand to perform the craft? - */ - public final boolean hasEnoughVis; - - public ArcaneCrafingCost( final float visCost, final Aspect primal, final boolean hasEnough ) - { - // Round to 1 decimal place - this.visCost = Math.round( visCost * 10.0F ) / 10.0F; - - this.primal = primal; - - this.hasEnoughVis = hasEnough; - } - } - - /** - * Y position for the player and hotbar inventory. - */ - private static int PLAYER_INV_POSITION_Y = 162, HOTBAR_INV_POSITION_Y = 220; - - /** - * Row and Column counts of the crafting grid. - */ - private static int CRAFTING_GRID_SIZE = 3; - - /** - * Total number of slots in the crafting grid - */ - public static int CRAFTING_GRID_TOTAL_SIZE = ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE * - ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; - - /** - * Starting position for crafting slots. - */ - public static int CRAFTING_SLOT_X_POS = 44, CRAFTING_SLOT_Y_POS = 90; - - /** - * Position of the output slot. - */ - private static int RESULT_SLOT_X_POS = 116, RESULT_SLOT_Y_POS = 126; - - /** - * Position of the wand slot. - */ - private static int WAND_SLOT_XPOS = 116, WAND_SLOT_YPOS = 90; - - /** - * Starting position of the view slots - */ - public static int VIEW_SLOT_XPOS = 206, VIEW_SLOT_YPOS = 8; - - /** - * Starting position for armor slots. - */ - public static int ARMOR_SLOT_X_POS = 8, ARMOR_SLOT_Y_POS = 81, ARMOR_SLOT_COUNT = 4; - - /** - * Cache the crafting manager instance - */ - private static CraftingManager CRAFT_MANAGER = CraftingManager.getInstance(); - - /** - * The arcane crafting terminal associated with the container. - */ - public final PartArcaneCraftingTerminal terminal; - - /** - * Network source representing the player who is interacting with the - * container. - */ - private final PlayerSource playerSource; - - /** - * The AE network item monitor we are attached to. - */ - private IMEMonitor monitor; - - /** - * Slot number of the first and last crafting slots. - */ - private int firstCraftingSlotNumber = -1, lastCraftingSlotNumber = -1; - - /** - * Slot number of the first and last view slots. - */ - private int firstViewSlotNumber = -1, lastViewSlotNumber = -1; - - /** - * Slot number of the wand. - */ - private final SlotRestrictive wandSlot; - - /** - * Slot number of the result. - */ - private final SlotArcaneCraftingResult resultSlot; - - /** - * The wand currently in the wand slot. - */ - private ItemStack wand; - - /** - * The required aspects for the current recipe. - */ - private AspectList requiredAspects; - - /** - * The required aspects, costs, and missing for the current recipe. - */ - private List craftingCost = new ArrayList(); - - /** - * Cached sorting order. - */ - private SortOrder cachedSortOrder = PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER; - - /** - * Cached sorting direction. - */ - private SortDir cachedSortDirection = PartArcaneCraftingTerminal.DEFAULT_SORT_DIR; - - /** - * Cached view mode. - */ - private ViewItems cachedViewMode = PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE; - - /** - * Creates the container - * - * @param terminal - * @param player - */ - public ContainerPartArcaneCraftingTerminal( final PartArcaneCraftingTerminal terminal, final EntityPlayer player ) - { - // Call super - super( player ); - - // Set the part - this.terminal = terminal; - - // Set the player source - this.playerSource = new PlayerSource( this.player, terminal ); - - // Bind to the players inventory - this.bindPlayerInventory( player.inventory, ContainerPartArcaneCraftingTerminal.PLAYER_INV_POSITION_Y, - ContainerPartArcaneCraftingTerminal.HOTBAR_INV_POSITION_Y ); - - // Add crafting slots - Slot craftingSlot = null; - for( int row = 0; row < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; row++ ) - { - for( int column = 0; column < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; column++ ) - { - // Calculate the index - int slotIndex = ( row * ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE ) + column; - - // Create the slot - craftingSlot = new Slot( terminal, slotIndex, ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_X_POS + - ( column * ContainerWithPlayerInventory.SLOT_SIZE ), ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_Y_POS + - ( row * ContainerWithPlayerInventory.SLOT_SIZE ) ); - - // Add the slot - this.addSlotToContainer( craftingSlot ); - - // Check first crafting slot number - if( ( row + column ) == 0 ) - { - this.firstCraftingSlotNumber = craftingSlot.slotNumber; - } - } - } - - // Set last crafting slot number - if( craftingSlot != null ) - { - this.lastCraftingSlotNumber = craftingSlot.slotNumber; - } - - // Create the result slot - this.resultSlot = new SlotArcaneCraftingResult( player, this, terminal, terminal, - PartArcaneCraftingTerminal.RESULT_SLOT_INDEX, ContainerPartArcaneCraftingTerminal.RESULT_SLOT_X_POS, - ContainerPartArcaneCraftingTerminal.RESULT_SLOT_Y_POS ); - - // Add the result slot - this.addSlotToContainer( this.resultSlot ); - - // Create the wand slot - this.wandSlot = new SlotRestrictive( terminal, PartArcaneCraftingTerminal.WAND_SLOT_INDEX, - ContainerPartArcaneCraftingTerminal.WAND_SLOT_XPOS, ContainerPartArcaneCraftingTerminal.WAND_SLOT_YPOS ); - - // Add the wand slot - this.addSlotToContainer( this.wandSlot ); - - // Create the view slots - SlotRestrictive viewSlot = null; - for( int viewSlotID = PartArcaneCraftingTerminal.VIEW_SLOT_MIN; viewSlotID <= PartArcaneCraftingTerminal.VIEW_SLOT_MAX; viewSlotID++ ) - { - // Calculate the y position - int row = viewSlotID - PartArcaneCraftingTerminal.VIEW_SLOT_MIN; - int yPos = ContainerPartArcaneCraftingTerminal.VIEW_SLOT_YPOS + ( row * ContainerWithPlayerInventory.SLOT_SIZE ); - - // Create the slot - viewSlot = new SlotRestrictive( terminal, viewSlotID, ContainerPartArcaneCraftingTerminal.VIEW_SLOT_XPOS, yPos ); - - // Add the slot - this.addSlotToContainer( viewSlot ); - - // Check first view slot - if( row == 0 ) - { - this.firstViewSlotNumber = viewSlot.slotNumber; - } - } - - // Set last view slot number - if( viewSlot != null ) - { - this.lastViewSlotNumber = viewSlot.slotNumber; - } - - // Create the armor slots - for( int armorIndex = 0; armorIndex < ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_COUNT; ++armorIndex ) - { - // Calculate y position - int yPos = ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_Y_POS + ( ContainerWithPlayerInventory.SLOT_SIZE * armorIndex ); - - // Create the slot - SlotArmor armorSlot = new SlotArmor( terminal, PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorIndex, - ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_X_POS, yPos, armorIndex, false ); - - // Add to container - this.addSlotToContainer( armorSlot ); - - /** - * Notes about the hidden slots - * I hate this, but I have tried everything I can think of, and the - * equipped armor will not change immediately unless - * the notification comes from the open container, this container. - */ - // Create the 'hidden'slot - armorSlot = new SlotArmor( player.inventory, 36 + ( 3 - armorIndex ), 0, -1000, armorIndex, false ); - - // Add to container - this.addSlotToContainer( armorSlot ); - - } - - if( EffectiveSide.isServerSide() ) - { - // Register with terminal - this.registerForUpdates(); - } - - // Attach to the monitor - this.attachToMonitor(); - - } - - /** - * Attempts to attach to the item monitor. - * - * @return - */ - private boolean attachToMonitor() - { - // Is this server side? - if( EffectiveSide.isClientSide() ) - { - return false; - } - - // Clear any existing - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - - // Get the grid - IGrid grid = this.terminal.getGridBlock().getGrid(); - if( grid != null ) - { - // Get the AE monitor - this.monitor = this.terminal.getItemInventory(); - if( this.monitor != null ) - { - // Register with the monitor. - this.monitor.addListener( this, grid.hashCode() ); - return true; - } - } - - return false; - } - - /** - * Attempts to clear the crafting grid by placing the items - * back in the ME network. - * - * @param sendUpdate - * If true, any changes made are sent across the network - * @return - */ - private boolean clearCraftingGrid( final boolean sendUpdate ) - { - // Ignored client side - if( EffectiveSide.isClientSide() ) - { - return false; - } - - // Assume the grid is clear - boolean clearedAll = true; - - for( int index = this.firstCraftingSlotNumber; index <= this.lastCraftingSlotNumber; index++ ) - { - // Get the slot - Slot slot = (Slot)this.inventorySlots.get( index ); - - // Ensure the slot is not null and has a stack - if( ( slot == null ) || ( !slot.getHasStack() ) ) - { - continue; - } - - // Set the stack - ItemStack slotStack = slot.getStack(); - - // Inject into the ME network - boolean didMerge = this.mergeWithMENetwork( slotStack ); - - // Did any merge? - if( !didMerge ) - { - // Items are left over in the grid - clearedAll = false; - continue; - } - - // Did the merger drain the stack? - if( ( slotStack == null ) || ( slotStack.stackSize == 0 ) ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Items are left over in the grid - clearedAll = false; - - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - } - - // Update - this.detectAndSendChanges(); - - // Return if we cleared the whole grid or not - return clearedAll; - } - - /** - * Handles automatically crafting items when the crafting - * output slot is shift+clicked - * - * @param player - */ - private void doShiftAutoCrafting( final EntityPlayer player ) - { - // Tracks if a crafting result could be placed in the players inventory - boolean didMerge; - - // Tracks how many items we have made - int autoCraftCounter = 0; - - // Get the current crafting result. - ItemStack resultStack = this.resultSlot.getStack(); - - // Make a copy of it - ItemStack slotStackOriginal = resultStack.copy(); - - for( autoCraftCounter = slotStackOriginal.stackSize; autoCraftCounter <= 64; autoCraftCounter += slotStackOriginal.stackSize ) - { - // Attempt to merge with the player inventory - didMerge = ( this.mergeSlotWithPlayerInventory( resultStack ) || this.mergeSlotWithHotbarInventory( resultStack ) ); - - // Were we able to merge? - if( didMerge ) - { - // Let the result slot know it was picked up - this.resultSlot.onPickupFromSlotViaTransfer( player, resultStack ); - - // Update the matrix - this.onCraftMatrixChanged( null ); - - // Get the stack in the result slot now. - resultStack = this.resultSlot.getStack(); - - // Is it empty? - if( ( resultStack == null ) || ( resultStack.stackSize == 0 ) ) - { - // Can't craft anymore, break the loop - break; - } - // Does it still match the output item? - if( !resultStack.getItem().equals( slotStackOriginal.getItem() ) ) - { - // Crafting result changed, break the loop - break; - } - } - else - { - // Unable to merge results, break the loop - break; - } - - } - - // Did we do any crafting? - if( autoCraftCounter > 0 ) - { - // Mark the result slot as dirty - this.resultSlot.onSlotChanged(); - - // Send changes - this.detectAndSendChanges(); - } - } - - /** - * Checks if two stacks match. Either directly, or by ore dictionary. - * - * @param keyStack - * @param potentialMatch - * @return - */ - private boolean doStacksMatch( final IAEItemStack keyStack, final IAEItemStack potentialMatch ) - { - return keyStack.isSameType(potentialMatch) || keyStack.sameOre(potentialMatch); - } - - /** - * Searches for a matching arcane crafting recipe result - * - * @return ItemStack of the result if found, null otherwise. - */ - private ItemStack findMatchingArcaneResult() - { - ItemStack arcaneResult = null; - - // Is there a matching recipe? - IArcaneRecipe matchingRecipe = ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult( this.terminal, 0, - ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, this.player ); - - if( matchingRecipe != null ) - { - // Found a match, validate it. - arcaneResult = this.validateWandVisAmount( matchingRecipe ); - } - - // Return the result - return arcaneResult; - } - - /** - * Searches for a matching regular(non arcane) crafting recipe result - * - * @return ItemStack of the result if found, null otherwise. - */ - private ItemStack findMatchingRegularResult() - { - // Create a new crafting inventory - InventoryCrafting craftingInventory = new InventoryCrafting( new ContainerInternalCrafting(), - ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE, ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE ); - - // Load the inventory based on what is in the part's inventory - for( int slotIndex = 0; slotIndex < ( ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE ); slotIndex++ ) - { - // Set the slot - craftingInventory.setInventorySlotContents( slotIndex, this.terminal.getStackInSlot( slotIndex ) ); - } - - // Return the result - return ContainerPartArcaneCraftingTerminal.CRAFT_MANAGER.findMatchingRecipe( craftingInventory, this.terminal.getWorldObj() ); - } - - /** - * Gets the view cells in the terminal. - * - * @return - */ - public ItemStack[] getViewCells() - { - List viewCells = new ArrayList(); - - Slot viewSlot; - for( int viewSlotIndex = this.firstViewSlotNumber; viewSlotIndex <= this.lastViewSlotNumber; viewSlotIndex++ ) - { - // Get the slot - viewSlot = this.getSlotOrNull( viewSlotIndex ); - - // Ensure the slot is not empty - if( ( viewSlot == null ) || !viewSlot.getHasStack() ) - { - continue; - } - - // Add the cell - viewCells.add( viewSlot.getStack() ); - } - - return viewCells.toArray( new ItemStack[viewCells.size()] ); - } - - /** - * Sets 'wand' if there is a wand in the wand slot. - */ - private void getWand() - { - // Is this the same wand that we have cached? - if( this.wand == this.wandSlot.getStack() ) - { - // Nothing has changed - return; - } - - // Is the item a valid crafting wand? - if( ThEUtils.isItemValidWand( this.wandSlot.getStack(), false ) ) - { - // Set the wand - this.wand = this.wandSlot.getStack(); - - return; - } - - // Set the wand to null - this.wand = null; - } - - /** - * Attempts to inject an itemstack into the ME network. - * Adjusts the stack size of the specified itemstack according to - * the results of the merger. - * - * @param itemStack - * @return True if any amount was merged, False otherwise. - */ - private boolean mergeWithMENetwork( final ItemStack itemStack ) - { - // Attempt to place in the ME system - IAEItemStack toInject = AEApi.instance().storage().createItemStack( itemStack ); - - // Get what is left over after the injection - IAEItemStack leftOver = this.monitor.injectItems( toInject, Actionable.MODULATE, this.playerSource ); - - // Do we have any left over? - if( ( leftOver != null ) && ( leftOver.getStackSize() > 0 ) ) - { - // Did we inject any? - if( leftOver.getStackSize() == toInject.getStackSize() ) - { - // No injection occurred - return false; - } - - // Some was injected, adjust the slot stack size - itemStack.stackSize = (int)leftOver.getStackSize(); - - return true; - } - - // All was injected - itemStack.stackSize = 0; - - return true; - } - - /** - * Attempts to add the itemstack to the view cell slots - * - * @param itemStack - * @return True if was moved, False otherwise. - */ - private boolean mergeWithViewCells( final ItemStack itemStack ) - { - // Ensure the item a view cell - if( !this.terminal.isItemValidForSlot( PartArcaneCraftingTerminal.VIEW_SLOT_MIN, itemStack ) ) - { - return false; - } - - Slot viewSlot; - for( int viewSlotIndex = this.firstViewSlotNumber; viewSlotIndex <= this.lastViewSlotNumber; viewSlotIndex++ ) - { - // Get the slot - viewSlot = this.getSlotOrNull( viewSlotIndex ); - - // Is there a slot? - if( viewSlot == null ) - { - // Somehow, there is a null slot - continue; - } - - // Ensure the slot is empty - if( viewSlot.getHasStack() ) - { - continue; - } - - // Insert the view cell - viewSlot.putStack( itemStack.copy() ); - - // Clear the source stack - itemStack.stackSize = 0; - - // Merge/move complete - return true; - } - - // Unable to move - return false; - } - - /** - * Informs the GUI that the view cells have changed - */ - @SideOnly(Side.CLIENT) - private void updateGUIViewCells() - { - // Get the current screen being displayed to the user - Gui gui = Minecraft.getMinecraft().currentScreen; - - // Is that screen the gui for the ACT? - if( gui instanceof GuiArcaneCraftingTerminal ) - { - ( (GuiArcaneCraftingTerminal)gui ).onViewCellsChanged( this.getViewCells() ); - } - } - - /** - * Checks if the wand has enough vis to complete the craft. - * Takes into consideration the players multiplier. - * - * @param forRecipe - * @return ItemStack of the result if wand has enough vis, null otherwise. - */ - private ItemStack validateWandVisAmount( final IArcaneRecipe forRecipe ) - { - boolean hasAll = true; - AspectList wandAspectList = null; - ItemWandCasting wandItem = null; - - // Get the cost - this.requiredAspects = ArcaneRecipeHelper.INSTANCE.getRecipeAspectCost( this.terminal, 0, - ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, forRecipe ); - - // Ensure there is a cost - if( this.requiredAspects == null ) - { - return null; - } - - // Cache the recipes aspects - Aspect[] recipeAspects = this.requiredAspects.getAspects(); - - // Do we have a wand? - if( this.wand != null ) - { - // Get the wand item - wandItem = ( (ItemWandCasting)this.wand.getItem() ); - - // Cache the wand's aspect list - wandAspectList = wandItem.getAllVis( this.wand ); - } - - // Check the wand amounts vs recipe aspects - for( Aspect currentAspect : recipeAspects ) - { - // Get the base required vis - int baseVis = this.requiredAspects.getAmount( currentAspect ); - - // Get the adjusted amount - int requiredVis = baseVis * 100; - - // Assume we do not have enough - boolean hasEnough = false; - - // Do we have a wand? - if( ( wandItem != null ) && ( wandAspectList != null ) ) - { - // Adjust the required amount by the wand modifier - requiredVis = (int)( requiredVis * wandItem.getConsumptionModifier( this.wand, this.player, currentAspect, true ) ); - - // Does the wand not have enough of vis of this aspect? - hasEnough = ( wandAspectList.getAmount( currentAspect ) >= requiredVis ); - } - - if( !hasEnough ) - { - // Mark that we do not have enough vis to complete crafting - hasAll = false; - } - - // Add to the cost list - this.craftingCost.add( new ArcaneCrafingCost( requiredVis / 100.0F, currentAspect, hasEnough ) ); - } - - // Did we have all the vis required? - if( hasAll ) - { - // Get the result of the recipe. - return ArcaneRecipeHelper.INSTANCE.getRecipeOutput( this.terminal, 0, - ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, forRecipe ); - } - - return null; - - } - - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - boolean sendModeUpdate = false; - - // Has the sorting order changed? - if( this.cachedSortOrder != this.terminal.getSortingOrder() ) - { - // Update - this.cachedSortOrder = this.terminal.getSortingOrder(); - sendModeUpdate = true; - } - - // Has the sorting direction changed? - if( this.cachedSortDirection != this.terminal.getSortingDirection() ) - { - // Update - this.cachedSortDirection = this.terminal.getSortingDirection(); - sendModeUpdate = true; - } - - // Has the view mode changed? - if( this.cachedViewMode != this.terminal.getViewMode() ) - { - // Update - this.cachedViewMode = this.terminal.getViewMode(); - sendModeUpdate = true; - } - - // Send update? - if( sendModeUpdate ) - { - // Send the mode info - Packet_C_ArcaneCraftingTerminal.sendModeChange( this.player, - this.cachedSortOrder, this.cachedSortDirection, this.cachedViewMode ); - } - - // Is the monitor null? - if( this.monitor == null ) - { - // Attempt to re-attach - if( this.attachToMonitor() ) - { - // Update the client - this.onClientRequestFullUpdate( this.player ); - } - } - - return false; - } - - /** - * Checks if the slot number belongs to the crafting matrix - * - * @param slotNumber - * @return - */ - protected boolean slotClickedWasInCraftingInventory( final int slotNumber ) - { - return ( slotNumber >= this.firstCraftingSlotNumber ) && ( slotNumber <= this.lastCraftingSlotNumber ); - } - - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.terminal != null ) - { - return this.terminal.isUseableByPlayer( player ); - } - return false; - } - - /** - * Changes the Y offset for all slots, except the view slots, in this - * container. - * - * @param deltaY - */ - public void changeSlotsYOffset( final int deltaY ) - { - for( Object slotObj : this.inventorySlots ) - { - // Get the slot - Slot slot = (Slot)slotObj; - - // Skip view slots - if( ( slot.slotNumber >= this.firstViewSlotNumber ) && ( slot.slotNumber <= this.lastViewSlotNumber ) ) - { - continue; - } - - // Adjust Y pos - slot.yDisplayPosition += deltaY; - } - } - - /** - * Gets the aspect cost and how much is missing for the current recipe. - * - * @return Null if not an arcane recipe, cost otherwise. - */ - public List getCraftingCost( final boolean forceUpdate ) - { - if( forceUpdate ) - { - this.craftingCost.clear(); - this.findMatchingArcaneResult(); - } - - // Does this recipe have costs? - if( this.craftingCost.isEmpty() ) - { - return Collections.emptyList(); - } - - // Return required and missing - return this.craftingCost; - } - - @Override - public ICraftingIssuerHost getCraftingHost() - { - return this.terminal; - } - - /** - * Called by the monitor to ensure we still want updates - */ - @Override - public boolean isValid( final Object authToken ) - { - if( this.monitor == null ) - { - return false; - } - - // Get the grid - IGrid grid = this.terminal.getGridBlock().getGrid(); - if( grid != null ) - { - if( grid.hashCode() == (Integer)authToken ) - { - return true; - } - } - - // Monitor no longer valid - this.monitor = null; - - // Update client - this.onClientRequestFullUpdate( this.player ); - - return false; - } - - /** - * Called when a client is setting up the crafting grid via NEI - * - * @param player - * @param gridItems - */ - public void onClientNEIRequestSetCraftingGrid( final EntityPlayer player, final IAEItemStack[] gridItems ) - { - // Attempt to clear the crafting grid - if( this.clearCraftingGrid( false ) ) - { - for( int craftingSlotIndex = 0; craftingSlotIndex < 9; craftingSlotIndex++ ) - { - // Get the stack - IAEItemStack slotStack = gridItems[craftingSlotIndex]; - - // Ensure the slot was not null - if( slotStack == null ) - { - // Skip null items - continue; - } - - // Find a matching stack. - ItemStack matchingStack = this.requestCraftingReplenishment( slotStack.getItemStack() ); - - // Ensure a stack was found - if( matchingStack != null ) - { - // Get the slot - Slot slot = (Slot)this.inventorySlots.get( this.firstCraftingSlotNumber + craftingSlotIndex ); - - // Set the slot contents - slot.putStack( matchingStack ); - } - } - - // Update clients - this.detectAndSendChanges(); - } - - } - - /** - * Called when a client has clicked on a craftable item. - * - * @param player - * @param result - */ - public void onClientRequestAutoCraft( final EntityPlayer player, final IAEItemStack result ) - { - // Get the host tile - TileEntity te = this.terminal.getHostTile(); - - // Launch the GUI - ThEGuiHandler.launchGui( ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - - // Setup the amount container - if( player.openContainer instanceof ContainerCraftAmount ) - { - // Get the container - ContainerCraftAmount cca = (ContainerCraftAmount)this.player.openContainer; - - // Create the open context - cca.setOpenContext( new ContainerOpenContext( te ) ); - cca.getOpenContext().setWorld( te.getWorldObj() ); - cca.getOpenContext().setX( te.xCoord ); - cca.getOpenContext().setY( te.yCoord ); - cca.getOpenContext().setZ( te.zCoord ); - cca.getOpenContext().setSide( this.terminal.getSide() ); - - // Set the item - cca.getCraftingItem().putStack( result.getItemStack() ); - cca.setItemToCraft( result ); - - // Issue update - if( player instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP)player ).isChangingQuantityOnly = false; - } - cca.detectAndSendChanges(); - } - } - - /** - * Called when a client has clicked the clear grid button - */ - public void onClientRequestClearCraftingGrid( final EntityPlayer player ) - { - this.clearCraftingGrid( true ); - } - - /** - * A client player is requesting to deposit their held item - * into the ME network. - */ - public void onClientRequestDeposit( final EntityPlayer player, final int mouseButton ) - { - // Ensure there is a player & monitor - if( ( player == null ) || ( this.monitor == null ) ) - { - return; - } - - // Get what the player is holding - ItemStack playerHolding = player.inventory.getItemStack(); - - // Is the player holding anything? - if( playerHolding == null ) - { - return; - } - - // Create the AE itemstack representation of the itemstack - IAEItemStack toInjectStack = AEApi.instance().storage().createItemStack( playerHolding ); - - // Was it a right click or wheel movement? - boolean depositOne = ( mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT ) || ( mouseButton == ThEGuiHelper.MOUSE_WHEEL_MOTION ); - - if( depositOne ) - { - // Set stack size to 1 - toInjectStack.setStackSize( 1 ); - } - - // Attempt to inject - IAEItemStack leftOverStack = this.monitor.injectItems( toInjectStack, Actionable.MODULATE, this.playerSource ); - - // Was there anything left over? - if( ( leftOverStack != null ) && ( leftOverStack.getStackSize() > 0 ) ) - { - // Were we only trying to inject one? - if( toInjectStack.getStackSize() == 1 ) - { - // No changes made - return; - } - - // Set what was left over as the itemstack being held - player.inventory.setItemStack( leftOverStack.getItemStack() ); - } - else - { - // Are we only depositing one, and there was more than 1 item? - if( ( depositOne ) && ( playerHolding.stackSize > 1 ) ) - { - // Set the player holding one less - playerHolding.stackSize-- ; - player.inventory.setItemStack( playerHolding ); - - // Set the leftover stack to match - leftOverStack = AEApi.instance().storage().createItemStack( playerHolding ); - } - else - { - // Set the player as holding nothing - player.inventory.setItemStack( null ); - } - } - - // Send the update to the client - Packet_C_Sync.sendPlayerHeldItem( player, ( leftOverStack == null ? null : leftOverStack.getItemStack() ) ); - } - - /** - * A client has requested that a region(inventory) be deposited into the ME - * network. - * - * @param player - * @param slotNumber - */ - public void onClientRequestDepositRegion( final EntityPlayer player, final int slotNumber ) - { - List slotsToDeposit = null; - - // Was the slot part of the player inventory? - if( this.slotClickedWasInPlayerInventory( slotNumber ) ) - { - // Get the items in the player inventory - slotsToDeposit = this.getNonEmptySlotsFromPlayerInventory(); - } - // Was the slot part of the hotbar? - else if( this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Get the items in the hotbar - slotsToDeposit = this.getNonEmptySlotsFromHotbar(); - } - - // Do we have any slots to transfer? - if( slotsToDeposit != null ) - { - for( Slot slot : slotsToDeposit ) - { - // Ensure the slot is not null and has a stack - if( ( slot == null ) || ( !slot.getHasStack() ) ) - { - continue; - } - - // Set the stack - ItemStack slotStack = slot.getStack(); - - // Inject into the ME network - boolean didMerge = this.mergeWithMENetwork( slotStack ); - - // Did any merge? - if( !didMerge ) - { - continue; - } - - // Did the merger drain the stack? - if( ( slotStack == null ) || ( slotStack.stackSize == 0 ) ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - } - - // Update - this.detectAndSendChanges(); - } - } - - /** - * A client player is requesting to extract an item stack out - * of the ME network. - * - * @param player - * @param requestAEStack - * @param mouseButton - */ - public void onClientRequestExtract( final EntityPlayer player, final IAEItemStack requestAEStack, final int mouseButton, - final boolean isShiftHeld ) - { - // Safety checks - if( ( player == null ) || ( this.monitor == null ) || ( requestAEStack == null ) || ( requestAEStack.getStackSize() == 0 ) ) - { - return; - } - - // Where to put the items if going directly into the players inventory - Slot targetSlot = null; - - // What the player is holding - ItemStack cursorStack = null; - - // Itemstack of the request - ItemStack requestStack = requestAEStack.getItemStack(); - - // Determine the amount to extract - int amountToExtract = 0; - switch ( mouseButton ) - { - case ThEGuiHelper.MOUSE_BUTTON_LEFT: - if( isShiftHeld ) - { - // Going to players inventory directly, search for a target slot. - targetSlot = this.locateMergeSlot( requestStack ); - if( targetSlot != null ) - { - // Found target slot, calculate how much room it has and set amount to extract - int slotRoom = 0; - if( targetSlot.getHasStack() ) - { - // Non empty slot, room = MaxSize - CurrentSize - ItemStack slotStack = targetSlot.getStack(); - slotRoom = slotStack.getMaxStackSize() - slotStack.stackSize; - } - else - { - // Empty slot, room = max stack size - slotRoom = requestStack.getMaxStackSize(); - } - - // Amount = whichever is smaller, request size, or room in slot - amountToExtract = Math.min( requestStack.stackSize, slotRoom ); - } - // Else no slot to put this in, amount remains zero. - } - else - { - // Going to cursor - // Full amount up to maxStackSize - amountToExtract = Math.min( requestStack.getMaxStackSize(), requestStack.stackSize ); - } - break; - - case ThEGuiHelper.MOUSE_BUTTON_RIGHT: - // Going to cursor - // Is shift being held? - if( isShiftHeld ) - { - // Extract 1 - amountToExtract = 1; - } - else - { - // Half amount up to half of maxStackSize - double halfRequest = Math.ceil( requestStack.stackSize / 2.0D ); - double halfMax = Math.ceil( requestStack.getMaxStackSize() / 2.0D ); - amountToExtract = (int)Math.min( halfMax, halfRequest ); - } - break; - - case ThEGuiHelper.MOUSE_BUTTON_WHEEL: - // Going to cursor - if( player.capabilities.isCreativeMode ) - { - requestStack.stackSize = requestStack.getMaxStackSize(); - player.inventory.setItemStack( requestStack ); - Packet_C_Sync.sendPlayerHeldItem( player, requestStack ); - } - // Done - return; - - case ThEGuiHelper.MOUSE_WHEEL_MOTION: - // Going to cursor - // Shift must be held - if( isShiftHeld ) - { - // Extract 1 - amountToExtract = 1; - } - } - - // If the output is the players cursor, ensure there is room, and the stacks match - if( ( targetSlot == null ) && ( amountToExtract > 0 ) ) - { - // Get what the player is holding - cursorStack = player.inventory.getItemStack(); - - // Holding anything? - if( cursorStack != null ) - { - // Items are the same? - if( !cursorStack.isItemEqual( requestStack ) || !ItemStack.areItemStackTagsEqual(cursorStack, requestStack) ) - { - // Item player is holding doesn't match the request - return; - } - // Ensure there is room - int cursorRoom = ( cursorStack.getMaxStackSize() - cursorStack.stackSize ); - amountToExtract = Math.min( cursorRoom, amountToExtract ); - } - } - - // Anything to extract? - if( amountToExtract <= 0 ) - { - // Nothing to extract - return; - } - - // Create the stack to extract - IAEItemStack toExtract = requestAEStack.copy(); - - // Set the size - toExtract.setStackSize( amountToExtract ); - - // Extract - IAEItemStack extractedStack = this.monitor.extractItems( toExtract, Actionable.MODULATE, this.playerSource ); - - // Was anything extracted? - if( ( extractedStack != null ) && ( extractedStack.getStackSize() > 0 ) ) - { - // Going to inventory? - if( targetSlot != null ) - { - if( targetSlot.getHasStack() ) - { - // Add to existing stack - targetSlot.getStack().stackSize += (int)extractedStack.getStackSize(); - } - else - { - // Set stack - targetSlot.putStack( extractedStack.getItemStack() ); - } - } - else - { - // Going to cursor - if( cursorStack != null ) - { - // Add to existing stack - cursorStack.stackSize += (int)extractedStack.getStackSize(); - } - else - { - // Set stack - this.player.inventory.setItemStack( extractedStack.getItemStack() ); - } - - // Send the update to the client - Packet_C_Sync.sendPlayerHeldItem( this.player, this.player.inventory.getItemStack() ); - - } - - } - - } - - /** - * A client has requested the full list of all items in the ME network. - * - * @param player - */ - public void onClientRequestFullUpdate( final EntityPlayer player ) - { - // Ensure we have a monitor & the terminal is active - if( ( this.monitor != null ) && ( this.terminal.isActive() ) ) - { - // Get the full list - IItemList fullList = this.monitor.getStorageList(); - - // Send to the client - Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems( player, fullList ); - } - else - { - // Send empty list - Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems( player, AEApi.instance().storage().createItemList() ); - } - } - - /** - * A client has request that the stored sorting order be changed. - * - * @param order - * @param dir - */ - public void onClientRequestSetSort( final SortOrder order, final SortDir dir, final ViewItems viewMode ) - { - // Inform the terminal - this.terminal.setSorts( order, dir, viewMode ); - } - - /** - * Called when a client has requested they swap their equipped armor with - * the stored armor. - * - * @param player - */ - public void onClientRequestSwapArmor( final EntityPlayer player ) - { - this.terminal.swapStoredArmor( player ); - this.detectAndSendChanges(); - Packet_C_ArcaneCraftingTerminal.updateAspectCost( player ); - } - - /** - * Unregister this container - */ - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - // Pass to super - super.onContainerClosed( player ); - - if( this.terminal != null ) - { - this.terminal.removeListener( this ); - } - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } - } - - /** - * Called when crafting inputs are changed. - */ - @Override - public void onCraftMatrixChanged( final IInventory inventory ) - { - // Reset crafting aspects - this.requiredAspects = null; - this.craftingCost.clear(); - - // Ensure wand - this.getWand(); - - // Get the matching regular crafting recipe. - ItemStack craftResult = this.findMatchingRegularResult(); - - // Was there not a regular match? - if( ( craftResult == null ) ) - { - // Get the matching arcane crafting recipe. - craftResult = this.findMatchingArcaneResult(); - } - - // Set the result slot aspects and wand - this.resultSlot.setResultAspects( this.requiredAspects ); - this.resultSlot.setWand( this.wand ); - - // Set the result - this.terminal.setInventorySlotContentsWithoutNotify( PartArcaneCraftingTerminal.RESULT_SLOT_INDEX, craftResult ); - - } - - /** - * AE API: called when the list updates its contents, this is mostly for - * handling power events. - */ - @Override - public void onListUpdate() - { - // Is the terminal no longer active? - if( !this.terminal.isActive() ) - { - // Send empty list to client - Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems( this.player, AEApi.instance().storage().createItemList() ); - } - } - - /** - * The view cells have been changed, inform the gui. - */ - public void onViewCellChange() - { - // Only client side - if( EffectiveSide.isClientSide() ) - { - // Update the gui - this.updateGUIViewCells(); - } - } - - /** - * Called when the amount of an item on the network changes. - */ - @Override - public void postChange( final IBaseMonitor monitor, final Iterable changes, final BaseActionSource actionSource ) - { - if( this.monitor == null ) - { - return; - } - - for( IAEItemStack change : changes ) - { - // Get the total amount of the item in the network - IAEItemStack newAmount = this.monitor.getStorageList().findPrecise( change ); - - // Is there no more? - if( newAmount == null ) - { - // Copy the item type from the change - newAmount = change.copy(); - - // Set amount to 0 - newAmount.setStackSize( 0 ); - } - - // Send the change to the client - Packet_C_ArcaneCraftingTerminal.stackAmountChanged( this.player, newAmount ); - } - } - - /** - * Registers the container for updates from the terminal part. - */ - public void registerForUpdates() - { - // Register the container with terminal - this.terminal.registerListener( this ); - } - - /** - * Attempts to extract an item from the network. - * Used when crafting to replenish the crafting grid. - * - * @param itemStack - * @return - */ - public ItemStack requestCraftingReplenishment( final ItemStack itemStack ) - { - if( this.monitor == null ) - { - return null; - } - - // Search the players inventory - ItemStack replenishmentPlayer = this.takeItemFromPlayer( itemStack, 1 ); - if( replenishmentPlayer != null ) - { - return replenishmentPlayer; - } - - // Create the AE request stack - IAEItemStack requestStack = AEApi.instance().storage().createItemStack( itemStack ); - - // Set the request amount to one - requestStack.setStackSize( 1 ); - - // Attempt an extraction - IAEItemStack replenishmentAE = this.monitor.extractItems( requestStack, Actionable.MODULATE, this.playerSource ); - - // Did we get a replenishment? - if( replenishmentAE != null ) - { - return replenishmentAE.getItemStack(); - } - - // Did not get a replenishment, search for items that match. - - // Get a list of all items in the ME network - IItemList networkItems = this.monitor.getStorageList(); - - // Search all items - for( IAEItemStack potentialMatch : networkItems ) - { - // Does the request match? - if( this.doStacksMatch( requestStack, potentialMatch ) ) - { - // Found a match - requestStack = potentialMatch.copy(); - - // Set the request amount to one - requestStack.setStackSize( 1 ); - - // Attempt an extraction - replenishmentAE = this.monitor.extractItems( requestStack, Actionable.MODULATE, this.playerSource ); - - // Did we get a replenishment? - if( ( replenishmentAE != null ) && ( replenishmentAE.getStackSize() > 0 ) ) - { - return replenishmentAE.getItemStack(); - } - } - - } - - // No matches at all :( - return null; - } - - /** - * Called when the player shift+clicks on a slot - */ - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Is this client side? - if( EffectiveSide.isClientSide() ) - { - // Do nothing. - return null; - } - - // Get the slot that was shift-clicked - Slot slot = this.getSlotOrNull( slotNumber ); - - // Is there a valid slot with and item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - boolean didMerge = false; - - // Get the itemstack in the slot - ItemStack slotStack = slot.getStack(); - - // Was the slot clicked in the crafting grid? - if( this.slotClickedWasInCraftingInventory( slotNumber ) ) - { - // Attempt to merge with the ME network - didMerge = this.mergeWithMENetwork( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the hotbar - didMerge = this.mergeSlotWithHotbarInventory( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } - } - // Was the slot clicked in the player or hotbar inventory? - else if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - - // Is the item a valid wand? - if( this.wandSlot.isItemValid( slotStack ) ) - { - // Attempt to merge with the wand - didMerge = this.mergeItemStack( slotStack, this.wandSlot.slotNumber, this.wandSlot.slotNumber + 1, false ); - } - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with view cells - didMerge = this.mergeWithViewCells( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the ME network - didMerge = this.mergeWithMENetwork( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the crafting grid - didMerge = this.mergeItemStack( slotStack, this.firstCraftingSlotNumber, this.lastCraftingSlotNumber + 1, false ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to swap hotbar<->player inventory - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - } - } - } - } - // Was the slot clicked the crafting result? - else if( slot == this.resultSlot ) - { - // Start the autocrafting loop - this.doShiftAutoCrafting( player ); - - return null; - } - // Wand? - else if( slot == this.wandSlot ) - { - // Attempt to merge with the hotbar - didMerge = this.mergeSlotWithHotbarInventory( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the ME network - didMerge = this.mergeWithMENetwork( slotStack ); - } - } - } - // Was the slot clicked a view cell? - else if( ( slotNumber >= this.firstViewSlotNumber ) && ( slotNumber <= this.lastViewSlotNumber ) ) - { - // Attempt to merge with the hotbar - didMerge = this.mergeSlotWithHotbarInventory( slotStack ); - - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } - - // Did we merge? - if( didMerge ) - { - - // Did the merger drain the stack? - if( ( slotStack == null ) || ( slotStack.stackSize == 0 ) ) - { - // Set the slot to have no item - slot.putStack( null ); - } - else - { - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - - // Send changes - this.detectAndSendChanges(); - } - - } - - // All taken care of! - return null; - } - public IGrid getHostGrid() - { - try - { - return this.terminal.getGridBlock().getGrid(); - } - catch( Exception e ) - { - return null; - } - } +public class ContainerPartArcaneCraftingTerminal extends ContainerWithPlayerInventory + implements IMEMonitorHandlerReceiver, ICraftingIssuerContainer { + /** + * Holds a single aspect cost for the current recipe. + * + * @author Nividica + * + */ + public class ArcaneCrafingCost { + /** + * How much vis does the recipe require? + */ + public final float visCost; + + /** + * Which aspect? + */ + public final Aspect primal; + + /** + * Do we have enough of this aspect in the wand to perform the craft? + */ + public final boolean hasEnoughVis; + + public ArcaneCrafingCost(final float visCost, final Aspect primal, final boolean hasEnough) { + // Round to 1 decimal place + this.visCost = Math.round(visCost * 10.0F) / 10.0F; + + this.primal = primal; + + this.hasEnoughVis = hasEnough; + } + } + + /** + * Y position for the player and hotbar inventory. + */ + private static int PLAYER_INV_POSITION_Y = 162, HOTBAR_INV_POSITION_Y = 220; + + /** + * Row and Column counts of the crafting grid. + */ + private static int CRAFTING_GRID_SIZE = 3; + + /** + * Total number of slots in the crafting grid + */ + public static int CRAFTING_GRID_TOTAL_SIZE = ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE + * ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; + + /** + * Starting position for crafting slots. + */ + public static int CRAFTING_SLOT_X_POS = 44, CRAFTING_SLOT_Y_POS = 90; + + /** + * Position of the output slot. + */ + private static int RESULT_SLOT_X_POS = 116, RESULT_SLOT_Y_POS = 126; + + /** + * Position of the wand slot. + */ + private static int WAND_SLOT_XPOS = 116, WAND_SLOT_YPOS = 90; + + /** + * Starting position of the view slots + */ + public static int VIEW_SLOT_XPOS = 206, VIEW_SLOT_YPOS = 8; + + /** + * Starting position for armor slots. + */ + public static int ARMOR_SLOT_X_POS = 8, ARMOR_SLOT_Y_POS = 81, ARMOR_SLOT_COUNT = 4; + + /** + * Cache the crafting manager instance + */ + private static CraftingManager CRAFT_MANAGER = CraftingManager.getInstance(); + + /** + * The arcane crafting terminal associated with the container. + */ + public final PartArcaneCraftingTerminal terminal; + + /** + * Network source representing the player who is interacting with the + * container. + */ + private final PlayerSource playerSource; + + /** + * The AE network item monitor we are attached to. + */ + private IMEMonitor monitor; + + /** + * Slot number of the first and last crafting slots. + */ + private int firstCraftingSlotNumber = -1, lastCraftingSlotNumber = -1; + + /** + * Slot number of the first and last view slots. + */ + private int firstViewSlotNumber = -1, lastViewSlotNumber = -1; + + /** + * Slot number of the wand. + */ + private final SlotRestrictive wandSlot; + + /** + * Slot number of the result. + */ + private final SlotArcaneCraftingResult resultSlot; + + /** + * The wand currently in the wand slot. + */ + private ItemStack wand; + + /** + * The required aspects for the current recipe. + */ + private AspectList requiredAspects; + + /** + * The required aspects, costs, and missing for the current recipe. + */ + private List craftingCost = new ArrayList(); + + /** + * Cached sorting order. + */ + private SortOrder cachedSortOrder = PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER; + + /** + * Cached sorting direction. + */ + private SortDir cachedSortDirection = PartArcaneCraftingTerminal.DEFAULT_SORT_DIR; + + /** + * Cached view mode. + */ + private ViewItems cachedViewMode = PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE; + + /** + * Creates the container + * + * @param terminal + * @param player + */ + public ContainerPartArcaneCraftingTerminal(final PartArcaneCraftingTerminal terminal, final EntityPlayer player) { + // Call super + super(player); + + // Set the part + this.terminal = terminal; + + // Set the player source + this.playerSource = new PlayerSource(this.player, terminal); + + // Bind to the players inventory + this.bindPlayerInventory( + player.inventory, + ContainerPartArcaneCraftingTerminal.PLAYER_INV_POSITION_Y, + ContainerPartArcaneCraftingTerminal.HOTBAR_INV_POSITION_Y); + + // Add crafting slots + Slot craftingSlot = null; + for (int row = 0; row < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; row++) { + for (int column = 0; column < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE; column++) { + // Calculate the index + int slotIndex = (row * ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE) + column; + + // Create the slot + craftingSlot = new Slot( + terminal, + slotIndex, + ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_X_POS + + (column * ContainerWithPlayerInventory.SLOT_SIZE), + ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_Y_POS + + (row * ContainerWithPlayerInventory.SLOT_SIZE)); + + // Add the slot + this.addSlotToContainer(craftingSlot); + + // Check first crafting slot number + if ((row + column) == 0) { + this.firstCraftingSlotNumber = craftingSlot.slotNumber; + } + } + } + + // Set last crafting slot number + if (craftingSlot != null) { + this.lastCraftingSlotNumber = craftingSlot.slotNumber; + } + + // Create the result slot + this.resultSlot = new SlotArcaneCraftingResult( + player, + this, + terminal, + terminal, + PartArcaneCraftingTerminal.RESULT_SLOT_INDEX, + ContainerPartArcaneCraftingTerminal.RESULT_SLOT_X_POS, + ContainerPartArcaneCraftingTerminal.RESULT_SLOT_Y_POS); + + // Add the result slot + this.addSlotToContainer(this.resultSlot); + + // Create the wand slot + this.wandSlot = new SlotRestrictive( + terminal, + PartArcaneCraftingTerminal.WAND_SLOT_INDEX, + ContainerPartArcaneCraftingTerminal.WAND_SLOT_XPOS, + ContainerPartArcaneCraftingTerminal.WAND_SLOT_YPOS); + + // Add the wand slot + this.addSlotToContainer(this.wandSlot); + + // Create the view slots + SlotRestrictive viewSlot = null; + for (int viewSlotID = PartArcaneCraftingTerminal.VIEW_SLOT_MIN; + viewSlotID <= PartArcaneCraftingTerminal.VIEW_SLOT_MAX; + viewSlotID++) { + // Calculate the y position + int row = viewSlotID - PartArcaneCraftingTerminal.VIEW_SLOT_MIN; + int yPos = + ContainerPartArcaneCraftingTerminal.VIEW_SLOT_YPOS + (row * ContainerWithPlayerInventory.SLOT_SIZE); + + // Create the slot + viewSlot = + new SlotRestrictive(terminal, viewSlotID, ContainerPartArcaneCraftingTerminal.VIEW_SLOT_XPOS, yPos); + + // Add the slot + this.addSlotToContainer(viewSlot); + + // Check first view slot + if (row == 0) { + this.firstViewSlotNumber = viewSlot.slotNumber; + } + } + + // Set last view slot number + if (viewSlot != null) { + this.lastViewSlotNumber = viewSlot.slotNumber; + } + + // Create the armor slots + for (int armorIndex = 0; armorIndex < ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_COUNT; ++armorIndex) { + // Calculate y position + int yPos = ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_Y_POS + + (ContainerWithPlayerInventory.SLOT_SIZE * armorIndex); + + // Create the slot + SlotArmor armorSlot = new SlotArmor( + terminal, + PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorIndex, + ContainerPartArcaneCraftingTerminal.ARMOR_SLOT_X_POS, + yPos, + armorIndex, + false); + + // Add to container + this.addSlotToContainer(armorSlot); + + /** + * Notes about the hidden slots + * I hate this, but I have tried everything I can think of, and the + * equipped armor will not change immediately unless + * the notification comes from the open container, this container. + */ + // Create the 'hidden'slot + armorSlot = new SlotArmor(player.inventory, 36 + (3 - armorIndex), 0, -1000, armorIndex, false); + + // Add to container + this.addSlotToContainer(armorSlot); + } + + if (EffectiveSide.isServerSide()) { + // Register with terminal + this.registerForUpdates(); + } + + // Attach to the monitor + this.attachToMonitor(); + } + + /** + * Attempts to attach to the item monitor. + * + * @return + */ + private boolean attachToMonitor() { + // Is this server side? + if (EffectiveSide.isClientSide()) { + return false; + } + + // Clear any existing + if (this.monitor != null) { + this.monitor.removeListener(this); + } + + // Get the grid + IGrid grid = this.terminal.getGridBlock().getGrid(); + if (grid != null) { + // Get the AE monitor + this.monitor = this.terminal.getItemInventory(); + if (this.monitor != null) { + // Register with the monitor. + this.monitor.addListener(this, grid.hashCode()); + return true; + } + } + + return false; + } + + /** + * Attempts to clear the crafting grid by placing the items + * back in the ME network. + * + * @param sendUpdate + * If true, any changes made are sent across the network + * @return + */ + private boolean clearCraftingGrid(final boolean sendUpdate) { + // Ignored client side + if (EffectiveSide.isClientSide()) { + return false; + } + + // Assume the grid is clear + boolean clearedAll = true; + + for (int index = this.firstCraftingSlotNumber; index <= this.lastCraftingSlotNumber; index++) { + // Get the slot + Slot slot = (Slot) this.inventorySlots.get(index); + + // Ensure the slot is not null and has a stack + if ((slot == null) || (!slot.getHasStack())) { + continue; + } + + // Set the stack + ItemStack slotStack = slot.getStack(); + + // Inject into the ME network + boolean didMerge = this.mergeWithMENetwork(slotStack); + + // Did any merge? + if (!didMerge) { + // Items are left over in the grid + clearedAll = false; + continue; + } + + // Did the merger drain the stack? + if ((slotStack == null) || (slotStack.stackSize == 0)) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Items are left over in the grid + clearedAll = false; + + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + } + + // Update + this.detectAndSendChanges(); + + // Return if we cleared the whole grid or not + return clearedAll; + } + + /** + * Handles automatically crafting items when the crafting + * output slot is shift+clicked + * + * @param player + */ + private void doShiftAutoCrafting(final EntityPlayer player) { + // Tracks if a crafting result could be placed in the players inventory + boolean didMerge; + + // Tracks how many items we have made + int autoCraftCounter = 0; + + // Get the current crafting result. + ItemStack resultStack = this.resultSlot.getStack(); + + // Make a copy of it + ItemStack slotStackOriginal = resultStack.copy(); + + for (autoCraftCounter = slotStackOriginal.stackSize; + autoCraftCounter <= 64; + autoCraftCounter += slotStackOriginal.stackSize) { + // Attempt to merge with the player inventory + didMerge = + (this.mergeSlotWithPlayerInventory(resultStack) || this.mergeSlotWithHotbarInventory(resultStack)); + + // Were we able to merge? + if (didMerge) { + // Let the result slot know it was picked up + this.resultSlot.onPickupFromSlotViaTransfer(player, resultStack); + + // Update the matrix + this.onCraftMatrixChanged(null); + + // Get the stack in the result slot now. + resultStack = this.resultSlot.getStack(); + + // Is it empty? + if ((resultStack == null) || (resultStack.stackSize == 0)) { + // Can't craft anymore, break the loop + break; + } + // Does it still match the output item? + if (!resultStack.getItem().equals(slotStackOriginal.getItem())) { + // Crafting result changed, break the loop + break; + } + } else { + // Unable to merge results, break the loop + break; + } + } + + // Did we do any crafting? + if (autoCraftCounter > 0) { + // Mark the result slot as dirty + this.resultSlot.onSlotChanged(); + + // Send changes + this.detectAndSendChanges(); + } + } + + /** + * Checks if two stacks match. Either directly, or by ore dictionary. + * + * @param keyStack + * @param potentialMatch + * @return + */ + private boolean doStacksMatch(final IAEItemStack keyStack, final IAEItemStack potentialMatch) { + return keyStack.isSameType(potentialMatch) || keyStack.sameOre(potentialMatch); + } + + /** + * Searches for a matching arcane crafting recipe result + * + * @return ItemStack of the result if found, null otherwise. + */ + private ItemStack findMatchingArcaneResult() { + ItemStack arcaneResult = null; + + // Is there a matching recipe? + IArcaneRecipe matchingRecipe = ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult( + this.terminal, 0, ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, this.player); + + if (matchingRecipe != null) { + // Found a match, validate it. + arcaneResult = this.validateWandVisAmount(matchingRecipe); + } + + // Return the result + return arcaneResult; + } + + /** + * Searches for a matching regular(non arcane) crafting recipe result + * + * @return ItemStack of the result if found, null otherwise. + */ + private ItemStack findMatchingRegularResult() { + // Create a new crafting inventory + InventoryCrafting craftingInventory = new InventoryCrafting( + new ContainerInternalCrafting(), + ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE, + ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_SIZE); + + // Load the inventory based on what is in the part's inventory + for (int slotIndex = 0; + slotIndex < (ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE); + slotIndex++) { + // Set the slot + craftingInventory.setInventorySlotContents(slotIndex, this.terminal.getStackInSlot(slotIndex)); + } + + // Return the result + return ContainerPartArcaneCraftingTerminal.CRAFT_MANAGER.findMatchingRecipe( + craftingInventory, this.terminal.getWorldObj()); + } + + /** + * Gets the view cells in the terminal. + * + * @return + */ + public ItemStack[] getViewCells() { + List viewCells = new ArrayList(); + + Slot viewSlot; + for (int viewSlotIndex = this.firstViewSlotNumber; viewSlotIndex <= this.lastViewSlotNumber; viewSlotIndex++) { + // Get the slot + viewSlot = this.getSlotOrNull(viewSlotIndex); + + // Ensure the slot is not empty + if ((viewSlot == null) || !viewSlot.getHasStack()) { + continue; + } + + // Add the cell + viewCells.add(viewSlot.getStack()); + } + + return viewCells.toArray(new ItemStack[viewCells.size()]); + } + + /** + * Sets 'wand' if there is a wand in the wand slot. + */ + private void getWand() { + // Is this the same wand that we have cached? + if (this.wand == this.wandSlot.getStack()) { + // Nothing has changed + return; + } + + // Is the item a valid crafting wand? + if (ThEUtils.isItemValidWand(this.wandSlot.getStack(), false)) { + // Set the wand + this.wand = this.wandSlot.getStack(); + + return; + } + + // Set the wand to null + this.wand = null; + } + + /** + * Attempts to inject an itemstack into the ME network. + * Adjusts the stack size of the specified itemstack according to + * the results of the merger. + * + * @param itemStack + * @return True if any amount was merged, False otherwise. + */ + private boolean mergeWithMENetwork(final ItemStack itemStack) { + // Attempt to place in the ME system + IAEItemStack toInject = AEApi.instance().storage().createItemStack(itemStack); + + // Get what is left over after the injection + IAEItemStack leftOver = this.monitor.injectItems(toInject, Actionable.MODULATE, this.playerSource); + + // Do we have any left over? + if ((leftOver != null) && (leftOver.getStackSize() > 0)) { + // Did we inject any? + if (leftOver.getStackSize() == toInject.getStackSize()) { + // No injection occurred + return false; + } + + // Some was injected, adjust the slot stack size + itemStack.stackSize = (int) leftOver.getStackSize(); + + return true; + } + + // All was injected + itemStack.stackSize = 0; + + return true; + } + + /** + * Attempts to add the itemstack to the view cell slots + * + * @param itemStack + * @return True if was moved, False otherwise. + */ + private boolean mergeWithViewCells(final ItemStack itemStack) { + // Ensure the item a view cell + if (!this.terminal.isItemValidForSlot(PartArcaneCraftingTerminal.VIEW_SLOT_MIN, itemStack)) { + return false; + } + + Slot viewSlot; + for (int viewSlotIndex = this.firstViewSlotNumber; viewSlotIndex <= this.lastViewSlotNumber; viewSlotIndex++) { + // Get the slot + viewSlot = this.getSlotOrNull(viewSlotIndex); + + // Is there a slot? + if (viewSlot == null) { + // Somehow, there is a null slot + continue; + } + + // Ensure the slot is empty + if (viewSlot.getHasStack()) { + continue; + } + + // Insert the view cell + viewSlot.putStack(itemStack.copy()); + + // Clear the source stack + itemStack.stackSize = 0; + + // Merge/move complete + return true; + } + + // Unable to move + return false; + } + + /** + * Informs the GUI that the view cells have changed + */ + @SideOnly(Side.CLIENT) + private void updateGUIViewCells() { + // Get the current screen being displayed to the user + Gui gui = Minecraft.getMinecraft().currentScreen; + + // Is that screen the gui for the ACT? + if (gui instanceof GuiArcaneCraftingTerminal) { + ((GuiArcaneCraftingTerminal) gui).onViewCellsChanged(this.getViewCells()); + } + } + + /** + * Checks if the wand has enough vis to complete the craft. + * Takes into consideration the players multiplier. + * + * @param forRecipe + * @return ItemStack of the result if wand has enough vis, null otherwise. + */ + private ItemStack validateWandVisAmount(final IArcaneRecipe forRecipe) { + boolean hasAll = true; + AspectList wandAspectList = null; + ItemWandCasting wandItem = null; + + // Get the cost + this.requiredAspects = ArcaneRecipeHelper.INSTANCE.getRecipeAspectCost( + this.terminal, 0, ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, forRecipe); + + // Ensure there is a cost + if (this.requiredAspects == null) { + return null; + } + + // Cache the recipes aspects + Aspect[] recipeAspects = this.requiredAspects.getAspects(); + + // Do we have a wand? + if (this.wand != null) { + // Get the wand item + wandItem = ((ItemWandCasting) this.wand.getItem()); + + // Cache the wand's aspect list + wandAspectList = wandItem.getAllVis(this.wand); + } + + // Check the wand amounts vs recipe aspects + for (Aspect currentAspect : recipeAspects) { + // Get the base required vis + int baseVis = this.requiredAspects.getAmount(currentAspect); + + // Get the adjusted amount + int requiredVis = baseVis * 100; + + // Assume we do not have enough + boolean hasEnough = false; + + // Do we have a wand? + if ((wandItem != null) && (wandAspectList != null)) { + // Adjust the required amount by the wand modifier + requiredVis = (int) + (requiredVis * wandItem.getConsumptionModifier(this.wand, this.player, currentAspect, true)); + + // Does the wand not have enough of vis of this aspect? + hasEnough = (wandAspectList.getAmount(currentAspect) >= requiredVis); + } + + if (!hasEnough) { + // Mark that we do not have enough vis to complete crafting + hasAll = false; + } + + // Add to the cost list + this.craftingCost.add(new ArcaneCrafingCost(requiredVis / 100.0F, currentAspect, hasEnough)); + } + + // Did we have all the vis required? + if (hasAll) { + // Get the result of the recipe. + return ArcaneRecipeHelper.INSTANCE.getRecipeOutput( + this.terminal, 0, ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE, forRecipe); + } + + return null; + } + + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + boolean sendModeUpdate = false; + + // Has the sorting order changed? + if (this.cachedSortOrder != this.terminal.getSortingOrder()) { + // Update + this.cachedSortOrder = this.terminal.getSortingOrder(); + sendModeUpdate = true; + } + + // Has the sorting direction changed? + if (this.cachedSortDirection != this.terminal.getSortingDirection()) { + // Update + this.cachedSortDirection = this.terminal.getSortingDirection(); + sendModeUpdate = true; + } + + // Has the view mode changed? + if (this.cachedViewMode != this.terminal.getViewMode()) { + // Update + this.cachedViewMode = this.terminal.getViewMode(); + sendModeUpdate = true; + } + + // Send update? + if (sendModeUpdate) { + // Send the mode info + Packet_C_ArcaneCraftingTerminal.sendModeChange( + this.player, this.cachedSortOrder, this.cachedSortDirection, this.cachedViewMode); + } + + // Is the monitor null? + if (this.monitor == null) { + // Attempt to re-attach + if (this.attachToMonitor()) { + // Update the client + this.onClientRequestFullUpdate(this.player); + } + } + + return false; + } + + /** + * Checks if the slot number belongs to the crafting matrix + * + * @param slotNumber + * @return + */ + protected boolean slotClickedWasInCraftingInventory(final int slotNumber) { + return (slotNumber >= this.firstCraftingSlotNumber) && (slotNumber <= this.lastCraftingSlotNumber); + } + + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.terminal != null) { + return this.terminal.isUseableByPlayer(player); + } + return false; + } + + /** + * Changes the Y offset for all slots, except the view slots, in this + * container. + * + * @param deltaY + */ + public void changeSlotsYOffset(final int deltaY) { + for (Object slotObj : this.inventorySlots) { + // Get the slot + Slot slot = (Slot) slotObj; + + // Skip view slots + if ((slot.slotNumber >= this.firstViewSlotNumber) && (slot.slotNumber <= this.lastViewSlotNumber)) { + continue; + } + + // Adjust Y pos + slot.yDisplayPosition += deltaY; + } + } + + /** + * Gets the aspect cost and how much is missing for the current recipe. + * + * @return Null if not an arcane recipe, cost otherwise. + */ + public List getCraftingCost(final boolean forceUpdate) { + if (forceUpdate) { + this.craftingCost.clear(); + this.findMatchingArcaneResult(); + } + + // Does this recipe have costs? + if (this.craftingCost.isEmpty()) { + return Collections.emptyList(); + } + + // Return required and missing + return this.craftingCost; + } + + @Override + public ICraftingIssuerHost getCraftingHost() { + return this.terminal; + } + + /** + * Called by the monitor to ensure we still want updates + */ + @Override + public boolean isValid(final Object authToken) { + if (this.monitor == null) { + return false; + } + + // Get the grid + IGrid grid = this.terminal.getGridBlock().getGrid(); + if (grid != null) { + if (grid.hashCode() == (Integer) authToken) { + return true; + } + } + + // Monitor no longer valid + this.monitor = null; + + // Update client + this.onClientRequestFullUpdate(this.player); + + return false; + } + + /** + * Called when a client is setting up the crafting grid via NEI + * + * @param player + * @param gridItems + */ + public void onClientNEIRequestSetCraftingGrid(final EntityPlayer player, final IAEItemStack[] gridItems) { + // Attempt to clear the crafting grid + if (this.clearCraftingGrid(false)) { + for (int craftingSlotIndex = 0; craftingSlotIndex < 9; craftingSlotIndex++) { + // Get the stack + IAEItemStack slotStack = gridItems[craftingSlotIndex]; + + // Ensure the slot was not null + if (slotStack == null) { + // Skip null items + continue; + } + + // Find a matching stack. + ItemStack matchingStack = this.requestCraftingReplenishment(slotStack.getItemStack()); + + // Ensure a stack was found + if (matchingStack != null) { + // Get the slot + Slot slot = (Slot) this.inventorySlots.get(this.firstCraftingSlotNumber + craftingSlotIndex); + + // Set the slot contents + slot.putStack(matchingStack); + } + } + + // Update clients + this.detectAndSendChanges(); + } + } + + /** + * Called when a client has clicked on a craftable item. + * + * @param player + * @param result + */ + public void onClientRequestAutoCraft(final EntityPlayer player, final IAEItemStack result) { + // Get the host tile + TileEntity te = this.terminal.getHostTile(); + + // Launch the GUI + ThEGuiHandler.launchGui( + ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + + // Setup the amount container + if (player.openContainer instanceof ContainerCraftAmount) { + // Get the container + ContainerCraftAmount cca = (ContainerCraftAmount) this.player.openContainer; + + // Create the open context + cca.setOpenContext(new ContainerOpenContext(te)); + cca.getOpenContext().setWorld(te.getWorldObj()); + cca.getOpenContext().setX(te.xCoord); + cca.getOpenContext().setY(te.yCoord); + cca.getOpenContext().setZ(te.zCoord); + cca.getOpenContext().setSide(this.terminal.getSide()); + + // Set the item + cca.getCraftingItem().putStack(result.getItemStack()); + cca.setItemToCraft(result); + + // Issue update + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).isChangingQuantityOnly = false; + } + cca.detectAndSendChanges(); + } + } + + /** + * Called when a client has clicked the clear grid button + */ + public void onClientRequestClearCraftingGrid(final EntityPlayer player) { + this.clearCraftingGrid(true); + } + + /** + * A client player is requesting to deposit their held item + * into the ME network. + */ + public void onClientRequestDeposit(final EntityPlayer player, final int mouseButton) { + // Ensure there is a player & monitor + if ((player == null) || (this.monitor == null)) { + return; + } + + // Get what the player is holding + ItemStack playerHolding = player.inventory.getItemStack(); + + // Is the player holding anything? + if (playerHolding == null) { + return; + } + + // Create the AE itemstack representation of the itemstack + IAEItemStack toInjectStack = AEApi.instance().storage().createItemStack(playerHolding); + + // Was it a right click or wheel movement? + boolean depositOne = + (mouseButton == ThEGuiHelper.MOUSE_BUTTON_RIGHT) || (mouseButton == ThEGuiHelper.MOUSE_WHEEL_MOTION); + + if (depositOne) { + // Set stack size to 1 + toInjectStack.setStackSize(1); + } + + // Attempt to inject + IAEItemStack leftOverStack = this.monitor.injectItems(toInjectStack, Actionable.MODULATE, this.playerSource); + + // Was there anything left over? + if ((leftOverStack != null) && (leftOverStack.getStackSize() > 0)) { + // Were we only trying to inject one? + if (toInjectStack.getStackSize() == 1) { + // No changes made + return; + } + + // Set what was left over as the itemstack being held + player.inventory.setItemStack(leftOverStack.getItemStack()); + } else { + // Are we only depositing one, and there was more than 1 item? + if ((depositOne) && (playerHolding.stackSize > 1)) { + // Set the player holding one less + playerHolding.stackSize--; + player.inventory.setItemStack(playerHolding); + + // Set the leftover stack to match + leftOverStack = AEApi.instance().storage().createItemStack(playerHolding); + } else { + // Set the player as holding nothing + player.inventory.setItemStack(null); + } + } + + // Send the update to the client + Packet_C_Sync.sendPlayerHeldItem(player, (leftOverStack == null ? null : leftOverStack.getItemStack())); + } + + /** + * A client has requested that a region(inventory) be deposited into the ME + * network. + * + * @param player + * @param slotNumber + */ + public void onClientRequestDepositRegion(final EntityPlayer player, final int slotNumber) { + List slotsToDeposit = null; + + // Was the slot part of the player inventory? + if (this.slotClickedWasInPlayerInventory(slotNumber)) { + // Get the items in the player inventory + slotsToDeposit = this.getNonEmptySlotsFromPlayerInventory(); + } + // Was the slot part of the hotbar? + else if (this.slotClickedWasInHotbarInventory(slotNumber)) { + // Get the items in the hotbar + slotsToDeposit = this.getNonEmptySlotsFromHotbar(); + } + + // Do we have any slots to transfer? + if (slotsToDeposit != null) { + for (Slot slot : slotsToDeposit) { + // Ensure the slot is not null and has a stack + if ((slot == null) || (!slot.getHasStack())) { + continue; + } + + // Set the stack + ItemStack slotStack = slot.getStack(); + + // Inject into the ME network + boolean didMerge = this.mergeWithMENetwork(slotStack); + + // Did any merge? + if (!didMerge) { + continue; + } + + // Did the merger drain the stack? + if ((slotStack == null) || (slotStack.stackSize == 0)) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + } + + // Update + this.detectAndSendChanges(); + } + } + + /** + * A client player is requesting to extract an item stack out + * of the ME network. + * + * @param player + * @param requestAEStack + * @param mouseButton + */ + public void onClientRequestExtract( + final EntityPlayer player, + final IAEItemStack requestAEStack, + final int mouseButton, + final boolean isShiftHeld) { + // Safety checks + if ((player == null) + || (this.monitor == null) + || (requestAEStack == null) + || (requestAEStack.getStackSize() == 0)) { + return; + } + + // Where to put the items if going directly into the players inventory + Slot targetSlot = null; + + // What the player is holding + ItemStack cursorStack = null; + + // Itemstack of the request + ItemStack requestStack = requestAEStack.getItemStack(); + + // Determine the amount to extract + int amountToExtract = 0; + switch (mouseButton) { + case ThEGuiHelper.MOUSE_BUTTON_LEFT: + if (isShiftHeld) { + // Going to players inventory directly, search for a target slot. + targetSlot = this.locateMergeSlot(requestStack); + if (targetSlot != null) { + // Found target slot, calculate how much room it has and set amount to extract + int slotRoom = 0; + if (targetSlot.getHasStack()) { + // Non empty slot, room = MaxSize - CurrentSize + ItemStack slotStack = targetSlot.getStack(); + slotRoom = slotStack.getMaxStackSize() - slotStack.stackSize; + } else { + // Empty slot, room = max stack size + slotRoom = requestStack.getMaxStackSize(); + } + + // Amount = whichever is smaller, request size, or room in slot + amountToExtract = Math.min(requestStack.stackSize, slotRoom); + } + // Else no slot to put this in, amount remains zero. + } else { + // Going to cursor + // Full amount up to maxStackSize + amountToExtract = Math.min(requestStack.getMaxStackSize(), requestStack.stackSize); + } + break; + + case ThEGuiHelper.MOUSE_BUTTON_RIGHT: + // Going to cursor + // Is shift being held? + if (isShiftHeld) { + // Extract 1 + amountToExtract = 1; + } else { + // Half amount up to half of maxStackSize + double halfRequest = Math.ceil(requestStack.stackSize / 2.0D); + double halfMax = Math.ceil(requestStack.getMaxStackSize() / 2.0D); + amountToExtract = (int) Math.min(halfMax, halfRequest); + } + break; + + case ThEGuiHelper.MOUSE_BUTTON_WHEEL: + // Going to cursor + if (player.capabilities.isCreativeMode) { + requestStack.stackSize = requestStack.getMaxStackSize(); + player.inventory.setItemStack(requestStack); + Packet_C_Sync.sendPlayerHeldItem(player, requestStack); + } + // Done + return; + + case ThEGuiHelper.MOUSE_WHEEL_MOTION: + // Going to cursor + // Shift must be held + if (isShiftHeld) { + // Extract 1 + amountToExtract = 1; + } + } + + // If the output is the players cursor, ensure there is room, and the stacks match + if ((targetSlot == null) && (amountToExtract > 0)) { + // Get what the player is holding + cursorStack = player.inventory.getItemStack(); + + // Holding anything? + if (cursorStack != null) { + // Items are the same? + if (!cursorStack.isItemEqual(requestStack) + || !ItemStack.areItemStackTagsEqual(cursorStack, requestStack)) { + // Item player is holding doesn't match the request + return; + } + // Ensure there is room + int cursorRoom = (cursorStack.getMaxStackSize() - cursorStack.stackSize); + amountToExtract = Math.min(cursorRoom, amountToExtract); + } + } + + // Anything to extract? + if (amountToExtract <= 0) { + // Nothing to extract + return; + } + + // Create the stack to extract + IAEItemStack toExtract = requestAEStack.copy(); + + // Set the size + toExtract.setStackSize(amountToExtract); + + // Extract + IAEItemStack extractedStack = this.monitor.extractItems(toExtract, Actionable.MODULATE, this.playerSource); + + // Was anything extracted? + if ((extractedStack != null) && (extractedStack.getStackSize() > 0)) { + // Going to inventory? + if (targetSlot != null) { + if (targetSlot.getHasStack()) { + // Add to existing stack + targetSlot.getStack().stackSize += (int) extractedStack.getStackSize(); + } else { + // Set stack + targetSlot.putStack(extractedStack.getItemStack()); + } + } else { + // Going to cursor + if (cursorStack != null) { + // Add to existing stack + cursorStack.stackSize += (int) extractedStack.getStackSize(); + } else { + // Set stack + this.player.inventory.setItemStack(extractedStack.getItemStack()); + } + + // Send the update to the client + Packet_C_Sync.sendPlayerHeldItem(this.player, this.player.inventory.getItemStack()); + } + } + } + + /** + * A client has requested the full list of all items in the ME network. + * + * @param player + */ + public void onClientRequestFullUpdate(final EntityPlayer player) { + // Ensure we have a monitor & the terminal is active + if ((this.monitor != null) && (this.terminal.isActive())) { + // Get the full list + IItemList fullList = this.monitor.getStorageList(); + + // Send to the client + Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems(player, fullList); + } else { + // Send empty list + Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems( + player, AEApi.instance().storage().createItemList()); + } + } + + /** + * A client has request that the stored sorting order be changed. + * + * @param order + * @param dir + */ + public void onClientRequestSetSort(final SortOrder order, final SortDir dir, final ViewItems viewMode) { + // Inform the terminal + this.terminal.setSorts(order, dir, viewMode); + } + + /** + * Called when a client has requested they swap their equipped armor with + * the stored armor. + * + * @param player + */ + public void onClientRequestSwapArmor(final EntityPlayer player) { + this.terminal.swapStoredArmor(player); + this.detectAndSendChanges(); + Packet_C_ArcaneCraftingTerminal.updateAspectCost(player); + } + + /** + * Unregister this container + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Pass to super + super.onContainerClosed(player); + + if (this.terminal != null) { + this.terminal.removeListener(this); + } + + // Is this server side? + if (EffectiveSide.isServerSide()) { + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } + } + + /** + * Called when crafting inputs are changed. + */ + @Override + public void onCraftMatrixChanged(final IInventory inventory) { + // Reset crafting aspects + this.requiredAspects = null; + this.craftingCost.clear(); + + // Ensure wand + this.getWand(); + + // Get the matching regular crafting recipe. + ItemStack craftResult = this.findMatchingRegularResult(); + + // Was there not a regular match? + if ((craftResult == null)) { + // Get the matching arcane crafting recipe. + craftResult = this.findMatchingArcaneResult(); + } + + // Set the result slot aspects and wand + this.resultSlot.setResultAspects(this.requiredAspects); + this.resultSlot.setWand(this.wand); + + // Set the result + this.terminal.setInventorySlotContentsWithoutNotify(PartArcaneCraftingTerminal.RESULT_SLOT_INDEX, craftResult); + } + + /** + * AE API: called when the list updates its contents, this is mostly for + * handling power events. + */ + @Override + public void onListUpdate() { + // Is the terminal no longer active? + if (!this.terminal.isActive()) { + // Send empty list to client + Packet_C_ArcaneCraftingTerminal.sendAllNetworkItems( + this.player, AEApi.instance().storage().createItemList()); + } + } + + /** + * The view cells have been changed, inform the gui. + */ + public void onViewCellChange() { + // Only client side + if (EffectiveSide.isClientSide()) { + // Update the gui + this.updateGUIViewCells(); + } + } + + /** + * Called when the amount of an item on the network changes. + */ + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable changes, + final BaseActionSource actionSource) { + if (this.monitor == null) { + return; + } + + for (IAEItemStack change : changes) { + // Get the total amount of the item in the network + IAEItemStack newAmount = this.monitor.getStorageList().findPrecise(change); + + // Is there no more? + if (newAmount == null) { + // Copy the item type from the change + newAmount = change.copy(); + + // Set amount to 0 + newAmount.setStackSize(0); + } + + // Send the change to the client + Packet_C_ArcaneCraftingTerminal.stackAmountChanged(this.player, newAmount); + } + } + + /** + * Registers the container for updates from the terminal part. + */ + public void registerForUpdates() { + // Register the container with terminal + this.terminal.registerListener(this); + } + + /** + * Attempts to extract an item from the network. + * Used when crafting to replenish the crafting grid. + * + * @param itemStack + * @return + */ + public ItemStack requestCraftingReplenishment(final ItemStack itemStack) { + if (this.monitor == null) { + return null; + } + + // Search the players inventory + ItemStack replenishmentPlayer = this.takeItemFromPlayer(itemStack, 1); + if (replenishmentPlayer != null) { + return replenishmentPlayer; + } + + // Create the AE request stack + IAEItemStack requestStack = AEApi.instance().storage().createItemStack(itemStack); + + // Set the request amount to one + requestStack.setStackSize(1); + + // Attempt an extraction + IAEItemStack replenishmentAE = this.monitor.extractItems(requestStack, Actionable.MODULATE, this.playerSource); + + // Did we get a replenishment? + if (replenishmentAE != null) { + return replenishmentAE.getItemStack(); + } + + // Did not get a replenishment, search for items that match. + + // Get a list of all items in the ME network + IItemList networkItems = this.monitor.getStorageList(); + + // Search all items + for (IAEItemStack potentialMatch : networkItems) { + // Does the request match? + if (this.doStacksMatch(requestStack, potentialMatch)) { + // Found a match + requestStack = potentialMatch.copy(); + + // Set the request amount to one + requestStack.setStackSize(1); + + // Attempt an extraction + replenishmentAE = this.monitor.extractItems(requestStack, Actionable.MODULATE, this.playerSource); + + // Did we get a replenishment? + if ((replenishmentAE != null) && (replenishmentAE.getStackSize() > 0)) { + return replenishmentAE.getItemStack(); + } + } + } + + // No matches at all :( + return null; + } + + /** + * Called when the player shift+clicks on a slot + */ + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Is this client side? + if (EffectiveSide.isClientSide()) { + // Do nothing. + return null; + } + + // Get the slot that was shift-clicked + Slot slot = this.getSlotOrNull(slotNumber); + + // Is there a valid slot with and item? + if ((slot != null) && (slot.getHasStack())) { + boolean didMerge = false; + + // Get the itemstack in the slot + ItemStack slotStack = slot.getStack(); + + // Was the slot clicked in the crafting grid? + if (this.slotClickedWasInCraftingInventory(slotNumber)) { + // Attempt to merge with the ME network + didMerge = this.mergeWithMENetwork(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the hotbar + didMerge = this.mergeSlotWithHotbarInventory(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } + } + // Was the slot clicked in the player or hotbar inventory? + else if (this.slotClickedWasInPlayerInventory(slotNumber) + || this.slotClickedWasInHotbarInventory(slotNumber)) { + + // Is the item a valid wand? + if (this.wandSlot.isItemValid(slotStack)) { + // Attempt to merge with the wand + didMerge = this.mergeItemStack( + slotStack, this.wandSlot.slotNumber, this.wandSlot.slotNumber + 1, false); + } + + // Did we merge? + if (!didMerge) { + // Attempt to merge with view cells + didMerge = this.mergeWithViewCells(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the ME network + didMerge = this.mergeWithMENetwork(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the crafting grid + didMerge = this.mergeItemStack( + slotStack, this.firstCraftingSlotNumber, this.lastCraftingSlotNumber + 1, false); + + // Did we merge? + if (!didMerge) { + // Attempt to swap hotbar<->player inventory + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + } + } + } + // Was the slot clicked the crafting result? + else if (slot == this.resultSlot) { + // Start the autocrafting loop + this.doShiftAutoCrafting(player); + + return null; + } + // Wand? + else if (slot == this.wandSlot) { + // Attempt to merge with the hotbar + didMerge = this.mergeSlotWithHotbarInventory(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the ME network + didMerge = this.mergeWithMENetwork(slotStack); + } + } + } + // Was the slot clicked a view cell? + else if ((slotNumber >= this.firstViewSlotNumber) && (slotNumber <= this.lastViewSlotNumber)) { + // Attempt to merge with the hotbar + didMerge = this.mergeSlotWithHotbarInventory(slotStack); + + // Did we merge? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } + + // Did we merge? + if (didMerge) { + + // Did the merger drain the stack? + if ((slotStack == null) || (slotStack.stackSize == 0)) { + // Set the slot to have no item + slot.putStack(null); + } else { + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + + // Send changes + this.detectAndSendChanges(); + } + } + + // All taken care of! + return null; + } + + public IGrid getHostGrid() { + try { + return this.terminal.getGridBlock().getGrid(); + } catch (Exception e) { + return null; + } + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaIOBus.java b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaIOBus.java index 20a533c7..bddcd16d 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaIOBus.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaIOBus.java @@ -1,7 +1,8 @@ package thaumicenergistics.common.container; -import java.util.List; import appeng.api.config.RedstoneMode; +import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; @@ -11,175 +12,160 @@ import thaumicenergistics.common.network.packet.client.Packet_C_AspectSlot; import thaumicenergistics.common.network.packet.client.Packet_C_EssentiaIOBus; import thaumicenergistics.common.parts.ThEPartEssentiaIOBus_Base; -import javax.annotation.Nonnull; - /** * Inventory container for the import and export busses. * * @author Nividica * */ -public class ContainerPartEssentiaIOBus - extends ContainerWithNetworkTool -{ - /** - * The number of upgrade slots we have - */ - private final static int NUMBER_OF_UPGRADE_SLOTS = 4; +public class ContainerPartEssentiaIOBus extends ContainerWithNetworkTool { + /** + * The number of upgrade slots we have + */ + private static final int NUMBER_OF_UPGRADE_SLOTS = 4; - /** - * The x position of the upgrade slots - */ - private final static int UPGRADE_X_POS = 187; + /** + * The x position of the upgrade slots + */ + private static final int UPGRADE_X_POS = 187; - /** - * The Y position for the upgrade slots - */ - private final static int UPGRADE_Y_POS = 8; + /** + * The Y position for the upgrade slots + */ + private static final int UPGRADE_Y_POS = 8; - /** - * Y position for the player inventory - */ - private final static int PLAYER_INV_POSITION_Y = 102; + /** + * Y position for the player inventory + */ + private static final int PLAYER_INV_POSITION_Y = 102; - /** - * Y position for the hotbar inventory - */ - private final static int HOTBAR_INV_POSITION_Y = 160; + /** + * Y position for the hotbar inventory + */ + private static final int HOTBAR_INV_POSITION_Y = 160; - /** - * The part associated with this container - */ - private final ThEPartEssentiaIOBus_Base bus; + /** + * The part associated with this container + */ + private final ThEPartEssentiaIOBus_Base bus; - /** - * Cached isVoidAllowed - */ - private boolean isVoidAllowed; + /** + * Cached isVoidAllowed + */ + private boolean isVoidAllowed; - /** - * Cached isVoidAllowed - */ - private boolean isCraftingOnly; + /** + * Cached isVoidAllowed + */ + private boolean isCraftingOnly; - /** - * Creates the container. - * - * @param part - * The AE part associated with the container. - * @param player - * The owner of the container. - */ - public ContainerPartEssentiaIOBus( final ThEPartEssentiaIOBus_Base part, final EntityPlayer player ) - { - // Call super - super( player ); + /** + * Creates the container. + * + * @param part + * The AE part associated with the container. + * @param player + * The owner of the container. + */ + public ContainerPartEssentiaIOBus(final ThEPartEssentiaIOBus_Base part, final EntityPlayer player) { + // Call super + super(player); - // Set the part - this.bus = part; + // Set the part + this.bus = part; - // Bind to the player's inventory - this.bindPlayerInventory( player.inventory, ContainerPartEssentiaIOBus.PLAYER_INV_POSITION_Y, - ContainerPartEssentiaIOBus.HOTBAR_INV_POSITION_Y ); + // Bind to the player's inventory + this.bindPlayerInventory( + player.inventory, + ContainerPartEssentiaIOBus.PLAYER_INV_POSITION_Y, + ContainerPartEssentiaIOBus.HOTBAR_INV_POSITION_Y); - // Add the upgrade slots - this.addUpgradeSlots( part.getUpgradeInventory(), ContainerPartEssentiaIOBus.NUMBER_OF_UPGRADE_SLOTS, - ContainerPartEssentiaIOBus.UPGRADE_X_POS, ContainerPartEssentiaIOBus.UPGRADE_Y_POS ); + // Add the upgrade slots + this.addUpgradeSlots( + part.getUpgradeInventory(), + ContainerPartEssentiaIOBus.NUMBER_OF_UPGRADE_SLOTS, + ContainerPartEssentiaIOBus.UPGRADE_X_POS, + ContainerPartEssentiaIOBus.UPGRADE_Y_POS); - // Bind to the network tool - this.bindToNetworkTool( player.inventory, part.getHost().getLocation(), 0, 0 ); + // Bind to the network tool + this.bindToNetworkTool(player.inventory, part.getHost().getLocation(), 0, 0); - // Register as a listener on the part - this.bus.addListener( this ); - } + // Register as a listener on the part + this.bus.addListener(this); + } - @Override - protected boolean detectAndSendChangesMP( @Nonnull final EntityPlayerMP playerMP ) - { - // Has the void mode changed? - if( this.isVoidAllowed != this.bus.isVoidAllowed() ) - { - // Update - this.isVoidAllowed = this.bus.isVoidAllowed(); - Packet_C_EssentiaIOBus.sendVoidMode( this.player, this.isVoidAllowed ); - } + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Has the void mode changed? + if (this.isVoidAllowed != this.bus.isVoidAllowed()) { + // Update + this.isVoidAllowed = this.bus.isVoidAllowed(); + Packet_C_EssentiaIOBus.sendVoidMode(this.player, this.isVoidAllowed); + } - if( this.isCraftingOnly != this.bus.isCraftingOnly() ) - { - // Update - this.isCraftingOnly = this.bus.isCraftingOnly(); - Packet_C_EssentiaIOBus.sendCraftingMode( this.player, this.isCraftingOnly ); - } + if (this.isCraftingOnly != this.bus.isCraftingOnly()) { + // Update + this.isCraftingOnly = this.bus.isCraftingOnly(); + Packet_C_EssentiaIOBus.sendCraftingMode(this.player, this.isCraftingOnly); + } - return false; - } + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.bus != null ) - { - return this.bus.isPartUseableByPlayer( player ); - } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.bus != null) { + return this.bus.isPartUseableByPlayer(player); + } + return false; + } - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - if( this.bus != null ) - { - this.bus.removeListener( this ); - } - } + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + if (this.bus != null) { + this.bus.removeListener(this); + } + } - public void setFilteredAspect( final List filteredAspects ) - { - Packet_C_AspectSlot.setFilterList( filteredAspects, this.player ); - } + public void setFilteredAspect(final List filteredAspects) { + Packet_C_AspectSlot.setFilterList(filteredAspects, this.player); + } - public void setFilterSize( final byte filterSize ) - { - Packet_C_EssentiaIOBus.sendFilterSize( this.player, filterSize ); - } + public void setFilterSize(final byte filterSize) { + Packet_C_EssentiaIOBus.sendFilterSize(this.player, filterSize); + } - public void setRedstoneControlled( final boolean isRedstoneControlled ) - { - Packet_C_EssentiaIOBus.sendRedstoneControlled( this.player, isRedstoneControlled ); - } - public void setHasCraftingCard( final boolean hasCraftingCard ) - { - Packet_C_EssentiaIOBus.sendHasCraftingCard( this.player, hasCraftingCard ); - } + public void setRedstoneControlled(final boolean isRedstoneControlled) { + Packet_C_EssentiaIOBus.sendRedstoneControlled(this.player, isRedstoneControlled); + } - public void setRedstoneMode( final RedstoneMode redstoneMode ) - { - Packet_C_EssentiaIOBus.sendRedstoneMode( this.player, redstoneMode ); - } + public void setHasCraftingCard(final boolean hasCraftingCard) { + Packet_C_EssentiaIOBus.sendHasCraftingCard(this.player, hasCraftingCard); + } - /** - * Called when the player shift+clicks on a slot. - */ - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Get the slot - Slot slot = this.getSlotOrNull( slotNumber ); + public void setRedstoneMode(final RedstoneMode redstoneMode) { + Packet_C_EssentiaIOBus.sendRedstoneMode(this.player, redstoneMode); + } - // Do we have a valid slot with an item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - // Can this aspect be added to the filter list? - if( ( this.bus != null ) && ( this.bus.addFilteredAspectFromItemstack( player, slot.getStack() ) ) ) - { - return null; - } + /** + * Called when the player shift+clicks on a slot. + */ + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Get the slot + Slot slot = this.getSlotOrNull(slotNumber); - // Pass to super - return super.transferStackInSlot( player, slotNumber ); - } + // Do we have a valid slot with an item? + if ((slot != null) && (slot.getHasStack())) { + // Can this aspect be added to the filter list? + if ((this.bus != null) && (this.bus.addFilteredAspectFromItemstack(player, slot.getStack()))) { + return null; + } - return null; - } + // Pass to super + return super.transferStackInSlot(player, slotNumber); + } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaLevelEmitter.java b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaLevelEmitter.java index 5f3a6dcf..49ec65b3 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaLevelEmitter.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaLevelEmitter.java @@ -1,8 +1,9 @@ package thaumicenergistics.common.container; +import appeng.api.config.RedstoneMode; import java.util.ArrayList; import java.util.List; -import appeng.api.config.RedstoneMode; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; @@ -12,137 +13,121 @@ import thaumicenergistics.common.network.packet.client.Packet_C_AspectSlot; import thaumicenergistics.common.network.packet.client.Packet_C_EssentiaEmitter; import thaumicenergistics.common.parts.PartEssentiaLevelEmitter; -import javax.annotation.Nonnull; - /** * Inventory container for essentia emitter. * * @author Nividica * */ -public class ContainerPartEssentiaLevelEmitter - extends ContainerWithPlayerInventory -{ - /** - * X position for the player inventory - */ - private static int PLAYER_INV_POSITION_Y = 102; +public class ContainerPartEssentiaLevelEmitter extends ContainerWithPlayerInventory { + /** + * X position for the player inventory + */ + private static int PLAYER_INV_POSITION_Y = 102; - /** - * Y position for the hotbar inventory - */ - private static int HOTBAR_INV_POSITION_Y = 160; + /** + * Y position for the hotbar inventory + */ + private static int HOTBAR_INV_POSITION_Y = 160; - /** - * The AE part associated with this container. - */ - private PartEssentiaLevelEmitter emitter; + /** + * The AE part associated with this container. + */ + private PartEssentiaLevelEmitter emitter; - /** - * The redstone mode the emitter is in. - */ - private RedstoneMode redstoneMode = null; + /** + * The redstone mode the emitter is in. + */ + private RedstoneMode redstoneMode = null; - /** - * The threshold value. - */ - private long thresholdLevel = -1; + /** + * The threshold value. + */ + private long thresholdLevel = -1; - /** - * The tracked aspect. - */ - private Aspect trackedAspect = null; + /** + * The tracked aspect. + */ + private Aspect trackedAspect = null; - /** - * Create the container. - * - * @param player - * The owner of this container. - */ - public ContainerPartEssentiaLevelEmitter( final PartEssentiaLevelEmitter part, final EntityPlayer player ) - { - // Call super - super( player ); + /** + * Create the container. + * + * @param player + * The owner of this container. + */ + public ContainerPartEssentiaLevelEmitter(final PartEssentiaLevelEmitter part, final EntityPlayer player) { + // Call super + super(player); - // Set the part - this.emitter = part; + // Set the part + this.emitter = part; - // Get the players inventory and bind it to the container. - this.bindPlayerInventory( player.inventory, ContainerPartEssentiaLevelEmitter.PLAYER_INV_POSITION_Y, - ContainerPartEssentiaLevelEmitter.HOTBAR_INV_POSITION_Y ); - } + // Get the players inventory and bind it to the container. + this.bindPlayerInventory( + player.inventory, + ContainerPartEssentiaLevelEmitter.PLAYER_INV_POSITION_Y, + ContainerPartEssentiaLevelEmitter.HOTBAR_INV_POSITION_Y); + } - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - // Threshold - if( this.thresholdLevel != this.emitter.getThresholdLevel() ) - { - this.thresholdLevel = this.emitter.getThresholdLevel(); - Packet_C_EssentiaEmitter.sendThresholdValue( this.thresholdLevel, this.player ); - } + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Threshold + if (this.thresholdLevel != this.emitter.getThresholdLevel()) { + this.thresholdLevel = this.emitter.getThresholdLevel(); + Packet_C_EssentiaEmitter.sendThresholdValue(this.thresholdLevel, this.player); + } - // Redstone mode - if( this.redstoneMode != this.emitter.getRedstoneMode() ) - { - this.redstoneMode = this.emitter.getRedstoneMode(); - Packet_C_EssentiaEmitter.sendRedstoneMode( this.redstoneMode, this.player ); - } + // Redstone mode + if (this.redstoneMode != this.emitter.getRedstoneMode()) { + this.redstoneMode = this.emitter.getRedstoneMode(); + Packet_C_EssentiaEmitter.sendRedstoneMode(this.redstoneMode, this.player); + } - // Tracked aspect - if( this.trackedAspect != this.emitter.getTrackedAspect() ) - { - this.trackedAspect = this.emitter.getTrackedAspect(); + // Tracked aspect + if (this.trackedAspect != this.emitter.getTrackedAspect()) { + this.trackedAspect = this.emitter.getTrackedAspect(); - List filter = new ArrayList(); - filter.add( this.trackedAspect ); - Packet_C_AspectSlot.setFilterList( filter, this.player ); - } + List filter = new ArrayList(); + filter.add(this.trackedAspect); + Packet_C_AspectSlot.setFilterList(filter, this.player); + } - return false; - } + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.emitter != null ) - { - return this.emitter.isPartUseableByPlayer( player ); - } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.emitter != null) { + return this.emitter.isPartUseableByPlayer(player); + } + return false; + } - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Get the slot - Slot slot = this.getSlotOrNull( slotNumber ); + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Get the slot + Slot slot = this.getSlotOrNull(slotNumber); - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - // Can we set the filter based on this item? - if( ( this.emitter != null ) && this.emitter.setFilteredAspectFromItemstack( player, slot.getStack() ) ) - { - return null; - } + if ((slot != null) && (slot.getHasStack())) { + // Can we set the filter based on this item? + if ((this.emitter != null) && this.emitter.setFilteredAspectFromItemstack(player, slot.getStack())) { + return null; + } - // Attempt to swap - if( this.swapSlotInventoryHotbar( slotNumber, slot.getStack() ) ) - { - // Did the merger drain the stack? - if( slot.getStack().stackSize == 0 ) - { - // Set the slot to have no item - slot.putStack( null ); - } + // Attempt to swap + if (this.swapSlotInventoryHotbar(slotNumber, slot.getStack())) { + // Did the merger drain the stack? + if (slot.getStack().stackSize == 0) { + // Set the slot to have no item + slot.putStack(null); + } - // Inform the slot its stack changed; - slot.onSlotChanged(); - } - } - - return null; - - } + // Inform the slot its stack changed; + slot.onSlotChanged(); + } + } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaStorageBus.java b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaStorageBus.java index 5a9d2adc..44a846e0 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaStorageBus.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerPartEssentiaStorageBus.java @@ -2,6 +2,7 @@ package thaumicenergistics.common.container; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; @@ -11,144 +12,132 @@ import thaumicenergistics.common.network.packet.client.Packet_C_AspectSlot; import thaumicenergistics.common.network.packet.client.Packet_C_EssentiaStorageBus; import thaumicenergistics.common.parts.PartEssentiaStorageBus; -import javax.annotation.Nonnull; - /** * {@link PartEssentiaStorageBus} container. * * @author Nividica * */ -public class ContainerPartEssentiaStorageBus - extends ContainerWithNetworkTool -{ - /** - * X position offset for upgrade slots - */ - private static final int UPGRADE_SLOT_X = 187; +public class ContainerPartEssentiaStorageBus extends ContainerWithNetworkTool { + /** + * X position offset for upgrade slots + */ + private static final int UPGRADE_SLOT_X = 187; - /** - * Y position offset for upgrade slots - */ - private static final int UPGRADE_SLOT_Y = 8; + /** + * Y position offset for upgrade slots + */ + private static final int UPGRADE_SLOT_Y = 8; - /** - * Y position for the player inventory - */ - private static int PLAYER_INV_POSITION_Y = 102; + /** + * Y position for the player inventory + */ + private static int PLAYER_INV_POSITION_Y = 102; - /** - * Y position for the hotbar inventory - */ - private static int HOTBAR_INV_POSITION_Y = 160; + /** + * Y position for the hotbar inventory + */ + private static int HOTBAR_INV_POSITION_Y = 160; - /** - * The essentia storage bus. - */ - private final PartEssentiaStorageBus storageBus; + /** + * The essentia storage bus. + */ + private final PartEssentiaStorageBus storageBus; - /** - * Cache of filteredAspects. - */ - private final ArrayList filteredAspects = new ArrayList( PartEssentiaStorageBus.FILTER_SIZE ); + /** + * Cache of filteredAspects. + */ + private final ArrayList filteredAspects = new ArrayList(PartEssentiaStorageBus.FILTER_SIZE); - /** - * Cache of isVoidAllowed. - */ - private boolean isVoidAllowed = false; + /** + * Cache of isVoidAllowed. + */ + private boolean isVoidAllowed = false; - public ContainerPartEssentiaStorageBus( final PartEssentiaStorageBus part, final EntityPlayer player ) - { - // Call super - super( player ); + public ContainerPartEssentiaStorageBus(final PartEssentiaStorageBus part, final EntityPlayer player) { + // Call super + super(player); - // Set the part - this.storageBus = part; + // Set the part + this.storageBus = part; - // Setup the filtered aspects - for( int i = 0; i < PartEssentiaStorageBus.FILTER_SIZE; ++i ) - { - this.filteredAspects.add( null ); - } + // Setup the filtered aspects + for (int i = 0; i < PartEssentiaStorageBus.FILTER_SIZE; ++i) { + this.filteredAspects.add(null); + } - // Add the upgrade slot - this.addUpgradeSlots( part.getUpgradeInventory(), 1, ContainerPartEssentiaStorageBus.UPGRADE_SLOT_X, - ContainerPartEssentiaStorageBus.UPGRADE_SLOT_Y ); + // Add the upgrade slot + this.addUpgradeSlots( + part.getUpgradeInventory(), + 1, + ContainerPartEssentiaStorageBus.UPGRADE_SLOT_X, + ContainerPartEssentiaStorageBus.UPGRADE_SLOT_Y); - // Bind to the player's inventory - this.bindPlayerInventory( player.inventory, ContainerPartEssentiaStorageBus.PLAYER_INV_POSITION_Y, - ContainerPartEssentiaStorageBus.HOTBAR_INV_POSITION_Y ); + // Bind to the player's inventory + this.bindPlayerInventory( + player.inventory, + ContainerPartEssentiaStorageBus.PLAYER_INV_POSITION_Y, + ContainerPartEssentiaStorageBus.HOTBAR_INV_POSITION_Y); - // Bind to the network tool - this.bindToNetworkTool( player.inventory, part.getHost().getLocation(), 0, 0 ); + // Bind to the network tool + this.bindToNetworkTool(player.inventory, part.getHost().getLocation(), 0, 0); + } - } + @Override + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + // Has the filtered list changed? + boolean updateFilters = false; + for (int filterIndex = 0; filterIndex < PartEssentiaStorageBus.FILTER_SIZE; ++filterIndex) { + if (this.filteredAspects.get(filterIndex) != this.storageBus.getFilteredAspect(filterIndex)) { + // Found mismatch + this.filteredAspects.set(filterIndex, this.storageBus.getFilteredAspect(filterIndex)); + updateFilters = true; + } + } + if (updateFilters) { + // Update the client + Packet_C_AspectSlot.setFilterList(this.filteredAspects, this.player); + } - @Override - protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP ) - { - // Has the filtered list changed? - boolean updateFilters = false; - for( int filterIndex = 0; filterIndex < PartEssentiaStorageBus.FILTER_SIZE; ++filterIndex ) - { - if( this.filteredAspects.get( filterIndex ) != this.storageBus.getFilteredAspect( filterIndex ) ) - { - // Found mismatch - this.filteredAspects.set( filterIndex, this.storageBus.getFilteredAspect( filterIndex ) ); - updateFilters = true; - } - } - if( updateFilters ) - { - // Update the client - Packet_C_AspectSlot.setFilterList( this.filteredAspects, this.player ); - } + // Has the void mode changed? + if (this.isVoidAllowed != this.storageBus.isVoidAllowed()) { + // Update + this.isVoidAllowed = this.storageBus.isVoidAllowed(); + Packet_C_EssentiaStorageBus.sendIsVoidAllowed(this.player, this.isVoidAllowed); + } - // Has the void mode changed? - if( this.isVoidAllowed != this.storageBus.isVoidAllowed() ) - { - // Update - this.isVoidAllowed = this.storageBus.isVoidAllowed(); - Packet_C_EssentiaStorageBus.sendIsVoidAllowed( this.player, this.isVoidAllowed ); - } + return false; + } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.storageBus != null) { + return this.storageBus.isPartUseableByPlayer(player); + } + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.storageBus != null ) - { - return this.storageBus.isPartUseableByPlayer( player ); - } - return false; - } + public void setFilteredAspects(final List filteredAspects) { + Packet_C_AspectSlot.setFilterList(filteredAspects, this.player); + } - public void setFilteredAspects( final List filteredAspects ) - { - Packet_C_AspectSlot.setFilterList( filteredAspects, this.player ); - } + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Get the slot + Slot slot = this.getSlotOrNull(slotNumber); - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Get the slot - Slot slot = this.getSlotOrNull( slotNumber ); + // Do we have a valid slot with an item? + if ((slot != null) && (slot.getHasStack())) { + // Can this aspect be added to the filter list? + if ((this.storageBus != null) + && (this.storageBus.addFilteredAspectFromItemstack(player, slot.getStack()))) { + return null; + } - // Do we have a valid slot with an item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - // Can this aspect be added to the filter list? - if( ( this.storageBus != null ) && ( this.storageBus.addFilteredAspectFromItemstack( player, slot.getStack() ) ) ) - { - return null; - } + // Pass to super + return super.transferStackInSlot(player, slotNumber); + } - // Pass to super - return super.transferStackInSlot( player, slotNumber ); - } - - return null; - } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerPriority.java b/src/main/java/thaumicenergistics/common/container/ContainerPriority.java index 77c5a390..2ccfd0fc 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerPriority.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerPriority.java @@ -15,91 +15,77 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class ContainerPriority - extends Container -{ +public class ContainerPriority extends Container { - /** - * The host we are setting the priority for - */ - public final IPriorityHost host; + /** + * The host we are setting the priority for + */ + public final IPriorityHost host; - /** - * Player associated with this container - */ - private final EntityPlayer player; + /** + * Player associated with this container + */ + private final EntityPlayer player; - public ContainerPriority( final IPriorityHost host, final EntityPlayer player ) - { - // Set the host - this.host = host; + public ContainerPriority(final IPriorityHost host, final EntityPlayer player) { + // Set the host + this.host = host; - // Set the player - this.player = player; - } + // Set the player + this.player = player; + } - /** - * Sends the priority to the client - */ - private void sendPriorityToClient() - { - // Send the priority to the client - Packet_C_Priority.sendPriority( this.host.getPriority(), this.player ); - } + /** + * Sends the priority to the client + */ + private void sendPriorityToClient() { + // Send the priority to the client + Packet_C_Priority.sendPriority(this.host.getPriority(), this.player); + } - @Override - public boolean canInteractWith( final EntityPlayer player ) - { - if( this.host instanceof IInventory ) - { - return ( (IInventory)this.host ).isUseableByPlayer( player ); - } - else if( this.host instanceof ThEPartBase ) - { - return ( (ThEPartBase)this.host ).isPartUseableByPlayer( player ); - } - else if( this.host instanceof TileEntity ) - { - return ThEUtils.canPlayerInteractWith( player, (TileEntity)this.host ); - } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer player) { + if (this.host instanceof IInventory) { + return ((IInventory) this.host).isUseableByPlayer(player); + } else if (this.host instanceof ThEPartBase) { + return ((ThEPartBase) this.host).isPartUseableByPlayer(player); + } else if (this.host instanceof TileEntity) { + return ThEUtils.canPlayerInteractWith(player, (TileEntity) this.host); + } + return false; + } - /** - * Called when a client requests to adjust the priority of the part. - * - * @param newPriority - */ - public void onClientRequestAdjustPriority( final int adjustment ) - { - // Adjust - int newPriority = this.host.getPriority() + adjustment; + /** + * Called when a client requests to adjust the priority of the part. + * + * @param newPriority + */ + public void onClientRequestAdjustPriority(final int adjustment) { + // Adjust + int newPriority = this.host.getPriority() + adjustment; - // Set - this.onClientRequestSetPriority( newPriority ); - } + // Set + this.onClientRequestSetPriority(newPriority); + } - /** - * Called when a client requests the priority of the part. - */ - public void onClientRequestPriority() - { - // Send the priority - this.sendPriorityToClient(); - } + /** + * Called when a client requests the priority of the part. + */ + public void onClientRequestPriority() { + // Send the priority + this.sendPriorityToClient(); + } - /** - * Called when a client requests to set the priority of the part. - * - * @param newPriority - */ - public void onClientRequestSetPriority( final int newPriority ) - { - // Set the priority - this.host.setPriority( newPriority ); - - // Send the reply - this.sendPriorityToClient(); - } + /** + * Called when a client requests to set the priority of the part. + * + * @param newPriority + */ + public void onClientRequestSetPriority(final int newPriority) { + // Set the priority + this.host.setPriority(newPriority); + // Send the reply + this.sendPriorityToClient(); + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerWirelessEssentiaTerminal.java b/src/main/java/thaumicenergistics/common/container/ContainerWirelessEssentiaTerminal.java index 55ae7093..405b3cb4 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerWirelessEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerWirelessEssentiaTerminal.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.container; -import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.Settings; @@ -11,6 +10,7 @@ import appeng.api.storage.data.IAEItemStack; import appeng.container.ContainerOpenContext; import appeng.container.implementations.ContainerCraftAmount; import appeng.util.Platform; +import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Slot; @@ -37,277 +37,244 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class ContainerWirelessEssentiaTerminal - extends ContainerEssentiaCellTerminalBase -{ +public class ContainerWirelessEssentiaTerminal extends ContainerEssentiaCellTerminalBase { - /** - * After this many ticks, power will be extracted from the terminal just for - * being open. - */ - private static final int EXTRACT_POWER_ON_TICK = 10; + /** + * After this many ticks, power will be extracted from the terminal just for + * being open. + */ + private static final int EXTRACT_POWER_ON_TICK = 10; - /** - * Handler used to interact with the wireless terminal. - */ - @Nonnull - private final HandlerWirelessEssentiaTerminal handler; + /** + * Handler used to interact with the wireless terminal. + */ + @Nonnull + private final HandlerWirelessEssentiaTerminal handler; - private Aspect tmpSelectedAspect; + private Aspect tmpSelectedAspect; - /** - * Import and export inventory slots. - */ - private TheInternalInventory privateInventory = new TheInternalInventory( ThaumicEnergistics.MOD_ID + ".item.essentia.cell.inventory", 2, 64 ) - { - @Override - public boolean isItemValidForSlot( final int slotID, final ItemStack itemStack ) - { - // Get the type - AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType( itemStack ); + /** + * Import and export inventory slots. + */ + private TheInternalInventory privateInventory = + new TheInternalInventory(ThaumicEnergistics.MOD_ID + ".item.essentia.cell.inventory", 2, 64) { + @Override + public boolean isItemValidForSlot(final int slotID, final ItemStack itemStack) { + // Get the type + AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType(itemStack); - // True if jar or jar label - return ( iType == AspectItemType.EssentiaContainer ) || ( iType == AspectItemType.JarLabel ); - } - }; + // True if jar or jar label + return (iType == AspectItemType.EssentiaContainer) || (iType == AspectItemType.JarLabel); + } + }; - /** - * Tracks the number of ticks elapsed. - */ - private int powerTickCounter = 1; + /** + * Tracks the number of ticks elapsed. + */ + private int powerTickCounter = 1; - /** - * The slot the terminal is in. - */ - private int terminalSlotIndex = -1; + /** + * The slot the terminal is in. + */ + private int terminalSlotIndex = -1; - /** - * - * @param player - * @param handler - */ - public ContainerWirelessEssentiaTerminal( final EntityPlayer player, final @Nonnull HandlerWirelessEssentiaTerminal handler ) - { - // Call super - super( player ); + /** + * + * @param player + * @param handler + */ + public ContainerWirelessEssentiaTerminal( + final EntityPlayer player, final @Nonnull HandlerWirelessEssentiaTerminal handler) { + // Call super + super(player); - // Bind our inventory - this.bindToInventory( this.privateInventory ); + // Bind our inventory + this.bindToInventory(this.privateInventory); - // Set the terminal slot index - this.terminalSlotIndex = player.inventory.currentItem; + // Set the terminal slot index + this.terminalSlotIndex = player.inventory.currentItem; - // Set the handler - this.handler = handler; + // Set the handler + this.handler = handler; - // Client side? - if( EffectiveSide.isClientSide() ) - { - // Request a full update from the server - Packet_S_EssentiaCellTerminal.sendFullUpdateRequest( player ); - } - } + // Client side? + if (EffectiveSide.isClientSide()) { + // Request a full update from the server + Packet_S_EssentiaCellTerminal.sendFullUpdateRequest(player); + } + } - @Override - protected BaseActionSource getActionSource() - { - return this.handler.getActionHost(); - } + @Override + protected BaseActionSource getActionSource() { + return this.handler.getActionHost(); + } - @Override - protected IGrid getHostGrid() - { - try - { - return this.handler.getActionableNode().getGrid(); - } - catch( Exception e ) - { - return null; - } - } + @Override + protected IGrid getHostGrid() { + try { + return this.handler.getActionableNode().getGrid(); + } catch (Exception e) { + return null; + } + } - @Override - protected Aspect getHostSelectedAspect() - { - return this.tmpSelectedAspect; - } + @Override + protected Aspect getHostSelectedAspect() { + return this.tmpSelectedAspect; + } - @Override - protected IMEEssentiaMonitor getNewMonitor() - { - return this.handler.getEssentiaInventory(); - } + @Override + protected IMEEssentiaMonitor getNewMonitor() { + return this.handler.getEssentiaInventory(); + } - @Override - protected void setHostSelectedAspect( final Aspect aspect ) - { - this.tmpSelectedAspect = aspect; - } + @Override + protected void setHostSelectedAspect(final Aspect aspect) { + this.tmpSelectedAspect = aspect; + } - @Override - public boolean canInteractWith( final EntityPlayer p_75145_1_ ) - { - if( this.handler != null ) - { - return this.handler.isConnected(); - } - return false; - } + @Override + public boolean canInteractWith(final EntityPlayer p_75145_1_) { + if (this.handler != null) { + return this.handler.isConnected(); + } + return false; + } - /** - * Transfers essentia, checks the network connectivity, and drains power. - */ - @Override - public void doWork( final int elapsedTicks ) - { - // Validate the handler - if( this.handler == null ) - { - // Invalid handler. - return; - } + /** + * Transfers essentia, checks the network connectivity, and drains power. + */ + @Override + public void doWork(final int elapsedTicks) { + // Validate the handler + if (this.handler == null) { + // Invalid handler. + return; + } - // Increment the tick counter. - this.powerTickCounter += elapsedTicks; + // Increment the tick counter. + this.powerTickCounter += elapsedTicks; - if( this.powerTickCounter > ContainerWirelessEssentiaTerminal.EXTRACT_POWER_ON_TICK ) - { - // Adjust the power multiplier - this.handler.updatePowerMultiplier(); + if (this.powerTickCounter > ContainerWirelessEssentiaTerminal.EXTRACT_POWER_ON_TICK) { + // Adjust the power multiplier + this.handler.updatePowerMultiplier(); - // Take power - this.handler.extractPower( this.powerTickCounter, Actionable.MODULATE ); + // Take power + this.handler.extractPower(this.powerTickCounter, Actionable.MODULATE); - // Update the item - this.player.inventory.mainInventory[this.terminalSlotIndex] = this.handler.getTerminalItem(); + // Update the item + this.player.inventory.mainInventory[this.terminalSlotIndex] = this.handler.getTerminalItem(); - // Reset the tick counter - this.powerTickCounter = 0; - } + // Reset the tick counter + this.powerTickCounter = 0; + } - // Transfer essentia if needed - this.transferEssentiaFromWorkSlots(); - } + // Transfer essentia if needed + this.transferEssentiaFromWorkSlots(); + } - @Override - public ICraftingIssuerHost getCraftingHost() - { - return this.handler; - } + @Override + public ICraftingIssuerHost getCraftingHost() { + return this.handler; + } - @Override - public void onClientRequestAutoCraft( final EntityPlayer player, final Aspect aspect ) - { - // Launch the GUI - ThEGuiHandler.launchGui( ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, player.worldObj, 0, 0, 0 ); + @Override + public void onClientRequestAutoCraft(final EntityPlayer player, final Aspect aspect) { + // Launch the GUI + ThEGuiHandler.launchGui(ThEGuiHandler.AUTO_CRAFTING_AMOUNT, player, player.worldObj, 0, 0, 0); - // Setup the amount container - if( player.openContainer instanceof ContainerCraftAmount ) - { - // Get the container - ContainerCraftAmount cca = (ContainerCraftAmount)this.player.openContainer; + // Setup the amount container + if (player.openContainer instanceof ContainerCraftAmount) { + // Get the container + ContainerCraftAmount cca = (ContainerCraftAmount) this.player.openContainer; - // Create the open context - cca.setOpenContext( new ContainerOpenContext( this.handler ) ); - cca.getOpenContext().setWorld( player.worldObj ); + // Create the open context + cca.setOpenContext(new ContainerOpenContext(this.handler)); + cca.getOpenContext().setWorld(player.worldObj); - // Create the result item - IAEItemStack result = AEApi.instance().storage().createItemStack( ItemCraftingAspect.createStackForAspect( aspect, 1 ) ); + // Create the result item + IAEItemStack result = + AEApi.instance().storage().createItemStack(ItemCraftingAspect.createStackForAspect(aspect, 1)); - // Set the item - cca.getCraftingItem().putStack( result.getItemStack() ); - cca.setItemToCraft( result ); + // Set the item + cca.getCraftingItem().putStack(result.getItemStack()); + cca.setItemToCraft(result); - // Issue update - if( player instanceof EntityPlayerMP ) - { - ( (EntityPlayerMP)player ).isChangingQuantityOnly = false; - } - cca.detectAndSendChanges(); - } + // Issue update + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).isChangingQuantityOnly = false; + } + cca.detectAndSendChanges(); + } + } - } + @Override + public void onClientRequestFullUpdate() { + // Send the sorting mode + Packet_C_EssentiaCellTerminal.sendViewingModes( + this.player, this.handler.getSortingMode(), this.handler.getViewMode()); - @Override - public void onClientRequestFullUpdate() - { - // Send the sorting mode - Packet_C_EssentiaCellTerminal.sendViewingModes( this.player, this.handler.getSortingMode(), this.handler.getViewMode() ); + // Send the list + Packet_C_EssentiaCellTerminal.sendFullList(this.player, this.repo.getAll()); + } - // Send the list - Packet_C_EssentiaCellTerminal.sendFullList( this.player, this.repo.getAll() ); - } + @Override + public void onClientRequestSortModeChange(final EntityPlayer player, final boolean backwards) { + // Change the sorting mode + AspectStackComparatorMode sortingMode; + if (backwards) { + sortingMode = this.handler.getSortingMode().previousMode(); + } else { + sortingMode = this.handler.getSortingMode().nextMode(); + } - @Override - public void onClientRequestSortModeChange( final EntityPlayer player, final boolean backwards ) - { - // Change the sorting mode - AspectStackComparatorMode sortingMode; - if( backwards ) - { - sortingMode = this.handler.getSortingMode().previousMode(); - } - else - { - sortingMode = this.handler.getSortingMode().nextMode(); - } + // Set the sorting mode. + this.handler.setSortingMode(sortingMode); - // Set the sorting mode. - this.handler.setSortingMode( sortingMode ); + // Send confirmation back to client + Packet_C_EssentiaCellTerminal.sendViewingModes(player, sortingMode, this.handler.getViewMode()); + } - // Send confirmation back to client - Packet_C_EssentiaCellTerminal.sendViewingModes( player, sortingMode, this.handler.getViewMode() ); - } + @Override + public void onClientRequestViewModeChange(final EntityPlayer player, final boolean backwards) { + // Change the view mode + ViewItems viewMode = + Platform.rotateEnum(this.handler.getViewMode(), backwards, Settings.VIEW_MODE.getPossibleValues()); - @Override - public void onClientRequestViewModeChange( final EntityPlayer player, final boolean backwards ) - { - // Change the view mode - ViewItems viewMode = Platform.rotateEnum( this.handler.getViewMode(), backwards, Settings.VIEW_MODE.getPossibleValues() ); + // Inform the handler of the change + this.handler.setViewMode(viewMode); - // Inform the handler of the change - this.handler.setViewMode( viewMode ); + // Send confirmation back to client + Packet_C_EssentiaCellTerminal.sendViewingModes(player, this.handler.getSortingMode(), viewMode); + } - // Send confirmation back to client - Packet_C_EssentiaCellTerminal.sendViewingModes( player, this.handler.getSortingMode(), viewMode ); - } + /** + * Drops any items in the import and export inventory. + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + super.onContainerClosed(player); - /** - * Drops any items in the import and export inventory. - */ - @Override - public void onContainerClosed(@Nonnull final EntityPlayer player ) - { - super.onContainerClosed( player ); + if (EffectiveSide.isServerSide()) { + for (int i = 0; i < 2; i++) { + this.player.dropPlayerItemWithRandomChoice(((Slot) this.inventorySlots.get(i)).getStack(), false); + } + } + } - if( EffectiveSide.isServerSide() ) - { - for( int i = 0; i < 2; i++ ) - { - this.player.dropPlayerItemWithRandomChoice( ( (Slot)this.inventorySlots.get( i ) ).getStack(), false ); - } - } - } - - @Override - public ItemStack slotClick( final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player ) - { - try - { - Slot clickedSlot = this.getSlotOrNull( slotNumber ); - // Protect the wireless terminal - if( ( clickedSlot.inventory == this.player.inventory ) && ( clickedSlot.getSlotIndex() == this.terminalSlotIndex ) ) - { - return null; - } - } - catch( Exception e ) - { - } - - return super.slotClick( slotNumber, buttonPressed, flag, player ); - - } + @Override + public ItemStack slotClick( + final int slotNumber, final int buttonPressed, final int flag, final EntityPlayer player) { + try { + Slot clickedSlot = this.getSlotOrNull(slotNumber); + // Protect the wireless terminal + if ((clickedSlot.inventory == this.player.inventory) + && (clickedSlot.getSlotIndex() == this.terminalSlotIndex)) { + return null; + } + } catch (Exception e) { + } + return super.slotClick(slotNumber, buttonPressed, flag, player); + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerWithNetworkTool.java b/src/main/java/thaumicenergistics/common/container/ContainerWithNetworkTool.java index 8b3a939f..2eab0416 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerWithNetworkTool.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerWithNetworkTool.java @@ -20,353 +20,341 @@ import thaumicenergistics.common.container.slot.SlotRestrictive; * @author Nividica * */ -public abstract class ContainerWithNetworkTool - extends ContainerWithPlayerInventory -{ - /** - * Number of rows in the network tool - */ - private static final int TOOL_ROWS = 3; +public abstract class ContainerWithNetworkTool extends ContainerWithPlayerInventory { + /** + * Number of rows in the network tool + */ + private static final int TOOL_ROWS = 3; - /** - * Number of columns in the network tool - */ - private static final int TOOL_COLUMNS = 3; + /** + * Number of columns in the network tool + */ + private static final int TOOL_COLUMNS = 3; - /** - * X position to start drawing slots - */ - private static final int TOOL_SLOT_X_OFFSET = 187; + /** + * X position to start drawing slots + */ + private static final int TOOL_SLOT_X_OFFSET = 187; - /** - * Y position to start drawing slots - */ - private static final int TOOL_SLOT_Y_OFFSET = 102; + /** + * Y position to start drawing slots + */ + private static final int TOOL_SLOT_Y_OFFSET = 102; - /** - * How far apart each slot should be drawn - */ - private static int UPGRADE_Y_POSITION_MULTIPLIER = 18; + /** + * How far apart each slot should be drawn + */ + private static int UPGRADE_Y_POSITION_MULTIPLIER = 18; - /** - * Index of the first network tool slot - */ - private int firstToolSlotNumber = -1; + /** + * Index of the first network tool slot + */ + private int firstToolSlotNumber = -1; - /** - * Index of the last network tool slot - */ - private int lastToolSlotNumber = -1; + /** + * Index of the last network tool slot + */ + private int lastToolSlotNumber = -1; - /** - * Index of the first upgrade slot - */ - private int firstUpgradeSlot = -1; + /** + * Index of the first upgrade slot + */ + private int firstUpgradeSlot = -1; - /** - * Index of the first upgrade slot - */ - private int lastUpgradeSlot = -1; + /** + * Index of the first upgrade slot + */ + private int lastUpgradeSlot = -1; - /** - * True if there is a network tool - */ - protected boolean hasNetworkTool = false; + /** + * True if there is a network tool + */ + protected boolean hasNetworkTool = false; - public ContainerWithNetworkTool( final EntityPlayer player ) - { - super( player ); - } + public ContainerWithNetworkTool(final EntityPlayer player) { + super(player); + } - /** - * Adds upgrade slots to the container. - * - * @param upgradeInventory - * @param count - * @param xPosition - * @param yPosition - */ - protected void addUpgradeSlots( final UpgradeInventory upgradeInventory, final int count, final int xPosition, final int yPosition ) - { - Slot upgradeSlot = null; + /** + * Adds upgrade slots to the container. + * + * @param upgradeInventory + * @param count + * @param xPosition + * @param yPosition + */ + protected void addUpgradeSlots( + final UpgradeInventory upgradeInventory, final int count, final int xPosition, final int yPosition) { + Slot upgradeSlot = null; - // Add the upgrade slots - for( int slotIndex = 0; slotIndex < count; slotIndex++ ) - { - // Create the slot - upgradeSlot = new SlotRestrictive( upgradeInventory, slotIndex, xPosition, yPosition + - ( slotIndex * ContainerWithNetworkTool.UPGRADE_Y_POSITION_MULTIPLIER ) ); + // Add the upgrade slots + for (int slotIndex = 0; slotIndex < count; slotIndex++) { + // Create the slot + upgradeSlot = new SlotRestrictive( + upgradeInventory, + slotIndex, + xPosition, + yPosition + (slotIndex * ContainerWithNetworkTool.UPGRADE_Y_POSITION_MULTIPLIER)); - // Add the slot - this.addSlotToContainer( upgradeSlot ); + // Add the slot + this.addSlotToContainer(upgradeSlot); - // Check first - if( slotIndex == 0 ) - { - this.firstUpgradeSlot = upgradeSlot.slotNumber; - } - } + // Check first + if (slotIndex == 0) { + this.firstUpgradeSlot = upgradeSlot.slotNumber; + } + } - // Set last - if( upgradeSlot != null ) - { - this.lastUpgradeSlot = upgradeSlot.slotNumber; - } - } + // Set last + if (upgradeSlot != null) { + this.lastUpgradeSlot = upgradeSlot.slotNumber; + } + } - protected void bindToNetworkTool( final InventoryPlayer playerInventory, final DimensionalCoord partLocation, final int slotOffsetX, - final int slotOffsetY ) - { - //Get the networkTool or null if absent (e.g. disabled in AE's config-file) - ItemStack nwTool = AEApi.instance().definitions().items().networkTool().maybeStack( 1 ).orNull(); + protected void bindToNetworkTool( + final InventoryPlayer playerInventory, + final DimensionalCoord partLocation, + final int slotOffsetX, + final int slotOffsetY) { + // Get the networkTool or null if absent (e.g. disabled in AE's config-file) + ItemStack nwTool = AEApi.instance() + .definitions() + .items() + .networkTool() + .maybeStack(1) + .orNull(); - //First of all is there a networkTool? - if( nwTool != null ) - { - // Check the player inventory for the network tool - for( int slotIndex = 0; slotIndex < playerInventory.getSizeInventory(); slotIndex++ ) - { - // Get the item in the current slot - ItemStack stack = playerInventory.getStackInSlot( slotIndex ); + // First of all is there a networkTool? + if (nwTool != null) { + // Check the player inventory for the network tool + for (int slotIndex = 0; slotIndex < playerInventory.getSizeInventory(); slotIndex++) { + // Get the item in the current slot + ItemStack stack = playerInventory.getStackInSlot(slotIndex); - // Is it the network tool? - if( ( stack != null ) && ( stack.isItemEqual( AEApi.instance().definitions().items().networkTool().maybeStack( 1 ).get() ) ) ) - { - // Get the gui item for the tool - IGuiItem guiItem = (IGuiItem)stack.getItem(); + // Is it the network tool? + if ((stack != null) + && (stack.isItemEqual(AEApi.instance() + .definitions() + .items() + .networkTool() + .maybeStack(1) + .get()))) { + // Get the gui item for the tool + IGuiItem guiItem = (IGuiItem) stack.getItem(); - // Get the gui for the tool - INetworkTool networkTool = (INetworkTool)guiItem.getGuiObject( stack, partLocation.getWorld(), partLocation.x, partLocation.y, - partLocation.z ); + // Get the gui for the tool + INetworkTool networkTool = (INetworkTool) guiItem.getGuiObject( + stack, partLocation.getWorld(), partLocation.x, partLocation.y, partLocation.z); - Slot toolSlot = null; + Slot toolSlot = null; - // Add a slot for each network tool slot - for( int column = 0; column < ContainerWithNetworkTool.TOOL_COLUMNS; column++ ) - { - for( int row = 0; row < ContainerWithNetworkTool.TOOL_ROWS; row++ ) - { - // Calculate the tools slot index - int slotToolIndex = column + ( row * ContainerWithNetworkTool.TOOL_COLUMNS ); + // Add a slot for each network tool slot + for (int column = 0; column < ContainerWithNetworkTool.TOOL_COLUMNS; column++) { + for (int row = 0; row < ContainerWithNetworkTool.TOOL_ROWS; row++) { + // Calculate the tools slot index + int slotToolIndex = column + (row * ContainerWithNetworkTool.TOOL_COLUMNS); - // Create the slot - toolSlot = new SlotNetworkTool( networkTool, slotToolIndex, ContainerWithNetworkTool.TOOL_SLOT_X_OFFSET + slotOffsetX + - ( column * ContainerWithPlayerInventory.SLOT_SIZE ), ( row * ContainerWithPlayerInventory.SLOT_SIZE ) + - ContainerWithNetworkTool.TOOL_SLOT_Y_OFFSET + slotOffsetY ); + // Create the slot + toolSlot = new SlotNetworkTool( + networkTool, + slotToolIndex, + ContainerWithNetworkTool.TOOL_SLOT_X_OFFSET + + slotOffsetX + + (column * ContainerWithPlayerInventory.SLOT_SIZE), + (row * ContainerWithPlayerInventory.SLOT_SIZE) + + ContainerWithNetworkTool.TOOL_SLOT_Y_OFFSET + + slotOffsetY); - // Add the slot - this.addSlotToContainer( toolSlot ); + // Add the slot + this.addSlotToContainer(toolSlot); - // Check first - if( slotToolIndex == 0 ) - { - this.firstToolSlotNumber = toolSlot.slotNumber; - } - } - } + // Check first + if (slotToolIndex == 0) { + this.firstToolSlotNumber = toolSlot.slotNumber; + } + } + } - // Set last - if( toolSlot != null ) - { - this.lastToolSlotNumber = toolSlot.slotNumber; - } + // Set last + if (toolSlot != null) { + this.lastToolSlotNumber = toolSlot.slotNumber; + } - // Mark that we have a network tool - this.hasNetworkTool = true; + // Mark that we have a network tool + this.hasNetworkTool = true; - // Done - return; - } - } - } - } + // Done + return; + } + } + } + } - /** - * Attempt to merge the specified slot stack with the tool inventory - * - * @param slotStack - * @return - */ - protected boolean mergeSlotWithNetworkTool( final ItemStack slotStack ) - { - if( this.hasNetworkTool ) - { - // Is the item an upgrade card? - if( !( slotStack.getItem() instanceof IUpgradeModule ) ) - { - // Not an upgrade module - return false; - } + /** + * Attempt to merge the specified slot stack with the tool inventory + * + * @param slotStack + * @return + */ + protected boolean mergeSlotWithNetworkTool(final ItemStack slotStack) { + if (this.hasNetworkTool) { + // Is the item an upgrade card? + if (!(slotStack.getItem() instanceof IUpgradeModule)) { + // Not an upgrade module + return false; + } - return this.mergeItemStack( slotStack, this.firstToolSlotNumber, this.lastToolSlotNumber + 1, false ); - } + return this.mergeItemStack(slotStack, this.firstToolSlotNumber, this.lastToolSlotNumber + 1, false); + } - return false; - } + return false; + } - /** - * Attempt to merge the specified slot stack with the upgrade inventory - * - * @param slotStack - * @return - */ - protected boolean mergeSlotWithUpgrades( final ItemStack slotStack ) - { - // Is the item an upgrade card? - if( !( slotStack.getItem() instanceof IUpgradeModule ) ) - { - // Not an upgrade module - return false; - } + /** + * Attempt to merge the specified slot stack with the upgrade inventory + * + * @param slotStack + * @return + */ + protected boolean mergeSlotWithUpgrades(final ItemStack slotStack) { + // Is the item an upgrade card? + if (!(slotStack.getItem() instanceof IUpgradeModule)) { + // Not an upgrade module + return false; + } - boolean didMerge = false; + boolean didMerge = false; - // Are there any open slots in the upgrade inventory? - for( int index = this.firstUpgradeSlot; index <= this.lastUpgradeSlot; index++ ) - { - // Get the slot - Slot upgradeSlot = (Slot)this.inventorySlots.get( index ); + // Are there any open slots in the upgrade inventory? + for (int index = this.firstUpgradeSlot; index <= this.lastUpgradeSlot; index++) { + // Get the slot + Slot upgradeSlot = (Slot) this.inventorySlots.get(index); - // Is the slot empty? - if( ( upgradeSlot != null ) && ( !upgradeSlot.getHasStack() ) ) - { - // Can the slot accept this item? - if( upgradeSlot.isItemValid( slotStack ) ) - { - // Create an itemstack of size 1 - ItemStack upgradeStack = slotStack.copy(); - upgradeStack.stackSize = 1; + // Is the slot empty? + if ((upgradeSlot != null) && (!upgradeSlot.getHasStack())) { + // Can the slot accept this item? + if (upgradeSlot.isItemValid(slotStack)) { + // Create an itemstack of size 1 + ItemStack upgradeStack = slotStack.copy(); + upgradeStack.stackSize = 1; - // Place the stack in the upgrade slot - upgradeSlot.putStack( upgradeStack ); + // Place the stack in the upgrade slot + upgradeSlot.putStack(upgradeStack); - // Decrement the slot stack - slotStack.stackSize-- ; + // Decrement the slot stack + slotStack.stackSize--; - // Mark that we merged - didMerge = true; + // Mark that we merged + didMerge = true; - // Is the slot stack at zero? - if( slotStack.stackSize == 0 ) - { - // Break the loop - break; - } - } - } - } + // Is the slot stack at zero? + if (slotStack.stackSize == 0) { + // Break the loop + break; + } + } + } + } - return didMerge; - } + return didMerge; + } - /** - * Checks if the slot clicked was in the network tools inventory - * - * @param slotNumber - * @return True if it was in the tools inventory, false otherwise. - */ - protected boolean slotClickedWasInNetworkTool( final int slotNumber ) - { - return this.hasNetworkTool && ( slotNumber >= this.firstToolSlotNumber ) && ( slotNumber <= this.lastToolSlotNumber ); - } + /** + * Checks if the slot clicked was in the network tools inventory + * + * @param slotNumber + * @return True if it was in the tools inventory, false otherwise. + */ + protected boolean slotClickedWasInNetworkTool(final int slotNumber) { + return this.hasNetworkTool + && (slotNumber >= this.firstToolSlotNumber) + && (slotNumber <= this.lastToolSlotNumber); + } - protected boolean slotClickedWasInUpgrades( final int slotNumber ) - { - return ( slotNumber >= this.firstUpgradeSlot ) && ( slotNumber <= this.lastUpgradeSlot ); - } + protected boolean slotClickedWasInUpgrades(final int slotNumber) { + return (slotNumber >= this.firstUpgradeSlot) && (slotNumber <= this.lastUpgradeSlot); + } - public boolean hasNetworkTool() - { - return this.hasNetworkTool; - } + public boolean hasNetworkTool() { + return this.hasNetworkTool; + } - /** - * Checks if the shift+click happend in the network tool. - */ - @Override - public ItemStack transferStackInSlot( final EntityPlayer player, final int slotNumber ) - { - // Note: mergeItemStack args: ItemStack stack, int slotStart, int slotEnd(exclusive), boolean reverse + /** + * Checks if the shift+click happend in the network tool. + */ + @Override + public ItemStack transferStackInSlot(final EntityPlayer player, final int slotNumber) { + // Note: mergeItemStack args: ItemStack stack, int slotStart, int slotEnd(exclusive), boolean reverse - // Get the slot that was clicked on - Slot slot = this.getSlotOrNull( slotNumber ); + // Get the slot that was clicked on + Slot slot = this.getSlotOrNull(slotNumber); - boolean didMerge = false; + boolean didMerge = false; - // Did we get a slot, and does it have a valid item? - if( ( slot != null ) && ( slot.getHasStack() ) ) - { - // Get the slots item stack - ItemStack slotStack = slot.getStack(); + // Did we get a slot, and does it have a valid item? + if ((slot != null) && (slot.getHasStack())) { + // Get the slots item stack + ItemStack slotStack = slot.getStack(); - // Was the slot clicked in the player or hotbar inventory? - if( this.slotClickedWasInPlayerInventory( slotNumber ) || this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - // Attempt to merge with the upgrade inventory - didMerge = this.mergeSlotWithUpgrades( slotStack ); + // Was the slot clicked in the player or hotbar inventory? + if (this.slotClickedWasInPlayerInventory(slotNumber) || this.slotClickedWasInHotbarInventory(slotNumber)) { + // Attempt to merge with the upgrade inventory + didMerge = this.mergeSlotWithUpgrades(slotStack); - // Did we merge? - if( !didMerge ) - { - // Attempt to merge with the network tool - didMerge = this.mergeSlotWithNetworkTool( slotStack ); - } + // Did we merge? + if (!didMerge) { + // Attempt to merge with the network tool + didMerge = this.mergeSlotWithNetworkTool(slotStack); + } - // Did we merge? - if( !didMerge ) - { - // Attempt to swap - didMerge = this.swapSlotInventoryHotbar( slotNumber, slotStack ); - } - } - // Was the slot clicked in the upgrades? - else if( this.slotClickedWasInUpgrades( slotNumber ) ) - { - // Attempt to merge with the network tool - didMerge = this.mergeSlotWithNetworkTool( slotStack ); + // Did we merge? + if (!didMerge) { + // Attempt to swap + didMerge = this.swapSlotInventoryHotbar(slotNumber, slotStack); + } + } + // Was the slot clicked in the upgrades? + else if (this.slotClickedWasInUpgrades(slotNumber)) { + // Attempt to merge with the network tool + didMerge = this.mergeSlotWithNetworkTool(slotStack); - // Did we merge with the network tool? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } - // Was the slot clicked in the network tool? - else if( this.hasNetworkTool && this.slotClickedWasInNetworkTool( slotNumber ) ) - { - // Attempt to merge with the upgrade inventory - didMerge = this.mergeSlotWithUpgrades( slotStack ); + // Did we merge with the network tool? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } + // Was the slot clicked in the network tool? + else if (this.hasNetworkTool && this.slotClickedWasInNetworkTool(slotNumber)) { + // Attempt to merge with the upgrade inventory + didMerge = this.mergeSlotWithUpgrades(slotStack); - // Did we merge with the upgrades? - if( !didMerge ) - { - // Attempt to merge with the player inventory - didMerge = this.mergeSlotWithPlayerInventory( slotStack ); - } - } + // Did we merge with the upgrades? + if (!didMerge) { + // Attempt to merge with the player inventory + didMerge = this.mergeSlotWithPlayerInventory(slotStack); + } + } - // Were we able to merge? - if( !didMerge ) - { - return null; - } + // Were we able to merge? + if (!didMerge) { + return null; + } - // Did the merger drain the stack? - if( slotStack.stackSize == 0 ) - { - // Set the slot to have no item - slot.putStack( null ); - } + // Did the merger drain the stack? + if (slotStack.stackSize == 0) { + // Set the slot to have no item + slot.putStack(null); + } - // Inform the slot its stack changed; - slot.onSlotChanged(); + // Inform the slot its stack changed; + slot.onSlotChanged(); - // Sync - this.detectAndSendChanges(); - } + // Sync + this.detectAndSendChanges(); + } - // Done ( returning null prevents retrySlotClick from being called ) - return null; - } + // Done ( returning null prevents retrySlotClick from being called ) + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/container/ContainerWithPlayerInventory.java b/src/main/java/thaumicenergistics/common/container/ContainerWithPlayerInventory.java index 9eb1cd25..c2125e43 100644 --- a/src/main/java/thaumicenergistics/common/container/ContainerWithPlayerInventory.java +++ b/src/main/java/thaumicenergistics/common/container/ContainerWithPlayerInventory.java @@ -14,314 +14,293 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public abstract class ContainerWithPlayerInventory - extends TheContainerBase -{ - /** - * The number of rows in the player inventory - */ - private static int ROWS = 3; +public abstract class ContainerWithPlayerInventory extends TheContainerBase { + /** + * The number of rows in the player inventory + */ + private static int ROWS = 3; - /** - * The number of columns in the player inventory - */ - private static int COLUMNS = 9; + /** + * The number of columns in the player inventory + */ + private static int COLUMNS = 9; - /** - * The width and height of the slots - */ - protected static final int SLOT_SIZE = 18; + /** + * The width and height of the slots + */ + protected static final int SLOT_SIZE = 18; - /** - * X position offset for inventory slots - */ - private static final int INVENTORY_X_OFFSET = 8; + /** + * X position offset for inventory slots + */ + private static final int INVENTORY_X_OFFSET = 8; - /** - * Array of player hotbar slots - */ - private final Slot[] hotbarSlots = new Slot[ContainerWithPlayerInventory.COLUMNS]; + /** + * Array of player hotbar slots + */ + private final Slot[] hotbarSlots = new Slot[ContainerWithPlayerInventory.COLUMNS]; - /** - * Array of player inventory slots. - */ - private final Slot[] playerSlots = new Slot[ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS]; + /** + * Array of player inventory slots. + */ + private final Slot[] playerSlots = + new Slot[ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS]; - public ContainerWithPlayerInventory( final EntityPlayer player ) - { - super( player ); - } + public ContainerWithPlayerInventory(final EntityPlayer player) { + super(player); + } - /** - * Attempt to merge the specified slot stack with the hotbar inventory - * - * @param slotStack - * @return - */ - protected final boolean mergeSlotWithHotbarInventory( final ItemStack slotStack ) - { - return this.mergeItemStack( slotStack, this.hotbarSlots[0].slotNumber, - this.hotbarSlots[ContainerWithPlayerInventory.COLUMNS - 1].slotNumber + 1, false ); - } + /** + * Attempt to merge the specified slot stack with the hotbar inventory + * + * @param slotStack + * @return + */ + protected final boolean mergeSlotWithHotbarInventory(final ItemStack slotStack) { + return this.mergeItemStack( + slotStack, + this.hotbarSlots[0].slotNumber, + this.hotbarSlots[ContainerWithPlayerInventory.COLUMNS - 1].slotNumber + 1, + false); + } - /** - * Attempt to merge the specified slot stack with the player inventory - * - * @param slotStack - * @return - */ - protected final boolean mergeSlotWithPlayerInventory( final ItemStack slotStack ) - { - return this.mergeItemStack( slotStack, this.playerSlots[0].slotNumber, - this.playerSlots[( ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS ) - 1].slotNumber + 1, false ); - } + /** + * Attempt to merge the specified slot stack with the player inventory + * + * @param slotStack + * @return + */ + protected final boolean mergeSlotWithPlayerInventory(final ItemStack slotStack) { + return this.mergeItemStack( + slotStack, + this.playerSlots[0].slotNumber, + this.playerSlots[(ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS) - 1] + .slotNumber + + 1, + false); + } - /** - * Checks if the slot clicked was in the hotbar inventory - * - * @param slotNumber - * @return True if it was in the hotbar inventory, false otherwise. - */ - protected final boolean slotClickedWasInHotbarInventory( final int slotNumber ) - { - return ( slotNumber >= this.hotbarSlots[0].slotNumber ) && - ( slotNumber <= this.hotbarSlots[ContainerWithPlayerInventory.COLUMNS - 1].slotNumber ); - } + /** + * Checks if the slot clicked was in the hotbar inventory + * + * @param slotNumber + * @return True if it was in the hotbar inventory, false otherwise. + */ + protected final boolean slotClickedWasInHotbarInventory(final int slotNumber) { + return (slotNumber >= this.hotbarSlots[0].slotNumber) + && (slotNumber <= this.hotbarSlots[ContainerWithPlayerInventory.COLUMNS - 1].slotNumber); + } - /** - * Checks if the slot clicked was in the player inventory - * - * @param slotNumber - * @return True if it was in the player inventory, false otherwise. - */ - protected final boolean slotClickedWasInPlayerInventory( final int slotNumber ) - { - return ( slotNumber >= this.playerSlots[0].slotNumber ) && - ( slotNumber <= this.playerSlots[( ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS ) - - 1].slotNumber ); - } + /** + * Checks if the slot clicked was in the player inventory + * + * @param slotNumber + * @return True if it was in the player inventory, false otherwise. + */ + protected final boolean slotClickedWasInPlayerInventory(final int slotNumber) { + return (slotNumber >= this.playerSlots[0].slotNumber) + && (slotNumber + <= this.playerSlots[ + (ContainerWithPlayerInventory.COLUMNS * ContainerWithPlayerInventory.ROWS) - 1] + .slotNumber); + } - /** - * Attempt to move the item from hotbar <-> player inventory - * - * @param slotNumber - * @return - */ - protected final boolean swapSlotInventoryHotbar( final int slotNumber, final ItemStack slotStack ) - { - if( this.slotClickedWasInHotbarInventory( slotNumber ) ) - { - return this.mergeSlotWithPlayerInventory( slotStack ); - } - else if( this.slotClickedWasInPlayerInventory( slotNumber ) ) - { - return this.mergeSlotWithHotbarInventory( slotStack ); - } + /** + * Attempt to move the item from hotbar <-> player inventory + * + * @param slotNumber + * @return + */ + protected final boolean swapSlotInventoryHotbar(final int slotNumber, final ItemStack slotStack) { + if (this.slotClickedWasInHotbarInventory(slotNumber)) { + return this.mergeSlotWithPlayerInventory(slotStack); + } else if (this.slotClickedWasInPlayerInventory(slotNumber)) { + return this.mergeSlotWithHotbarInventory(slotStack); + } - return false; - } + return false; + } - /** - * Searches the players inventory & hotbar for the specified stack. - * - * @param searchStack - * @param amount - * @return - */ - @Nullable - protected final ItemStack takeItemFromPlayer( final ItemStack searchStack, final int amount ) - { - // Sanity check - if( ( searchStack == null ) || ( amount <= 0 ) ) - { - return null; - } + /** + * Searches the players inventory & hotbar for the specified stack. + * + * @param searchStack + * @param amount + * @return + */ + @Nullable + protected final ItemStack takeItemFromPlayer(final ItemStack searchStack, final int amount) { + // Sanity check + if ((searchStack == null) || (amount <= 0)) { + return null; + } - Slot matchingSlot = null; + Slot matchingSlot = null; - // Search inventory - for( Slot slot : this.playerSlots ) - { - // Empty? - if( !slot.getHasStack() ) - { - // Skip - continue; - } + // Search inventory + for (Slot slot : this.playerSlots) { + // Empty? + if (!slot.getHasStack()) { + // Skip + continue; + } - // Check for match - if( ThEUtils.areStacksEqualIgnoreAmount( searchStack, slot.getStack() ) ) - { - // Found match - matchingSlot = slot; - break; - } - } + // Check for match + if (ThEUtils.areStacksEqualIgnoreAmount(searchStack, slot.getStack())) { + // Found match + matchingSlot = slot; + break; + } + } - if( matchingSlot == null ) - { - // Search hotbar - for( Slot slot : this.hotbarSlots ) - { - // Empty? - if( !slot.getHasStack() ) - { - // Skip - continue; - } + if (matchingSlot == null) { + // Search hotbar + for (Slot slot : this.hotbarSlots) { + // Empty? + if (!slot.getHasStack()) { + // Skip + continue; + } - // Check for match - if( ThEUtils.areStacksEqualIgnoreAmount( searchStack, slot.getStack() ) ) - { - // Found match - matchingSlot = slot; - break; - } - } - } + // Check for match + if (ThEUtils.areStacksEqualIgnoreAmount(searchStack, slot.getStack())) { + // Found match + matchingSlot = slot; + break; + } + } + } - if( matchingSlot == null ) - { - // No matches - return null; - } + if (matchingSlot == null) { + // No matches + return null; + } - // Check amount - ItemStack matchStack = matchingSlot.getStack(); - if( matchStack.stackSize < amount ) - { - // Not enough to take - return null; - } + // Check amount + ItemStack matchStack = matchingSlot.getStack(); + if (matchStack.stackSize < amount) { + // Not enough to take + return null; + } - // Split - ItemStack result = matchStack.splitStack( amount ); + // Split + ItemStack result = matchStack.splitStack(amount); - // Anything left in the stack? - if( matchStack.stackSize == 0 ) - { - // Null the slot - matchingSlot.putStack( null ); - } - else - { - // Update the slot - matchingSlot.putStack( matchStack ); - } + // Anything left in the stack? + if (matchStack.stackSize == 0) { + // Null the slot + matchingSlot.putStack(null); + } else { + // Update the slot + matchingSlot.putStack(matchStack); + } - return result; - } + return result; + } - /** - * Binds the player inventory to this container. - * - * @param playerInventory - * Inventory to bind - * @param inventoryOffsetY - * The Y position offset for the slots - * @param hotbarPositionY - * The Y position offset for hotbar slots - */ - public final void bindPlayerInventory( final IInventory playerInventory, final int inventoryOffsetY, final int hotbarPositionY ) - { - // Hot-bar ID's 0-8 - for( int column = 0; column < ContainerWithPlayerInventory.COLUMNS; column++ ) - { - // Create the slot - this.hotbarSlots[column] = new Slot( playerInventory, column, - ContainerWithPlayerInventory.INVENTORY_X_OFFSET + ( column * ContainerWithPlayerInventory.SLOT_SIZE ), hotbarPositionY ); + /** + * Binds the player inventory to this container. + * + * @param playerInventory + * Inventory to bind + * @param inventoryOffsetY + * The Y position offset for the slots + * @param hotbarPositionY + * The Y position offset for hotbar slots + */ + public final void bindPlayerInventory( + final IInventory playerInventory, final int inventoryOffsetY, final int hotbarPositionY) { + // Hot-bar ID's 0-8 + for (int column = 0; column < ContainerWithPlayerInventory.COLUMNS; column++) { + // Create the slot + this.hotbarSlots[column] = new Slot( + playerInventory, + column, + ContainerWithPlayerInventory.INVENTORY_X_OFFSET + (column * ContainerWithPlayerInventory.SLOT_SIZE), + hotbarPositionY); - // Add the slot - this.addSlotToContainer( this.hotbarSlots[column] ); - } + // Add the slot + this.addSlotToContainer(this.hotbarSlots[column]); + } - // Main inventory ID's 9-36 - for( int row = 0; row < ContainerWithPlayerInventory.ROWS; row++ ) - { - for( int column = 0; column < ContainerWithPlayerInventory.COLUMNS; column++ ) - { - // Calculate index - int index = column + ( row * ContainerWithPlayerInventory.COLUMNS ); + // Main inventory ID's 9-36 + for (int row = 0; row < ContainerWithPlayerInventory.ROWS; row++) { + for (int column = 0; column < ContainerWithPlayerInventory.COLUMNS; column++) { + // Calculate index + int index = column + (row * ContainerWithPlayerInventory.COLUMNS); - // Create the slot - this.playerSlots[index] = new Slot( playerInventory, ContainerWithPlayerInventory.COLUMNS + index, - ContainerWithPlayerInventory.INVENTORY_X_OFFSET + ( column * ContainerWithPlayerInventory.SLOT_SIZE ), - ( row * ContainerWithPlayerInventory.SLOT_SIZE ) + inventoryOffsetY ); + // Create the slot + this.playerSlots[index] = new Slot( + playerInventory, + ContainerWithPlayerInventory.COLUMNS + index, + ContainerWithPlayerInventory.INVENTORY_X_OFFSET + + (column * ContainerWithPlayerInventory.SLOT_SIZE), + (row * ContainerWithPlayerInventory.SLOT_SIZE) + inventoryOffsetY); - // Add the slot - this.addSlotToContainer( this.playerSlots[index] ); - } - } - } + // Add the slot + this.addSlotToContainer(this.playerSlots[index]); + } + } + } - /** - * Gets all non-empty slot from the hotbar inventory. - * - * @return - */ - public final ArrayList getNonEmptySlotsFromHotbar() - { - ArrayList list = new ArrayList(); + /** + * Gets all non-empty slot from the hotbar inventory. + * + * @return + */ + public final ArrayList getNonEmptySlotsFromHotbar() { + ArrayList list = new ArrayList(); - for( Slot slot : this.hotbarSlots ) - { - if( slot.getHasStack() ) - { - list.add( slot ); - } - } + for (Slot slot : this.hotbarSlots) { + if (slot.getHasStack()) { + list.add(slot); + } + } - return list; - } + return list; + } - /** - * Gets all non-empty slot from the player inventory. - * - * @return - */ - public final ArrayList getNonEmptySlotsFromPlayerInventory() - { - ArrayList list = new ArrayList(); + /** + * Gets all non-empty slot from the player inventory. + * + * @return + */ + public final ArrayList getNonEmptySlotsFromPlayerInventory() { + ArrayList list = new ArrayList(); - for( Slot slot : this.playerSlots ) - { - if( slot.getHasStack() ) - { - list.add( slot ); - } - } + for (Slot slot : this.playerSlots) { + if (slot.getHasStack()) { + list.add(slot); + } + } - return list; - } + return list; + } - /** - * Returns the first slot that contains the item and has room for more, - * or the first empty slot if no non-full matches are found. - * - * @param stack - * @return - */ - public final Slot locateMergeSlot( final ItemStack stack ) - { - Slot emptySlot = null; + /** + * Returns the first slot that contains the item and has room for more, + * or the first empty slot if no non-full matches are found. + * + * @param stack + * @return + */ + public final Slot locateMergeSlot(final ItemStack stack) { + Slot emptySlot = null; - for( Slot slot : this.playerSlots ) - { - if( slot.getHasStack() ) - { - ItemStack slotStack = slot.getStack(); - // Same items, and room? - if( ( slotStack.stackSize < slotStack.getMaxStackSize() ) && slotStack.isItemEqual( stack ) && ItemStack.areItemStackTagsEqual(slotStack, stack)) - { - // Found merge slot - return slot; - } - } - else if( emptySlot == null ) - { - emptySlot = slot; - } - } - return emptySlot; - } + for (Slot slot : this.playerSlots) { + if (slot.getHasStack()) { + ItemStack slotStack = slot.getStack(); + // Same items, and room? + if ((slotStack.stackSize < slotStack.getMaxStackSize()) + && slotStack.isItemEqual(stack) + && ItemStack.areItemStackTagsEqual(slotStack, stack)) { + // Found merge slot + return slot; + } + } else if (emptySlot == null) { + emptySlot = slot; + } + } + return emptySlot; + } } diff --git a/src/main/java/thaumicenergistics/common/container/TheContainerBase.java b/src/main/java/thaumicenergistics/common/container/TheContainerBase.java index 60ec716e..052b1d59 100644 --- a/src/main/java/thaumicenergistics/common/container/TheContainerBase.java +++ b/src/main/java/thaumicenergistics/common/container/TheContainerBase.java @@ -15,122 +15,106 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public abstract class TheContainerBase - extends Container -{ - /** - * Maps slotNumber -> Slot - */ - private final HashMap slotMap = new HashMap(); +public abstract class TheContainerBase extends Container { + /** + * Maps slotNumber -> Slot + */ + private final HashMap slotMap = new HashMap(); - /** - * Set if the player is an MP player. - */ - private final EntityPlayerMP playerMP; + /** + * Set if the player is an MP player. + */ + private final EntityPlayerMP playerMP; - /** - * The player interacting with this container. - */ - protected final EntityPlayer player; + /** + * The player interacting with this container. + */ + protected final EntityPlayer player; - public TheContainerBase( final EntityPlayer player ) - { - // Set the player - this.player = player; - if( player instanceof EntityPlayerMP ) - { - this.playerMP = (EntityPlayerMP)player; - } - else - { - this.playerMP = null; - } - } + public TheContainerBase(final EntityPlayer player) { + // Set the player + this.player = player; + if (player instanceof EntityPlayerMP) { + this.playerMP = (EntityPlayerMP) player; + } else { + this.playerMP = null; + } + } - /** - * Adds a slot to the container and the slot map. - */ - @Override - protected Slot addSlotToContainer( @Nonnull final Slot slot ) - { - // Call super - super.addSlotToContainer( slot ); + /** + * Adds a slot to the container and the slot map. + */ + @Override + protected Slot addSlotToContainer(@Nonnull final Slot slot) { + // Call super + super.addSlotToContainer(slot); - // Map the slot - if( this.slotMap.put( slot.slotNumber, slot ) != null ) - { - ThELog.warning( "Duplicate Slot Number Detected: %d", slot.slotNumber ); - } + // Map the slot + if (this.slotMap.put(slot.slotNumber, slot) != null) { + ThELog.warning("Duplicate Slot Number Detected: %d", slot.slotNumber); + } - return slot; - } + return slot; + } - /** - * Detects server side changes to send to the player.
- * When modifying slots, return true to set {@code playerMP.isChangingQuantityOnly} to {@code false}, - * or set it directly with the player argument. - * - * @param playerMP - * - * @return - */ - protected boolean detectAndSendChangesMP( @Nonnull final EntityPlayerMP playerMP ) - { - return false; - } + /** + * Detects server side changes to send to the player.
+ * When modifying slots, return true to set {@code playerMP.isChangingQuantityOnly} to {@code false}, + * or set it directly with the player argument. + * + * @param playerMP + * + * @return + */ + protected boolean detectAndSendChangesMP(@Nonnull final EntityPlayerMP playerMP) { + return false; + } - @Override - public void detectAndSendChanges() - { - // Call super - super.detectAndSendChanges(); + @Override + public void detectAndSendChanges() { + // Call super + super.detectAndSendChanges(); - // MP player? - if( this.playerMP != null ) - { - if( this.detectAndSendChangesMP( this.playerMP ) ) - { - this.playerMP.isChangingQuantityOnly = false; + // MP player? + if (this.playerMP != null) { + if (this.detectAndSendChangesMP(this.playerMP)) { + this.playerMP.isChangingQuantityOnly = false; - // Call super - super.detectAndSendChanges(); - } - } - } + // Call super + super.detectAndSendChanges(); + } + } + } - /** - * Use getSlotOrNull. - */ - @Override - @Deprecated - public Slot getSlot( final int slotNumber ) - { - return super.getSlot( slotNumber ); - } + /** + * Use getSlotOrNull. + */ + @Override + @Deprecated + public Slot getSlot(final int slotNumber) { + return super.getSlot(slotNumber); + } - /** - * Returns the slot with the specified slot number or null. - * - * @param slotNumber - * @return - */ - @Nullable - public Slot getSlotOrNull( final int slotNumber ) - { - return this.slotMap.getOrDefault( slotNumber, null ); - } + /** + * Returns the slot with the specified slot number or null. + * + * @param slotNumber + * @return + */ + @Nullable + public Slot getSlotOrNull(final int slotNumber) { + return this.slotMap.getOrDefault(slotNumber, null); + } - /** - * Clears the slot map. - */ - @Override - public void onContainerClosed( @Nonnull final EntityPlayer player ) - { - // Call super - super.onContainerClosed( player ); - - // Clear the map - this.slotMap.clear(); - } + /** + * Clears the slot map. + */ + @Override + public void onContainerClosed(@Nonnull final EntityPlayer player) { + // Call super + super.onContainerClosed(player); + // Clear the map + this.slotMap.clear(); + } } diff --git a/src/main/java/thaumicenergistics/common/container/slot/SlotArcaneCraftingResult.java b/src/main/java/thaumicenergistics/common/container/slot/SlotArcaneCraftingResult.java index 1801cf0e..c01d5d3a 100644 --- a/src/main/java/thaumicenergistics/common/container/slot/SlotArcaneCraftingResult.java +++ b/src/main/java/thaumicenergistics/common/container/slot/SlotArcaneCraftingResult.java @@ -18,203 +18,181 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class SlotArcaneCraftingResult - extends SlotCrafting -{ - /** - * The inventory of the terminal - */ - private IInventory terminalInventory; +public class SlotArcaneCraftingResult extends SlotCrafting { + /** + * The inventory of the terminal + */ + private IInventory terminalInventory; - /** - * Aspects required for this craft. - */ - private AspectList craftingAspects = null; + /** + * Aspects required for this craft. + */ + private AspectList craftingAspects = null; - /** - * Itemstack that represents the wand. - */ - private ItemStack wand; + /** + * Itemstack that represents the wand. + */ + private ItemStack wand; - /** - * The wand item. - */ - private ItemWandCasting wandItem; + /** + * The wand item. + */ + private ItemWandCasting wandItem; - /** - * The container that hosts this slot. - */ - private ContainerPartArcaneCraftingTerminal hostContianer; + /** + * The container that hosts this slot. + */ + private ContainerPartArcaneCraftingTerminal hostContianer; - /** - * Creates the slot - * - * @param player - * @param terminalInventory - * @param slotInventory - * @param slotIndex - * @param xPos - * @param yPos - */ - public SlotArcaneCraftingResult( final EntityPlayer player, final ContainerPartArcaneCraftingTerminal hostContianer, - final IInventory terminalInventory, final IInventory slotInventory, final int slotIndex, final int xPos, - final int yPos ) - { - // Call super - super( player, terminalInventory, slotInventory, slotIndex, xPos, yPos ); + /** + * Creates the slot + * + * @param player + * @param terminalInventory + * @param slotInventory + * @param slotIndex + * @param xPos + * @param yPos + */ + public SlotArcaneCraftingResult( + final EntityPlayer player, + final ContainerPartArcaneCraftingTerminal hostContianer, + final IInventory terminalInventory, + final IInventory slotInventory, + final int slotIndex, + final int xPos, + final int yPos) { + // Call super + super(player, terminalInventory, slotInventory, slotIndex, xPos, yPos); - // Set the matrix - this.terminalInventory = terminalInventory; + // Set the matrix + this.terminalInventory = terminalInventory; - // Set the container - this.hostContianer = hostContianer; - } + // Set the container + this.hostContianer = hostContianer; + } - @Override - public void onPickupFromSlot( final EntityPlayer player, final ItemStack itemStack ) - { - // Call the transfer - this.onPickupFromSlotViaTransfer( player, itemStack ); + @Override + public void onPickupFromSlot(final EntityPlayer player, final ItemStack itemStack) { + // Call the transfer + this.onPickupFromSlotViaTransfer(player, itemStack); - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Send any changes to the client - this.hostContianer.detectAndSendChanges(); - } - } + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Send any changes to the client + this.hostContianer.detectAndSendChanges(); + } + } - /** - * Similar to the onPickupFromSlot, with the key difference being - * that this function call will not update the client. - * - * @param player - * @param itemStack - */ - public void onPickupFromSlotViaTransfer( final EntityPlayer player, final ItemStack itemStack ) - { - // Fire crafting event - FMLCommonHandler.instance().firePlayerCraftingEvent( player, itemStack, this.terminalInventory ); + /** + * Similar to the onPickupFromSlot, with the key difference being + * that this function call will not update the client. + * + * @param player + * @param itemStack + */ + public void onPickupFromSlotViaTransfer(final EntityPlayer player, final ItemStack itemStack) { + // Fire crafting event + FMLCommonHandler.instance().firePlayerCraftingEvent(player, itemStack, this.terminalInventory); - // Seems to fire achievements, and handles the item creation - this.onCrafting( itemStack ); + // Seems to fire achievements, and handles the item creation + this.onCrafting(itemStack); - if( EffectiveSide.isClientSide() ) - { - // No more work on the client side. - return; - } + if (EffectiveSide.isClientSide()) { + // No more work on the client side. + return; + } - // Arcane recipe? - if( ( this.craftingAspects != null ) ) - { - // Consume wand vis - this.wandItem.consumeAllVisCrafting( this.wand, player, this.craftingAspects, true ); + // Arcane recipe? + if ((this.craftingAspects != null)) { + // Consume wand vis + this.wandItem.consumeAllVisCrafting(this.wand, player, this.craftingAspects, true); + } - } + // Loop over all crafting slots + for (int slotIndex = 0; slotIndex < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE; slotIndex++) { + // Get the itemstack in this slot + ItemStack slotStack = this.terminalInventory.getStackInSlot(slotIndex); - // Loop over all crafting slots - for( int slotIndex = 0; slotIndex < ContainerPartArcaneCraftingTerminal.CRAFTING_GRID_TOTAL_SIZE; slotIndex++ ) - { - // Get the itemstack in this slot - ItemStack slotStack = this.terminalInventory.getStackInSlot( slotIndex ); + // Is there a stack? + if (slotStack == null) { + // Next + continue; + } - // Is there a stack? - if( slotStack == null ) - { - // Next - continue; - } + // Checked at the end to see if we need to decrement the slot + boolean shouldDecrement = true; - // Checked at the end to see if we need to decrement the slot - boolean shouldDecrement = true; + // Does the item have a container? + if (slotStack.getItem().hasContainerItem(slotStack)) { + // Get the container item + ItemStack slotContainerStack = slotStack.getItem().getContainerItem(slotStack); - // Does the item have a container? - if( slotStack.getItem().hasContainerItem( slotStack ) ) - { - // Get the container item - ItemStack slotContainerStack = slotStack.getItem().getContainerItem( slotStack ); + // Is the container item damage-able? + if (slotContainerStack.isItemStackDamageable()) { + // Did we kill it? + if (slotContainerStack.getItemDamage() >= slotContainerStack.getMaxDamage()) { + // Fire forge event + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, slotContainerStack)); - // Is the container item damage-able? - if( slotContainerStack.isItemStackDamageable() ) - { - // Did we kill it? - if( slotContainerStack.getItemDamage() >= slotContainerStack.getMaxDamage() ) - { - // Fire forge event - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, slotContainerStack ) ); + // Null the container stack + slotContainerStack = null; + } + } - // Null the container stack - slotContainerStack = null; - } - } + // Did we not kill the container item? + if (slotContainerStack != null) { + /* + * Should the item stay in the crafting grid, or if it is supposed to go back to the + * players inventory but can't? + */ + if (!slotStack.getItem().doesContainerItemLeaveCraftingGrid(slotStack) + || !player.inventory.addItemStackToInventory(slotContainerStack)) { + // Place it back in the grid + this.terminalInventory.setInventorySlotContents(slotIndex, slotContainerStack); - // Did we not kill the container item? - if( slotContainerStack != null ) - { - /* - * Should the item stay in the crafting grid, or if it is supposed to go back to the - * players inventory but can't? - */ - if( !slotStack.getItem().doesContainerItemLeaveCraftingGrid( slotStack ) || - !player.inventory.addItemStackToInventory( slotContainerStack ) ) - { - // Place it back in the grid - this.terminalInventory.setInventorySlotContents( slotIndex, slotContainerStack ); + // Set NOT to decrement + shouldDecrement = false; + } + } + } - // Set NOT to decrement - shouldDecrement = false; - } - } - } + // If decrementing it would result in it being empty, ask the ME system for a replenishment. + if (shouldDecrement && (slotStack.stackSize == 1)) { + // First check if we can replenish it from the ME network + ItemStack replenishment = this.hostContianer.requestCraftingReplenishment(slotStack); - // If decrementing it would result in it being empty, ask the ME system for a replenishment. - if( shouldDecrement && ( slotStack.stackSize == 1 ) ) - { - // First check if we can replenish it from the ME network - ItemStack replenishment = this.hostContianer.requestCraftingReplenishment( slotStack ); + // Did we get a replenishment? + if (replenishment != null) { + // Did the item change? + if (!ItemStack.areItemStacksEqual(replenishment, slotStack)) { + // Set the slot contents to the replenishment + this.terminalInventory.setInventorySlotContents(slotIndex, replenishment); + } - // Did we get a replenishment? - if( replenishment != null ) - { - // Did the item change? - if( !ItemStack.areItemStacksEqual( replenishment, slotStack ) ) - { - // Set the slot contents to the replenishment - this.terminalInventory.setInventorySlotContents( slotIndex, replenishment ); - } + // And mark not to decrement + shouldDecrement = false; + } + } - // And mark not to decrement - shouldDecrement = false; - } - } + // Decrement the stack? + if (shouldDecrement) { + this.terminalInventory.decrStackSize(slotIndex, 1); + } + } + } - // Decrement the stack? - if( shouldDecrement ) - { - this.terminalInventory.decrStackSize( slotIndex, 1 ); - } - - } - } - - public void setResultAspects( final AspectList aspectList ) - { - this.craftingAspects = aspectList; - } - - public void setWand( final ItemStack wand ) - { - if( wand != null ) - { - this.wand = wand; - this.wandItem = (ItemWandCasting)wand.getItem(); - } - else - { - this.wand = null; - this.wandItem = null; - } - } + public void setResultAspects(final AspectList aspectList) { + this.craftingAspects = aspectList; + } + public void setWand(final ItemStack wand) { + if (wand != null) { + this.wand = wand; + this.wandItem = (ItemWandCasting) wand.getItem(); + } else { + this.wand = null; + this.wandItem = null; + } + } } diff --git a/src/main/java/thaumicenergistics/common/container/slot/SlotArmor.java b/src/main/java/thaumicenergistics/common/container/slot/SlotArmor.java index a4fb1917..3e542e44 100644 --- a/src/main/java/thaumicenergistics/common/container/slot/SlotArmor.java +++ b/src/main/java/thaumicenergistics/common/container/slot/SlotArmor.java @@ -15,70 +15,67 @@ import thaumcraft.api.IVisDiscountGear; * @author Nividica * */ -public class SlotArmor - extends Slot -{ +public class SlotArmor extends Slot { - /** - * The armor type. - */ - private final int armorType; + /** + * The armor type. + */ + private final int armorType; - /** - * If true will only accept vis discount armor. - */ - private final boolean restrictToVisArmor; + /** + * If true will only accept vis discount armor. + */ + private final boolean restrictToVisArmor; - /** - * - * @param inventory - * @param index - * @param x - * @param y - * @param armorType - * 0: Helmet, 1: Chest, 2: Legs, 3: Boots - */ - public SlotArmor( final IInventory inventory, final int index, final int x, final int y, final int armorType, final boolean restrictToVisArmor ) - { - // Call super - super( inventory, index, x, y ); + /** + * + * @param inventory + * @param index + * @param x + * @param y + * @param armorType + * 0: Helmet, 1: Chest, 2: Legs, 3: Boots + */ + public SlotArmor( + final IInventory inventory, + final int index, + final int x, + final int y, + final int armorType, + final boolean restrictToVisArmor) { + // Call super + super(inventory, index, x, y); - // Set the armor type - this.armorType = armorType; + // Set the armor type + this.armorType = armorType; - // Set if the armor is restricted - this.restrictToVisArmor = restrictToVisArmor; - } + // Set if the armor is restricted + this.restrictToVisArmor = restrictToVisArmor; + } - @Override - @SideOnly(Side.CLIENT) - public IIcon getBackgroundIconIndex() - { - return ItemArmor.func_94602_b( this.armorType ); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getBackgroundIconIndex() { + return ItemArmor.func_94602_b(this.armorType); + } - @Override - public int getSlotStackLimit() - { - return 1; - } + @Override + public int getSlotStackLimit() { + return 1; + } - @Override - public boolean isItemValid( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return false; - } + @Override + public boolean isItemValid(final ItemStack itemStack) { + if (itemStack == null) { + return false; + } - // Vis armor? - if( ( this.restrictToVisArmor && !( itemStack.getItem() instanceof IVisDiscountGear ) ) ) - { - return false; - } - - // Valid armor for this slot? - return itemStack.getItem().isValidArmor( itemStack, this.armorType, null ); - } + // Vis armor? + if ((this.restrictToVisArmor && !(itemStack.getItem() instanceof IVisDiscountGear))) { + return false; + } + // Valid armor for this slot? + return itemStack.getItem().isValidArmor(itemStack, this.armorType, null); + } } diff --git a/src/main/java/thaumicenergistics/common/container/slot/SlotNetworkTool.java b/src/main/java/thaumicenergistics/common/container/slot/SlotNetworkTool.java index 6b50af48..4dc5ad54 100644 --- a/src/main/java/thaumicenergistics/common/container/slot/SlotNetworkTool.java +++ b/src/main/java/thaumicenergistics/common/container/slot/SlotNetworkTool.java @@ -12,50 +12,43 @@ import net.minecraft.item.ItemStack; * @author Nividica * */ -public class SlotNetworkTool - extends Slot -{ - /** - * Creates the slot. - * - * @param inventory - * The inventory of the network tool. - * @param slotIndex - * Index of the slot - * @param xDisplayPosition - * X position of the slot - * @param yDisplayPosition - * Y position of the slot - */ - public SlotNetworkTool( final INetworkTool inventory, final int slotIndex, final int xDisplayPosition, final int yDisplayPosition ) - { - // Pass to super - super( inventory, slotIndex, xDisplayPosition, yDisplayPosition ); +public class SlotNetworkTool extends Slot { + /** + * Creates the slot. + * + * @param inventory + * The inventory of the network tool. + * @param slotIndex + * Index of the slot + * @param xDisplayPosition + * X position of the slot + * @param yDisplayPosition + * Y position of the slot + */ + public SlotNetworkTool( + final INetworkTool inventory, final int slotIndex, final int xDisplayPosition, final int yDisplayPosition) { + // Pass to super + super(inventory, slotIndex, xDisplayPosition, yDisplayPosition); + } - } + /** + * Called to see if an item can go in this inventory + */ + @Override + public boolean isItemValid(final ItemStack itemStack) { + // Is the itemstack valid? + if (itemStack != null) { + // Get the item + Item item = itemStack.getItem(); - /** - * Called to see if an item can go in this inventory - */ - @Override - public boolean isItemValid( final ItemStack itemStack ) - { - // Is the itemstack valid? - if( itemStack != null ) - { - // Get the item - Item item = itemStack.getItem(); - - // Is the item an upgrade card? - if( item instanceof IUpgradeModule ) - { - // True if a valid upgrade - return ( (IUpgradeModule)item ).getType( itemStack ) != null; - } - } - - // Not an upgrade or invalid itemstack - return false; - } + // Is the item an upgrade card? + if (item instanceof IUpgradeModule) { + // True if a valid upgrade + return ((IUpgradeModule) item).getType(itemStack) != null; + } + } + // Not an upgrade or invalid itemstack + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/container/slot/SlotRestrictive.java b/src/main/java/thaumicenergistics/common/container/slot/SlotRestrictive.java index 46a84161..f373a80f 100644 --- a/src/main/java/thaumicenergistics/common/container/slot/SlotRestrictive.java +++ b/src/main/java/thaumicenergistics/common/container/slot/SlotRestrictive.java @@ -10,38 +10,34 @@ import net.minecraft.item.ItemStack; * @author Nividica * */ -public class SlotRestrictive - extends Slot -{ - private int myIndex; +public class SlotRestrictive extends Slot { + private int myIndex; - /** - * Create the slot. - * - * @param inventory - * Inventory it belongs to. - * @param index - * Index of the slot - * @param x - * X position of the slot - * @param y - * Y position of the slot - */ - public SlotRestrictive( final IInventory inventory, final int index, final int x, final int y ) - { - // Pass to super - super( inventory, index, x, y ); + /** + * Create the slot. + * + * @param inventory + * Inventory it belongs to. + * @param index + * Index of the slot + * @param x + * X position of the slot + * @param y + * Y position of the slot + */ + public SlotRestrictive(final IInventory inventory, final int index, final int x, final int y) { + // Pass to super + super(inventory, index, x, y); - // Set this index - this.myIndex = index; - } + // Set this index + this.myIndex = index; + } - /** - * Pass the is valid call to the inventory. - */ - @Override - public boolean isItemValid( final ItemStack itemstack ) - { - return this.inventory.isItemValidForSlot( this.myIndex, itemstack ); - } + /** + * Pass the is valid call to the inventory. + */ + @Override + public boolean isItemValid(final ItemStack itemstack) { + return this.inventory.isItemValidForSlot(this.myIndex, itemstack); + } } diff --git a/src/main/java/thaumicenergistics/common/entities/AIAENetworkGolem.java b/src/main/java/thaumicenergistics/common/entities/AIAENetworkGolem.java index d9ce46a5..779d898d 100644 --- a/src/main/java/thaumicenergistics/common/entities/AIAENetworkGolem.java +++ b/src/main/java/thaumicenergistics/common/entities/AIAENetworkGolem.java @@ -24,380 +24,352 @@ import thaumicenergistics.common.items.ItemGolemWirelessBackpack; * @author Nividica * */ -public abstract class AIAENetworkGolem - extends EntityAIBase -{ - protected class NetworkHandler - extends WirelessAELink - { - /** - * The maximum number of items the golem can inject/extract per update. - */ - private final int maxItemRate; +public abstract class AIAENetworkGolem extends EntityAIBase { + protected class NetworkHandler extends WirelessAELink { + /** + * The maximum number of items the golem can inject/extract per update. + */ + private final int maxItemRate; - /** - * The maximum amount of fluid, in mb, the golem can inject/extract per update. - */ - private final int maxFluidRate; + /** + * The maximum amount of fluid, in mb, the golem can inject/extract per update. + */ + private final int maxFluidRate; - /** - * The maximum amount of essentia the golem can inject/extract per update. - */ - private final int maxEssentiaRate; + /** + * The maximum amount of essentia the golem can inject/extract per update. + */ + private final int maxEssentiaRate; - /** - * Data associated with the wireless state of the backpack. - */ - public final WirelessGolemHandler.WirelessServerData wirelessStateData; + /** + * Data associated with the wireless state of the backpack. + */ + public final WirelessGolemHandler.WirelessServerData wirelessStateData; - public NetworkHandler( final WirelessGolemHandler.WirelessServerData wsd, final int maxItems, final int maxFluids, final int maxEssentia ) - { - // Call super - super( null, wsd.encryptionKey ); + public NetworkHandler( + final WirelessGolemHandler.WirelessServerData wsd, + final int maxItems, + final int maxFluids, + final int maxEssentia) { + // Call super + super(null, wsd.encryptionKey); - // Set maximums - this.maxItemRate = maxItems; - this.maxFluidRate = maxFluids; - this.maxEssentiaRate = maxEssentia; + // Set maximums + this.maxItemRate = maxItems; + this.maxFluidRate = maxFluids; + this.maxEssentiaRate = maxEssentia; - // Set state data - this.wirelessStateData = wsd; + // Set state data + this.wirelessStateData = wsd; - // Attempt to connect to AP - this.isConnected(); + // Attempt to connect to AP + this.isConnected(); + } - } + @Override + protected int getUserPositionX() { + return (int) AIAENetworkGolem.this.golem.posX; + } - @Override - protected int getUserPositionX() - { - return (int)AIAENetworkGolem.this.golem.posX; - } + @Override + protected int getUserPositionY() { + return (int) AIAENetworkGolem.this.golem.posY; + } - @Override - protected int getUserPositionY() - { - return (int)AIAENetworkGolem.this.golem.posY; - } + @Override + protected int getUserPositionZ() { + return (int) AIAENetworkGolem.this.golem.posZ; + } - @Override - protected int getUserPositionZ() - { - return (int)AIAENetworkGolem.this.golem.posZ; - } + @Override + protected World getUserWorld() { + return AIAENetworkGolem.this.golem.worldObj; + } - @Override - protected World getUserWorld() - { - return AIAENetworkGolem.this.golem.worldObj; - } + @Override + protected boolean hasPowerToCommunicate() { + // MAGIC GOLEM POWER! YEAH!! + return true; + } - @Override - protected boolean hasPowerToCommunicate() - { - // MAGIC GOLEM POWER! YEAH!! - return true; - } + /** + * Attempts to deposit the itemstack into the AE system. + * The {@code stack.stacksize} will change according to how many items were left over after the deposit. + * + * @param stack + */ + public void depositStack(final ItemStack stack) { + // Get the item monitor + IMEMonitor monitor = this.getItemInventory(); + if (monitor == null) { + return; + } - /** - * Attempts to deposit the itemstack into the AE system. - * The {@code stack.stacksize} will change according to how many items were left over after the deposit. - * - * @param stack - */ - public void depositStack( final ItemStack stack ) - { - // Get the item monitor - IMEMonitor monitor = this.getItemInventory(); - if( monitor == null ) - { - return; - } + // Create the AE stack + IAEItemStack aeStack = AEApi.instance().storage().createItemStack(stack); - // Create the AE stack - IAEItemStack aeStack = AEApi.instance().storage().createItemStack( stack ); + // Set size + int depositSize = Math.min(stack.stackSize, this.maxItemRate); + aeStack.setStackSize(depositSize); - // Set size - int depositSize = Math.min( stack.stackSize, this.maxItemRate ); - aeStack.setStackSize( depositSize ); + // Deposit + IAEItemStack rejected = + AEApi.instance().storage().poweredInsert(this.getEnergyGrid(), monitor, aeStack, this.actionSource); + if (rejected != null) { + depositSize -= (int) rejected.getStackSize(); + } - // Deposit - IAEItemStack rejected = AEApi.instance().storage().poweredInsert( this.getEnergyGrid(), monitor, aeStack, this.actionSource ); - if( rejected != null ) - { - depositSize -= (int)rejected.getStackSize(); - } + // Reduce stack by number of items deposited + stack.stackSize -= depositSize; + } - // Reduce stack by number of items deposited - stack.stackSize -= depositSize; - } + /** + * Extracts essentia from the network. + * + * @param aspect + * @param amount + * @param mode + * @return The amount extracted. + */ + public long extractEssentia(final Aspect aspect, final int amount, final Actionable mode) { + // Get the essentia monitor + IMEEssentiaMonitor monitor = this.getEssentiaInventory(); + if (monitor == null) { + return 0; + } - /** - * Extracts essentia from the network. - * - * @param aspect - * @param amount - * @param mode - * @return The amount extracted. - */ - public long extractEssentia( final Aspect aspect, final int amount, final Actionable mode ) - { - // Get the essentia monitor - IMEEssentiaMonitor monitor = this.getEssentiaInventory(); - if( monitor == null ) - { - return 0; - } + return monitor.extractEssentia( + aspect, + Math.min(amount, this.maxEssentiaRate), + mode, + this.actionSource, + mode == Actionable.MODULATE); + } - return monitor.extractEssentia( aspect, Math.min( amount, this.maxEssentiaRate ), mode, this.actionSource, mode == Actionable.MODULATE ); + /** + * Extracts fluids from the network. + * + * @param target + * @return + */ + public FluidStack extractFluid(final FluidStack target) { + // Get the fluid monitor + IMEMonitor monitor = this.getFluidInventory(); + if (monitor == null) { + return null; + } - } + // Get power grid + IEnergyGrid eGrid = this.getEnergyGrid(); + if (eGrid == null) { + return null; + } - /** - * Extracts fluids from the network. - * - * @param target - * @return - */ - public FluidStack extractFluid( final FluidStack target ) - { - // Get the fluid monitor - IMEMonitor monitor = this.getFluidInventory(); - if( monitor == null ) - { - return null; - } + // Calculate request size + long requestSize = Math.min(target.amount, this.maxFluidRate); - // Get power grid - IEnergyGrid eGrid = this.getEnergyGrid(); - if( eGrid == null ) - { - return null; - } + // Calculate power required + double pwrReq = requestSize / 100.0; + if (eGrid.extractAEPower(pwrReq, Actionable.SIMULATE, PowerMultiplier.CONFIG) < pwrReq) { + // Not enough power + return null; + } - // Calculate request size - long requestSize = Math.min( target.amount, this.maxFluidRate ); + // Create the fluid stack + IAEFluidStack aeRequest = AEApi.instance().storage().createFluidStack(target); - // Calculate power required - double pwrReq = requestSize / 100.0; - if( eGrid.extractAEPower( pwrReq, Actionable.SIMULATE, PowerMultiplier.CONFIG ) < pwrReq ) - { - // Not enough power - return null; - } + // Set size + aeRequest.setStackSize(requestSize); - // Create the fluid stack - IAEFluidStack aeRequest = AEApi.instance().storage().createFluidStack( target ); + // Extract + IAEFluidStack extracted = monitor.extractItems(aeRequest, Actionable.MODULATE, this.actionSource); + if (extracted == null) { + return null; + } - // Set size - aeRequest.setStackSize( requestSize ); + // Take power + pwrReq = extracted.getStackSize() / 100.0; + eGrid.extractAEPower(pwrReq, Actionable.MODULATE, PowerMultiplier.CONFIG); - // Extract - IAEFluidStack extracted = monitor.extractItems( aeRequest, Actionable.MODULATE, this.actionSource ); - if( extracted == null ) - { - return null; - } + return extracted.getFluidStack(); + } - // Take power - pwrReq = extracted.getStackSize() / 100.0; - eGrid.extractAEPower( pwrReq, Actionable.MODULATE, PowerMultiplier.CONFIG ); + /** + * Extracts items from the network. + * + * @param target + * @return Extracted stack. + */ + public ItemStack extractStack(final ItemStack target) { + // Get the item monitor + IMEMonitor monitor = this.getItemInventory(); + if (monitor == null) { + return null; + } - return extracted.getFluidStack(); + // Create the AE stack + IAEItemStack aeRequest = AEApi.instance().storage().createItemStack(target); - } + // Set size + aeRequest.setStackSize(Math.min(target.stackSize, this.maxItemRate)); - /** - * Extracts items from the network. - * - * @param target - * @return Extracted stack. - */ - public ItemStack extractStack( final ItemStack target ) - { - // Get the item monitor - IMEMonitor monitor = this.getItemInventory(); - if( monitor == null ) - { - return null; - } + // Extract + IAEItemStack extracted = AEApi.instance() + .storage() + .poweredExtraction(this.getEnergyGrid(), monitor, aeRequest, this.actionSource); + if (extracted == null) { + return null; + } - // Create the AE stack - IAEItemStack aeRequest = AEApi.instance().storage().createItemStack( target ); + return extracted.getItemStack(); + } - // Set size - aeRequest.setStackSize( Math.min( target.stackSize, this.maxItemRate ) ); + /** + * Inserts essentia into the network. + * + * @param aspect + * @param amount + * @return Amount injected + */ + public long insertEssentia(final Aspect aspect, final int amount) { + // Get the essentia monitor + IMEEssentiaMonitor monitor = this.getEssentiaInventory(); + if (monitor == null) { + return 0; + } - // Extract - IAEItemStack extracted = AEApi.instance().storage().poweredExtraction( this.getEnergyGrid(), monitor, aeRequest, this.actionSource ); - if( extracted == null ) - { - return null; - } + // Calculate the amount to inject + int amountToInject = Math.min(amount, this.maxEssentiaRate); - return extracted.getItemStack(); - } + // Attempt to inject + long amountRejected = + monitor.injectEssentia(aspect, amountToInject, Actionable.MODULATE, this.actionSource, true); - /** - * Inserts essentia into the network. - * - * @param aspect - * @param amount - * @return Amount injected - */ - public long insertEssentia( final Aspect aspect, final int amount ) - { - // Get the essentia monitor - IMEEssentiaMonitor monitor = this.getEssentiaInventory(); - if( monitor == null ) - { - return 0; - } + // Return the amount that was injected + return amountToInject - amountRejected; + } - // Calculate the amount to inject - int amountToInject = Math.min( amount, this.maxEssentiaRate ); + /** + * Checks if the network can be interacted with. + * + * @return + */ + @Override + public boolean isConnected() { + // Connected to network? + this.wirelessStateData.isInRange = super.isConnected(); + return this.wirelessStateData.isInRange; + } + } - // Attempt to inject - long amountRejected = monitor.injectEssentia( aspect, amountToInject, Actionable.MODULATE, this.actionSource, true ); + private static final int NETWORK_COOLDOWN = 20; - // Return the amount that was injected - return amountToInject - amountRejected; - } + /** + *
+     * Base     100, 250, 500
+     * Advanced 200, 500, 1000
+     * 
+ */ + private static final int[] FLUID_RATES = new int[] {100, 250, 500}; - /** - * Checks if the network can be interacted with. - * - * @return - */ - @Override - public boolean isConnected() - { - // Connected to network? - this.wirelessStateData.isInRange = super.isConnected(); - return this.wirelessStateData.isInRange; - } + /** + *
+     * Base      8, 24, 32
+     * Advanced 16, 48, 64
+     * 
+ */ + private static final int[] ITEM_RATES = new int[] {8, 24, 32}; - } + /** + *
+     * Base     4, 12, 16
+     * Advanced 8, 24, 32
+     * 
+ */ + private static final int[] ESS_RATES = new int[] {4, 12, 16}; - private static final int NETWORK_COOLDOWN = 20; + /** + * How many ticks until the golem can interact with the network again. + */ + private int actionTimer = 0; - /** - *
-	 * Base     100, 250, 500
-	 * Advanced 200, 500, 1000
-	 * 
- */ - private static final int[] FLUID_RATES = new int[] { 100, 250, 500 }; + /** + * Handles AE network communication. + */ + public final NetworkHandler network; - /** - *
-	 * Base      8, 24, 32
-	 * Advanced 16, 48, 64
-	 * 
- */ - private static final int[] ITEM_RATES = new int[] { 8, 24, 32 }; + /** + * The golem the script is attached to. + */ + protected final EntityGolemBase golem; - /** - *
-	 * Base     4, 12, 16
-	 * Advanced 8, 24, 32
-	 * 
- */ - private static final int[] ESS_RATES = new int[] { 4, 12, 16 }; + public AIAENetworkGolem(final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd) { + // Set the golem + this.golem = golem; - /** - * How many ticks until the golem can interact with the network again. - */ - private int actionTimer = 0; + // Get rate multiplier + int rateMult = (golem.advanced ? 2 : 1); - /** - * Handles AE network communication. - */ - public final NetworkHandler network; + // Get number of order upgrades + int orderUpgrades = this.golem.getUpgradeAmount(GolemUpgradeTypes.Order.upgradeID); + if (orderUpgrades > 2) { + orderUpgrades = 2; + } else if (orderUpgrades < 0) { + orderUpgrades = 0; + } - /** - * The golem the script is attached to. - */ - protected final EntityGolemBase golem; + // Set interaction maximums + int maxItems = AIAENetworkGolem.ITEM_RATES[orderUpgrades] * rateMult; + int maxEssentia = AIAENetworkGolem.ESS_RATES[orderUpgrades] * rateMult; + int maxFluids = AIAENetworkGolem.FLUID_RATES[orderUpgrades] * rateMult; - public AIAENetworkGolem( final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd ) - { - // Set the golem - this.golem = golem; + // Create the network handler + this.network = new NetworkHandler(wsd, maxItems, maxFluids, maxEssentia); + } - // Get rate multiplier - int rateMult = ( golem.advanced ? 2 : 1 ); + /** + * Called to decrement the action timer. + * + * @return True if cooled down. + */ + private boolean cooledDown() { + if (this.actionTimer > 0) { + --this.actionTimer; + return false; + } + return true; + } - // Get number of order upgrades - int orderUpgrades = this.golem.getUpgradeAmount( GolemUpgradeTypes.Order.upgradeID ); - if( orderUpgrades > 2 ) - { - orderUpgrades = 2; - } - else if( orderUpgrades < 0 ) - { - orderUpgrades = 0; - } + /** + * + */ + private void restartNetworkCooldown() { + // Reset network timer + this.actionTimer = AIAENetworkGolem.NETWORK_COOLDOWN; + } - // Set interaction maximums - int maxItems = AIAENetworkGolem.ITEM_RATES[orderUpgrades] * rateMult; - int maxEssentia = AIAENetworkGolem.ESS_RATES[orderUpgrades] * rateMult; - int maxFluids = AIAENetworkGolem.FLUID_RATES[orderUpgrades] * rateMult; + /** + * Return true if network interaction is required this update. + * + * @return + */ + protected abstract boolean needsNetworkNow(); - // Create the network handler - this.network = new NetworkHandler( wsd, maxItems, maxFluids, maxEssentia ); - } + @Override + public final boolean shouldExecute() { + // Check the network timer + if (this.cooledDown()) { + this.restartNetworkCooldown(); - /** - * Called to decrement the action timer. - * - * @return True if cooled down. - */ - private boolean cooledDown() - { - if( this.actionTimer > 0 ) - { - --this.actionTimer; - return false; - } - return true; - } - - /** - * - */ - private void restartNetworkCooldown() - { - // Reset network timer - this.actionTimer = AIAENetworkGolem.NETWORK_COOLDOWN; - } - - /** - * Return true if network interaction is required this update. - * - * @return - */ - protected abstract boolean needsNetworkNow(); - - @Override - public final boolean shouldExecute() - { - // Check the network timer - if( this.cooledDown() ) - { - this.restartNetworkCooldown(); - - // IsConnected needs to be checked before needsNetwork - // This ensures the wireless state data is kept up-to-date - if( this.network.isConnected() ) - { - return this.needsNetworkNow(); - } - } - return false; - } - - @Override - public abstract void updateTask(); + // IsConnected needs to be checked before needsNetwork + // This ensures the wireless state data is kept up-to-date + if (this.network.isConnected()) { + return this.needsNetworkNow(); + } + } + return false; + } + @Override + public abstract void updateTask(); } diff --git a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiEssentia.java b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiEssentia.java index e0757eef..a80adc8f 100644 --- a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiEssentia.java +++ b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiEssentia.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.entities; -import java.util.HashSet; import appeng.api.config.Actionable; +import java.util.HashSet; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; @@ -21,326 +21,285 @@ import thaumicenergistics.common.entities.WirelessGolemHandler.WirelessServerDat * @author Nividica * */ -public class AIGolemWifiEssentia - extends AIAENetworkGolem -{ - private final HashSet checkedJars = new HashSet(); +public class AIGolemWifiEssentia extends AIAENetworkGolem { + private final HashSet checkedJars = new HashSet(); - /** - * The jar the golem plan's to fill up. - */ - private TileJarFillable targetJar = null; + /** + * The jar the golem plan's to fill up. + */ + private TileJarFillable targetJar = null; - /** - * Distance to the target jar. - */ - private double targetDistance = 0; + /** + * Distance to the target jar. + */ + private double targetDistance = 0; - /** - * Is the target jar a void jar? - */ - private boolean targetVoid; + /** + * Is the target jar a void jar? + */ + private boolean targetVoid; - /** - * The square range of the golem. - */ - private double golemRange; + /** + * The square range of the golem. + */ + private double golemRange; - /** - * True if the golem is filling up jars, false if the golem is emptying something. - */ - private boolean modeFill; + /** + * True if the golem is filling up jars, false if the golem is emptying something. + */ + private boolean modeFill; - public AIGolemWifiEssentia( final EntityGolemBase golem, final WirelessServerData wsd ) - { - super( golem, wsd ); - } + public AIGolemWifiEssentia(final EntityGolemBase golem, final WirelessServerData wsd) { + super(golem, wsd); + } - /** - * Checks jars connected to the specified jar for potential targets. - * - * @param world - * @param gHomePos - * @param teJar - */ - private void checkConnectedJars( final World world, final ChunkCoordinates gHomePos, final TileEntity teJar ) - { - int x, y, z, setOp; + /** + * Checks jars connected to the specified jar for potential targets. + * + * @param world + * @param gHomePos + * @param teJar + */ + private void checkConnectedJars(final World world, final ChunkCoordinates gHomePos, final TileEntity teJar) { + int x, y, z, setOp; - // Sanity check - if( this.checkedJars.size() >= 200 ) - { - return; - } + // Sanity check + if (this.checkedJars.size() >= 200) { + return; + } - // Check each direction - for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - // Get the position - x = side.offsetX + teJar.xCoord; - y = side.offsetY + teJar.yCoord; - z = side.offsetZ + teJar.zCoord; + // Check each direction + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + // Get the position + x = side.offsetX + teJar.xCoord; + y = side.offsetY + teJar.yCoord; + z = side.offsetZ + teJar.zCoord; - // Get the tile entity - TileEntity te = world.getTileEntity( x, y, z ); + // Get the tile entity + TileEntity te = world.getTileEntity(x, y, z); - // Ensure the tile is a jar - if( !( te instanceof TileJarFillable ) ) - { - continue; - } + // Ensure the tile is a jar + if (!(te instanceof TileJarFillable)) { + continue; + } - // Set the jar if it is closer - setOp = this.setTargetIfValid( (TileJarFillable)te, gHomePos ); - if( setOp > 2 ) - { - // Check it's connected jars - this.checkConnectedJars( world, gHomePos, te ); - } + // Set the jar if it is closer + setOp = this.setTargetIfValid((TileJarFillable) te, gHomePos); + if (setOp > 2) { + // Check it's connected jars + this.checkConnectedJars(world, gHomePos, te); + } + } + } - } - } + /** + * Locates the nearest valid jar as a target. + */ + private void findClosestValidJar() { + // Is there a target? + if (this.targetJar != null) { + // Is the jar still there? + if (this.golem.worldObj.getTileEntity(this.targetJar.xCoord, this.targetJar.yCoord, this.targetJar.zCoord) + == this.targetJar) { - /** - * Locates the nearest valid jar as a target. - */ - private void findClosestValidJar() - { - // Is there a target? - if( this.targetJar != null ) - { - // Is the jar still there? - if( this.golem.worldObj.getTileEntity( this.targetJar.xCoord, - this.targetJar.yCoord, this.targetJar.zCoord ) == this.targetJar ) - { + // Can it hold more? + Aspect wantedAspect = + (this.targetJar.aspectFilter != null ? this.targetJar.aspectFilter : this.targetJar.aspect); + if ((wantedAspect != null) && (this.targetVoid || (this.targetJar.amount < this.targetJar.maxAmount))) { + // Can the wanted aspect be extracted? + if (this.network.extractEssentia(wantedAspect, 1, Actionable.SIMULATE) > 0) { + return; + } + } + } + } - // Can it hold more? - Aspect wantedAspect = ( this.targetJar.aspectFilter != null ? this.targetJar.aspectFilter : this.targetJar.aspect ); - if( ( wantedAspect != null ) && ( this.targetVoid || ( this.targetJar.amount < this.targetJar.maxAmount ) ) ) - { - // Can the wanted aspect be extracted? - if( this.network.extractEssentia( wantedAspect, 1, Actionable.SIMULATE ) > 0 ) - { - return; - } - } - } - } + // Reset target jar + this.targetJar = null; + this.targetDistance = Double.MAX_VALUE; + this.targetVoid = false; - // Reset target jar - this.targetJar = null; - this.targetDistance = Double.MAX_VALUE; - this.targetVoid = false; + // Get the world the golem is in + World world = this.golem.worldObj; + int worldDim = world.provider.dimensionId; - // Get the world the golem is in - World world = this.golem.worldObj; - int worldDim = world.provider.dimensionId; + // Calculate the squared range + this.golemRange = this.golem.getRange(); + this.golemRange *= this.golemRange; - // Calculate the squared range - this.golemRange = this.golem.getRange(); - this.golemRange *= this.golemRange; + // Get the golems position + ChunkCoordinates gHomePos = this.golem.getHomePosition(); - // Get the golems position - ChunkCoordinates gHomePos = this.golem.getHomePosition(); + // Check each of the golems markers + for (Marker marker : this.golem.getMarkers()) { + // Ensure the marker is in the same dimension + if (marker.dim != worldDim) { + continue; + } - // Check each of the golems markers - for( Marker marker : this.golem.getMarkers() ) - { - // Ensure the marker is in the same dimension - if( marker.dim != worldDim ) - { - continue; - } + // Get the tile entity + TileEntity markedTile = world.getTileEntity(marker.x, marker.y, marker.z); - // Get the tile entity - TileEntity markedTile = world.getTileEntity( marker.x, marker.y, marker.z ); + // Ensure the tile is a jar + if (!(markedTile instanceof TileJarFillable)) { + continue; + } - // Ensure the tile is a jar - if( !( markedTile instanceof TileJarFillable ) ) - { - continue; - } + // Set the jar if it is closer + this.setTargetIfValid((TileJarFillable) markedTile, gHomePos); - // Set the jar if it is closer - this.setTargetIfValid( (TileJarFillable)markedTile, gHomePos ); + // Check connected jars + this.checkConnectedJars(world, gHomePos, markedTile); + } - // Check connected jars - this.checkConnectedJars( world, gHomePos, markedTile ); - } + // Reset checked + this.checkedJars.clear(); + } - // Reset checked - this.checkedJars.clear(); - } + /** + * Sets the target if the jar is valid, closer, and in range. + * + * @param jar + * @param gHomePos + * @return 1 = Jar out of range, 2 = Jar already visited, 3 = Invalid jar, 4 = Set as target + */ + private int setTargetIfValid(final TileJarFillable jar, final ChunkCoordinates gHomePos) { + if (!this.checkedJars.add(jar)) { + return 2; + } - /** - * Sets the target if the jar is valid, closer, and in range. - * - * @param jar - * @param gHomePos - * @return 1 = Jar out of range, 2 = Jar already visited, 3 = Invalid jar, 4 = Set as target - */ - private int setTargetIfValid( final TileJarFillable jar, final ChunkCoordinates gHomePos ) - { - if( !this.checkedJars.add( jar ) ) - { - return 2; - } + // In range of golem? + double distance = jar.getDistanceFrom(gHomePos.posX, gHomePos.posY, gHomePos.posZ); + if (distance > this.golemRange) { + return 1; + } - // In range of golem? - double distance = jar.getDistanceFrom( gHomePos.posX, gHomePos.posY, gHomePos.posZ ); - if( distance > this.golemRange ) - { - return 1; - } + // If the current target is voiding, but the potential target is not, + // then do not bother with the distance check. + boolean isVoid = (jar instanceof TileJarFillableVoid); + if (!(this.targetVoid && !isVoid)) { + // Check distance + if (distance > this.targetDistance) { + return 1; + } + } - // If the current target is voiding, but the potential target is not, - // then do not bother with the distance check. - boolean isVoid = ( jar instanceof TileJarFillableVoid ); - if( !( this.targetVoid && !isVoid ) ) - { - // Check distance - if( distance > this.targetDistance ) - { - return 1; - } - } + // Check for essentia + if (jar.aspect == null) { + // Check for label + if (jar.aspectFilter == null) { + return 3; + } + } - // Check for essentia - if( jar.aspect == null ) - { - // Check for label - if( jar.aspectFilter == null ) - { - return 3; - } - } + // Check amount + if (!isVoid && (jar.amount >= jar.maxAmount)) { + return 3; + } - // Check amount - if( !isVoid && ( jar.amount >= jar.maxAmount ) ) - { - return 3; - } + // Valid target + this.targetJar = jar; + this.targetDistance = distance; + this.targetVoid = isVoid; - // Valid target - this.targetJar = jar; - this.targetDistance = distance; - this.targetVoid = isVoid; + return 4; + } - return 4; + @Override + protected boolean needsNetworkNow() { + // Determine the mode - } + // Get the tile entity at the golems home + ChunkCoordinates gHomePos = this.golem.getHomePosition(); + ForgeDirection side = ForgeDirection.getOrientation(this.golem.homeFacing); + TileEntity te = this.golem.worldObj.getTileEntity( + gHomePos.posX - side.offsetX, gHomePos.posY - side.offsetY, gHomePos.posZ - side.offsetZ); - @Override - protected boolean needsNetworkNow() - { - // Determine the mode + // Is the tile an essentia transport? + this.modeFill = !(te instanceof IEssentiaTransport); - // Get the tile entity at the golems home - ChunkCoordinates gHomePos = this.golem.getHomePosition(); - ForgeDirection side = ForgeDirection.getOrientation( this.golem.homeFacing ); - TileEntity te = this.golem.worldObj.getTileEntity( gHomePos.posX - side.offsetX, - gHomePos.posY - side.offsetY, - gHomePos.posZ - side.offsetZ ); + // If the tile is not valid, check above it for alembic + if (this.modeFill) { + for (int i = 1; (i < 6) && this.modeFill; ++i) { + te = this.golem.worldObj.getTileEntity( + gHomePos.posX - side.offsetX, (gHomePos.posY - side.offsetY) + i, gHomePos.posZ - side.offsetZ); + this.modeFill = !(te instanceof TileAlembic); + } + } - // Is the tile an essentia transport? - this.modeFill = !( te instanceof IEssentiaTransport ); + // Fill mode + if (this.modeFill) { + // Needs network if the golem is not carrying anything, and there is a target jar + if (this.golem.essentiaAmount > 0) { + return false; + } - // If the tile is not valid, check above it for alembic - if( this.modeFill ) - { - for( int i = 1; ( i < 6 ) && this.modeFill; ++i ) - { - te = this.golem.worldObj.getTileEntity( gHomePos.posX - side.offsetX, - ( gHomePos.posY - side.offsetY ) + i, - gHomePos.posZ - side.offsetZ ); - this.modeFill = !( te instanceof TileAlembic ); - } - } + // Golem is not carrying anything, find a jar + this.findClosestValidJar(); + return (this.targetJar != null); + } - // Fill mode - if( this.modeFill ) - { - // Needs network if the golem is not carrying anything, and there is a target jar - if( this.golem.essentiaAmount > 0 ) - { - return false; - } + // Empty mode + return (this.golem.getNavigator().noPath() && (this.golem.essentiaAmount > 0)); + } - // Golem is not carrying anything, find a jar - this.findClosestValidJar(); - return( this.targetJar != null ); - } + @Override + public void updateTask() { + // Fill mode + if (this.modeFill) { + // Get the wanted aspect + Aspect wantedAspect = + (this.targetJar.aspectFilter != null ? this.targetJar.aspectFilter : this.targetJar.aspect); + if (wantedAspect == null) { + // Jar is invalid now + this.targetJar = null; + return; + } - // Empty mode - return( this.golem.getNavigator().noPath() && ( this.golem.essentiaAmount > 0 ) ); - } + // Get the capacity of the jar + int amount = this.targetJar.maxAmount; - @Override - public void updateTask() - { - // Fill mode - if( this.modeFill ) - { - // Get the wanted aspect - Aspect wantedAspect = ( this.targetJar.aspectFilter != null ? this.targetJar.aspectFilter : this.targetJar.aspect ); - if( wantedAspect == null ) - { - // Jar is invalid now - this.targetJar = null; - return; - } + // Is the jar not voiding + if (!this.targetVoid) { + // Calculate the max amount to extract + amount -= this.targetJar.amount; + if (amount < 1) { + // Jar is full + this.targetJar = null; + return; + } + } - // Get the capacity of the jar - int amount = this.targetJar.maxAmount; + // Attempt extraction + int extractedAmount = (int) this.network.extractEssentia(wantedAspect, amount, Actionable.MODULATE); + if (extractedAmount <= 0) { + return; + } - // Is the jar not voiding - if( !this.targetVoid ) - { - // Calculate the max amount to extract - amount -= this.targetJar.amount; - if( amount < 1 ) - { - // Jar is full - this.targetJar = null; - return; - } - } + // Set the golems essentia + this.golem.essentia = wantedAspect; + this.golem.essentiaAmount = extractedAmount; + } else { + // Mode empty + if ((this.golem.essentia == null) + || (this.golem.essentiaAmount <= 0) + || !this.golem.getNavigator().noPath()) { + return; + } - // Attempt extraction - int extractedAmount = (int)this.network.extractEssentia( wantedAspect, amount, Actionable.MODULATE ); - if( extractedAmount <= 0 ) - { - return; - } + // Attempt injection + int injectedAmount = (int) this.network.insertEssentia(this.golem.essentia, this.golem.essentiaAmount); + if (injectedAmount == 0) { + return; + } - // Set the golems essentia - this.golem.essentia = wantedAspect; - this.golem.essentiaAmount = extractedAmount; - } - else - { - // Mode empty - if( ( this.golem.essentia == null ) || ( this.golem.essentiaAmount <= 0 ) || !this.golem.getNavigator().noPath() ) - { - return; - } - - // Attempt injection - int injectedAmount = (int)this.network.insertEssentia( this.golem.essentia, this.golem.essentiaAmount ); - if( injectedAmount == 0 ) - { - return; - } - - // Update golem - this.golem.essentiaAmount -= injectedAmount; - if( this.golem.essentiaAmount <= 0 ) - { - this.golem.essentia = null; - } - } - - this.golem.updateCarried(); - } + // Update golem + this.golem.essentiaAmount -= injectedAmount; + if (this.golem.essentiaAmount <= 0) { + this.golem.essentia = null; + } + } + this.golem.updateCarried(); + } } diff --git a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiFill.java b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiFill.java index 673cacdb..2193fdb1 100644 --- a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiFill.java +++ b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiFill.java @@ -9,37 +9,29 @@ import thaumcraft.common.entities.golems.EntityGolemBase; * @author Nividica * */ -public class AIGolemWifiFill - extends AIAENetworkGolem -{ +public class AIGolemWifiFill extends AIAENetworkGolem { - public AIGolemWifiFill( final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd ) - { - super( golem, wsd ); - } + public AIGolemWifiFill(final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd) { + super(golem, wsd); + } - @Override - protected boolean needsNetworkNow() - { - // Is the golem watching for anything? - return( this.golem.itemWatched != null ); - } - - @Override - public void updateTask() - { - // Get the stack the golem is watching for. - ItemStack watched = this.golem.itemWatched; - if( watched != null ) - { - // Attempt extraction - ItemStack extracted = this.network.extractStack( watched ); - if( extracted != null ) - { - this.golem.setCarried( extracted ); - this.golem.itemWatched = null; - } - } - } + @Override + protected boolean needsNetworkNow() { + // Is the golem watching for anything? + return (this.golem.itemWatched != null); + } + @Override + public void updateTask() { + // Get the stack the golem is watching for. + ItemStack watched = this.golem.itemWatched; + if (watched != null) { + // Attempt extraction + ItemStack extracted = this.network.extractStack(watched); + if (extracted != null) { + this.golem.setCarried(extracted); + this.golem.itemWatched = null; + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiGather.java b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiGather.java index 47e8968e..26705c01 100644 --- a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiGather.java +++ b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiGather.java @@ -9,42 +9,34 @@ import thaumcraft.common.entities.golems.EntityGolemBase; * @author Nividica * */ -public class AIGolemWifiGather - extends AIAENetworkGolem -{ - public AIGolemWifiGather( final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd ) - { - super( golem, wsd ); - } +public class AIGolemWifiGather extends AIAENetworkGolem { + public AIGolemWifiGather(final EntityGolemBase golem, final WirelessGolemHandler.WirelessServerData wsd) { + super(golem, wsd); + } - @Override - public boolean needsNetworkNow() - { - // Execute when the golem is holding something - return( this.golem.getCarried() != null ); - } + @Override + public boolean needsNetworkNow() { + // Execute when the golem is holding something + return (this.golem.getCarried() != null); + } - @Override - public void updateTask() - { - ItemStack heldItem = this.golem.getCarried(); + @Override + public void updateTask() { + ItemStack heldItem = this.golem.getCarried(); - // Ensure the golem is holding something. - if( heldItem != null ) - { - // Deposit the item - this.network.depositStack( heldItem ); + // Ensure the golem is holding something. + if (heldItem != null) { + // Deposit the item + this.network.depositStack(heldItem); - // Was the stack drained? - if( heldItem.stackSize == 0 ) - { - // Clear what the golem is holding - this.golem.setCarried( null ); - - // Throw his arms up for good measure. - this.golem.startActionTimer(); - } - } - } + // Was the stack drained? + if (heldItem.stackSize == 0) { + // Clear what the golem is holding + this.golem.setCarried(null); + // Throw his arms up for good measure. + this.golem.startActionTimer(); + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiLiquid.java b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiLiquid.java index 06f32482..4ca1a23a 100644 --- a/src/main/java/thaumicenergistics/common/entities/AIGolemWifiLiquid.java +++ b/src/main/java/thaumicenergistics/common/entities/AIGolemWifiLiquid.java @@ -12,76 +12,63 @@ import thaumicenergistics.common.entities.WirelessGolemHandler.WirelessServerDat * @author Nividica * */ -public class AIGolemWifiLiquid - extends AIAENetworkGolem -{ +public class AIGolemWifiLiquid extends AIAENetworkGolem { - private FluidStack wantedFluid; + private FluidStack wantedFluid; - public AIGolemWifiLiquid( final EntityGolemBase golem, final WirelessServerData wsd ) - { - super( golem, wsd ); - } + public AIGolemWifiLiquid(final EntityGolemBase golem, final WirelessServerData wsd) { + super(golem, wsd); + } - @Override - protected boolean needsNetworkNow() - { - // Is the golem in-need of a fluid? - ArrayList fluids = GolemHelper.getMissingLiquids( this.golem ); + @Override + protected boolean needsNetworkNow() { + // Is the golem in-need of a fluid? + ArrayList fluids = GolemHelper.getMissingLiquids(this.golem); - // Don't bother if the golem is asking for EVERY fluid, only if there is a specific request. - if( ( fluids != null ) && ( fluids.size() == 1 ) ) - { - // Set the wanted fluid - this.wantedFluid = fluids.get( 0 ).copy(); + // Don't bother if the golem is asking for EVERY fluid, only if there is a specific request. + if ((fluids != null) && (fluids.size() == 1)) { + // Set the wanted fluid + this.wantedFluid = fluids.get(0).copy(); - // Verify that the golem is carrying the fluid, or nothing - if( ( this.golem.fluidCarried == null ) || ( this.golem.fluidCarried.getFluid() == this.wantedFluid.getFluid() ) ) - { - return true; - } - this.wantedFluid = null; - } - return false; - } + // Verify that the golem is carrying the fluid, or nothing + if ((this.golem.fluidCarried == null) + || (this.golem.fluidCarried.getFluid() == this.wantedFluid.getFluid())) { + return true; + } + this.wantedFluid = null; + } + return false; + } - @Override - public void updateTask() - { - if( this.wantedFluid == null ) - { - return; - } + @Override + public void updateTask() { + if (this.wantedFluid == null) { + return; + } - // Is the golem carrying the fluid? - int existingSize = 0; - if( this.golem.fluidCarried != null ) - { - existingSize = this.golem.fluidCarried.amount; - } + // Is the golem carrying the fluid? + int existingSize = 0; + if (this.golem.fluidCarried != null) { + existingSize = this.golem.fluidCarried.amount; + } - // Calculate maximum request size - this.wantedFluid.amount = 1000 - existingSize; + // Calculate maximum request size + this.wantedFluid.amount = 1000 - existingSize; - // Attempt extraction - FluidStack extracted = this.network.extractFluid( this.wantedFluid ); - if( extracted == null ) - { - return; - } + // Attempt extraction + FluidStack extracted = this.network.extractFluid(this.wantedFluid); + if (extracted == null) { + return; + } - // Add to existing? - if( existingSize > 0 ) - { - this.golem.fluidCarried.amount += extracted.amount; - } - else - { - this.golem.fluidCarried = extracted; - } - this.golem.updateCarried(); - - this.wantedFluid = null; - } + // Add to existing? + if (existingSize > 0) { + this.golem.fluidCarried.amount += extracted.amount; + } else { + this.golem.fluidCarried = extracted; + } + this.golem.updateCarried(); + this.wantedFluid = null; + } } diff --git a/src/main/java/thaumicenergistics/common/entities/WirelessGolemHandler.java b/src/main/java/thaumicenergistics/common/entities/WirelessGolemHandler.java index a1c50b86..3f3b9ea6 100644 --- a/src/main/java/thaumicenergistics/common/entities/WirelessGolemHandler.java +++ b/src/main/java/thaumicenergistics/common/entities/WirelessGolemHandler.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.entities; -import org.lwjgl.opengl.GL11; import appeng.api.AEApi; import appeng.items.parts.ItemFacade; import cpw.mods.fml.relauncher.Side; @@ -11,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import org.lwjgl.opengl.GL11; import thaumcraft.common.config.ConfigBlocks; import thaumcraft.common.entities.golems.EntityGolemBase; import thaumicenergistics.api.entities.IGolemHookHandler; @@ -28,706 +28,641 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class WirelessGolemHandler - implements IGolemHookHandler -{ - /** - * Data stored on the client side. - * - * @author Nividica - * - */ - public static class WirelessClientData - { - public boolean isInRange = false; - public float pearlRotation = 0.0f; - public BackpackSkins skin = BackpackSkins.Thaumium; - } - - /** - * Data stored on the server side. - * - * @author Nividica - * - */ - public static class WirelessServerData - { - public final String encryptionKey; - public int tickCounter = 0; - public boolean isInRange = false; - public ItemStack facade = null; - public BackpackSkins skin = BackpackSkins.Thaumium; - - public WirelessServerData( final String encKey ) - { - this.encryptionKey = encKey; - } - } - - private static WirelessGolemHandler INSTANCE = null; - - /** - * NBT keys - */ - private static final String NBTKEY_WIFI_KEY = "wifiBackpackKey", NBTKEY_FACADE = "facade"; - - /** - * State flags. - */ - private static final Character SYNCFLAG_HAS_WIFI_IN_RANGE = Character.valueOf( 'i' ), - SYNCFLAG_HAS_WIFI_OUT_OF_RANGE = Character.valueOf( 'o' ), - SYNCFLAG_NO_WIFI = Character.valueOf( 'n' ), - SYNCFIELD_SKIN = 'a'; - - @SideOnly(Side.CLIENT) - private ModelGolemWifiBackpack addonModel; - - /** - * ID of the wifi sync field. - */ - private int wifiSyncID = -1; - - /** - * ID of the skin sync field. - */ - private int skinSyncID = -1; - - /** - * Cache of the backpack item. - */ - private ItemGolemWirelessBackpack backpackItem; - - /** - * Item that represents a facade, or null. - */ - private ItemFacade facadeItem; - - /** - * Private constructor. - */ - private WirelessGolemHandler() - { - // Setup the backpack model if client side - if( EffectiveSide.isClientSide() ) - { - this.setupModel(); - } - - // Store a reference to the backpack item. - this.backpackItem = (ItemGolemWirelessBackpack)ItemEnum.GOLEM_WIFI_BACKPACK.getItem(); - - // Store a reference to the facade item - this.facadeItem = (ItemFacade)AEApi.instance().definitions().items().facade().maybeItem().orNull(); - } - - /** - * Returns the instance of the handler - * - * @return - */ - public static WirelessGolemHandler getInstance() - { - if( INSTANCE == null ) - { - INSTANCE = new WirelessGolemHandler(); - } - return INSTANCE; - } - - /** - * Gets a character based on the skin. - * - * @param skin - * @return - */ - private Character backpackSkinToSyncChar( final BackpackSkins skin ) - { - int id = 0; - if( skin != null ) - { - id = skin.ordinal(); - } - return Character.valueOf( (char)( SYNCFIELD_SKIN + id ) ); - } - - /** - * Han the backpack be handled? - * - * @param golem - * @param handlerData - * @param player - * @param side - * @return - */ - private InteractionLevel canHandleInteration_Backpack( final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, - final Side side ) - { - // Does the golem already have a backpack on? - if( handlerData != null ) - { - // Already has backpack. - return InteractionLevel.NoInteraction; - } - - // Is the core valid? - GolemCoreType core = GolemCoreType.getCoreByID( golem.getCore() ); - if( core == null ) - { - return InteractionLevel.NoInteraction; - } - switch ( core ) - { - // Unsupported cores - case Butcher: - case Empty: - case Fish: - case Guard: - case Harvest: - case Lumber: - case Sorting: - case Use: - default: - return InteractionLevel.NoInteraction; - - // Supported cores - case Gather: - case Fill: - case Liquid: - case Essentia: - break; - } - - // Client side? - if( side == Side.CLIENT ) - { - //Swing the item - player.swingItem(); - return InteractionLevel.NoInteraction; - } - - return InteractionLevel.FullInteraction; - } - - /** - * Can the facade be handled? - * - * @param golem - * @param handlerData - * @param player - * @param side - * @param heldItem - * @return - */ - private InteractionLevel canHandleInteration_Facade( final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, - final Side side, - final ItemStack heldItem ) - { - // Is the golem wearing a backpack? - if( handlerData == null ) - { - // No backpack to apply it to - return InteractionLevel.NoInteraction; - } - - // Get the skin for the facade - BackpackSkins skin = this.getSkinFromFacade( heldItem ); - if( skin == null ) - { - // Unsupported facade - return InteractionLevel.NoInteraction; - } - - // Client side? - if( ( side == Side.CLIENT ) && ( handlerData instanceof WirelessClientData ) ) - { - //Swing the item - player.swingItem(); - - // Set the skin - ( (WirelessClientData)handlerData ).skin = skin; - - return InteractionLevel.NoInteraction; - } - - return InteractionLevel.SyncInteraction; - } - - /** - * Returns the skin associated with the facade, or null if there is not one. - * - * @param facade - * @return - */ - private BackpackSkins getSkinFromFacade( final ItemStack facade ) - { - Block b = this.facadeItem.getBlock( facade ); - int metaData = this.facadeItem.getMeta( facade ); - - if( b == ConfigBlocks.blockCosmeticSolid ) - { - // Thaumium block? - if( metaData == 4 ) - { - return BackpackSkins.Thaumium; - } - // Tallow block? - else if( metaData == 5 ) - { - return BackpackSkins.Tallow; - } - } - // Greatwood log? - else if( ( b == ConfigBlocks.blockMagicalLog ) && ( metaData == 0 ) ) - { - return BackpackSkins.GreatWood; - } - // Flesh? - else if( ( b == ConfigBlocks.blockTaint ) && ( metaData == 2 ) ) - { - return BackpackSkins.Flesh; - } - // Stone block? - else if( b == Blocks.stone ) - { - return BackpackSkins.Stone; - } - // Hay block? - else if( b == Blocks.hay_block ) - { - return BackpackSkins.Straw; - } - // Bricks? - else if( b == Blocks.brick_block ) - { - return BackpackSkins.Clay; - } - // Iron? - else if( b == Blocks.iron_block ) - { - return BackpackSkins.Iron; - } - else if( b == Blocks.gold_block ) - { - return BackpackSkins.Gold; - } - else if( b == Blocks.diamond_block ) - { - return BackpackSkins.Diamond; - } - - return null; - } - - /** - * Creates the wifi addon model. - */ - @SideOnly(Side.CLIENT) - private void setupModel() - { - this.addonModel = new ModelGolemWifiBackpack(); - } - - /** - * Gets the skin based on the character - * - * @param skinSyncChar - * @return - */ - private BackpackSkins syncCharToBackpackSkin( final char skinSyncChar ) - { - int id = skinSyncChar - SYNCFIELD_SKIN; - if( ( id < 0 ) || ( id > BackpackSkins.VALUES.length ) ) - { - id = 0; - } - return BackpackSkins.VALUES[id]; - } - - @Override - public void addDefaultSyncEntries( final IGolemHookSyncRegistry syncRegistry ) - { - // Register the wifi entry - this.wifiSyncID = syncRegistry.registerSyncChar( this, SYNCFLAG_NO_WIFI ); - - // Register facade item - this.skinSyncID = syncRegistry.registerSyncChar( this, this.backpackSkinToSyncChar( BackpackSkins.Thaumium ) ); - } - - @Override - public void bellLeftClicked( final EntityGolemBase golem, final Object handlerData, final ItemStack itemGolemPlacer, final EntityPlayer player, - final boolean dismantled, final Side side ) - { - // Goes the golem have a backpack on? - if( handlerData instanceof WirelessServerData ) - { - WirelessServerData wsd = ( (WirelessServerData)handlerData ); - - // Create a new backpack item - ItemStack backpack = ItemEnum.GOLEM_WIFI_BACKPACK.getStack(); - - // Set the key - this.backpackItem.setEncryptionKey( backpack, wsd.encryptionKey, null ); - - // Drop the backpack - golem.entityDropItem( backpack, 0.5f ); - - // Is there a facade? - if( wsd.facade != null ) - { - // Drop the facade - golem.entityDropItem( wsd.facade, 0.5f ); - } - } - - } - - @Override - public InteractionLevel canHandleInteraction( final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, final Side side ) - { - // Get the held item - ItemStack heldItem = player.inventory.getCurrentItem(); - - // Empty hand? - if( heldItem == null ) - { - return InteractionLevel.NoInteraction; - } - - // Backpack? - if( heldItem.getItem() == this.backpackItem ) - { - return this.canHandleInteration_Backpack( golem, handlerData, player, side ); - } - - // Facade? - else if( ( this.facadeItem != null ) && ( heldItem.getItem() == this.facadeItem ) ) - { - return this.canHandleInteration_Facade( golem, handlerData, player, side, heldItem ); - } - - return InteractionLevel.NoInteraction; - - } - - @Override - public Object customInteraction( final EntityGolemBase golem, final Object handlerData, final IGolemHookSyncRegistry syncData, - final EntityPlayer player, final Side side ) - { - // Get the held item - ItemStack heldItem = player.inventory.getCurrentItem(); - - // Backpack? - if( heldItem.getItem() == this.backpackItem ) - { - // Is the backpack linked? - String encKey = this.backpackItem.getEncryptionKey( heldItem ); - if( encKey != null ) - { - // Play sound - golem.worldObj.playSoundAtEntity( golem, "thaumcraft:upgrade", 0.5F, 1.0F ); - - // Take the item - player.inventory.setInventorySlotContents( player.inventory.currentItem, null ); - - // Create the data - return new WirelessServerData( encKey ); - } - } - - // Facade? - else if( ( this.facadeItem != null ) && ( heldItem.getItem() == this.facadeItem ) ) - { - WirelessServerData wsd = (WirelessServerData)handlerData; - - // Is there a facade set? - if( ( wsd.facade != null ) && ( !player.capabilities.isCreativeMode ) ) - { - // Drop the old facade - golem.entityDropItem( wsd.facade, 0.5f ); - } - - // Set facade - wsd.facade = heldItem.copy(); - wsd.facade.stackSize = 1; - - // Take a facade from the player - if( !player.capabilities.isCreativeMode ) - { - --heldItem.stackSize; - if( heldItem.stackSize <= 0 ) - { - player.inventory.setInventorySlotContents( player.inventory.currentItem, null ); - } - } - - // Set the skin - wsd.skin = this.getSkinFromFacade( wsd.facade ); - syncData.updateSyncChar( this, this.skinSyncID, this.backpackSkinToSyncChar( wsd.skin ) ); - - // Play sound - golem.worldObj.playSoundAtEntity( golem, "thaumcraft:cameraticks", 0.5F, 1.0F ); - - return wsd; - } - - return null; - } - - @Override - public void golemTick( final EntityGolemBase golem, final Object serverHandlerData, final IGolemHookSyncRegistry syncData ) - { - // Has backpack? - if( serverHandlerData instanceof WirelessServerData ) - { - WirelessServerData wsd = (WirelessServerData)serverHandlerData; - - // Set sync data every 18th tick - if( ++wsd.tickCounter > 18 ) - { - // Reset counter - wsd.tickCounter = 0; - - // Set sync data - syncData.updateSyncChar( this, this.wifiSyncID, ( wsd.isInRange ? SYNCFLAG_HAS_WIFI_IN_RANGE : SYNCFLAG_HAS_WIFI_OUT_OF_RANGE ) ); - syncData.updateSyncChar( this, this.skinSyncID, this.backpackSkinToSyncChar( wsd.skin ) ); - } - } - } - - @Override - public boolean needsDynamicUpdates() - { - return true; - } - - @Override - public boolean needsRenderer() - { - return true; - } - - @Override - public Object readEntityFromNBT( final EntityGolemBase golem, final NBTTagCompound nbtTag ) - { - WirelessServerData wsd = null; - - // Does the golem have a backpack? - if( nbtTag.hasKey( NBTKEY_WIFI_KEY ) ) - { - // Create the data - wsd = new WirelessServerData( nbtTag.getString( NBTKEY_WIFI_KEY ) ); - - if( nbtTag.hasKey( NBTKEY_FACADE ) ) - { - // Read the facade - try - { - wsd.facade = ItemStack.loadItemStackFromNBT( nbtTag.getCompoundTag( NBTKEY_FACADE ) ); - wsd.skin = this.getSkinFromFacade( wsd.facade ); - } - catch( Exception e ) - { - // Invalid facade - } - } - - } - - return wsd; - } - - @Override - @SideOnly(Side.CLIENT) - public void renderGolem( final EntityGolemBase golem, final Object clientHandlerData, final double x, final double y, final double z, - final float partialElaspsedTick ) - { - if( !( clientHandlerData instanceof WirelessClientData ) ) - { - return; - } - WirelessClientData wcd = (WirelessClientData)clientHandlerData; - - if( golem.hurtTime > 0 ) - { - // Red tint - GL11.glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); - } - else if( golem.healing > 0 ) - { - // Green tint - GL11.glColor3f( 0.5f, 1.0f, 0.5f ); - } - else - { - // Full white - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - - // Is the golem in range and active? - boolean golemActive = wcd.isInRange && !golem.inactive; - - // Update the rotation of the pearl - if( golemActive && !Minecraft.getMinecraft().isGamePaused() ) - { - wcd.pearlRotation += partialElaspsedTick * 2.0f; - if( wcd.pearlRotation >= 360.0f ) - { - wcd.pearlRotation -= 360.0f; - } - - } - - // Push the matrix - GL11.glPushMatrix(); - - // Translate to the golem - GL11.glTranslatef( (float)x, (float)y + 0.64f, (float)z ); - - // Rotate to face away from the golem - float golemYaw = 270.0f; - - // Interpolate the golems rotation - golemYaw -= ( ( golem.renderYawOffset * partialElaspsedTick ) + ( golem.prevRenderYawOffset * ( 1.0f - partialElaspsedTick ) ) ); - - // Rotate with the golem - GL11.glRotatef( golemYaw, 0.0f, 1.0f, 0.0f ); - - // Translate just behind the golem - GL11.glTranslatef( -0.16f, 0.0f, 0.0f ); - - // Scale - GL11.glScalef( 0.8f, 0.8f, 0.8f ); - - // Render - this.addonModel.render( wcd.pearlRotation, 0.0625f, golemActive, wcd.skin ); - - // Pop the matrix - GL11.glPopMatrix(); - - } - - @Override - public Object setupGolem( final EntityGolemBase golem, final Object handlerData, final IGolemHookSyncRegistry syncData, final Side side ) - { - if( side == Side.CLIENT ) - { - return handlerData; - } - - // Does the golem have a backpack? - if( handlerData instanceof WirelessServerData ) - { - WirelessServerData wsd = (WirelessServerData)handlerData; - - // Get the golems core - GolemCoreType core = GolemCoreType.getCoreByID( golem.getCore() ); - if( core != null ) - { - switch ( core ) - { - case Gather: - // Add Gather AI script - golem.tasks.addTask( 1, new AIGolemWifiGather( golem, wsd ) ); - break; - - case Fill: - // Add Fill AI script - golem.tasks.addTask( 3, new AIGolemWifiFill( golem, wsd ) ); - break; - - case Liquid: - // Add liquid AI script - golem.tasks.addTask( 2, new AIGolemWifiLiquid( golem, wsd ) ); - break; - - case Essentia: - // Add essentia AI script - golem.tasks.addTask( 2, new AIGolemWifiEssentia( golem, wsd ) ); - break; - default: - break; - } - } - - // Update the sync data - syncData.updateSyncChar( this, this.wifiSyncID, ( wsd.isInRange ? SYNCFLAG_HAS_WIFI_IN_RANGE : SYNCFLAG_HAS_WIFI_OUT_OF_RANGE ) ); - } - else - { - // Update the sync data - syncData.updateSyncChar( this, this.wifiSyncID, SYNCFLAG_NO_WIFI ); - } - - return handlerData; - } - - @Override - public Object spawnGolemFromItemStack( final EntityGolemBase golem, final ItemStack itemGolemPlacer, final Side side ) - { - return null; - } - - @Override - @SideOnly(Side.CLIENT) - public Object syncDataChanged( final IGolemHookSyncRegistry syncData, final Object clientHandlerData ) - { - // Does the golem have on a backpack? - char syncFlag = syncData.getSyncCharOrDefault( this.wifiSyncID, SYNCFLAG_NO_WIFI ); - boolean inRange; - if( syncFlag == SYNCFLAG_HAS_WIFI_IN_RANGE ) - { - inRange = true; - } - else if( syncFlag == SYNCFLAG_HAS_WIFI_OUT_OF_RANGE ) - { - inRange = false; - } - else - { - // No backpack. - return null; - } - - // Has existing data? - WirelessClientData wcd = null; - if( clientHandlerData instanceof WirelessClientData ) - { - wcd = (WirelessClientData)clientHandlerData; - } - else - { - // Create new data - wcd = new WirelessClientData(); - } - - // Update the range - wcd.isInRange = inRange; - - // Get the skin - char skinChar = syncData.getSyncCharOrDefault( this.skinSyncID, SYNCFIELD_SKIN ); - wcd.skin = this.syncCharToBackpackSkin( skinChar ); - - return wcd; - } - - @Override - public void writeEntityNBT( final EntityGolemBase golem, final Object serverHandlerData, final NBTTagCompound nbtTag ) - { - // Does the golem have a backpack? - if( serverHandlerData instanceof WirelessServerData ) - { - WirelessServerData wsd = ( (WirelessServerData)serverHandlerData ); - - // Write network key - nbtTag.setString( NBTKEY_WIFI_KEY, wsd.encryptionKey ); - - // Has facade? - if( wsd.facade != null ) - { - // Write the facade - nbtTag.setTag( NBTKEY_FACADE, wsd.facade.writeToNBT( new NBTTagCompound() ) ); - } - } - } - +public class WirelessGolemHandler implements IGolemHookHandler { + /** + * Data stored on the client side. + * + * @author Nividica + * + */ + public static class WirelessClientData { + public boolean isInRange = false; + public float pearlRotation = 0.0f; + public BackpackSkins skin = BackpackSkins.Thaumium; + } + + /** + * Data stored on the server side. + * + * @author Nividica + * + */ + public static class WirelessServerData { + public final String encryptionKey; + public int tickCounter = 0; + public boolean isInRange = false; + public ItemStack facade = null; + public BackpackSkins skin = BackpackSkins.Thaumium; + + public WirelessServerData(final String encKey) { + this.encryptionKey = encKey; + } + } + + private static WirelessGolemHandler INSTANCE = null; + + /** + * NBT keys + */ + private static final String NBTKEY_WIFI_KEY = "wifiBackpackKey", NBTKEY_FACADE = "facade"; + + /** + * State flags. + */ + private static final Character SYNCFLAG_HAS_WIFI_IN_RANGE = Character.valueOf('i'), + SYNCFLAG_HAS_WIFI_OUT_OF_RANGE = Character.valueOf('o'), + SYNCFLAG_NO_WIFI = Character.valueOf('n'), + SYNCFIELD_SKIN = 'a'; + + @SideOnly(Side.CLIENT) + private ModelGolemWifiBackpack addonModel; + + /** + * ID of the wifi sync field. + */ + private int wifiSyncID = -1; + + /** + * ID of the skin sync field. + */ + private int skinSyncID = -1; + + /** + * Cache of the backpack item. + */ + private ItemGolemWirelessBackpack backpackItem; + + /** + * Item that represents a facade, or null. + */ + private ItemFacade facadeItem; + + /** + * Private constructor. + */ + private WirelessGolemHandler() { + // Setup the backpack model if client side + if (EffectiveSide.isClientSide()) { + this.setupModel(); + } + + // Store a reference to the backpack item. + this.backpackItem = (ItemGolemWirelessBackpack) ItemEnum.GOLEM_WIFI_BACKPACK.getItem(); + + // Store a reference to the facade item + this.facadeItem = (ItemFacade) + AEApi.instance().definitions().items().facade().maybeItem().orNull(); + } + + /** + * Returns the instance of the handler + * + * @return + */ + public static WirelessGolemHandler getInstance() { + if (INSTANCE == null) { + INSTANCE = new WirelessGolemHandler(); + } + return INSTANCE; + } + + /** + * Gets a character based on the skin. + * + * @param skin + * @return + */ + private Character backpackSkinToSyncChar(final BackpackSkins skin) { + int id = 0; + if (skin != null) { + id = skin.ordinal(); + } + return Character.valueOf((char) (SYNCFIELD_SKIN + id)); + } + + /** + * Han the backpack be handled? + * + * @param golem + * @param handlerData + * @param player + * @param side + * @return + */ + private InteractionLevel canHandleInteration_Backpack( + final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, final Side side) { + // Does the golem already have a backpack on? + if (handlerData != null) { + // Already has backpack. + return InteractionLevel.NoInteraction; + } + + // Is the core valid? + GolemCoreType core = GolemCoreType.getCoreByID(golem.getCore()); + if (core == null) { + return InteractionLevel.NoInteraction; + } + switch (core) { + // Unsupported cores + case Butcher: + case Empty: + case Fish: + case Guard: + case Harvest: + case Lumber: + case Sorting: + case Use: + default: + return InteractionLevel.NoInteraction; + + // Supported cores + case Gather: + case Fill: + case Liquid: + case Essentia: + break; + } + + // Client side? + if (side == Side.CLIENT) { + // Swing the item + player.swingItem(); + return InteractionLevel.NoInteraction; + } + + return InteractionLevel.FullInteraction; + } + + /** + * Can the facade be handled? + * + * @param golem + * @param handlerData + * @param player + * @param side + * @param heldItem + * @return + */ + private InteractionLevel canHandleInteration_Facade( + final EntityGolemBase golem, + final Object handlerData, + final EntityPlayer player, + final Side side, + final ItemStack heldItem) { + // Is the golem wearing a backpack? + if (handlerData == null) { + // No backpack to apply it to + return InteractionLevel.NoInteraction; + } + + // Get the skin for the facade + BackpackSkins skin = this.getSkinFromFacade(heldItem); + if (skin == null) { + // Unsupported facade + return InteractionLevel.NoInteraction; + } + + // Client side? + if ((side == Side.CLIENT) && (handlerData instanceof WirelessClientData)) { + // Swing the item + player.swingItem(); + + // Set the skin + ((WirelessClientData) handlerData).skin = skin; + + return InteractionLevel.NoInteraction; + } + + return InteractionLevel.SyncInteraction; + } + + /** + * Returns the skin associated with the facade, or null if there is not one. + * + * @param facade + * @return + */ + private BackpackSkins getSkinFromFacade(final ItemStack facade) { + Block b = this.facadeItem.getBlock(facade); + int metaData = this.facadeItem.getMeta(facade); + + if (b == ConfigBlocks.blockCosmeticSolid) { + // Thaumium block? + if (metaData == 4) { + return BackpackSkins.Thaumium; + } + // Tallow block? + else if (metaData == 5) { + return BackpackSkins.Tallow; + } + } + // Greatwood log? + else if ((b == ConfigBlocks.blockMagicalLog) && (metaData == 0)) { + return BackpackSkins.GreatWood; + } + // Flesh? + else if ((b == ConfigBlocks.blockTaint) && (metaData == 2)) { + return BackpackSkins.Flesh; + } + // Stone block? + else if (b == Blocks.stone) { + return BackpackSkins.Stone; + } + // Hay block? + else if (b == Blocks.hay_block) { + return BackpackSkins.Straw; + } + // Bricks? + else if (b == Blocks.brick_block) { + return BackpackSkins.Clay; + } + // Iron? + else if (b == Blocks.iron_block) { + return BackpackSkins.Iron; + } else if (b == Blocks.gold_block) { + return BackpackSkins.Gold; + } else if (b == Blocks.diamond_block) { + return BackpackSkins.Diamond; + } + + return null; + } + + /** + * Creates the wifi addon model. + */ + @SideOnly(Side.CLIENT) + private void setupModel() { + this.addonModel = new ModelGolemWifiBackpack(); + } + + /** + * Gets the skin based on the character + * + * @param skinSyncChar + * @return + */ + private BackpackSkins syncCharToBackpackSkin(final char skinSyncChar) { + int id = skinSyncChar - SYNCFIELD_SKIN; + if ((id < 0) || (id > BackpackSkins.VALUES.length)) { + id = 0; + } + return BackpackSkins.VALUES[id]; + } + + @Override + public void addDefaultSyncEntries(final IGolemHookSyncRegistry syncRegistry) { + // Register the wifi entry + this.wifiSyncID = syncRegistry.registerSyncChar(this, SYNCFLAG_NO_WIFI); + + // Register facade item + this.skinSyncID = syncRegistry.registerSyncChar(this, this.backpackSkinToSyncChar(BackpackSkins.Thaumium)); + } + + @Override + public void bellLeftClicked( + final EntityGolemBase golem, + final Object handlerData, + final ItemStack itemGolemPlacer, + final EntityPlayer player, + final boolean dismantled, + final Side side) { + // Goes the golem have a backpack on? + if (handlerData instanceof WirelessServerData) { + WirelessServerData wsd = ((WirelessServerData) handlerData); + + // Create a new backpack item + ItemStack backpack = ItemEnum.GOLEM_WIFI_BACKPACK.getStack(); + + // Set the key + this.backpackItem.setEncryptionKey(backpack, wsd.encryptionKey, null); + + // Drop the backpack + golem.entityDropItem(backpack, 0.5f); + + // Is there a facade? + if (wsd.facade != null) { + // Drop the facade + golem.entityDropItem(wsd.facade, 0.5f); + } + } + } + + @Override + public InteractionLevel canHandleInteraction( + final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, final Side side) { + // Get the held item + ItemStack heldItem = player.inventory.getCurrentItem(); + + // Empty hand? + if (heldItem == null) { + return InteractionLevel.NoInteraction; + } + + // Backpack? + if (heldItem.getItem() == this.backpackItem) { + return this.canHandleInteration_Backpack(golem, handlerData, player, side); + } + + // Facade? + else if ((this.facadeItem != null) && (heldItem.getItem() == this.facadeItem)) { + return this.canHandleInteration_Facade(golem, handlerData, player, side, heldItem); + } + + return InteractionLevel.NoInteraction; + } + + @Override + public Object customInteraction( + final EntityGolemBase golem, + final Object handlerData, + final IGolemHookSyncRegistry syncData, + final EntityPlayer player, + final Side side) { + // Get the held item + ItemStack heldItem = player.inventory.getCurrentItem(); + + // Backpack? + if (heldItem.getItem() == this.backpackItem) { + // Is the backpack linked? + String encKey = this.backpackItem.getEncryptionKey(heldItem); + if (encKey != null) { + // Play sound + golem.worldObj.playSoundAtEntity(golem, "thaumcraft:upgrade", 0.5F, 1.0F); + + // Take the item + player.inventory.setInventorySlotContents(player.inventory.currentItem, null); + + // Create the data + return new WirelessServerData(encKey); + } + } + + // Facade? + else if ((this.facadeItem != null) && (heldItem.getItem() == this.facadeItem)) { + WirelessServerData wsd = (WirelessServerData) handlerData; + + // Is there a facade set? + if ((wsd.facade != null) && (!player.capabilities.isCreativeMode)) { + // Drop the old facade + golem.entityDropItem(wsd.facade, 0.5f); + } + + // Set facade + wsd.facade = heldItem.copy(); + wsd.facade.stackSize = 1; + + // Take a facade from the player + if (!player.capabilities.isCreativeMode) { + --heldItem.stackSize; + if (heldItem.stackSize <= 0) { + player.inventory.setInventorySlotContents(player.inventory.currentItem, null); + } + } + + // Set the skin + wsd.skin = this.getSkinFromFacade(wsd.facade); + syncData.updateSyncChar(this, this.skinSyncID, this.backpackSkinToSyncChar(wsd.skin)); + + // Play sound + golem.worldObj.playSoundAtEntity(golem, "thaumcraft:cameraticks", 0.5F, 1.0F); + + return wsd; + } + + return null; + } + + @Override + public void golemTick( + final EntityGolemBase golem, final Object serverHandlerData, final IGolemHookSyncRegistry syncData) { + // Has backpack? + if (serverHandlerData instanceof WirelessServerData) { + WirelessServerData wsd = (WirelessServerData) serverHandlerData; + + // Set sync data every 18th tick + if (++wsd.tickCounter > 18) { + // Reset counter + wsd.tickCounter = 0; + + // Set sync data + syncData.updateSyncChar( + this, + this.wifiSyncID, + (wsd.isInRange ? SYNCFLAG_HAS_WIFI_IN_RANGE : SYNCFLAG_HAS_WIFI_OUT_OF_RANGE)); + syncData.updateSyncChar(this, this.skinSyncID, this.backpackSkinToSyncChar(wsd.skin)); + } + } + } + + @Override + public boolean needsDynamicUpdates() { + return true; + } + + @Override + public boolean needsRenderer() { + return true; + } + + @Override + public Object readEntityFromNBT(final EntityGolemBase golem, final NBTTagCompound nbtTag) { + WirelessServerData wsd = null; + + // Does the golem have a backpack? + if (nbtTag.hasKey(NBTKEY_WIFI_KEY)) { + // Create the data + wsd = new WirelessServerData(nbtTag.getString(NBTKEY_WIFI_KEY)); + + if (nbtTag.hasKey(NBTKEY_FACADE)) { + // Read the facade + try { + wsd.facade = ItemStack.loadItemStackFromNBT(nbtTag.getCompoundTag(NBTKEY_FACADE)); + wsd.skin = this.getSkinFromFacade(wsd.facade); + } catch (Exception e) { + // Invalid facade + } + } + } + + return wsd; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderGolem( + final EntityGolemBase golem, + final Object clientHandlerData, + final double x, + final double y, + final double z, + final float partialElaspsedTick) { + if (!(clientHandlerData instanceof WirelessClientData)) { + return; + } + WirelessClientData wcd = (WirelessClientData) clientHandlerData; + + if (golem.hurtTime > 0) { + // Red tint + GL11.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); + } else if (golem.healing > 0) { + // Green tint + GL11.glColor3f(0.5f, 1.0f, 0.5f); + } else { + // Full white + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + // Is the golem in range and active? + boolean golemActive = wcd.isInRange && !golem.inactive; + + // Update the rotation of the pearl + if (golemActive && !Minecraft.getMinecraft().isGamePaused()) { + wcd.pearlRotation += partialElaspsedTick * 2.0f; + if (wcd.pearlRotation >= 360.0f) { + wcd.pearlRotation -= 360.0f; + } + } + + // Push the matrix + GL11.glPushMatrix(); + + // Translate to the golem + GL11.glTranslatef((float) x, (float) y + 0.64f, (float) z); + + // Rotate to face away from the golem + float golemYaw = 270.0f; + + // Interpolate the golems rotation + golemYaw -= ((golem.renderYawOffset * partialElaspsedTick) + + (golem.prevRenderYawOffset * (1.0f - partialElaspsedTick))); + + // Rotate with the golem + GL11.glRotatef(golemYaw, 0.0f, 1.0f, 0.0f); + + // Translate just behind the golem + GL11.glTranslatef(-0.16f, 0.0f, 0.0f); + + // Scale + GL11.glScalef(0.8f, 0.8f, 0.8f); + + // Render + this.addonModel.render(wcd.pearlRotation, 0.0625f, golemActive, wcd.skin); + + // Pop the matrix + GL11.glPopMatrix(); + } + + @Override + public Object setupGolem( + final EntityGolemBase golem, + final Object handlerData, + final IGolemHookSyncRegistry syncData, + final Side side) { + if (side == Side.CLIENT) { + return handlerData; + } + + // Does the golem have a backpack? + if (handlerData instanceof WirelessServerData) { + WirelessServerData wsd = (WirelessServerData) handlerData; + + // Get the golems core + GolemCoreType core = GolemCoreType.getCoreByID(golem.getCore()); + if (core != null) { + switch (core) { + case Gather: + // Add Gather AI script + golem.tasks.addTask(1, new AIGolemWifiGather(golem, wsd)); + break; + + case Fill: + // Add Fill AI script + golem.tasks.addTask(3, new AIGolemWifiFill(golem, wsd)); + break; + + case Liquid: + // Add liquid AI script + golem.tasks.addTask(2, new AIGolemWifiLiquid(golem, wsd)); + break; + + case Essentia: + // Add essentia AI script + golem.tasks.addTask(2, new AIGolemWifiEssentia(golem, wsd)); + break; + default: + break; + } + } + + // Update the sync data + syncData.updateSyncChar( + this, + this.wifiSyncID, + (wsd.isInRange ? SYNCFLAG_HAS_WIFI_IN_RANGE : SYNCFLAG_HAS_WIFI_OUT_OF_RANGE)); + } else { + // Update the sync data + syncData.updateSyncChar(this, this.wifiSyncID, SYNCFLAG_NO_WIFI); + } + + return handlerData; + } + + @Override + public Object spawnGolemFromItemStack( + final EntityGolemBase golem, final ItemStack itemGolemPlacer, final Side side) { + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public Object syncDataChanged(final IGolemHookSyncRegistry syncData, final Object clientHandlerData) { + // Does the golem have on a backpack? + char syncFlag = syncData.getSyncCharOrDefault(this.wifiSyncID, SYNCFLAG_NO_WIFI); + boolean inRange; + if (syncFlag == SYNCFLAG_HAS_WIFI_IN_RANGE) { + inRange = true; + } else if (syncFlag == SYNCFLAG_HAS_WIFI_OUT_OF_RANGE) { + inRange = false; + } else { + // No backpack. + return null; + } + + // Has existing data? + WirelessClientData wcd = null; + if (clientHandlerData instanceof WirelessClientData) { + wcd = (WirelessClientData) clientHandlerData; + } else { + // Create new data + wcd = new WirelessClientData(); + } + + // Update the range + wcd.isInRange = inRange; + + // Get the skin + char skinChar = syncData.getSyncCharOrDefault(this.skinSyncID, SYNCFIELD_SKIN); + wcd.skin = this.syncCharToBackpackSkin(skinChar); + + return wcd; + } + + @Override + public void writeEntityNBT( + final EntityGolemBase golem, final Object serverHandlerData, final NBTTagCompound nbtTag) { + // Does the golem have a backpack? + if (serverHandlerData instanceof WirelessServerData) { + WirelessServerData wsd = ((WirelessServerData) serverHandlerData); + + // Write network key + nbtTag.setString(NBTKEY_WIFI_KEY, wsd.encryptionKey); + + // Has facade? + if (wsd.facade != null) { + // Write the facade + nbtTag.setTag(NBTKEY_FACADE, wsd.facade.writeToNBT(new NBTTagCompound())); + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/features/CommonDependantItems.java b/src/main/java/thaumicenergistics/common/features/CommonDependantItems.java index a63f45e0..741a3f4c 100644 --- a/src/main/java/thaumicenergistics/common/features/CommonDependantItems.java +++ b/src/main/java/thaumicenergistics/common/features/CommonDependantItems.java @@ -1,11 +1,11 @@ package thaumicenergistics.common.features; -import com.google.common.base.Optional; import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.api.definitions.IParts; +import com.google.common.base.Optional; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -20,211 +20,203 @@ import thaumcraft.common.config.ConfigItems; * @author Nividica * */ -public class CommonDependantItems -{ - // MC Items ========================== - public String VanillaGlass = "blockGlass"; - public String IronIngot = "ingotIron"; - public ItemStack VanillaLapis; - public ItemStack RedstoneDust; - public ItemStack RedstoneTorch; - public String Cobblestone = "cobblestone"; - public String NetherQuartz = "gemQuartz"; +public class CommonDependantItems { + // MC Items ========================== + public String VanillaGlass = "blockGlass"; + public String IronIngot = "ingotIron"; + public ItemStack VanillaLapis; + public ItemStack RedstoneDust; + public ItemStack RedstoneTorch; + public String Cobblestone = "cobblestone"; + public String NetherQuartz = "gemQuartz"; - // TC Items ========================== - public ItemStack ZombieBrain; - public ItemStack Thaumonomicon; - public ItemStack AirShard; - public ItemStack FireShard; - public ItemStack WaterShard; - public ItemStack EarthShard; - public ItemStack OrderShard; - public ItemStack EntropyShard; - public ItemStack BallanceShard; - public ItemStack EtheralEssence; - public ItemStack SalisMundus; - public Object WardedGlass; - public ItemStack ThaumiumIngot; - public ItemStack ArcaneWorkTable; - public ItemStack WardedJar; - public ItemStack FilterTube; - public ItemStack EssentiaMirror; - public ItemStack VisFilter; - public ItemStack QuickSilverDrop; - public ItemStack Thaumometer; - public ItemStack Nitor; + // TC Items ========================== + public ItemStack ZombieBrain; + public ItemStack Thaumonomicon; + public ItemStack AirShard; + public ItemStack FireShard; + public ItemStack WaterShard; + public ItemStack EarthShard; + public ItemStack OrderShard; + public ItemStack EntropyShard; + public ItemStack BallanceShard; + public ItemStack EtheralEssence; + public ItemStack SalisMundus; + public Object WardedGlass; + public ItemStack ThaumiumIngot; + public ItemStack ArcaneWorkTable; + public ItemStack WardedJar; + public ItemStack FilterTube; + public ItemStack EssentiaMirror; + public ItemStack VisFilter; + public ItemStack QuickSilverDrop; + public ItemStack Thaumometer; + public ItemStack Nitor; - // AE Items ========================= - public Object VibrantGlass; - public ItemStack EngineeringProcessor; - public ItemStack CalculationProcessor; - public ItemStack LogicProcessor; - public String IlluminatedPanel = "itemIlluminatedPanel"; - public ItemStack MolecularAssembler; - public ItemStack CertusQuartz; - public ItemStack ChargedCertusQuartz; - public ItemStack PureCertusQuartz; - public Object QuartzGlass; - public Object MECellWorkbench; - public ItemStack METerminal; - public ItemStack MEP2P; - public ItemStack MEInterface; - public ItemStack WirelessReceiver; - public ItemStack DenseCell; - public ItemStack FormationCore; - public ItemStack AnnihilationCore; - public ItemStack CertusWrench; - public ItemStack VibrationChamber; - public ItemStack MEInterfacePart; - public ItemStack FluixCrystal; - public ItemStack MECharger; + // AE Items ========================= + public Object VibrantGlass; + public ItemStack EngineeringProcessor; + public ItemStack CalculationProcessor; + public ItemStack LogicProcessor; + public String IlluminatedPanel = "itemIlluminatedPanel"; + public ItemStack MolecularAssembler; + public ItemStack CertusQuartz; + public ItemStack ChargedCertusQuartz; + public ItemStack PureCertusQuartz; + public Object QuartzGlass; + public Object MECellWorkbench; + public ItemStack METerminal; + public ItemStack MEP2P; + public ItemStack MEInterface; + public ItemStack WirelessReceiver; + public ItemStack DenseCell; + public ItemStack FormationCore; + public ItemStack AnnihilationCore; + public ItemStack CertusWrench; + public ItemStack VibrationChamber; + public ItemStack MEInterfacePart; + public ItemStack FluixCrystal; + public ItemStack MECharger; - /** - * Populates the common items - */ - public CommonDependantItems() - { - // MC items - this.VanillaLapis = new ItemStack( (Item)Item.itemRegistry.getObject( "dye" ), 1, 4 ); - this.RedstoneDust = new ItemStack( (Item)Item.itemRegistry.getObject( "redstone" ) ); - this.RedstoneTorch = new ItemStack( net.minecraft.init.Blocks.redstone_torch ); + /** + * Populates the common items + */ + public CommonDependantItems() { + // MC items + this.VanillaLapis = new ItemStack((Item) Item.itemRegistry.getObject("dye"), 1, 4); + this.RedstoneDust = new ItemStack((Item) Item.itemRegistry.getObject("redstone")); + this.RedstoneTorch = new ItemStack(net.minecraft.init.Blocks.redstone_torch); - // AE items - this.populateAEItems(); + // AE items + this.populateAEItems(); - // TC items - this.populateTCItems(); - } + // TC items + this.populateTCItems(); + } - /** - * Attempts to get the specified AE item. - * Returns a stack of size 1, or null. - * - * @param def - * @return - */ - private ItemStack getAEItem( final IItemDefinition def ) - { - // Ensure there is a definition - if( def == null ) - { - return null; - } + /** + * Attempts to get the specified AE item. + * Returns a stack of size 1, or null. + * + * @param def + * @return + */ + private ItemStack getAEItem(final IItemDefinition def) { + // Ensure there is a definition + if (def == null) { + return null; + } - // Attempt to get a stack - Optional item = def.maybeStack( 1 ); + // Attempt to get a stack + Optional item = def.maybeStack(1); - // Was a stack retrieved? - if( item.isPresent() ) - { - // Return the stack - return item.get(); - } + // Was a stack retrieved? + if (item.isPresent()) { + // Return the stack + return item.get(); + } - // Stack was not retrieved - return null; - } + // Stack was not retrieved + return null; + } - /** - * Gets an item based on if it is available and allowed by the specified - * config flag. - * - * @param configDependency - * @param preferred - * @param alt - * @return - */ - private Object getItemOrAlt( final boolean configDependency, final ItemStack preferred, final Object alt ) - { - if( ( preferred == null ) || ( !configDependency ) ) - { - return alt; - } + /** + * Gets an item based on if it is available and allowed by the specified + * config flag. + * + * @param configDependency + * @param preferred + * @param alt + * @return + */ + private Object getItemOrAlt(final boolean configDependency, final ItemStack preferred, final Object alt) { + if ((preferred == null) || (!configDependency)) { + return alt; + } - return preferred; - } + return preferred; + } - /** - * Gets an AE item, or if unavailable sets the item to the specified - * alternative. - * - * @param def - * @param alt - * @return - */ - private Object getItemOrAlt( final IItemDefinition def, final Object alt ) - { - ItemStack defItem = this.getAEItem( def ); - return( defItem == null ? alt : defItem ); - } + /** + * Gets an AE item, or if unavailable sets the item to the specified + * alternative. + * + * @param def + * @param alt + * @return + */ + private Object getItemOrAlt(final IItemDefinition def, final Object alt) { + ItemStack defItem = this.getAEItem(def); + return (defItem == null ? alt : defItem); + } - private void populateAEItems() - { - // Mats - IMaterials aeMaterials = AEApi.instance().definitions().materials(); - this.EngineeringProcessor = this.getAEItem( aeMaterials.engProcessor() ); - this.CalculationProcessor = this.getAEItem( aeMaterials.calcProcessor() ); - this.LogicProcessor = this.getAEItem( aeMaterials.logicProcessor() ); - this.CertusQuartz = this.getAEItem( aeMaterials.certusQuartzCrystal() ); - this.ChargedCertusQuartz = this.getAEItem( aeMaterials.certusQuartzCrystalCharged() ); - this.PureCertusQuartz = this.getAEItem( aeMaterials.purifiedCertusQuartzCrystal() ); - this.WirelessReceiver = this.getAEItem( aeMaterials.wireless() ); - this.AnnihilationCore = this.getAEItem( aeMaterials.annihilationCore() ); - this.FormationCore = this.getAEItem( aeMaterials.formationCore() ); - this.FluixCrystal = this.getAEItem( aeMaterials.fluixCrystal() ); + private void populateAEItems() { + // Mats + IMaterials aeMaterials = AEApi.instance().definitions().materials(); + this.EngineeringProcessor = this.getAEItem(aeMaterials.engProcessor()); + this.CalculationProcessor = this.getAEItem(aeMaterials.calcProcessor()); + this.LogicProcessor = this.getAEItem(aeMaterials.logicProcessor()); + this.CertusQuartz = this.getAEItem(aeMaterials.certusQuartzCrystal()); + this.ChargedCertusQuartz = this.getAEItem(aeMaterials.certusQuartzCrystalCharged()); + this.PureCertusQuartz = this.getAEItem(aeMaterials.purifiedCertusQuartzCrystal()); + this.WirelessReceiver = this.getAEItem(aeMaterials.wireless()); + this.AnnihilationCore = this.getAEItem(aeMaterials.annihilationCore()); + this.FormationCore = this.getAEItem(aeMaterials.formationCore()); + this.FluixCrystal = this.getAEItem(aeMaterials.fluixCrystal()); - // Blocks - IBlocks aeBlocks = AEApi.instance().definitions().blocks(); - this.VibrantGlass = this.getItemOrAlt( aeBlocks.quartzVibrantGlass(), this.VanillaGlass ); - this.MolecularAssembler = this.getAEItem( aeBlocks.molecularAssembler() ); - this.QuartzGlass = this.getItemOrAlt( aeBlocks.quartzGlass(), this.VanillaGlass ); - this.MECellWorkbench = this.getItemOrAlt( aeBlocks.cellWorkbench(), new ItemStack( Blocks.crafting_table ) ); - this.MEInterface = this.getAEItem( aeBlocks.iface() ); - this.DenseCell = (ItemStack)this.getItemOrAlt( aeBlocks.energyCellDense(), this.getAEItem( aeBlocks.energyCell() ) ); - this.VibrationChamber = this.getAEItem( aeBlocks.vibrationChamber() ); + // Blocks + IBlocks aeBlocks = AEApi.instance().definitions().blocks(); + this.VibrantGlass = this.getItemOrAlt(aeBlocks.quartzVibrantGlass(), this.VanillaGlass); + this.MolecularAssembler = this.getAEItem(aeBlocks.molecularAssembler()); + this.QuartzGlass = this.getItemOrAlt(aeBlocks.quartzGlass(), this.VanillaGlass); + this.MECellWorkbench = this.getItemOrAlt(aeBlocks.cellWorkbench(), new ItemStack(Blocks.crafting_table)); + this.MEInterface = this.getAEItem(aeBlocks.iface()); + this.DenseCell = + (ItemStack) this.getItemOrAlt(aeBlocks.energyCellDense(), this.getAEItem(aeBlocks.energyCell())); + this.VibrationChamber = this.getAEItem(aeBlocks.vibrationChamber()); - // Parts - IParts aeParts = AEApi.instance().definitions().parts(); - this.MECharger = this.getAEItem( aeBlocks.charger() ); - this.MEInterfacePart = this.getAEItem( aeParts.iface() ); - this.METerminal = this.getAEItem( aeParts.terminal() ); - this.MEP2P = this.getAEItem( aeParts.p2PTunnelME() ); + // Parts + IParts aeParts = AEApi.instance().definitions().parts(); + this.MECharger = this.getAEItem(aeBlocks.charger()); + this.MEInterfacePart = this.getAEItem(aeParts.iface()); + this.METerminal = this.getAEItem(aeParts.terminal()); + this.MEP2P = this.getAEItem(aeParts.p2PTunnelME()); - // Items - this.CertusWrench = this.getAEItem( AEApi.instance().definitions().items().certusQuartzWrench() ); + // Items + this.CertusWrench = + this.getAEItem(AEApi.instance().definitions().items().certusQuartzWrench()); + } - } + private void populateTCItems() { + // Shards + this.AirShard = new ItemStack(ConfigItems.itemShard, 1, 0); + this.FireShard = new ItemStack(ConfigItems.itemShard, 1, 1); + this.WaterShard = new ItemStack(ConfigItems.itemShard, 1, 2); + this.EarthShard = new ItemStack(ConfigItems.itemShard, 1, 3); + this.OrderShard = new ItemStack(ConfigItems.itemShard, 1, 4); + this.EntropyShard = new ItemStack(ConfigItems.itemShard, 1, 5); + this.BallanceShard = new ItemStack(ConfigItems.itemShard, 1, 6); - private void populateTCItems() - { - // Shards - this.AirShard = new ItemStack( ConfigItems.itemShard, 1, 0 ); - this.FireShard = new ItemStack( ConfigItems.itemShard, 1, 1 ); - this.WaterShard = new ItemStack( ConfigItems.itemShard, 1, 2 ); - this.EarthShard = new ItemStack( ConfigItems.itemShard, 1, 3 ); - this.OrderShard = new ItemStack( ConfigItems.itemShard, 1, 4 ); - this.EntropyShard = new ItemStack( ConfigItems.itemShard, 1, 5 ); - this.BallanceShard = new ItemStack( ConfigItems.itemShard, 1, 6 ); + // Resources + this.Nitor = new ItemStack(ConfigItems.itemResource, 1, 1); + this.ThaumiumIngot = new ItemStack(ConfigItems.itemResource, 1, 2); + this.VisFilter = new ItemStack(ConfigItems.itemResource, 1, 8); + this.SalisMundus = new ItemStack(ConfigItems.itemResource, 1, 14); - // Resources - this.Nitor = new ItemStack( ConfigItems.itemResource, 1, 1 ); - this.ThaumiumIngot = new ItemStack( ConfigItems.itemResource, 1, 2 ); - this.VisFilter = new ItemStack( ConfigItems.itemResource, 1, 8 ); - this.SalisMundus = new ItemStack( ConfigItems.itemResource, 1, 14 ); + // Blocks + this.WardedJar = new ItemStack(ConfigBlocks.blockJar, 1, 0); + this.ArcaneWorkTable = new ItemStack(ConfigBlocks.blockTable, 1, 15); + this.FilterTube = new ItemStack(ConfigBlocks.blockTube, 1, 3); + this.WardedGlass = this.getItemOrAlt( + Config.wardedStone, new ItemStack(ConfigBlocks.blockCosmeticOpaque, 1, 2), this.VanillaGlass); + this.EssentiaMirror = (ItemStack) + this.getItemOrAlt(Config.allowMirrors, new ItemStack(ConfigBlocks.blockMirror, 1, 6), this.WardedJar); - // Blocks - this.WardedJar = new ItemStack( ConfigBlocks.blockJar, 1, 0 ); - this.ArcaneWorkTable = new ItemStack( ConfigBlocks.blockTable, 1, 15 ); - this.FilterTube = new ItemStack( ConfigBlocks.blockTube, 1, 3 ); - this.WardedGlass = this.getItemOrAlt( Config.wardedStone, new ItemStack( ConfigBlocks.blockCosmeticOpaque, 1, 2 ), this.VanillaGlass ); - this.EssentiaMirror = (ItemStack)this.getItemOrAlt( Config.allowMirrors, new ItemStack( ConfigBlocks.blockMirror, 1, 6 ), this.WardedJar ); - - // Items - this.Thaumometer = new ItemStack( ConfigItems.itemThaumometer ); - this.Thaumonomicon = new ItemStack( ConfigItems.itemThaumonomicon ); - this.EtheralEssence = new ItemStack( ConfigItems.itemWispEssence ); - this.ZombieBrain = new ItemStack( ConfigItems.itemZombieBrain ); - this.QuickSilverDrop = new ItemStack( ConfigItems.itemNugget, 1, 5 ); - - } + // Items + this.Thaumometer = new ItemStack(ConfigItems.itemThaumometer); + this.Thaumonomicon = new ItemStack(ConfigItems.itemThaumonomicon); + this.EtheralEssence = new ItemStack(ConfigItems.itemWispEssence); + this.ZombieBrain = new ItemStack(ConfigItems.itemZombieBrain); + this.QuickSilverDrop = new ItemStack(ConfigItems.itemNugget, 1, 5); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureACT.java b/src/main/java/thaumicenergistics/common/features/FeatureACT.java index 1ca59c24..db26e3df 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureACT.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureACT.java @@ -22,89 +22,82 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureACT - extends ThEThaumcraftResearchFeature -{ +public class FeatureACT extends ThEThaumcraftResearchFeature { - public FeatureACT() - { - super( ResearchTypes.ARCANE_TERMINAL.getKey() ); - } + public FeatureACT() { + super(ResearchTypes.ARCANE_TERMINAL.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on crafting terminal - if( !AEConfig.instance.isFeatureEnabled( AEFeature.CraftingTerminal ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on crafting terminal + if (!AEConfig.instance.isFeatureEnabled(AEFeature.CraftingTerminal)) { + return false; + } - return theConfig.craftArcaneCraftingTerminal(); - } + return theConfig.craftArcaneCraftingTerminal(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.CalculationProcessor, cdi.METerminal }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.CalculationProcessor, cdi.METerminal}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureThaumicEnergistics; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureThaumicEnergistics; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack ArcaneCraftingTerminal = ThEApi.instance().parts().ArcaneCrafting_Terminal.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack ArcaneCraftingTerminal = + ThEApi.instance().parts().ArcaneCrafting_Terminal.getStack(); - // Arcane Crafting Terminal - AspectList actAspectList = new AspectList(); + // Arcane Crafting Terminal + AspectList actAspectList = new AspectList(); - // Set aspects - actAspectList.add( Aspect.AIR, 10 ); - actAspectList.add( Aspect.EARTH, 10 ); - actAspectList.add( Aspect.ENTROPY, 10 ); - actAspectList.add( Aspect.FIRE, 10 ); - actAspectList.add( Aspect.ORDER, 10 ); - actAspectList.add( Aspect.WATER, 10 ); + // Set aspects + actAspectList.add(Aspect.AIR, 10); + actAspectList.add(Aspect.EARTH, 10); + actAspectList.add(Aspect.ENTROPY, 10); + actAspectList.add(Aspect.FIRE, 10); + actAspectList.add(Aspect.ORDER, 10); + actAspectList.add(Aspect.WATER, 10); - // Set recipe - Object[] actRecipe = new Object[] { cdi.METerminal, cdi.ArcaneWorkTable, cdi.CalculationProcessor }; + // Set recipe + Object[] actRecipe = new Object[] {cdi.METerminal, cdi.ArcaneWorkTable, cdi.CalculationProcessor}; - // Register - RecipeRegistry.PART_ARCANE_TERMINAL = ThaumcraftApi.addShapelessArcaneCraftingRecipe( this.researchKey, - ArcaneCraftingTerminal, actAspectList, actRecipe ); - } + // Register + RecipeRegistry.PART_ARCANE_TERMINAL = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, ArcaneCraftingTerminal, actAspectList, actRecipe); + } - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList actAspectList = new AspectList(); - actAspectList.add( Aspect.CRAFT, 5 ); - actAspectList.add( Aspect.ENERGY, 3 ); - actAspectList.add( Aspect.MECHANISM, 3 ); - actAspectList.add( Aspect.VOID, 3 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList actAspectList = new AspectList(); + actAspectList.add(Aspect.CRAFT, 5); + actAspectList.add(Aspect.ENERGY, 3); + actAspectList.add(Aspect.MECHANISM, 3); + actAspectList.add(Aspect.VOID, 3); - // Set the icon - ItemStack actIcon = AEPartsEnum.ArcaneCraftingTerminal.getStack(); + // Set the icon + ItemStack actIcon = AEPartsEnum.ArcaneCraftingTerminal.getStack(); - // Set the pages - ResearchPage[] actPages = new ResearchPage[] { new ResearchPage( ResearchTypes.ARCANE_TERMINAL.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.PART_ARCANE_TERMINAL ) }; + // Set the pages + ResearchPage[] actPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.ARCANE_TERMINAL.getPageName(1)), + new ResearchPage(RecipeRegistry.PART_ARCANE_TERMINAL) + }; - // Create the IO research - ResearchTypes.ARCANE_TERMINAL.createResearchItem( actAspectList, ResearchRegistry.COMPLEXITY_SMALL, actIcon, actPages ); - ResearchTypes.ARCANE_TERMINAL.researchItem.setParents( this.getFirstValidParentKey( false ) ); - ResearchTypes.ARCANE_TERMINAL.researchItem.registerResearchItem(); - } + // Create the IO research + ResearchTypes.ARCANE_TERMINAL.createResearchItem( + actAspectList, ResearchRegistry.COMPLEXITY_SMALL, actIcon, actPages); + ResearchTypes.ARCANE_TERMINAL.researchItem.setParents(this.getFirstValidParentKey(false)); + ResearchTypes.ARCANE_TERMINAL.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Arcane.java b/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Arcane.java index c2bb4d5c..5b820b2a 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Arcane.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Arcane.java @@ -23,175 +23,203 @@ import thaumicenergistics.common.tiles.TileArcaneAssembler; * @author Nividica * */ -public class FeatureAutocrafting_Arcane - extends ThEThaumcraftResearchFeature -{ +public class FeatureAutocrafting_Arcane extends ThEThaumcraftResearchFeature { - public FeatureAutocrafting_Arcane() - { - super( ResearchTypes.ARCANE_ASSEMBLER.getKey() ); - } + public FeatureAutocrafting_Arcane() { + super(ResearchTypes.ARCANE_ASSEMBLER.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on crafting CPU's - if( !AEConfig.instance.isFeatureEnabled( AEFeature.CraftingCPU ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on crafting CPU's + if (!AEConfig.instance.isFeatureEnabled(AEFeature.CraftingCPU)) { + return false; + } - // Depends on assembler - if( !AEConfig.instance.isFeatureEnabled( AEFeature.MolecularAssembler ) ) - { - return false; - } + // Depends on assembler + if (!AEConfig.instance.isFeatureEnabled(AEFeature.MolecularAssembler)) { + return false; + } - return theConfig.craftArcaneAssembler(); - } + return theConfig.craftArcaneAssembler(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.VibrantGlass, cdi.CalculationProcessor, cdi.LogicProcessor, cdi.MolecularAssembler }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.VibrantGlass, cdi.CalculationProcessor, cdi.LogicProcessor, cdi.MolecularAssembler}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureVRI; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureVRI; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // Thaumcraft items - ItemStack CraftingScepter = VisCraftingHelper.INSTANCE.getCraftingScepter(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // Thaumcraft items + ItemStack CraftingScepter = VisCraftingHelper.INSTANCE.getCraftingScepter(); - // My Items - ItemStack KnowledgeCore = ThEApi.instance().items().KnowledgeCore.getStack(); - ItemStack KnowledgeInscriber = ThEApi.instance().blocks().KnowledgeInscriber.getStack(); - ItemStack ArcaneAssembler = ThEApi.instance().blocks().ArcaneAssembler.getStack(); - ArcaneAssembler.setTagCompound( TileArcaneAssembler.getCraftTag() ); + // My Items + ItemStack KnowledgeCore = ThEApi.instance().items().KnowledgeCore.getStack(); + ItemStack KnowledgeInscriber = + ThEApi.instance().blocks().KnowledgeInscriber.getStack(); + ItemStack ArcaneAssembler = ThEApi.instance().blocks().ArcaneAssembler.getStack(); + ArcaneAssembler.setTagCompound(TileArcaneAssembler.getCraftTag()); - // Knowledge Core - AspectList kCoreAspects = new AspectList(); + // Knowledge Core + AspectList kCoreAspects = new AspectList(); - // Set KC crafting aspects - kCoreAspects.add( Aspect.WATER, 3 ); - kCoreAspects.add( Aspect.ORDER, 3 ); - kCoreAspects.add( Aspect.EARTH, 1 ); + // Set KC crafting aspects + kCoreAspects.add(Aspect.WATER, 3); + kCoreAspects.add(Aspect.ORDER, 3); + kCoreAspects.add(Aspect.EARTH, 1); - // Set KC recipe - Object[] kCoreRecipe = new Object[] { "VLV", "LZL", "VCV", 'V', cdi.VibrantGlass, 'L', cdi.VanillaLapis, 'Z', cdi.ZombieBrain, 'C', - cdi.CalculationProcessor }; + // Set KC recipe + Object[] kCoreRecipe = new Object[] { + "VLV", + "LZL", + "VCV", + 'V', + cdi.VibrantGlass, + 'L', + cdi.VanillaLapis, + 'Z', + cdi.ZombieBrain, + 'C', + cdi.CalculationProcessor + }; - // Register KC - RecipeRegistry.ITEM_KNOWLEDGE_CORE = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - KnowledgeCore, kCoreAspects, kCoreRecipe ); + // Register KC + RecipeRegistry.ITEM_KNOWLEDGE_CORE = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, KnowledgeCore, kCoreAspects, kCoreRecipe); - // Knowledge Inscriber - AspectList kiAspects = new AspectList(); + // Knowledge Inscriber + AspectList kiAspects = new AspectList(); - // Set KI crafting aspects - kiAspects.add( Aspect.WATER, 5 ); - kiAspects.add( Aspect.ORDER, 5 ); - kiAspects.add( Aspect.EARTH, 5 ); - kiAspects.add( Aspect.ENTROPY, 5 ); - kiAspects.add( Aspect.FIRE, 5 ); - kiAspects.add( Aspect.AIR, 5 ); + // Set KI crafting aspects + kiAspects.add(Aspect.WATER, 5); + kiAspects.add(Aspect.ORDER, 5); + kiAspects.add(Aspect.EARTH, 5); + kiAspects.add(Aspect.ENTROPY, 5); + kiAspects.add(Aspect.FIRE, 5); + kiAspects.add(Aspect.AIR, 5); - // Set KI recipe - Object[] kiRecipe = new Object[] { "IPI", " T ", "ILI", 'I', cdi.IronIngot, 'P', cdi.IlluminatedPanel, 'T', cdi.Thaumonomicon, 'L', - cdi.LogicProcessor }; + // Set KI recipe + Object[] kiRecipe = new Object[] { + "IPI", + " T ", + "ILI", + 'I', + cdi.IronIngot, + 'P', + cdi.IlluminatedPanel, + 'T', + cdi.Thaumonomicon, + 'L', + cdi.LogicProcessor + }; - // Register KI - RecipeRegistry.BLOCK_KNOWLEDGE_INSCRIBER = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - KnowledgeInscriber, kiAspects, kiRecipe ); + // Register KI + RecipeRegistry.BLOCK_KNOWLEDGE_INSCRIBER = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, KnowledgeInscriber, kiAspects, kiRecipe); - // Arcane Assembler - AspectList assemblerAspects = new AspectList(); + // Arcane Assembler + AspectList assemblerAspects = new AspectList(); - // Set Assembler crafting aspects - assemblerAspects.add( Aspect.CRAFT, 64 ); - assemblerAspects.add( Aspect.EXCHANGE, 32 ); - assemblerAspects.add( Aspect.AURA, 16 ); - assemblerAspects.add( Aspect.MAGIC, 16 ); - assemblerAspects.add( Aspect.METAL, 8 ); - assemblerAspects.add( Aspect.CRYSTAL, 8 ); + // Set Assembler crafting aspects + assemblerAspects.add(Aspect.CRAFT, 64); + assemblerAspects.add(Aspect.EXCHANGE, 32); + assemblerAspects.add(Aspect.AURA, 16); + assemblerAspects.add(Aspect.MAGIC, 16); + assemblerAspects.add(Aspect.METAL, 8); + assemblerAspects.add(Aspect.CRYSTAL, 8); - // Set Assembler recipe - ItemStack[] assemblerRecipe = { CraftingScepter, cdi.AirShard, cdi.EarthShard, cdi.WaterShard, cdi.BallanceShard, cdi.OrderShard, - cdi.EntropyShard, cdi.FireShard }; + // Set Assembler recipe + ItemStack[] assemblerRecipe = { + CraftingScepter, + cdi.AirShard, + cdi.EarthShard, + cdi.WaterShard, + cdi.BallanceShard, + cdi.OrderShard, + cdi.EntropyShard, + cdi.FireShard + }; - // Register Assembler - RecipeRegistry.BLOCK_ARCANE_ASSEMBLER = ThaumcraftApi.addInfusionCraftingRecipe( this.researchKey, - ArcaneAssembler, 7, assemblerAspects, cdi.MolecularAssembler, assemblerRecipe ); - } + // Register Assembler + RecipeRegistry.BLOCK_ARCANE_ASSEMBLER = ThaumcraftApi.addInfusionCraftingRecipe( + this.researchKey, ArcaneAssembler, 7, assemblerAspects, cdi.MolecularAssembler, assemblerRecipe); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.SCEPTRE.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.SCEPTRE.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set Assembler research aspects - AspectList assemblerAspectList = new AspectList(); - assemblerAspectList.add( Aspect.CRAFT, 5 ); - assemblerAspectList.add( Aspect.MECHANISM, 3 ); - assemblerAspectList.add( Aspect.MIND, 3 ); - assemblerAspectList.add( Aspect.EXCHANGE, 3 ); - assemblerAspectList.add( Aspect.AURA, 3 ); - assemblerAspectList.add( Aspect.GREED, 3 ); + @Override + protected void registerResearch() { + // Set Assembler research aspects + AspectList assemblerAspectList = new AspectList(); + assemblerAspectList.add(Aspect.CRAFT, 5); + assemblerAspectList.add(Aspect.MECHANISM, 3); + assemblerAspectList.add(Aspect.MIND, 3); + assemblerAspectList.add(Aspect.EXCHANGE, 3); + assemblerAspectList.add(Aspect.AURA, 3); + assemblerAspectList.add(Aspect.GREED, 3); - // Set the icon - ItemStack assemblerIcon = ThEApi.instance().blocks().ArcaneAssembler.getStack(); + // Set the icon + ItemStack assemblerIcon = ThEApi.instance().blocks().ArcaneAssembler.getStack(); - // Set the pages - ResearchPage[] assemblerPages = new ResearchPage[] { new ResearchPage( ResearchTypes.ARCANE_ASSEMBLER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_ARCANE_ASSEMBLER ), - new ResearchPage( ResearchTypes.ARCANE_ASSEMBLER.getPageName( 2 ) ), - new ResearchPage( ResearchTypes.ARCANE_ASSEMBLER.getPageName( 3 ) ) }; + // Set the pages + ResearchPage[] assemblerPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.ARCANE_ASSEMBLER.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_ARCANE_ASSEMBLER), + new ResearchPage(ResearchTypes.ARCANE_ASSEMBLER.getPageName(2)), + new ResearchPage(ResearchTypes.ARCANE_ASSEMBLER.getPageName(3)) + }; - // Create the assembler research - ResearchTypes.ARCANE_ASSEMBLER.createResearchItem( assemblerAspectList, ResearchRegistry.COMPLEXITY_LARGE, assemblerIcon, assemblerPages ); + // Create the assembler research + ResearchTypes.ARCANE_ASSEMBLER.createResearchItem( + assemblerAspectList, ResearchRegistry.COMPLEXITY_LARGE, assemblerIcon, assemblerPages); - // Set the parents - ResearchTypes.ARCANE_ASSEMBLER.researchItem.setParents( this.getFirstValidParentKey( false ), PseudoResearchTypes.SCEPTRE.getKey() ); - ResearchTypes.ARCANE_ASSEMBLER.researchItem.setParentsHidden( FeatureRegistry.instance().featureACT.getFirstValidParentKey( true ) ); - ResearchTypes.ARCANE_ASSEMBLER.researchItem.setConcealed(); + // Set the parents + ResearchTypes.ARCANE_ASSEMBLER.researchItem.setParents( + this.getFirstValidParentKey(false), PseudoResearchTypes.SCEPTRE.getKey()); + ResearchTypes.ARCANE_ASSEMBLER.researchItem.setParentsHidden( + FeatureRegistry.instance().featureACT.getFirstValidParentKey(true)); + ResearchTypes.ARCANE_ASSEMBLER.researchItem.setConcealed(); - // Register the research - ResearchTypes.ARCANE_ASSEMBLER.researchItem.registerResearchItem(); + // Register the research + ResearchTypes.ARCANE_ASSEMBLER.researchItem.registerResearchItem(); - // Set Knowledge Inscriber research aspects - AspectList kiAspectList = new AspectList(); - kiAspectList.add( Aspect.MIND, 5 ); - kiAspectList.add( Aspect.MECHANISM, 3 ); - kiAspectList.add( Aspect.CRAFT, 3 ); - kiAspectList.add( Aspect.EXCHANGE, 1 ); + // Set Knowledge Inscriber research aspects + AspectList kiAspectList = new AspectList(); + kiAspectList.add(Aspect.MIND, 5); + kiAspectList.add(Aspect.MECHANISM, 3); + kiAspectList.add(Aspect.CRAFT, 3); + kiAspectList.add(Aspect.EXCHANGE, 1); - // Set the icon - ItemStack kiIcon = ThEApi.instance().blocks().KnowledgeInscriber.getStack(); + // Set the icon + ItemStack kiIcon = ThEApi.instance().blocks().KnowledgeInscriber.getStack(); - // Set the pages - ResearchPage[] kiPages = new ResearchPage[] { new ResearchPage( ResearchTypes.KNOWLEDGE_INSCRIBER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.ITEM_KNOWLEDGE_CORE ), new ResearchPage( RecipeRegistry.BLOCK_KNOWLEDGE_INSCRIBER ), - new ResearchPage( ResearchTypes.KNOWLEDGE_INSCRIBER.getPageName( 2 ) ) }; + // Set the pages + ResearchPage[] kiPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.KNOWLEDGE_INSCRIBER.getPageName(1)), + new ResearchPage(RecipeRegistry.ITEM_KNOWLEDGE_CORE), + new ResearchPage(RecipeRegistry.BLOCK_KNOWLEDGE_INSCRIBER), + new ResearchPage(ResearchTypes.KNOWLEDGE_INSCRIBER.getPageName(2)) + }; - // Create the KI research - ResearchTypes.KNOWLEDGE_INSCRIBER.createResearchItem( kiAspectList, ResearchRegistry.COMPLEXITY_SMALL, kiIcon, kiPages ); - ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setSecondary(); + // Create the KI research + ResearchTypes.KNOWLEDGE_INSCRIBER.createResearchItem( + kiAspectList, ResearchRegistry.COMPLEXITY_SMALL, kiIcon, kiPages); + ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setSecondary(); - // Set the parent - ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setParents( ResearchTypes.ARCANE_ASSEMBLER.getKey() ); - ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setConcealed(); - - // Register the research - ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.registerResearchItem(); - } + // Set the parent + ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setParents(ResearchTypes.ARCANE_ASSEMBLER.getKey()); + ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.setConcealed(); + // Register the research + ResearchTypes.KNOWLEDGE_INSCRIBER.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Essentia.java b/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Essentia.java index f3a89334..90795238 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Essentia.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureAutocrafting_Essentia.java @@ -21,97 +21,99 @@ import thaumicenergistics.common.tiles.TileDistillationPatternEncoder; * @author Nividica * */ -public class FeatureAutocrafting_Essentia - extends ThEThaumcraftResearchFeature -{ +public class FeatureAutocrafting_Essentia extends ThEThaumcraftResearchFeature { - public FeatureAutocrafting_Essentia() - { - super( ResearchTypes.DISTILLATION_PATTERN_ENCODER.getKey() ); - } + public FeatureAutocrafting_Essentia() { + super(ResearchTypes.DISTILLATION_PATTERN_ENCODER.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on crafting CPU's - if( !AEConfig.instance.isFeatureEnabled( AEFeature.CraftingCPU ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on crafting CPU's + if (!AEConfig.instance.isFeatureEnabled(AEFeature.CraftingCPU)) { + return false; + } - return theConfig.craftDistillationPatternEncoder(); - } + return theConfig.craftDistillationPatternEncoder(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.MEInterface, cdi.EngineeringProcessor }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.MEInterface, cdi.EngineeringProcessor}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureEssentiaIOBuses; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureEssentiaIOBuses; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack dpeStack = ThEApi.instance().blocks().DistillationPatternEncoder.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack dpeStack = + ThEApi.instance().blocks().DistillationPatternEncoder.getStack(); - // Aspect list - AspectList dpeAspects = new AspectList(); - dpeAspects.add( Aspect.ORDER, 5 ); - dpeAspects.add( Aspect.ENTROPY, 5 ); - dpeAspects.add( Aspect.FIRE, 3 ); + // Aspect list + AspectList dpeAspects = new AspectList(); + dpeAspects.add(Aspect.ORDER, 5); + dpeAspects.add(Aspect.ENTROPY, 5); + dpeAspects.add(Aspect.FIRE, 3); - // Recipe - Object[] dpeRecipe = new Object[] { "IPI", " T ", "IEI", 'I', cdi.IronIngot, 'P', cdi.IlluminatedPanel, 'T', cdi.Thaumometer, 'E', - cdi.EngineeringProcessor }; + // Recipe + Object[] dpeRecipe = new Object[] { + "IPI", + " T ", + "IEI", + 'I', + cdi.IronIngot, + 'P', + cdi.IlluminatedPanel, + 'T', + cdi.Thaumometer, + 'E', + cdi.EngineeringProcessor + }; - // Register - RecipeRegistry.BLOCK_DISTILLATION_PATTERN_ENCODER = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - dpeStack, dpeAspects, dpeRecipe ); + // Register + RecipeRegistry.BLOCK_DISTILLATION_PATTERN_ENCODER = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, dpeStack, dpeAspects, dpeRecipe); + } - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerResearch() { + // Aspect list + AspectList dpeAspects = new AspectList(); + dpeAspects.add(Aspect.CRAFT, 5); + dpeAspects.add(Aspect.EXCHANGE, 5); + dpeAspects.add(Aspect.ENTROPY, 5); + dpeAspects.add(Aspect.MECHANISM, 3); + dpeAspects.add(Aspect.GREED, 3); + dpeAspects.add(Aspect.MIND, 1); - @Override - protected void registerResearch() - { - // Aspect list - AspectList dpeAspects = new AspectList(); - dpeAspects.add( Aspect.CRAFT, 5 ); - dpeAspects.add( Aspect.EXCHANGE, 5 ); - dpeAspects.add( Aspect.ENTROPY, 5 ); - dpeAspects.add( Aspect.MECHANISM, 3 ); - dpeAspects.add( Aspect.GREED, 3 ); - dpeAspects.add( Aspect.MIND, 1 ); + // Icon + ItemStack dpeIcon = + ThEApi.instance().blocks().DistillationPatternEncoder.getStack(); - // Icon - ItemStack dpeIcon = ThEApi.instance().blocks().DistillationPatternEncoder.getStack(); + // Pages + ResearchPage[] dpePages = new ResearchPage[] { + new ResearchPage(ResearchTypes.DISTILLATION_PATTERN_ENCODER.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_DISTILLATION_PATTERN_ENCODER) + }; - // Pages - ResearchPage[] dpePages = new ResearchPage[] { new ResearchPage( ResearchTypes.DISTILLATION_PATTERN_ENCODER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_DISTILLATION_PATTERN_ENCODER ) }; + // Create the research item + ResearchTypes.DISTILLATION_PATTERN_ENCODER.createResearchItem( + dpeAspects, ResearchRegistry.COMPLEXITY_LARGE, dpeIcon, dpePages); - // Create the research item - ResearchTypes.DISTILLATION_PATTERN_ENCODER.createResearchItem( dpeAspects, ResearchRegistry.COMPLEXITY_LARGE, dpeIcon, dpePages ); - - // Set parents - ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setParents( this.getFirstValidParentKey( false ) ); - ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setParentsHidden( - FeatureRegistry.instance().featureEssentiaMonitoring.getFirstValidParentKey( true ) ); - ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setConcealed(); - - // Register the research - ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.registerResearchItem(); - - } + // Set parents + ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setParents(this.getFirstValidParentKey(false)); + ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setParentsHidden( + FeatureRegistry.instance().featureEssentiaMonitoring.getFirstValidParentKey(true)); + ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.setConcealed(); + // Register the research + ResearchTypes.DISTILLATION_PATTERN_ENCODER.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureCells.java b/src/main/java/thaumicenergistics/common/features/FeatureCells.java index 7f5da667..8364554c 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureCells.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureCells.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.features; -import java.util.ArrayList; import appeng.core.AEConfig; import appeng.core.features.AEFeature; import cpw.mods.fml.common.registry.GameRegistry; +import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.oredict.ShapedOreRecipe; @@ -32,274 +32,369 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureCells - extends ThEThaumcraftResearchFeature -{ - public FeatureCells() - { - super( ResearchTypes.STORAGE.getKey() ); - } +public class FeatureCells extends ThEThaumcraftResearchFeature { + public FeatureCells() { + super(ResearchTypes.STORAGE.getKey()); + } - /** - * Helper function to replace a single item with a group of items in a - * recipe. - * - * @param recipe - * @param ingredient - * @param group - */ - private void replaceRecipeIngredientWithGroup( final ShapedArcaneRecipe recipe, final ItemStack ingredient, final ArrayList group ) - { - // Get the input - Object[] input = recipe.getInput(); + /** + * Helper function to replace a single item with a group of items in a + * recipe. + * + * @param recipe + * @param ingredient + * @param group + */ + private void replaceRecipeIngredientWithGroup( + final ShapedArcaneRecipe recipe, final ItemStack ingredient, final ArrayList group) { + // Get the input + Object[] input = recipe.getInput(); - // For every listed slot change the input to the group - for( int index = 0; index < input.length; index++ ) - { - Object slot = input[index]; + // For every listed slot change the input to the group + for (int index = 0; index < input.length; index++) { + Object slot = input[index]; - // Is this slot an itemstack? - if( slot instanceof ItemStack ) - { - // Does it match the stack to replace? - if( ingredient.isItemEqual( (ItemStack)slot ) ) - { - // Replace it - input[index] = group; - } - } - } - } + // Is this slot an itemstack? + if (slot instanceof ItemStack) { + // Does it match the stack to replace? + if (ingredient.isItemEqual((ItemStack) slot)) { + // Replace it + input[index] = group; + } + } + } + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on cells - if( !AEConfig.instance.isFeatureEnabled( AEFeature.StorageCells ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on cells + if (!AEConfig.instance.isFeatureEnabled(AEFeature.StorageCells)) { + return false; + } - return theConfig.craftEssentiaCells(); - } + return theConfig.craftEssentiaCells(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.ChargedCertusQuartz, cdi.CertusQuartz, cdi.PureCertusQuartz, cdi.LogicProcessor, cdi.EngineeringProcessor, - cdi.CalculationProcessor, cdi.QuartzGlass, cdi.MECellWorkbench }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] { + cdi.ChargedCertusQuartz, + cdi.CertusQuartz, + cdi.PureCertusQuartz, + cdi.LogicProcessor, + cdi.EngineeringProcessor, + cdi.CalculationProcessor, + cdi.QuartzGlass, + cdi.MECellWorkbench + }; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureThaumicEnergistics; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureThaumicEnergistics; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - IThEItems theItems = ThEApi.instance().items(); - ItemStack EssentiaStorageComponent_1k = theItems.EssentiaStorageComponent_1k.getStack(); - ItemStack EssentiaStorageComponent_4k = theItems.EssentiaStorageComponent_4k.getStack(); - ItemStack EssentiaStorageComponent_16k = theItems.EssentiaStorageComponent_16k.getStack(); - ItemStack EssentiaStorageComponent_64k = theItems.EssentiaStorageComponent_64k.getStack(); - ItemStack EssentiaCell_Housing = theItems.EssentiaCell_Casing.getStack(); - ItemStack EssentiaCell_1k = theItems.EssentiaCell_1k.getStack(); - ItemStack EssentiaCell_4k = theItems.EssentiaCell_4k.getStack(); - ItemStack EssentiaCell_16k = theItems.EssentiaCell_16k.getStack(); - ItemStack EssentiaCell_64k = theItems.EssentiaCell_64k.getStack(); - ItemStack EssentiaCellWorkbench = ThEApi.instance().blocks().EssentiaCellWorkbench.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + IThEItems theItems = ThEApi.instance().items(); + ItemStack EssentiaStorageComponent_1k = theItems.EssentiaStorageComponent_1k.getStack(); + ItemStack EssentiaStorageComponent_4k = theItems.EssentiaStorageComponent_4k.getStack(); + ItemStack EssentiaStorageComponent_16k = theItems.EssentiaStorageComponent_16k.getStack(); + ItemStack EssentiaStorageComponent_64k = theItems.EssentiaStorageComponent_64k.getStack(); + ItemStack EssentiaCell_Housing = theItems.EssentiaCell_Casing.getStack(); + ItemStack EssentiaCell_1k = theItems.EssentiaCell_1k.getStack(); + ItemStack EssentiaCell_4k = theItems.EssentiaCell_4k.getStack(); + ItemStack EssentiaCell_16k = theItems.EssentiaCell_16k.getStack(); + ItemStack EssentiaCell_64k = theItems.EssentiaCell_64k.getStack(); + ItemStack EssentiaCellWorkbench = + ThEApi.instance().blocks().EssentiaCellWorkbench.getStack(); - // Item Groups - ArrayList GroupQuartz = new ArrayList( 3 ); - GroupQuartz.add( cdi.CertusQuartz ); - GroupQuartz.add( cdi.ChargedCertusQuartz ); - GroupQuartz.add( cdi.PureCertusQuartz ); + // Item Groups + ArrayList GroupQuartz = new ArrayList(3); + GroupQuartz.add(cdi.CertusQuartz); + GroupQuartz.add(cdi.ChargedCertusQuartz); + GroupQuartz.add(cdi.PureCertusQuartz); - // Housing =============================================== + // Housing =============================================== - // Housing recipe - Object[] recipeHousing = new Object[] { "WRW", "R R", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot }; + // Housing recipe + Object[] recipeHousing = + new Object[] {"WRW", "R R", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot}; - // Register Housing - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_HOUSING = new ShapedOreRecipe( EssentiaCell_Housing, false, recipeHousing ) ); + // Register Housing + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_HOUSING = new ShapedOreRecipe(EssentiaCell_Housing, false, recipeHousing)); - // 1K ==================================================== + // 1K ==================================================== - // 1K Storage aspects - AspectList aspects1KStorage = new AspectList(); - aspects1KStorage.add( Aspect.FIRE, 3 ); - aspects1KStorage.add( Aspect.ORDER, 1 ); + // 1K Storage aspects + AspectList aspects1KStorage = new AspectList(); + aspects1KStorage.add(Aspect.FIRE, 3); + aspects1KStorage.add(Aspect.ORDER, 1); - // 1K Storage recipe - Object[] recipe1KStorage = new Object[] { "EQ ", "QPQ", " QE", 'E', cdi.EtheralEssence, 'Q', cdi.CertusQuartz, 'P', cdi.LogicProcessor }; + // 1K Storage recipe + Object[] recipe1KStorage = new Object[] { + "EQ ", "QPQ", " QE", 'E', cdi.EtheralEssence, 'Q', cdi.CertusQuartz, 'P', cdi.LogicProcessor + }; - // 1K Cell recipe - Object[] recipe1KCell = new Object[] { "WRW", "RCR", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot, 'C', - EssentiaStorageComponent_1k }; + // 1K Cell recipe + Object[] recipe1KCell = new Object[] { + "WRW", + "RCR", + "TTT", + 'W', + cdi.WardedGlass, + 'R', + cdi.RedstoneDust, + 'T', + cdi.ThaumiumIngot, + 'C', + EssentiaStorageComponent_1k + }; - // Register 1K storage - RecipeRegistry.ITEM_STORAGE_COMPONENT_1K = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - EssentiaStorageComponent_1k, - aspects1KStorage, recipe1KStorage ); + // Register 1K storage + RecipeRegistry.ITEM_STORAGE_COMPONENT_1K = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaStorageComponent_1k, aspects1KStorage, recipe1KStorage); - // Register 1K cell - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPED = new ShapedOreRecipe( EssentiaCell_1k, false, recipe1KCell ) ); - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPELESS = new ShapelessOreRecipe( EssentiaCell_1k, EssentiaStorageComponent_1k, - EssentiaCell_Housing ) ); + // Register 1K cell + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPED = new ShapedOreRecipe(EssentiaCell_1k, false, recipe1KCell)); + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPELESS = + new ShapelessOreRecipe(EssentiaCell_1k, EssentiaStorageComponent_1k, EssentiaCell_Housing)); - // Replace regular certus quartz with any of the certus quartz variants in the 1K storage component - this.replaceRecipeIngredientWithGroup( (ShapedArcaneRecipe)RecipeRegistry.ITEM_STORAGE_COMPONENT_1K, cdi.CertusQuartz, GroupQuartz ); + // Replace regular certus quartz with any of the certus quartz variants in the 1K storage component + this.replaceRecipeIngredientWithGroup( + (ShapedArcaneRecipe) RecipeRegistry.ITEM_STORAGE_COMPONENT_1K, cdi.CertusQuartz, GroupQuartz); - // 4K =================================================== + // 4K =================================================== - // 4K Storage aspects - AspectList aspects4KStorage = new AspectList(); - aspects4KStorage.add( Aspect.FIRE, 3 ); - aspects4KStorage.add( Aspect.ORDER, 2 ); + // 4K Storage aspects + AspectList aspects4KStorage = new AspectList(); + aspects4KStorage.add(Aspect.FIRE, 3); + aspects4KStorage.add(Aspect.ORDER, 2); - // 4K Storage recipe - Object[] recipe4KStorage = new Object[] { "EPE", "1G1", "E1E", 'E', cdi.EtheralEssence, '1', EssentiaStorageComponent_1k, 'P', - cdi.CalculationProcessor, 'G', cdi.QuartzGlass }; + // 4K Storage recipe + Object[] recipe4KStorage = new Object[] { + "EPE", + "1G1", + "E1E", + 'E', + cdi.EtheralEssence, + '1', + EssentiaStorageComponent_1k, + 'P', + cdi.CalculationProcessor, + 'G', + cdi.QuartzGlass + }; - // 4K Cell recipe - Object[] recipe4KCell = new Object[] { "WRW", "RCR", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot, 'C', - EssentiaStorageComponent_4k }; + // 4K Cell recipe + Object[] recipe4KCell = new Object[] { + "WRW", + "RCR", + "TTT", + 'W', + cdi.WardedGlass, + 'R', + cdi.RedstoneDust, + 'T', + cdi.ThaumiumIngot, + 'C', + EssentiaStorageComponent_4k + }; - // Register 4K storage - RecipeRegistry.ITEM_STORAGE_COMPONENT_4K = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - EssentiaStorageComponent_4k, - aspects4KStorage, recipe4KStorage ); + // Register 4K storage + RecipeRegistry.ITEM_STORAGE_COMPONENT_4K = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaStorageComponent_4k, aspects4KStorage, recipe4KStorage); - // Register 4K cell - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPED = new ShapedOreRecipe( EssentiaCell_4k, false, recipe4KCell ) ); - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPELESS = new ShapelessOreRecipe( EssentiaCell_4k, EssentiaStorageComponent_4k, - EssentiaCell_Housing ) ); + // Register 4K cell + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPED = new ShapedOreRecipe(EssentiaCell_4k, false, recipe4KCell)); + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPELESS = + new ShapelessOreRecipe(EssentiaCell_4k, EssentiaStorageComponent_4k, EssentiaCell_Housing)); - // 16K =================================================== + // 16K =================================================== - // 16K Storage aspects - AspectList aspects16KStorage = new AspectList(); - aspects16KStorage.add( Aspect.FIRE, 3 ); - aspects16KStorage.add( Aspect.ORDER, 4 ); + // 16K Storage aspects + AspectList aspects16KStorage = new AspectList(); + aspects16KStorage.add(Aspect.FIRE, 3); + aspects16KStorage.add(Aspect.ORDER, 4); - // 16K Storage recipe - Object[] recipe16KStorage = new Object[] { "SPE", "4G4", "E4S", 'E', cdi.EtheralEssence, 'S', cdi.SalisMundus, '4', - EssentiaStorageComponent_4k, 'P', cdi.EngineeringProcessor, 'G', cdi.QuartzGlass }; + // 16K Storage recipe + Object[] recipe16KStorage = new Object[] { + "SPE", + "4G4", + "E4S", + 'E', + cdi.EtheralEssence, + 'S', + cdi.SalisMundus, + '4', + EssentiaStorageComponent_4k, + 'P', + cdi.EngineeringProcessor, + 'G', + cdi.QuartzGlass + }; - // 16K Cell recipe - Object[] recipe16KCell = new Object[] { "WRW", "RCR", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot, 'C', - EssentiaStorageComponent_16k }; + // 16K Cell recipe + Object[] recipe16KCell = new Object[] { + "WRW", + "RCR", + "TTT", + 'W', + cdi.WardedGlass, + 'R', + cdi.RedstoneDust, + 'T', + cdi.ThaumiumIngot, + 'C', + EssentiaStorageComponent_16k + }; - // Register 16K storage - RecipeRegistry.ITEM_STORAGE_COMPONENT_16K = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - EssentiaStorageComponent_16k, - aspects16KStorage, recipe16KStorage ); + // Register 16K storage + RecipeRegistry.ITEM_STORAGE_COMPONENT_16K = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaStorageComponent_16k, aspects16KStorage, recipe16KStorage); - // Register 16K cell - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPED = new ShapedOreRecipe( EssentiaCell_16k, false, recipe16KCell ) ); - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPELESS = new ShapelessOreRecipe( EssentiaCell_16k, - EssentiaStorageComponent_16k, - EssentiaCell_Housing ) ); + // Register 16K cell + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPED = + new ShapedOreRecipe(EssentiaCell_16k, false, recipe16KCell)); + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPELESS = + new ShapelessOreRecipe(EssentiaCell_16k, EssentiaStorageComponent_16k, EssentiaCell_Housing)); - // 64K =================================================== + // 64K =================================================== - // 64K Storage aspects - AspectList aspects64KStorage = new AspectList(); - aspects64KStorage.add( Aspect.FIRE, 3 ); - aspects64KStorage.add( Aspect.ORDER, 8 ); + // 64K Storage aspects + AspectList aspects64KStorage = new AspectList(); + aspects64KStorage.add(Aspect.FIRE, 3); + aspects64KStorage.add(Aspect.ORDER, 8); - // 64K Storage recipe - Object[] recipe64KStorage = new Object[] { "SPS", "6G6", "S6S", 'S', cdi.SalisMundus, '6', EssentiaStorageComponent_16k, 'P', - cdi.EngineeringProcessor, 'G', cdi.QuartzGlass }; + // 64K Storage recipe + Object[] recipe64KStorage = new Object[] { + "SPS", + "6G6", + "S6S", + 'S', + cdi.SalisMundus, + '6', + EssentiaStorageComponent_16k, + 'P', + cdi.EngineeringProcessor, + 'G', + cdi.QuartzGlass + }; - // 64K Cell recipe - Object[] recipe64KCell = new Object[] { "WRW", "RCR", "TTT", 'W', cdi.WardedGlass, 'R', cdi.RedstoneDust, 'T', cdi.ThaumiumIngot, 'C', - EssentiaStorageComponent_64k }; + // 64K Cell recipe + Object[] recipe64KCell = new Object[] { + "WRW", + "RCR", + "TTT", + 'W', + cdi.WardedGlass, + 'R', + cdi.RedstoneDust, + 'T', + cdi.ThaumiumIngot, + 'C', + EssentiaStorageComponent_64k + }; - // Register 64K storage - RecipeRegistry.ITEM_STORAGE_COMPONENT_64K = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, - EssentiaStorageComponent_64k, - aspects64KStorage, recipe64KStorage ); + // Register 64K storage + RecipeRegistry.ITEM_STORAGE_COMPONENT_64K = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaStorageComponent_64k, aspects64KStorage, recipe64KStorage); - // 64K Storage Cell - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPED = new ShapedOreRecipe( EssentiaCell_64k, false, recipe64KCell ) ); - GameRegistry.addRecipe( RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPELESS = new ShapelessOreRecipe( EssentiaCell_64k, - EssentiaStorageComponent_64k, - EssentiaCell_Housing ) ); + // 64K Storage Cell + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPED = + new ShapedOreRecipe(EssentiaCell_64k, false, recipe64KCell)); + GameRegistry.addRecipe( + RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPELESS = + new ShapelessOreRecipe(EssentiaCell_64k, EssentiaStorageComponent_64k, EssentiaCell_Housing)); - // Workbench - GameRegistry.addRecipe( RecipeRegistry.BLOCK_CELL_WORKBENCH = new ShapelessOreRecipe( EssentiaCellWorkbench, EssentiaStorageComponent_1k, - cdi.MECellWorkbench ) ); - } + // Workbench + GameRegistry.addRecipe( + RecipeRegistry.BLOCK_CELL_WORKBENCH = new ShapelessOreRecipe( + EssentiaCellWorkbench, EssentiaStorageComponent_1k, cdi.MECellWorkbench)); + } - @Override - protected void registerPseudoParents() - { - if( Config.wardedStone ) - { - PseudoResearchTypes.WARDED.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + if (Config.wardedStone) { + PseudoResearchTypes.WARDED.registerPsudeoResearch(); + } - PseudoResearchTypes.DISTILESSENTIA.registerPsudeoResearch(); - } + PseudoResearchTypes.DISTILESSENTIA.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList storageAspectList = new AspectList(); - storageAspectList.add( Aspect.VOID, 5 ); - storageAspectList.add( Aspect.ENERGY, 5 ); - storageAspectList.add( Aspect.CRYSTAL, 3 ); - storageAspectList.add( Aspect.METAL, 3 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList storageAspectList = new AspectList(); + storageAspectList.add(Aspect.VOID, 5); + storageAspectList.add(Aspect.ENERGY, 5); + storageAspectList.add(Aspect.CRYSTAL, 3); + storageAspectList.add(Aspect.METAL, 3); - // Set the icon - ItemStack storageIcon = ThEApi.instance().items().EssentiaCell_64k.getStack(); + // Set the icon + ItemStack storageIcon = ThEApi.instance().items().EssentiaCell_64k.getStack(); - // Get the component recipes - IArcaneRecipe[] storageComponentRecipes = new IArcaneRecipe[] { RecipeRegistry.ITEM_STORAGE_COMPONENT_4K, - RecipeRegistry.ITEM_STORAGE_COMPONENT_16K, - RecipeRegistry.ITEM_STORAGE_COMPONENT_64K }; + // Get the component recipes + IArcaneRecipe[] storageComponentRecipes = new IArcaneRecipe[] { + RecipeRegistry.ITEM_STORAGE_COMPONENT_4K, + RecipeRegistry.ITEM_STORAGE_COMPONENT_16K, + RecipeRegistry.ITEM_STORAGE_COMPONENT_64K + }; - // Get the cell shaped recipes - IRecipe[] storageCellsShaped = new IRecipe[] { RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPED, RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPED, - RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPED, RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPED }; + // Get the cell shaped recipes + IRecipe[] storageCellsShaped = new IRecipe[] { + RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPED, + RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPED, + RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPED, + RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPED + }; - // Get the cell shapeless recipes - IRecipe[] storageCellsShapeless = new IRecipe[] { RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPELESS, - RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPELESS, - RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPELESS, RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPELESS }; + // Get the cell shapeless recipes + IRecipe[] storageCellsShapeless = new IRecipe[] { + RecipeRegistry.ITEM_STORAGE_CELL_1K_SHAPELESS, + RecipeRegistry.ITEM_STORAGE_CELL_4K_SHAPELESS, + RecipeRegistry.ITEM_STORAGE_CELL_16K_SHAPELESS, + RecipeRegistry.ITEM_STORAGE_CELL_64K_SHAPELESS + }; - // Set the pages - ResearchPage[] storagePages = new ResearchPage[] { new ResearchPage( ResearchTypes.STORAGE.getPageName( 1 ) ), - new ResearchPage( ResearchTypes.STORAGE.getPageName( 2 ) ), new ResearchPage( RecipeRegistry.ITEM_STORAGE_COMPONENT_1K ), - new ResearchPage( storageComponentRecipes ), new ResearchPage( RecipeRegistry.ITEM_STORAGE_HOUSING ), - new ResearchPage( storageCellsShaped ), new ResearchPage( storageCellsShapeless ), - new ResearchPage( RecipeRegistry.BLOCK_CELL_WORKBENCH ) }; + // Set the pages + ResearchPage[] storagePages = new ResearchPage[] { + new ResearchPage(ResearchTypes.STORAGE.getPageName(1)), + new ResearchPage(ResearchTypes.STORAGE.getPageName(2)), + new ResearchPage(RecipeRegistry.ITEM_STORAGE_COMPONENT_1K), + new ResearchPage(storageComponentRecipes), + new ResearchPage(RecipeRegistry.ITEM_STORAGE_HOUSING), + new ResearchPage(storageCellsShaped), + new ResearchPage(storageCellsShapeless), + new ResearchPage(RecipeRegistry.BLOCK_CELL_WORKBENCH) + }; - String[] storageParents; + String[] storageParents; - // Is the warded stone research enabled? - if( Config.wardedStone ) - { - storageParents = new String[3]; - storageParents[2] = PseudoResearchTypes.WARDED.getKey(); - } - else - { - storageParents = new String[2]; - } - storageParents[0] = this.getFirstValidParentKey( false ); - storageParents[1] = PseudoResearchTypes.DISTILESSENTIA.getKey(); - - // Create the storage research - ResearchTypes.STORAGE.createResearchItem( storageAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, storageIcon, storagePages ); - ResearchTypes.STORAGE.researchItem.setParents( storageParents ); - ResearchTypes.STORAGE.researchItem.setParentsHidden( "DISTILESSENTIA" ); - ResearchTypes.STORAGE.researchItem.registerResearchItem(); - } + // Is the warded stone research enabled? + if (Config.wardedStone) { + storageParents = new String[3]; + storageParents[2] = PseudoResearchTypes.WARDED.getKey(); + } else { + storageParents = new String[2]; + } + storageParents[0] = this.getFirstValidParentKey(false); + storageParents[1] = PseudoResearchTypes.DISTILESSENTIA.getKey(); + // Create the storage research + ResearchTypes.STORAGE.createResearchItem( + storageAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, storageIcon, storagePages); + ResearchTypes.STORAGE.researchItem.setParents(storageParents); + ResearchTypes.STORAGE.researchItem.setParentsHidden("DISTILESSENTIA"); + ResearchTypes.STORAGE.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureConversionCores.java b/src/main/java/thaumicenergistics/common/features/FeatureConversionCores.java index b5f5a01e..1417ddd0 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureConversionCores.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureConversionCores.java @@ -20,88 +20,96 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureConversionCores - extends ThEThaumcraftResearchFeature -{ +public class FeatureConversionCores extends ThEThaumcraftResearchFeature { - public FeatureConversionCores() - { - super( ResearchTypes.CORES.getKey() ); - } + public FeatureConversionCores() { + super(ResearchTypes.CORES.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - return true; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + return true; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.FormationCore, cdi.AnnihilationCore }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.FormationCore, cdi.AnnihilationCore}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureThaumicEnergistics; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureThaumicEnergistics; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); - ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); + ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); - // Set Coalescence Core aspects - AspectList coalescenceAspects = new AspectList(); - coalescenceAspects.add( Aspect.WATER, 2 ); - coalescenceAspects.add( Aspect.ORDER, 2 ); + // Set Coalescence Core aspects + AspectList coalescenceAspects = new AspectList(); + coalescenceAspects.add(Aspect.WATER, 2); + coalescenceAspects.add(Aspect.ORDER, 2); - // Register Coalescence Core - RecipeRegistry.MATERIAL_COALESCENCE_CORE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( this.researchKey, - CoalescenceCore, coalescenceAspects, cdi.QuickSilverDrop, cdi.QuickSilverDrop, cdi.QuickSilverDrop, cdi.OrderShard, cdi.FormationCore ); + // Register Coalescence Core + RecipeRegistry.MATERIAL_COALESCENCE_CORE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, + CoalescenceCore, + coalescenceAspects, + cdi.QuickSilverDrop, + cdi.QuickSilverDrop, + cdi.QuickSilverDrop, + cdi.OrderShard, + cdi.FormationCore); - // Set Diffusion Core aspects - AspectList diffusionAspects = new AspectList(); - diffusionAspects.add( Aspect.WATER, 2 ); - diffusionAspects.add( Aspect.ENTROPY, 2 ); + // Set Diffusion Core aspects + AspectList diffusionAspects = new AspectList(); + diffusionAspects.add(Aspect.WATER, 2); + diffusionAspects.add(Aspect.ENTROPY, 2); - // Register Diffusion Core - RecipeRegistry.MATERIAL_DIFFUSION_CORE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( this.researchKey, - DiffusionCore, diffusionAspects, cdi.QuickSilverDrop, cdi.QuickSilverDrop, cdi.QuickSilverDrop, cdi.EntropyShard, cdi.AnnihilationCore ); - } + // Register Diffusion Core + RecipeRegistry.MATERIAL_DIFFUSION_CORE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, + DiffusionCore, + diffusionAspects, + cdi.QuickSilverDrop, + cdi.QuickSilverDrop, + cdi.QuickSilverDrop, + cdi.EntropyShard, + cdi.AnnihilationCore); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.DISTILESSENTIA.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.DISTILESSENTIA.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList coreAspectList = new AspectList(); - coreAspectList.add( Aspect.SLIME, 3 ); - coreAspectList.add( Aspect.MAGIC, 5 ); - coreAspectList.add( Aspect.MECHANISM, 5 ); - coreAspectList.add( Aspect.EXCHANGE, 5 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList coreAspectList = new AspectList(); + coreAspectList.add(Aspect.SLIME, 3); + coreAspectList.add(Aspect.MAGIC, 5); + coreAspectList.add(Aspect.MECHANISM, 5); + coreAspectList.add(Aspect.EXCHANGE, 5); - // Set the icon - ItemStack coreIcon = ItemMaterial.MaterialTypes.COALESCENCE_CORE.getStack(); + // Set the icon + ItemStack coreIcon = ItemMaterial.MaterialTypes.COALESCENCE_CORE.getStack(); - // Set the pages - ResearchPage[] corePages = new ResearchPage[] { new ResearchPage( ResearchTypes.CORES.getPageName( 1 ) ), - new ResearchPage( ResearchTypes.CORES.getPageName( 2 ) ), new ResearchPage( RecipeRegistry.MATERIAL_COALESCENCE_CORE ), - new ResearchPage( RecipeRegistry.MATERIAL_DIFFUSION_CORE ) }; - - // Create the core research - ResearchTypes.CORES.createResearchItem( coreAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, coreIcon, corePages ); - ResearchTypes.CORES.researchItem.setParents( this.getFirstValidParentKey( false ), PseudoResearchTypes.DISTILESSENTIA.getKey() ); - ResearchTypes.CORES.researchItem.setParentsHidden( "DISTILESSENTIA" ); - ResearchTypes.CORES.researchItem.registerResearchItem(); - } + // Set the pages + ResearchPage[] corePages = new ResearchPage[] { + new ResearchPage(ResearchTypes.CORES.getPageName(1)), + new ResearchPage(ResearchTypes.CORES.getPageName(2)), + new ResearchPage(RecipeRegistry.MATERIAL_COALESCENCE_CORE), + new ResearchPage(RecipeRegistry.MATERIAL_DIFFUSION_CORE) + }; + // Create the core research + ResearchTypes.CORES.createResearchItem(coreAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, coreIcon, corePages); + ResearchTypes.CORES.researchItem.setParents( + this.getFirstValidParentKey(false), PseudoResearchTypes.DISTILESSENTIA.getKey()); + ResearchTypes.CORES.researchItem.setParentsHidden("DISTILESSENTIA"); + ResearchTypes.CORES.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaIOBuses.java b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaIOBuses.java index ede50e5b..70077538 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaIOBuses.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaIOBuses.java @@ -1,8 +1,8 @@ package thaumicenergistics.common.features; -import java.util.ArrayList; import appeng.core.AEConfig; import appeng.core.features.AEFeature; +import java.util.ArrayList; import net.minecraft.item.ItemStack; import thaumcraft.api.ThaumcraftApi; import thaumcraft.api.aspects.Aspect; @@ -26,135 +26,144 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureEssentiaIOBuses - extends ThEThaumcraftResearchFeature -{ +public class FeatureEssentiaIOBuses extends ThEThaumcraftResearchFeature { - private boolean isImportExportEnabled = false; + private boolean isImportExportEnabled = false; - public FeatureEssentiaIOBuses() - { - super( ResearchTypes.IO.getKey() ); - } + public FeatureEssentiaIOBuses() { + super(ResearchTypes.IO.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - this.isImportExportEnabled = theConfig.craftIOBuses() && ( AEConfig.instance.isFeatureEnabled( AEFeature.ImportBus ) || AEConfig.instance - .isFeatureEnabled( AEFeature.ExportBus ) ); + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + this.isImportExportEnabled = theConfig.craftIOBuses() + && (AEConfig.instance.isFeatureEnabled(AEFeature.ImportBus) + || AEConfig.instance.isFeatureEnabled(AEFeature.ExportBus)); - return true; - } + return true; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return null; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return null; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureConversionCores; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureConversionCores; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); - ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); - ItemStack EssentiaStorageBus = ThEApi.instance().parts().Essentia_StorageBus.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); + ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); + ItemStack EssentiaStorageBus = + ThEApi.instance().parts().Essentia_StorageBus.getStack(); - // Set Storage Bus aspects - AspectList storageAspectList = new AspectList(); - storageAspectList.add( Aspect.FIRE, 3 ); - storageAspectList.add( Aspect.EARTH, 3 ); - storageAspectList.add( Aspect.WATER, 1 ); + // Set Storage Bus aspects + AspectList storageAspectList = new AspectList(); + storageAspectList.add(Aspect.FIRE, 3); + storageAspectList.add(Aspect.EARTH, 3); + storageAspectList.add(Aspect.WATER, 1); - // Storage Bus recipe - Object[] recipeStorageBus = new Object[] { true, "DFC", "IWI", 'D', DiffusionCore, 'C', CoalescenceCore, 'I', cdi.IronIngot, 'F', - cdi.FilterTube, 'W', cdi.WardedGlass }; + // Storage Bus recipe + Object[] recipeStorageBus = new Object[] { + true, + "DFC", + "IWI", + 'D', + DiffusionCore, + 'C', + CoalescenceCore, + 'I', + cdi.IronIngot, + 'F', + cdi.FilterTube, + 'W', + cdi.WardedGlass + }; - // Register the storage bus - RecipeRegistry.PART_STORAGE_BUS = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, EssentiaStorageBus, - storageAspectList, recipeStorageBus ); + // Register the storage bus + RecipeRegistry.PART_STORAGE_BUS = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaStorageBus, storageAspectList, recipeStorageBus); - // Is import and export enabled? - if( this.isImportExportEnabled ) - { - // My items - ItemStack EssentiaImportBus = ThEApi.instance().parts().Essentia_ImportBus.getStack(); - ItemStack EssentiaExportBus = ThEApi.instance().parts().Essentia_ExportBus.getStack(); + // Is import and export enabled? + if (this.isImportExportEnabled) { + // My items + ItemStack EssentiaImportBus = + ThEApi.instance().parts().Essentia_ImportBus.getStack(); + ItemStack EssentiaExportBus = + ThEApi.instance().parts().Essentia_ExportBus.getStack(); - // Set IO Bus aspects - AspectList ioAspectList = new AspectList(); - ioAspectList.add( Aspect.FIRE, 2 ); - ioAspectList.add( Aspect.EARTH, 2 ); - ioAspectList.add( Aspect.WATER, 1 ); + // Set IO Bus aspects + AspectList ioAspectList = new AspectList(); + ioAspectList.add(Aspect.FIRE, 2); + ioAspectList.add(Aspect.EARTH, 2); + ioAspectList.add(Aspect.WATER, 1); - // Import Bus recipe - Object[] recipeImportBus = new Object[] { "JDJ", "IFI", 'J', cdi.WardedJar, 'D', DiffusionCore, 'I', cdi.IronIngot, 'F', cdi.FilterTube }; + // Import Bus recipe + Object[] recipeImportBus = new Object[] { + "JDJ", "IFI", 'J', cdi.WardedJar, 'D', DiffusionCore, 'I', cdi.IronIngot, 'F', cdi.FilterTube + }; - // Export Bus recipe - Object[] recipeExportBus = new Object[] { "JCJ", "IFI", 'J', cdi.WardedJar, 'C', CoalescenceCore, 'I', cdi.IronIngot, 'F', - cdi.FilterTube }; + // Export Bus recipe + Object[] recipeExportBus = new Object[] { + "JCJ", "IFI", 'J', cdi.WardedJar, 'C', CoalescenceCore, 'I', cdi.IronIngot, 'F', cdi.FilterTube + }; - // Register Import Bus - RecipeRegistry.PART_IMPORT_BUS = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, EssentiaImportBus, - ioAspectList, recipeImportBus ); + // Register Import Bus + RecipeRegistry.PART_IMPORT_BUS = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaImportBus, ioAspectList, recipeImportBus); - // Register Export Bus - RecipeRegistry.PART_EXPORT_BUS = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, EssentiaExportBus, - ioAspectList, recipeExportBus ); - } - } + // Register Export Bus + RecipeRegistry.PART_EXPORT_BUS = ThaumcraftApi.addArcaneCraftingRecipe( + this.researchKey, EssentiaExportBus, ioAspectList, recipeExportBus); + } + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.TUBEFILTER.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.TUBEFILTER.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList ioAspectList = new AspectList(); - ioAspectList.add( Aspect.MECHANISM, 5 ); - ioAspectList.add( Aspect.METAL, 3 ); - ioAspectList.add( Aspect.CRYSTAL, 3 ); - ioAspectList.add( Aspect.AIR, 3 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList ioAspectList = new AspectList(); + ioAspectList.add(Aspect.MECHANISM, 5); + ioAspectList.add(Aspect.METAL, 3); + ioAspectList.add(Aspect.CRYSTAL, 3); + ioAspectList.add(Aspect.AIR, 3); - // Set the icon - ItemStack ioIcon = AEPartsEnum.EssentiaExportBus.getStack(); + // Set the icon + ItemStack ioIcon = AEPartsEnum.EssentiaExportBus.getStack(); - ArrayList pageList = new ArrayList(); + ArrayList pageList = new ArrayList(); - // Info pages - if( this.isImportExportEnabled ) - { - pageList.add( new ResearchPage( ResearchTypes.IO.getPageName( 1 ) ) ); - } - pageList.add( new ResearchPage( ResearchTypes.IO.getPageName( 2 ) ) ); + // Info pages + if (this.isImportExportEnabled) { + pageList.add(new ResearchPage(ResearchTypes.IO.getPageName(1))); + } + pageList.add(new ResearchPage(ResearchTypes.IO.getPageName(2))); - // Recipe pages - if( this.isImportExportEnabled ) - { - pageList.add( new ResearchPage( RecipeRegistry.PART_IMPORT_BUS ) ); - pageList.add( new ResearchPage( RecipeRegistry.PART_EXPORT_BUS ) ); - } + // Recipe pages + if (this.isImportExportEnabled) { + pageList.add(new ResearchPage(RecipeRegistry.PART_IMPORT_BUS)); + pageList.add(new ResearchPage(RecipeRegistry.PART_EXPORT_BUS)); + } - pageList.add( new ResearchPage( RecipeRegistry.PART_STORAGE_BUS ) ); + pageList.add(new ResearchPage(RecipeRegistry.PART_STORAGE_BUS)); - // Set the pages - ResearchPage[] ioPages = pageList.toArray( new ResearchPage[pageList.size()] ); + // Set the pages + ResearchPage[] ioPages = pageList.toArray(new ResearchPage[pageList.size()]); - // Create the IO research - ResearchTypes.IO.createResearchItem( ioAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, ioIcon, ioPages ); - ResearchTypes.IO.researchItem.setParents( this.getFirstValidParentKey( false ), PseudoResearchTypes.TUBEFILTER.getKey() ); - ResearchTypes.IO.researchItem.setParentsHidden( "TUBEFILTER" ); - ResearchTypes.IO.researchItem.setConcealed(); - ResearchTypes.IO.researchItem.registerResearchItem(); - } + // Create the IO research + ResearchTypes.IO.createResearchItem(ioAspectList, ResearchRegistry.COMPLEXITY_MEDIUM, ioIcon, ioPages); + ResearchTypes.IO.researchItem.setParents( + this.getFirstValidParentKey(false), PseudoResearchTypes.TUBEFILTER.getKey()); + ResearchTypes.IO.researchItem.setParentsHidden("TUBEFILTER"); + ResearchTypes.IO.researchItem.setConcealed(); + ResearchTypes.IO.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaMonitoring.java b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaMonitoring.java index 13775b07..21be74c1 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaMonitoring.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaMonitoring.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.features; -import java.util.ArrayList; import appeng.core.AEConfig; import appeng.core.features.AEFeature; import cpw.mods.fml.common.registry.GameRegistry; +import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.ShapelessOreRecipe; import thaumcraft.api.ThaumcraftApi; @@ -29,143 +29,144 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureEssentiaMonitoring - extends ThEThaumcraftResearchFeature -{ +public class FeatureEssentiaMonitoring extends ThEThaumcraftResearchFeature { - private boolean isWirelessEnabled = false, isConversionEnabled = false; + private boolean isWirelessEnabled = false, isConversionEnabled = false; - public FeatureEssentiaMonitoring() - { - super( ResearchTypes.ESSENTIA_TERMINAL.getKey() ); - } + public FeatureEssentiaMonitoring() { + super(ResearchTypes.ESSENTIA_TERMINAL.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - this.isConversionEnabled = AEConfig.instance.isFeatureEnabled( AEFeature.PartConversionMonitor ); - this.isWirelessEnabled = AEConfig.instance.isFeatureEnabled( AEFeature.WirelessAccessTerminal ) && theConfig.craftWirelessEssentiaTerminal(); - return true; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + this.isConversionEnabled = AEConfig.instance.isFeatureEnabled(AEFeature.PartConversionMonitor); + this.isWirelessEnabled = AEConfig.instance.isFeatureEnabled(AEFeature.WirelessAccessTerminal) + && theConfig.craftWirelessEssentiaTerminal(); + return true; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - this.isWirelessEnabled &= ( cdi.DenseCell != null ) && ( cdi.WirelessReceiver != null ); + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + this.isWirelessEnabled &= (cdi.DenseCell != null) && (cdi.WirelessReceiver != null); - return new Object[] { cdi.LogicProcessor, cdi.CalculationProcessor }; - } + return new Object[] {cdi.LogicProcessor, cdi.CalculationProcessor}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureConversionCores; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureConversionCores; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - IThEItems theItems = ThEApi.instance().items(); - IThEParts theParts = ThEApi.instance().parts(); - ItemStack DiffusionCore = theItems.DiffusionCore.getStack(); - ItemStack CoalescenceCore = theItems.CoalescenceCore.getStack(); - ItemStack EssentiaTerminal = theParts.Essentia_Terminal.getStack(); - ItemStack EssentiaLevelEmitter = theParts.Essentia_LevelEmitter.getStack(); - ItemStack EssentiaStorageMonitor = theParts.Essentia_StorageMonitor.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + IThEItems theItems = ThEApi.instance().items(); + IThEParts theParts = ThEApi.instance().parts(); + ItemStack DiffusionCore = theItems.DiffusionCore.getStack(); + ItemStack CoalescenceCore = theItems.CoalescenceCore.getStack(); + ItemStack EssentiaTerminal = theParts.Essentia_Terminal.getStack(); + ItemStack EssentiaLevelEmitter = theParts.Essentia_LevelEmitter.getStack(); + ItemStack EssentiaStorageMonitor = theParts.Essentia_StorageMonitor.getStack(); - // Set Essentia Terminal aspects - AspectList etAspectList = new AspectList(); - etAspectList.add( Aspect.WATER, 5 ); - etAspectList.add( Aspect.ORDER, 2 ); - etAspectList.add( Aspect.FIRE, 1 ); + // Set Essentia Terminal aspects + AspectList etAspectList = new AspectList(); + etAspectList.add(Aspect.WATER, 5); + etAspectList.add(Aspect.ORDER, 2); + etAspectList.add(Aspect.FIRE, 1); - // Register Essentia Terminal - RecipeRegistry.PART_ESSENTIA_TERMINAL = ThaumcraftApi.addShapelessArcaneCraftingRecipe( - this.researchKey, EssentiaTerminal, etAspectList, cdi.IlluminatedPanel, DiffusionCore, - CoalescenceCore, cdi.LogicProcessor, cdi.VisFilter ); + // Register Essentia Terminal + RecipeRegistry.PART_ESSENTIA_TERMINAL = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, + EssentiaTerminal, + etAspectList, + cdi.IlluminatedPanel, + DiffusionCore, + CoalescenceCore, + cdi.LogicProcessor, + cdi.VisFilter); - // Is wireless term enabled? - if( this.isWirelessEnabled ) - { - ItemStack WirelessEssentiaTerminal = theItems.WirelessEssentiaTerminal.getStack(); + // Is wireless term enabled? + if (this.isWirelessEnabled) { + ItemStack WirelessEssentiaTerminal = theItems.WirelessEssentiaTerminal.getStack(); - // Register Wireless Essentia Terminal - GameRegistry.addRecipe( RecipeRegistry.ITEM_WIRELESS_ESSENTIA_TERMINAL = new ShapelessOreRecipe( WirelessEssentiaTerminal, - cdi.WirelessReceiver, EssentiaTerminal, cdi.DenseCell ) ); - } + // Register Wireless Essentia Terminal + GameRegistry.addRecipe( + RecipeRegistry.ITEM_WIRELESS_ESSENTIA_TERMINAL = new ShapelessOreRecipe( + WirelessEssentiaTerminal, cdi.WirelessReceiver, EssentiaTerminal, cdi.DenseCell)); + } - // Set Essentia Level Emitter aspects - AspectList emitterAspectList = new AspectList(); - emitterAspectList.add( Aspect.FIRE, 4 ); + // Set Essentia Level Emitter aspects + AspectList emitterAspectList = new AspectList(); + emitterAspectList.add(Aspect.FIRE, 4); - // Set Essentia Level Emitter crafting result count - EssentiaLevelEmitter.stackSize = 4; + // Set Essentia Level Emitter crafting result count + EssentiaLevelEmitter.stackSize = 4; - // Register Essentia Level Emitter - RecipeRegistry.PART_ESSENTIA_LEVEL_EMITTER = ThaumcraftApi.addShapelessArcaneCraftingRecipe( - this.researchKey, EssentiaLevelEmitter, emitterAspectList, cdi.CalculationProcessor, - cdi.RedstoneTorch, cdi.SalisMundus ); + // Register Essentia Level Emitter + RecipeRegistry.PART_ESSENTIA_LEVEL_EMITTER = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, + EssentiaLevelEmitter, + emitterAspectList, + cdi.CalculationProcessor, + cdi.RedstoneTorch, + cdi.SalisMundus); - // Register Essentia Storage Monitor - GameRegistry.addRecipe( RecipeRegistry.PART_ESSENTIA_STORAGE_MONITOR = new ShapelessOreRecipe( EssentiaStorageMonitor, EssentiaLevelEmitter, - cdi.IlluminatedPanel ) ); + // Register Essentia Storage Monitor + GameRegistry.addRecipe( + RecipeRegistry.PART_ESSENTIA_STORAGE_MONITOR = + new ShapelessOreRecipe(EssentiaStorageMonitor, EssentiaLevelEmitter, cdi.IlluminatedPanel)); - // Is conversion monitor enabled? - if( this.isConversionEnabled ) - { - ItemStack EssentiaConversionMonitor = theParts.Essentia_ConversionMonitor.getStack(); + // Is conversion monitor enabled? + if (this.isConversionEnabled) { + ItemStack EssentiaConversionMonitor = theParts.Essentia_ConversionMonitor.getStack(); - // Register Essentia Conversion Monitor - GameRegistry.addRecipe( RecipeRegistry.PART_ESSENTIA_CONVERSION_MONITOR = new ShapelessOreRecipe( EssentiaConversionMonitor, - CoalescenceCore, EssentiaStorageMonitor, DiffusionCore ) ); - } - } + // Register Essentia Conversion Monitor + GameRegistry.addRecipe( + RecipeRegistry.PART_ESSENTIA_CONVERSION_MONITOR = new ShapelessOreRecipe( + EssentiaConversionMonitor, CoalescenceCore, EssentiaStorageMonitor, DiffusionCore)); + } + } - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList etAspectList = new AspectList(); - etAspectList.add( Aspect.EXCHANGE, 5 ); - etAspectList.add( Aspect.SENSES, 5 ); - etAspectList.add( Aspect.ENERGY, 3 ); - etAspectList.add( Aspect.WATER, 3 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList etAspectList = new AspectList(); + etAspectList.add(Aspect.EXCHANGE, 5); + etAspectList.add(Aspect.SENSES, 5); + etAspectList.add(Aspect.ENERGY, 3); + etAspectList.add(Aspect.WATER, 3); - // Set the icon - ItemStack etIcon = AEPartsEnum.EssentiaTerminal.getStack(); + // Set the icon + ItemStack etIcon = AEPartsEnum.EssentiaTerminal.getStack(); - // Setup pages - ArrayList pageList = new ArrayList(); - pageList.add( new ResearchPage( ResearchTypes.ESSENTIA_TERMINAL.getPageName( 1 ) ) ); - pageList.add( new ResearchPage( ResearchTypes.ESSENTIA_TERMINAL.getPageName( 2 ) ) ); - pageList.add( new ResearchPage( RecipeRegistry.PART_ESSENTIA_TERMINAL ) ); - if( this.isWirelessEnabled ) - { - pageList.add( new ResearchPage( RecipeRegistry.ITEM_WIRELESS_ESSENTIA_TERMINAL ) ); - } - pageList.add( new ResearchPage( ResearchTypes.ESSENTIA_TERMINAL.getPageName( 3 ) ) ); - pageList.add( new ResearchPage( RecipeRegistry.PART_ESSENTIA_LEVEL_EMITTER ) ); - pageList.add( new ResearchPage( ResearchTypes.ESSENTIA_TERMINAL.getPageName( 4 ) ) ); - pageList.add( new ResearchPage( RecipeRegistry.PART_ESSENTIA_STORAGE_MONITOR ) ); - if( this.isConversionEnabled ) - { - pageList.add( new ResearchPage( RecipeRegistry.PART_ESSENTIA_CONVERSION_MONITOR ) ); - } + // Setup pages + ArrayList pageList = new ArrayList(); + pageList.add(new ResearchPage(ResearchTypes.ESSENTIA_TERMINAL.getPageName(1))); + pageList.add(new ResearchPage(ResearchTypes.ESSENTIA_TERMINAL.getPageName(2))); + pageList.add(new ResearchPage(RecipeRegistry.PART_ESSENTIA_TERMINAL)); + if (this.isWirelessEnabled) { + pageList.add(new ResearchPage(RecipeRegistry.ITEM_WIRELESS_ESSENTIA_TERMINAL)); + } + pageList.add(new ResearchPage(ResearchTypes.ESSENTIA_TERMINAL.getPageName(3))); + pageList.add(new ResearchPage(RecipeRegistry.PART_ESSENTIA_LEVEL_EMITTER)); + pageList.add(new ResearchPage(ResearchTypes.ESSENTIA_TERMINAL.getPageName(4))); + pageList.add(new ResearchPage(RecipeRegistry.PART_ESSENTIA_STORAGE_MONITOR)); + if (this.isConversionEnabled) { + pageList.add(new ResearchPage(RecipeRegistry.PART_ESSENTIA_CONVERSION_MONITOR)); + } - // Set the pages - ResearchPage[] etPages = pageList.toArray( new ResearchPage[pageList.size()] ); + // Set the pages + ResearchPage[] etPages = pageList.toArray(new ResearchPage[pageList.size()]); - // Create the IO research - ResearchTypes.ESSENTIA_TERMINAL.createResearchItem( etAspectList, ResearchRegistry.COMPLEXITY_SMALL, etIcon, etPages ); - ResearchTypes.ESSENTIA_TERMINAL.researchItem.setParents( this.getFirstValidParentKey( false ) ); - ResearchTypes.ESSENTIA_TERMINAL.researchItem.setConcealed(); - ResearchTypes.ESSENTIA_TERMINAL.researchItem.setSecondary(); - ResearchTypes.ESSENTIA_TERMINAL.researchItem.registerResearchItem(); - } + // Create the IO research + ResearchTypes.ESSENTIA_TERMINAL.createResearchItem( + etAspectList, ResearchRegistry.COMPLEXITY_SMALL, etIcon, etPages); + ResearchTypes.ESSENTIA_TERMINAL.researchItem.setParents(this.getFirstValidParentKey(false)); + ResearchTypes.ESSENTIA_TERMINAL.researchItem.setConcealed(); + ResearchTypes.ESSENTIA_TERMINAL.researchItem.setSecondary(); + ResearchTypes.ESSENTIA_TERMINAL.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaProvider.java b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaProvider.java index ffeddaca..50a84d1f 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaProvider.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaProvider.java @@ -20,87 +20,86 @@ import thaumicenergistics.common.tiles.TileEssentiaProvider; * @author Nividica * */ -public class FeatureEssentiaProvider - extends ThEThaumcraftResearchFeature -{ +public class FeatureEssentiaProvider extends ThEThaumcraftResearchFeature { - public FeatureEssentiaProvider() - { - super( ResearchTypes.ESSENTIA_PROVIDER.getKey() ); - } + public FeatureEssentiaProvider() { + super(ResearchTypes.ESSENTIA_PROVIDER.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on ThE config - return theConfig.craftEssentiaProvider(); - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on ThE config + return theConfig.craftEssentiaProvider(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.MEInterface }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.MEInterface}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureEssentiaIOBuses; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureEssentiaIOBuses; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); - ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); - ItemStack EssentiaProvider = ThEApi.instance().blocks().EssentiaProvider.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); + ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); + ItemStack EssentiaProvider = ThEApi.instance().blocks().EssentiaProvider.getStack(); - // Set Essentia Provider aspects - AspectList essentiaProviderList = new AspectList(); - essentiaProviderList.add( Aspect.MECHANISM, 64 ); - essentiaProviderList.add( Aspect.MAGIC, 32 ); - essentiaProviderList.add( Aspect.ORDER, 32 ); - essentiaProviderList.add( Aspect.EXCHANGE, 16 ); + // Set Essentia Provider aspects + AspectList essentiaProviderList = new AspectList(); + essentiaProviderList.add(Aspect.MECHANISM, 64); + essentiaProviderList.add(Aspect.MAGIC, 32); + essentiaProviderList.add(Aspect.ORDER, 32); + essentiaProviderList.add(Aspect.EXCHANGE, 16); - // Essentia Provider recipe - ItemStack[] recipeEssentiaProvider = { cdi.FilterTube, cdi.SalisMundus, CoalescenceCore, cdi.WaterShard, cdi.FilterTube, cdi.SalisMundus, - DiffusionCore, cdi.WaterShard }; + // Essentia Provider recipe + ItemStack[] recipeEssentiaProvider = { + cdi.FilterTube, + cdi.SalisMundus, + CoalescenceCore, + cdi.WaterShard, + cdi.FilterTube, + cdi.SalisMundus, + DiffusionCore, + cdi.WaterShard + }; - // Register Essentia Provider - RecipeRegistry.BLOCK_ESSENTIA_PROVIDER = ThaumcraftApi.addInfusionCraftingRecipe( this.researchKey, - EssentiaProvider, 3, essentiaProviderList, cdi.MEInterface, recipeEssentiaProvider ); - } + // Register Essentia Provider + RecipeRegistry.BLOCK_ESSENTIA_PROVIDER = ThaumcraftApi.addInfusionCraftingRecipe( + this.researchKey, EssentiaProvider, 3, essentiaProviderList, cdi.MEInterface, recipeEssentiaProvider); + } - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerResearch() - { - // Set Essentia Provider research aspects - AspectList essentiaProviderList = new AspectList(); - essentiaProviderList.add( Aspect.MECHANISM, 3 ); - essentiaProviderList.add( Aspect.MAGIC, 5 ); - essentiaProviderList.add( Aspect.ORDER, 3 ); - essentiaProviderList.add( Aspect.SENSES, 7 ); + @Override + protected void registerResearch() { + // Set Essentia Provider research aspects + AspectList essentiaProviderList = new AspectList(); + essentiaProviderList.add(Aspect.MECHANISM, 3); + essentiaProviderList.add(Aspect.MAGIC, 5); + essentiaProviderList.add(Aspect.ORDER, 3); + essentiaProviderList.add(Aspect.SENSES, 7); - // Set research icon - ItemStack essentiaProviderIcon = new ItemStack( BlockEnum.ESSENTIA_PROVIDER.getBlock(), 1 ); + // Set research icon + ItemStack essentiaProviderIcon = new ItemStack(BlockEnum.ESSENTIA_PROVIDER.getBlock(), 1); - // Set research pages - ResearchPage[] essentiaProviderPages = new ResearchPage[] { new ResearchPage( ResearchTypes.ESSENTIA_PROVIDER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_ESSENTIA_PROVIDER ) }; - - // Create the research - ResearchTypes.ESSENTIA_PROVIDER.createResearchItem( essentiaProviderList, ResearchRegistry.COMPLEXITY_LARGE, essentiaProviderIcon, - essentiaProviderPages ); - ResearchTypes.ESSENTIA_PROVIDER.researchItem.setParents( this.getFirstValidParentKey( false ) ); - ResearchTypes.ESSENTIA_PROVIDER.researchItem.setParentsHidden( "INFUSION", "TUBEFILTER" ); - ResearchTypes.ESSENTIA_PROVIDER.researchItem.setConcealed(); - ResearchTypes.ESSENTIA_PROVIDER.researchItem.registerResearchItem(); - } + // Set research pages + ResearchPage[] essentiaProviderPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.ESSENTIA_PROVIDER.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_ESSENTIA_PROVIDER) + }; + // Create the research + ResearchTypes.ESSENTIA_PROVIDER.createResearchItem( + essentiaProviderList, ResearchRegistry.COMPLEXITY_LARGE, essentiaProviderIcon, essentiaProviderPages); + ResearchTypes.ESSENTIA_PROVIDER.researchItem.setParents(this.getFirstValidParentKey(false)); + ResearchTypes.ESSENTIA_PROVIDER.researchItem.setParentsHidden("INFUSION", "TUBEFILTER"); + ResearchTypes.ESSENTIA_PROVIDER.researchItem.setConcealed(); + ResearchTypes.ESSENTIA_PROVIDER.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaVibrationChamber.java index 25fd7d61..4f157750 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureEssentiaVibrationChamber.java @@ -21,96 +21,92 @@ import thaumicenergistics.common.tiles.TileEssentiaVibrationChamber; * @author Nividica * */ -public class FeatureEssentiaVibrationChamber - extends ThEThaumcraftResearchFeature -{ - public FeatureEssentiaVibrationChamber() - { - super( ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getKey() ); - } +public class FeatureEssentiaVibrationChamber extends ThEThaumcraftResearchFeature { + public FeatureEssentiaVibrationChamber() { + super(ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on power generation - if( !AEConfig.instance.isFeatureEnabled( AEFeature.PowerGen ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on power generation + if (!AEConfig.instance.isFeatureEnabled(AEFeature.PowerGen)) { + return false; + } - return theConfig.craftEssentiaVibrationChamber(); - } + return theConfig.craftEssentiaVibrationChamber(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - // Depends on warded jars, annihilation core, and vibration chamber - return new Object[] { cdi.WardedJar, cdi.VibrationChamber, cdi.AnnihilationCore }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + // Depends on warded jars, annihilation core, and vibration chamber + return new Object[] {cdi.WardedJar, cdi.VibrationChamber, cdi.AnnihilationCore}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureConversionCores; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureConversionCores; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My Items - ItemStack EssVibrationChamber = ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); - ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My Items + ItemStack EssVibrationChamber = + ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); + ItemStack DiffusionCore = ThEApi.instance().items().DiffusionCore.getStack(); - // Chamber aspects - AspectList chamberAspects = new AspectList(); - chamberAspects.add( Aspect.WATER, 2 ); - chamberAspects.add( Aspect.ENTROPY, 4 ); - chamberAspects.add( Aspect.FIRE, 7 ); - chamberAspects.add( Aspect.ORDER, 4 ); + // Chamber aspects + AspectList chamberAspects = new AspectList(); + chamberAspects.add(Aspect.WATER, 2); + chamberAspects.add(Aspect.ENTROPY, 4); + chamberAspects.add(Aspect.FIRE, 7); + chamberAspects.add(Aspect.ORDER, 4); - // Register Chamber - RecipeRegistry.BLOCK_ESSENTIA_VIBRATION_CHAMBER = ThaumcraftApi.addShapelessArcaneCraftingRecipe( this.researchKey, - EssVibrationChamber, chamberAspects, cdi.VibrationChamber, DiffusionCore, - cdi.WardedJar ); - } + // Register Chamber + RecipeRegistry.BLOCK_ESSENTIA_VIBRATION_CHAMBER = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, + EssVibrationChamber, + chamberAspects, + cdi.VibrationChamber, + DiffusionCore, + cdi.WardedJar); + } - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList chamberAspects = new AspectList(); - chamberAspects.add( Aspect.MECHANISM, 5 ); // Its a machine that - chamberAspects.add( Aspect.MAGIC, 3 ); // Takes essentia, specifically - chamberAspects.add( Aspect.WATER, 1 ); // Takes liquid essentia then - chamberAspects.add( Aspect.MOTION, 3 ); // Vibrates to - chamberAspects.add( Aspect.ENERGY, 5 ); // Produces power + @Override + protected void registerResearch() { + // Set the research aspects + AspectList chamberAspects = new AspectList(); + chamberAspects.add(Aspect.MECHANISM, 5); // Its a machine that + chamberAspects.add(Aspect.MAGIC, 3); // Takes essentia, specifically + chamberAspects.add(Aspect.WATER, 1); // Takes liquid essentia then + chamberAspects.add(Aspect.MOTION, 3); // Vibrates to + chamberAspects.add(Aspect.ENERGY, 5); // Produces power - // Get the icon - ItemStack chamberIcon = ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); + // Get the icon + ItemStack chamberIcon = + ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); - // Create the pages - ResearchPage[] storagePages = new ResearchPage[] { new ResearchPage( ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_ESSENTIA_VIBRATION_CHAMBER ), - new ResearchPage( ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName( 2 ) ), - new ResearchPage( ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName( 3 ) ) }; + // Create the pages + ResearchPage[] storagePages = new ResearchPage[] { + new ResearchPage(ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_ESSENTIA_VIBRATION_CHAMBER), + new ResearchPage(ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName(2)), + new ResearchPage(ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.getPageName(3)) + }; - // Create the research - ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.createResearchItem( chamberAspects, ResearchRegistry.COMPLEXITY_MEDIUM, chamberIcon, storagePages ); + // Create the research + ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.createResearchItem( + chamberAspects, ResearchRegistry.COMPLEXITY_MEDIUM, chamberIcon, storagePages); - // Set the parent to the cores - ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.setParents( this.getFirstValidParentKey( false ) ); + // Set the parent to the cores + ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.setParents(this.getFirstValidParentKey(false)); - // Hide until the parent has been researched - ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.setConcealed(); - - // Register - ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.registerResearchItem(); - - } + // Hide until the parent has been researched + ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.setConcealed(); + // Register + ResearchTypes.ESSENTIA_VIBRATION_CHAMBER.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureGearbox.java b/src/main/java/thaumicenergistics/common/features/FeatureGearbox.java index d3dfe180..176d660b 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureGearbox.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureGearbox.java @@ -21,137 +21,132 @@ import thaumicenergistics.common.tiles.TileGearBox; * @author Nividica * */ -public class FeatureGearbox - extends ThEThaumcraftResearchFeature -{ +public class FeatureGearbox extends ThEThaumcraftResearchFeature { - public FeatureGearbox() - { - super( ResearchTypes.IRON_GEARBOX.getKey() ); - } + public FeatureGearbox() { + super(ResearchTypes.IRON_GEARBOX.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - return true; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + return true; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return null; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return null; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return null; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return null; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // Ore dictionary items - Object WoodGear = "gearWood"; - String IronGear = "gearIron"; + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // Ore dictionary items + Object WoodGear = "gearWood"; + String IronGear = "gearIron"; - // Are there any wooden gears? - if( OreDictionary.getOres( "gearWood" ).size() == 0 ) - { - // Fall back on a stick :-/ - WoodGear = new ItemStack( (Item)Item.itemRegistry.getObject( "stick" ) ); - } + // Are there any wooden gears? + if (OreDictionary.getOres("gearWood").size() == 0) { + // Fall back on a stick :-/ + WoodGear = new ItemStack((Item) Item.itemRegistry.getObject("stick")); + } - // My Items - ItemStack IronGearBox = ThEApi.instance().blocks().IronGearBox.getStack(); - ItemStack ThaumiumGearBox = ThEApi.instance().blocks().ThaumiumGearBox.getStack(); - ItemStack ThEIronGear = ThEApi.instance().items().IronGear.getStack(); + // My Items + ItemStack IronGearBox = ThEApi.instance().blocks().IronGearBox.getStack(); + ItemStack ThaumiumGearBox = ThEApi.instance().blocks().ThaumiumGearBox.getStack(); + ItemStack ThEIronGear = ThEApi.instance().items().IronGear.getStack(); - // Set Iron Gear aspects - AspectList ironGearAspects = new AspectList(); - ironGearAspects.add( Aspect.EARTH, 1 ); - ironGearAspects.add( Aspect.FIRE, 1 ); + // Set Iron Gear aspects + AspectList ironGearAspects = new AspectList(); + ironGearAspects.add(Aspect.EARTH, 1); + ironGearAspects.add(Aspect.FIRE, 1); - // Iron Gear recipe - Object[] recipeIronGear = new Object[] { " I ", " W ", "I I", 'I', cdi.IronIngot, 'W', WoodGear }; + // Iron Gear recipe + Object[] recipeIronGear = new Object[] {" I ", " W ", "I I", 'I', cdi.IronIngot, 'W', WoodGear}; - // Register Iron Gear - RecipeRegistry.MATERIAL_IRON_GEAR = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, ThEIronGear, - ironGearAspects, recipeIronGear ); + // Register Iron Gear + RecipeRegistry.MATERIAL_IRON_GEAR = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, ThEIronGear, ironGearAspects, recipeIronGear); - // Set Iron Gear Box aspects - AspectList igbAspects = new AspectList(); - igbAspects.add( Aspect.AIR, 2 ); - igbAspects.add( Aspect.ORDER, 2 ); + // Set Iron Gear Box aspects + AspectList igbAspects = new AspectList(); + igbAspects.add(Aspect.AIR, 2); + igbAspects.add(Aspect.ORDER, 2); - // Iron Gear Box recipe - Object[] recipeIronGearBox = new Object[] { "SGS", "GGG", "SGS", 'S', cdi.Cobblestone, 'G', IronGear }; + // Iron Gear Box recipe + Object[] recipeIronGearBox = new Object[] {"SGS", "GGG", "SGS", 'S', cdi.Cobblestone, 'G', IronGear}; - RecipeRegistry.BLOCK_IRONGEARBOX = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, IronGearBox, - igbAspects, recipeIronGearBox ); + RecipeRegistry.BLOCK_IRONGEARBOX = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, IronGearBox, igbAspects, recipeIronGearBox); - // Set Thaumium Gear Box aspects - AspectList tgbAspects = new AspectList(); - tgbAspects.add( Aspect.METAL, 16 ); - tgbAspects.add( Aspect.MAGIC, 16 ); + // Set Thaumium Gear Box aspects + AspectList tgbAspects = new AspectList(); + tgbAspects.add(Aspect.METAL, 16); + tgbAspects.add(Aspect.MAGIC, 16); - // Register Thaumium Gear Box - RecipeRegistry.BLOCK_THAUMIUMGEARBOX = ThaumcraftApi.addCrucibleRecipe( ResearchRegistry.ResearchTypes.THAUMIUM_GEARBOX.getKey(), - ThaumiumGearBox, IronGearBox, tgbAspects ); - } + // Register Thaumium Gear Box + RecipeRegistry.BLOCK_THAUMIUMGEARBOX = ThaumcraftApi.addCrucibleRecipe( + ResearchRegistry.ResearchTypes.THAUMIUM_GEARBOX.getKey(), ThaumiumGearBox, IronGearBox, tgbAspects); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.COREUSE.registerPsudeoResearch(); + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.COREUSE.registerPsudeoResearch(); + } - } + @Override + protected void registerResearch() { + // Set the research aspects for the Iron Gear Box + AspectList igbAspects = new AspectList(); + igbAspects.add(Aspect.MECHANISM, 6); + igbAspects.add(Aspect.METAL, 4); + igbAspects.add(Aspect.EXCHANGE, 4); - @Override - protected void registerResearch() - { - // Set the research aspects for the Iron Gear Box - AspectList igbAspects = new AspectList(); - igbAspects.add( Aspect.MECHANISM, 6 ); - igbAspects.add( Aspect.METAL, 4 ); - igbAspects.add( Aspect.EXCHANGE, 4 ); + // Set the icon for the Iron Gear Box + ItemStack igbIcon = ThEApi.instance().items().IronGear.getStack(); - // Set the icon for the Iron Gear Box - ItemStack igbIcon = ThEApi.instance().items().IronGear.getStack(); + // Set the pages for the Iron Gear Box + ResearchPage[] igbPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.IRON_GEARBOX.getPageName(1)), + new ResearchPage(ResearchTypes.IRON_GEARBOX.getPageName(2)), + new ResearchPage(RecipeRegistry.MATERIAL_IRON_GEAR), + new ResearchPage(RecipeRegistry.BLOCK_IRONGEARBOX) + }; - // Set the pages for the Iron Gear Box - ResearchPage[] igbPages = new ResearchPage[] { new ResearchPage( ResearchTypes.IRON_GEARBOX.getPageName( 1 ) ), - new ResearchPage( ResearchTypes.IRON_GEARBOX.getPageName( 2 ) ), new ResearchPage( RecipeRegistry.MATERIAL_IRON_GEAR ), - new ResearchPage( RecipeRegistry.BLOCK_IRONGEARBOX ) }; + // Create the research for the Iron Gear Box + ResearchTypes.IRON_GEARBOX.createResearchItem(igbAspects, ResearchRegistry.COMPLEXITY_SMALL, igbIcon, igbPages); - // Create the research for the Iron Gear Box - ResearchTypes.IRON_GEARBOX.createResearchItem( igbAspects, ResearchRegistry.COMPLEXITY_SMALL, igbIcon, igbPages ); + // Set as secondary and register + ResearchTypes.IRON_GEARBOX.researchItem.setSecondary().registerResearchItem(); - // Set as secondary and register - ResearchTypes.IRON_GEARBOX.researchItem.setSecondary().registerResearchItem(); + // Set the research aspects for the Thaumium Gear Box + AspectList tgbAspects = new AspectList(); + tgbAspects.add(Aspect.MECHANISM, 10); + tgbAspects.add(Aspect.MAGIC, 8); + tgbAspects.add(Aspect.METAL, 5); - // Set the research aspects for the Thaumium Gear Box - AspectList tgbAspects = new AspectList(); - tgbAspects.add( Aspect.MECHANISM, 10 ); - tgbAspects.add( Aspect.MAGIC, 8 ); - tgbAspects.add( Aspect.METAL, 5 ); + // Set the icon for the Thaumium Gear Box + ItemStack tgbIcon = ThEApi.instance().blocks().ThaumiumGearBox.getStack(); - // Set the icon for the Thaumium Gear Box - ItemStack tgbIcon = ThEApi.instance().blocks().ThaumiumGearBox.getStack(); + // Set the pages for the Thaumium Gear Box + ResearchPage[] tgbPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.THAUMIUM_GEARBOX.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_THAUMIUMGEARBOX) + }; - // Set the pages for the Thaumium Gear Box - ResearchPage[] tgbPages = new ResearchPage[] { new ResearchPage( ResearchTypes.THAUMIUM_GEARBOX.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_THAUMIUMGEARBOX ) }; + // Create the item for the Thaumium Gear Box + ResearchTypes.THAUMIUM_GEARBOX.createResearchItem( + tgbAspects, ResearchRegistry.COMPLEXITY_SMALL, tgbIcon, tgbPages); - // Create the item for the Thaumium Gear Box - ResearchTypes.THAUMIUM_GEARBOX.createResearchItem( tgbAspects, ResearchRegistry.COMPLEXITY_SMALL, tgbIcon, tgbPages ); - - // Set parents for the Thaumium Gear Box - ResearchTypes.THAUMIUM_GEARBOX.researchItem.setParents( this.getFirstValidParentKey( true ), PseudoResearchTypes.COREUSE.getKey() ); - ResearchTypes.THAUMIUM_GEARBOX.researchItem.setParentsHidden( "COREUSE" ); - - // Set as secondary and register - ResearchTypes.THAUMIUM_GEARBOX.researchItem.setSecondary().registerResearchItem(); - } + // Set parents for the Thaumium Gear Box + ResearchTypes.THAUMIUM_GEARBOX.researchItem.setParents( + this.getFirstValidParentKey(true), PseudoResearchTypes.COREUSE.getKey()); + ResearchTypes.THAUMIUM_GEARBOX.researchItem.setParentsHidden("COREUSE"); + // Set as secondary and register + ResearchTypes.THAUMIUM_GEARBOX.researchItem.setSecondary().registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureGolemBackpack.java b/src/main/java/thaumicenergistics/common/features/FeatureGolemBackpack.java index 6be5e841..92db0122 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureGolemBackpack.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureGolemBackpack.java @@ -21,112 +21,111 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class FeatureGolemBackpack - extends ThEThaumcraftResearchFeature -{ +public class FeatureGolemBackpack extends ThEThaumcraftResearchFeature { - public FeatureGolemBackpack() - { - super( ResearchRegistry.ResearchTypes.GOLEM_BACKPACK.getKey() ); - } + public FeatureGolemBackpack() { + super(ResearchRegistry.ResearchTypes.GOLEM_BACKPACK.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Did the core fail to transform the required classes? - if( ThECore.golemHooksTransformFailed ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Did the core fail to transform the required classes? + if (ThECore.golemHooksTransformFailed) { + return false; + } - return theConfig.craftGolemWifiBackpack(); - } + return theConfig.craftGolemWifiBackpack(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.MEInterfacePart, cdi.WirelessReceiver, - cdi.FluixCrystal, cdi.MECharger }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.MEInterfacePart, cdi.WirelessReceiver, cdi.FluixCrystal, cdi.MECharger}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureConversionCores; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureConversionCores; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // Backpack item - ItemStack backpack = ThEApi.instance().items().GolemWifiBackpack.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // Backpack item + ItemStack backpack = ThEApi.instance().items().GolemWifiBackpack.getStack(); - // Aspects - AspectList aspects = new AspectList(); - aspects.add( Aspect.AIR, 6 ); - aspects.add( Aspect.FIRE, 4 ); - aspects.add( Aspect.ORDER, 3 ); + // Aspects + AspectList aspects = new AspectList(); + aspects.add(Aspect.AIR, 6); + aspects.add(Aspect.FIRE, 4); + aspects.add(Aspect.ORDER, 3); - // Recipe - Object[] recipe = new Object[] { "TIT", "NWN", "FCF", - 'T', cdi.ThaumiumIngot, - 'I', cdi.MEInterfacePart, - 'N', cdi.Nitor, - 'W', cdi.WirelessReceiver, - 'F', cdi.FluixCrystal, - 'C', cdi.MECharger }; + // Recipe + Object[] recipe = new Object[] { + "TIT", + "NWN", + "FCF", + 'T', + cdi.ThaumiumIngot, + 'I', + cdi.MEInterfacePart, + 'N', + cdi.Nitor, + 'W', + cdi.WirelessReceiver, + 'F', + cdi.FluixCrystal, + 'C', + cdi.MECharger + }; - // Register - RecipeRegistry.ITEM_GOLEM_WIFI_BACKPACK = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, backpack, aspects, recipe ); + // Register + RecipeRegistry.ITEM_GOLEM_WIFI_BACKPACK = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, backpack, aspects, recipe); + } - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.COREGATHER.registerPsudeoResearch(); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.COREGATHER.registerPsudeoResearch(); - } + @Override + protected void registerResearch() { + // Set the research aspects + AspectList aspects = new AspectList(); + aspects.add(Aspect.ENERGY, 5); + aspects.add(Aspect.AURA, 5); + aspects.add(Aspect.MIND, 3); + aspects.add(Aspect.ARMOR, 3); + aspects.add(Aspect.MOTION, 1); + aspects.add(Aspect.EXCHANGE, 1); - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList aspects = new AspectList(); - aspects.add( Aspect.ENERGY, 5 ); - aspects.add( Aspect.AURA, 5 ); - aspects.add( Aspect.MIND, 3 ); - aspects.add( Aspect.ARMOR, 3 ); - aspects.add( Aspect.MOTION, 1 ); - aspects.add( Aspect.EXCHANGE, 1 ); + // Set the icon + ItemStack icon = ThEApi.instance().items().GolemWifiBackpack.getStack(); - // Set the icon - ItemStack icon = ThEApi.instance().items().GolemWifiBackpack.getStack(); + // Set the pages + ResearchPage[] pages = new ResearchPage[] { + new ResearchPage(ResearchTypes.GOLEM_BACKPACK.getPageName(1)), + new ResearchPage(RecipeRegistry.ITEM_GOLEM_WIFI_BACKPACK), + new ResearchPage(ResearchTypes.GOLEM_BACKPACK.getPageName(2)), + new ResearchPage(ResearchTypes.GOLEM_BACKPACK.getPageName(3)), + new ResearchPage(ResearchTypes.GOLEM_BACKPACK.getPageName("COREGATHER")), + new ResearchPage("COREFILL", ResearchTypes.GOLEM_BACKPACK.getPageName("COREFILL")), + new ResearchPage("CORELIQUID", ResearchTypes.GOLEM_BACKPACK.getPageName("CORELIQUID")), + new ResearchPage("COREALCHEMY", ResearchTypes.GOLEM_BACKPACK.getPageName("COREALCHEMY")), + new ResearchPage("UPGRADEORDER", ResearchTypes.GOLEM_BACKPACK.getPageName("UPGRADEORDER")), + new ResearchPage("ADVANCEDGOLEM", ResearchTypes.GOLEM_BACKPACK.getPageName("ADVANCEDGOLEM")) + }; - // Set the pages - ResearchPage[] pages = new ResearchPage[] { - new ResearchPage( ResearchTypes.GOLEM_BACKPACK.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.ITEM_GOLEM_WIFI_BACKPACK ), - new ResearchPage( ResearchTypes.GOLEM_BACKPACK.getPageName( 2 ) ), - new ResearchPage( ResearchTypes.GOLEM_BACKPACK.getPageName( 3 ) ), - new ResearchPage( ResearchTypes.GOLEM_BACKPACK.getPageName( "COREGATHER" ) ), - new ResearchPage( "COREFILL", ResearchTypes.GOLEM_BACKPACK.getPageName( "COREFILL" ) ), - new ResearchPage( "CORELIQUID", ResearchTypes.GOLEM_BACKPACK.getPageName( "CORELIQUID" ) ), - new ResearchPage( "COREALCHEMY", ResearchTypes.GOLEM_BACKPACK.getPageName( "COREALCHEMY" ) ), - new ResearchPage( "UPGRADEORDER", ResearchTypes.GOLEM_BACKPACK.getPageName( "UPGRADEORDER" ) ), - new ResearchPage( "ADVANCEDGOLEM", ResearchTypes.GOLEM_BACKPACK.getPageName( "ADVANCEDGOLEM" ) ) }; + // Create the research + ResearchTypes.GOLEM_BACKPACK.createResearchItem(aspects, ResearchRegistry.COMPLEXITY_LARGE, icon, pages); - // Create the research - ResearchTypes.GOLEM_BACKPACK.createResearchItem( aspects, ResearchRegistry.COMPLEXITY_LARGE, icon, pages ); + // Set parents + ResearchTypes.GOLEM_BACKPACK.researchItem.setParents( + this.getFirstValidParentKey(false), "COREGATHER", PseudoResearchTypes.COREGATHER.getKey()); - // Set parents - ResearchTypes.GOLEM_BACKPACK.researchItem.setParents( this.getFirstValidParentKey( false ), "COREGATHER", - PseudoResearchTypes.COREGATHER.getKey() ); - - // Hide until the parent has been researched - ResearchTypes.GOLEM_BACKPACK.researchItem.setConcealed(); - - // Register - ResearchTypes.GOLEM_BACKPACK.researchItem.registerResearchItem(); - } + // Hide until the parent has been researched + ResearchTypes.GOLEM_BACKPACK.researchItem.setConcealed(); + // Register + ResearchTypes.GOLEM_BACKPACK.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureInfusionProvider.java b/src/main/java/thaumicenergistics/common/features/FeatureInfusionProvider.java index 72b4c355..9e27e566 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureInfusionProvider.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureInfusionProvider.java @@ -22,101 +22,103 @@ import thaumicenergistics.common.tiles.TileInfusionProvider; * @author Nividica * */ -public class FeatureInfusionProvider - extends ThEThaumcraftResearchFeature -{ - public FeatureInfusionProvider() - { - super( ResearchTypes.INFUSION_PROVIDER.getKey() ); - } +public class FeatureInfusionProvider extends ThEThaumcraftResearchFeature { + public FeatureInfusionProvider() { + super(ResearchTypes.INFUSION_PROVIDER.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on ThEConfig - return theConfig.craftInfusionProvider(); - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on ThEConfig + return theConfig.craftInfusionProvider(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.MEInterface }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.MEInterface}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureEssentiaIOBuses; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureEssentiaIOBuses; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); - ItemStack InfusionProvider = ThEApi.instance().blocks().InfusionProvider.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack CoalescenceCore = ThEApi.instance().items().CoalescenceCore.getStack(); + ItemStack InfusionProvider = ThEApi.instance().blocks().InfusionProvider.getStack(); - // Set required aspects for infusion provider - AspectList infusionProviderList = new AspectList(); - infusionProviderList.add( Aspect.MECHANISM, 64 ); - infusionProviderList.add( Aspect.MAGIC, 32 ); - infusionProviderList.add( Aspect.ORDER, 32 ); - infusionProviderList.add( Aspect.EXCHANGE, 16 ); + // Set required aspects for infusion provider + AspectList infusionProviderList = new AspectList(); + infusionProviderList.add(Aspect.MECHANISM, 64); + infusionProviderList.add(Aspect.MAGIC, 32); + infusionProviderList.add(Aspect.ORDER, 32); + infusionProviderList.add(Aspect.EXCHANGE, 16); - // Infusion provider recipe items - ItemStack[] infusionProviderRecipeItems = { cdi.EssentiaMirror, cdi.SalisMundus, CoalescenceCore, cdi.AirShard, cdi.EssentiaMirror, - cdi.SalisMundus, CoalescenceCore, cdi.AirShard }; + // Infusion provider recipe items + ItemStack[] infusionProviderRecipeItems = { + cdi.EssentiaMirror, + cdi.SalisMundus, + CoalescenceCore, + cdi.AirShard, + cdi.EssentiaMirror, + cdi.SalisMundus, + CoalescenceCore, + cdi.AirShard + }; - // Create the infusion provider recipe - RecipeRegistry.BLOCK_INFUSION_PROVIDER = ThaumcraftApi.addInfusionCraftingRecipe( this.researchKey, - InfusionProvider, 4, infusionProviderList, cdi.MEInterface, infusionProviderRecipeItems ); - } + // Create the infusion provider recipe + RecipeRegistry.BLOCK_INFUSION_PROVIDER = ThaumcraftApi.addInfusionCraftingRecipe( + this.researchKey, + InfusionProvider, + 4, + infusionProviderList, + cdi.MEInterface, + infusionProviderRecipeItems); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.INFUSION.registerPsudeoResearch(); - if( Config.allowMirrors ) - { - PseudoResearchTypes.MIRROR.registerPsudeoResearch(); - } - else - { - PseudoResearchTypes.JAR.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.INFUSION.registerPsudeoResearch(); + if (Config.allowMirrors) { + PseudoResearchTypes.MIRROR.registerPsudeoResearch(); + } else { + PseudoResearchTypes.JAR.registerPsudeoResearch(); + } + } - } + @Override + protected void registerResearch() { + // Set the research aspects + AspectList infusionProviderList = new AspectList(); + infusionProviderList.add(Aspect.MECHANISM, 3); + infusionProviderList.add(Aspect.MAGIC, 3); + infusionProviderList.add(Aspect.EXCHANGE, 7); + infusionProviderList.add(Aspect.MOTION, 7); + infusionProviderList.add(Aspect.SENSES, 5); - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList infusionProviderList = new AspectList(); - infusionProviderList.add( Aspect.MECHANISM, 3 ); - infusionProviderList.add( Aspect.MAGIC, 3 ); - infusionProviderList.add( Aspect.EXCHANGE, 7 ); - infusionProviderList.add( Aspect.MOTION, 7 ); - infusionProviderList.add( Aspect.SENSES, 5 ); + // Set the icon + ItemStack infusionProviderIcon = new ItemStack(BlockEnum.INFUSION_PROVIDER.getBlock(), 1); - // Set the icon - ItemStack infusionProviderIcon = new ItemStack( BlockEnum.INFUSION_PROVIDER.getBlock(), 1 ); + // Set the pages + ResearchPage[] infusionProviderPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.INFUSION_PROVIDER.getPageName(1)), + new ResearchPage(RecipeRegistry.BLOCK_INFUSION_PROVIDER) + }; - // Set the pages - ResearchPage[] infusionProviderPages = new ResearchPage[] { new ResearchPage( ResearchTypes.INFUSION_PROVIDER.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.BLOCK_INFUSION_PROVIDER ) }; - - // Are mirrors allowed? - String researchKeyMirrorOrJar = ( Config.allowMirrors ? "MIRROR" : "JARLABEL" ); - String pseudoKeyMirrorOrJar = ( Config.allowMirrors ? PseudoResearchTypes.MIRROR.getKey() : PseudoResearchTypes.JAR.getKey() ); - - // Create the infusion provider research - ResearchTypes.INFUSION_PROVIDER.createResearchItem( infusionProviderList, ResearchRegistry.COMPLEXITY_LARGE, infusionProviderIcon, - infusionProviderPages ); - ResearchTypes.INFUSION_PROVIDER.researchItem.setParents( this.getFirstValidParentKey( false ), pseudoKeyMirrorOrJar, - PseudoResearchTypes.INFUSION.getKey() ); - ResearchTypes.INFUSION_PROVIDER.researchItem.setParentsHidden( researchKeyMirrorOrJar, "INFUSION" ); - ResearchTypes.INFUSION_PROVIDER.researchItem.setConcealed().setSpecial(); - ResearchTypes.INFUSION_PROVIDER.researchItem.registerResearchItem(); - } + // Are mirrors allowed? + String researchKeyMirrorOrJar = (Config.allowMirrors ? "MIRROR" : "JARLABEL"); + String pseudoKeyMirrorOrJar = + (Config.allowMirrors ? PseudoResearchTypes.MIRROR.getKey() : PseudoResearchTypes.JAR.getKey()); + // Create the infusion provider research + ResearchTypes.INFUSION_PROVIDER.createResearchItem( + infusionProviderList, ResearchRegistry.COMPLEXITY_LARGE, infusionProviderIcon, infusionProviderPages); + ResearchTypes.INFUSION_PROVIDER.researchItem.setParents( + this.getFirstValidParentKey(false), pseudoKeyMirrorOrJar, PseudoResearchTypes.INFUSION.getKey()); + ResearchTypes.INFUSION_PROVIDER.researchItem.setParentsHidden(researchKeyMirrorOrJar, "INFUSION"); + ResearchTypes.INFUSION_PROVIDER.researchItem.setConcealed().setSpecial(); + ResearchTypes.INFUSION_PROVIDER.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureQuartzDupe.java b/src/main/java/thaumicenergistics/common/features/FeatureQuartzDupe.java index a1049145..401c4765 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureQuartzDupe.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureQuartzDupe.java @@ -19,99 +19,97 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureQuartzDupe - extends ThEThaumcraftResearchFeature -{ - public FeatureQuartzDupe() - { - super( ResearchTypes.CERTUS_DUPE.getKey() ); - } +public class FeatureQuartzDupe extends ThEThaumcraftResearchFeature { + public FeatureQuartzDupe() { + super(ResearchTypes.CERTUS_DUPE.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on ThE config - return theConfig.enableCertusQuartzDupe(); - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on ThE config + return theConfig.enableCertusQuartzDupe(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return null; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return null; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return null; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return null; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // Certus - String Certus1 = "crystalCertusQuartz"; - ItemStack Certus2 = OreDictionary.getOres( Certus1 ).get( 0 ).copy(); - Certus2.stackSize = 2; + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // Certus + String Certus1 = "crystalCertusQuartz"; + ItemStack Certus2 = OreDictionary.getOres(Certus1).get(0).copy(); + Certus2.stackSize = 2; - // Nether - String NetherQuartz1 = "gemQuartz"; - ItemStack NetherQuartz2 = OreDictionary.getOres( NetherQuartz1 ).get( 0 ).copy(); - NetherQuartz2.stackSize = 2; + // Nether + String NetherQuartz1 = "gemQuartz"; + ItemStack NetherQuartz2 = OreDictionary.getOres(NetherQuartz1).get(0).copy(); + NetherQuartz2.stackSize = 2; - // Certus Quartz - if( cdi.CertusQuartz != null ) - { - AspectList certusAspects = new AspectList(); - certusAspects.add( Aspect.CRYSTAL, 4 ); - certusAspects.add( Aspect.WATER, 2 ); - RecipeRegistry.DUPE_CERTUS = ThaumcraftApi.addCrucibleRecipe( ResearchRegistry.ResearchTypes.CERTUS_DUPE.getKey(), Certus2, Certus1, - certusAspects ); - } + // Certus Quartz + if (cdi.CertusQuartz != null) { + AspectList certusAspects = new AspectList(); + certusAspects.add(Aspect.CRYSTAL, 4); + certusAspects.add(Aspect.WATER, 2); + RecipeRegistry.DUPE_CERTUS = ThaumcraftApi.addCrucibleRecipe( + ResearchRegistry.ResearchTypes.CERTUS_DUPE.getKey(), Certus2, Certus1, certusAspects); + } - // Nether Quartz - AspectList nQAspects = new AspectList(); - nQAspects.add( Aspect.CRYSTAL, 4 ); - nQAspects.add( Aspect.WATER, 2 ); - nQAspects.add( Aspect.ENERGY, 2 ); - RecipeRegistry.DUPE_NETHER_QUARTZ = ThaumcraftApi.addCrucibleRecipe( ResearchRegistry.ResearchTypes.CERTUS_DUPE.getKey(), NetherQuartz2, - NetherQuartz1, nQAspects ); + // Nether Quartz + AspectList nQAspects = new AspectList(); + nQAspects.add(Aspect.CRYSTAL, 4); + nQAspects.add(Aspect.WATER, 2); + nQAspects.add(Aspect.ENERGY, 2); + RecipeRegistry.DUPE_NETHER_QUARTZ = ThaumcraftApi.addCrucibleRecipe( + ResearchRegistry.ResearchTypes.CERTUS_DUPE.getKey(), NetherQuartz2, NetherQuartz1, nQAspects); + } - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.DUPE.registerPsudeoResearch(); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.DUPE.registerPsudeoResearch(); - } + @Override + protected void registerResearch() { + // Set aspects + AspectList certusDupeAspects = new AspectList(); + certusDupeAspects.add(Aspect.CRYSTAL, 5); - @Override - protected void registerResearch() - { - // Set aspects - AspectList certusDupeAspects = new AspectList(); - certusDupeAspects.add( Aspect.CRYSTAL, 5 ); + // Get icon + ItemStack certusDupeIcon = AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeStack(1) + .get(); - // Get icon - ItemStack certusDupeIcon = AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).get(); + // Set pages + ResearchPage[] certusDupePages = new ResearchPage[] { + new ResearchPage(ResearchTypes.CERTUS_DUPE.getPageName(1)), + new ResearchPage(RecipeRegistry.DUPE_CERTUS), + new ResearchPage(RecipeRegistry.DUPE_NETHER_QUARTZ) + }; + // Create the item + ResearchTypes.CERTUS_DUPE.createResearchItem( + certusDupeAspects, ResearchRegistry.COMPLEXITY_SMALL, certusDupeIcon, certusDupePages); - // Set pages - ResearchPage[] certusDupePages = new ResearchPage[] { new ResearchPage( ResearchTypes.CERTUS_DUPE.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.DUPE_CERTUS ), new ResearchPage( RecipeRegistry.DUPE_NETHER_QUARTZ ) }; - // Create the item - ResearchTypes.CERTUS_DUPE.createResearchItem( certusDupeAspects, ResearchRegistry.COMPLEXITY_SMALL, certusDupeIcon, certusDupePages ); + // Set parents + ResearchTypes.CERTUS_DUPE.researchItem.setParents(PseudoResearchTypes.DUPE.getKey()); + ResearchTypes.CERTUS_DUPE.researchItem.setParentsHidden("ALCHEMICALDUPLICATION"); - // Set parents - ResearchTypes.CERTUS_DUPE.researchItem.setParents( PseudoResearchTypes.DUPE.getKey() ); - ResearchTypes.CERTUS_DUPE.researchItem.setParentsHidden( "ALCHEMICALDUPLICATION" ); + // Set secondary and concealed + ResearchTypes.CERTUS_DUPE.researchItem.setSecondary().setConcealed(); - // Set secondary and concealed - ResearchTypes.CERTUS_DUPE.researchItem.setSecondary().setConcealed(); + // Trigger when certus is scanned + ResearchTypes.CERTUS_DUPE.researchItem.setItemTriggers(certusDupeIcon); - // Trigger when certus is scanned - ResearchTypes.CERTUS_DUPE.researchItem.setItemTriggers( certusDupeIcon ); - - // Register - ResearchTypes.CERTUS_DUPE.researchItem.registerResearchItem(); - } + // Register + ResearchTypes.CERTUS_DUPE.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureThaumcraftFacades.java b/src/main/java/thaumicenergistics/common/features/FeatureThaumcraftFacades.java index 8984e5e0..79c0b1af 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureThaumcraftFacades.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureThaumcraftFacades.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.features; -import java.util.regex.Pattern; import appeng.core.FacadeConfig; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; +import java.util.regex.Pattern; import net.minecraft.block.Block; import net.minecraftforge.common.config.Property; import thaumcraft.common.config.Config; @@ -16,124 +16,110 @@ import thaumicenergistics.api.IThEConfig; * @author Nividica * */ -public class FeatureThaumcraftFacades - extends ThEDependencyFeatureBase -{ +public class FeatureThaumcraftFacades extends ThEDependencyFeatureBase { - /** - * Ensures the blocks name is clean - */ - private final Pattern sanitizer; + /** + * Ensures the blocks name is clean + */ + private final Pattern sanitizer; - public FeatureThaumcraftFacades() - { - // Set the pattern - this.sanitizer = Pattern.compile( "[^a-zA-Z0-9]" ); - } + public FeatureThaumcraftFacades() { + // Set the pattern + this.sanitizer = Pattern.compile("[^a-zA-Z0-9]"); + } - /** - * Forces the specified stack to have a facade if possible. - * - * @param block - * @param meta - */ - private void forceEnabled( final Block block, final int meta ) - { - // Sanity check - if( block == null ) - { - return; - } + /** + * Forces the specified stack to have a facade if possible. + * + * @param block + * @param meta + */ + private void forceEnabled(final Block block, final int meta) { + // Sanity check + if (block == null) { + return; + } - // Get the uid for the block - UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor( block ); - if( uid == null ) - { - return; - } + // Get the uid for the block + UniqueIdentifier uid = GameRegistry.findUniqueIdentifierFor(block); + if (uid == null) { + return; + } - // Get the mod and block names - String modName = this.sanitizer.matcher( uid.modId ).replaceAll( "" ); - String blockName = this.sanitizer.matcher( uid.name ).replaceAll( "" ); + // Get the mod and block names + String modName = this.sanitizer.matcher(uid.modId).replaceAll(""); + String blockName = this.sanitizer.matcher(uid.name).replaceAll(""); - // Get the property - Property prop = FacadeConfig.instance.get( modName, blockName + ( meta == 0 ? "" : "." + meta ), true ); + // Get the property + Property prop = FacadeConfig.instance.get(modName, blockName + (meta == 0 ? "" : "." + meta), true); - // Set it to true - prop.set( true ); + // Set it to true + prop.set(true); + } - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + return theConfig.forceTCFacades(); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - return theConfig.forceTCFacades(); - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return null; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return null; - } + @Override + protected void registerAdditional() { + // Call super + super.registerAdditional(); - @Override - protected void registerAdditional() - { - // Call super - super.registerAdditional(); + // Amber block + this.forceEnabled(ConfigBlocks.blockCosmeticOpaque, 0); - // Amber block - this.forceEnabled( ConfigBlocks.blockCosmeticOpaque, 0 ); + // Amber brick + this.forceEnabled(ConfigBlocks.blockCosmeticOpaque, 1); - // Amber brick - this.forceEnabled( ConfigBlocks.blockCosmeticOpaque, 1 ); + // Warded glass + if (Config.allowMirrors) { + this.forceEnabled(ConfigBlocks.blockCosmeticOpaque, 2); + } - // Warded glass - if( Config.allowMirrors ) - { - this.forceEnabled( ConfigBlocks.blockCosmeticOpaque, 2 ); - } + // Obsidian tile + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 1); - // Obsidian tile - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 1 ); + // Thaumium block + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 4); - // Thaumium block - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 4 ); + // Tallow block + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 5); - // Tallow block - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 5 ); + // Arcane stone block + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 6); - // Arcane stone block - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 6 ); + // Arcane stone brick + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 7); - // Arcane stone brick - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 7 ); + // Ancient stone + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 11); - // Ancient stone - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 11 ); + // Ancient rock + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 12); - // Ancient rock - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 12 ); + // Crusted stone + this.forceEnabled(ConfigBlocks.blockCosmeticSolid, 14); - // Crusted stone - this.forceEnabled( ConfigBlocks.blockCosmeticSolid, 14 ); + // Greatwood planks + this.forceEnabled(ConfigBlocks.blockWoodenDevice, 6); - // Greatwood planks - this.forceEnabled( ConfigBlocks.blockWoodenDevice, 6 ); + // Silverwood planks + this.forceEnabled(ConfigBlocks.blockWoodenDevice, 7); - // Silverwood planks - this.forceEnabled( ConfigBlocks.blockWoodenDevice, 7 ); + // Crusted taint + this.forceEnabled(ConfigBlocks.blockTaint, 0); - // Crusted taint - this.forceEnabled( ConfigBlocks.blockTaint, 0 ); - - // Flesh block :< - this.forceEnabled( ConfigBlocks.blockTaint, 2 ); - } - - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - } + // Flesh block :< + this.forceEnabled(ConfigBlocks.blockTaint, 2); + } + @Override + protected void registerCrafting(final CommonDependantItems cdi) {} } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureThaumicEnergisticsResearch.java b/src/main/java/thaumicenergistics/common/features/FeatureThaumicEnergisticsResearch.java index 5c4400a7..089254db 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureThaumicEnergisticsResearch.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureThaumicEnergisticsResearch.java @@ -16,71 +16,66 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureThaumicEnergisticsResearch - extends ThEThaumcraftResearchFeature -{ +public class FeatureThaumicEnergisticsResearch extends ThEThaumcraftResearchFeature { - /** - * Research background image - */ - private static final ResourceLocation RESEARCH_BACKGROUND = new ResourceLocation( ThaumicEnergistics.MOD_ID, - "textures/research/Research.Background.png" ); + /** + * Research background image + */ + private static final ResourceLocation RESEARCH_BACKGROUND = + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/research/Research.Background.png"); - /** - * Research tab image - */ - private static final ResourceLocation TAB_ICON = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/research/tab.icon.png" ); + /** + * Research tab image + */ + private static final ResourceLocation TAB_ICON = + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/research/tab.icon.png"); - public FeatureThaumicEnergisticsResearch() - { - super( ResearchTypes.BASIC.getKey() ); - } + public FeatureThaumicEnergisticsResearch() { + super(ResearchTypes.BASIC.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - return true; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + return true; + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return null; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return null; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return null; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return null; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - } + @Override + protected void registerCrafting(final CommonDependantItems cdi) {} - @Override - protected void registerPseudoParents() - { - } + @Override + protected void registerPseudoParents() {} - @Override - protected void registerResearch() - { + @Override + protected void registerResearch() { - // Create the research tab - ResearchCategories.registerCategory( - ResearchRegistry.TERESEARCH_TAB, FeatureThaumicEnergisticsResearch.TAB_ICON, - FeatureThaumicEnergisticsResearch.RESEARCH_BACKGROUND ); - - // Create the basic research item - ResearchTypes.BASIC.researchItem = new ResearchItem( this.researchKey, - ResearchRegistry.TERESEARCH_TAB, new AspectList(), - 0, 0, 0, FeatureThaumicEnergisticsResearch.TAB_ICON ); - ResearchTypes.BASIC.researchItem.setPages( new ResearchPage[] { - new ResearchPage( ResearchTypes.BASIC.getPageName( 1 ) ) } ); - ResearchTypes.BASIC.researchItem.setRound().setAutoUnlock(); - ResearchTypes.BASIC.researchItem.registerResearchItem(); - } + // Create the research tab + ResearchCategories.registerCategory( + ResearchRegistry.TERESEARCH_TAB, + FeatureThaumicEnergisticsResearch.TAB_ICON, + FeatureThaumicEnergisticsResearch.RESEARCH_BACKGROUND); + // Create the basic research item + ResearchTypes.BASIC.researchItem = new ResearchItem( + this.researchKey, + ResearchRegistry.TERESEARCH_TAB, + new AspectList(), + 0, + 0, + 0, + FeatureThaumicEnergisticsResearch.TAB_ICON); + ResearchTypes.BASIC.researchItem.setPages( + new ResearchPage[] {new ResearchPage(ResearchTypes.BASIC.getPageName(1))}); + ResearchTypes.BASIC.researchItem.setRound().setAutoUnlock(); + ResearchTypes.BASIC.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureVisRelayInterface.java b/src/main/java/thaumicenergistics/common/features/FeatureVisRelayInterface.java index d504555d..0729d122 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureVisRelayInterface.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureVisRelayInterface.java @@ -23,86 +23,79 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureVisRelayInterface - extends ThEThaumcraftResearchFeature -{ - public FeatureVisRelayInterface() - { - super( ResearchTypes.VIS_RELAY_INTERFACE.getKey() ); - } +public class FeatureVisRelayInterface extends ThEThaumcraftResearchFeature { + public FeatureVisRelayInterface() { + super(ResearchTypes.VIS_RELAY_INTERFACE.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on P2P - if( !AEConfig.instance.isFeatureEnabled( AEFeature.P2PTunnel ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on P2P + if (!AEConfig.instance.isFeatureEnabled(AEFeature.P2PTunnel)) { + return false; + } - return theConfig.craftVisRelayInterface(); - } + return theConfig.craftVisRelayInterface(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.MEP2P }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.MEP2P}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return FeatureRegistry.instance().featureACT; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return FeatureRegistry.instance().featureACT; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack VisInterface = ThEApi.instance().parts().VisRelay_Interface.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack VisInterface = ThEApi.instance().parts().VisRelay_Interface.getStack(); - // Vis interface - AspectList visInterfaceAspectList = new AspectList(); - visInterfaceAspectList.add( Aspect.AIR, 2 ); - visInterfaceAspectList.add( Aspect.EARTH, 2 ); - visInterfaceAspectList.add( Aspect.ENTROPY, 2 ); - visInterfaceAspectList.add( Aspect.FIRE, 2 ); - visInterfaceAspectList.add( Aspect.ORDER, 2 ); - visInterfaceAspectList.add( Aspect.WATER, 2 ); - RecipeRegistry.PART_VIS_INTERFACE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( this.researchKey, - VisInterface, visInterfaceAspectList, cdi.BallanceShard, cdi.MEP2P ); - } + // Vis interface + AspectList visInterfaceAspectList = new AspectList(); + visInterfaceAspectList.add(Aspect.AIR, 2); + visInterfaceAspectList.add(Aspect.EARTH, 2); + visInterfaceAspectList.add(Aspect.ENTROPY, 2); + visInterfaceAspectList.add(Aspect.FIRE, 2); + visInterfaceAspectList.add(Aspect.ORDER, 2); + visInterfaceAspectList.add(Aspect.WATER, 2); + RecipeRegistry.PART_VIS_INTERFACE = ThaumcraftApi.addShapelessArcaneCraftingRecipe( + this.researchKey, VisInterface, visInterfaceAspectList, cdi.BallanceShard, cdi.MEP2P); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.VISPOWER.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.VISPOWER.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList vriAspects = new AspectList(); - vriAspects.add( Aspect.AURA, 5 ); - vriAspects.add( Aspect.ENERGY, 4 ); - vriAspects.add( Aspect.VOID, 3 ); - vriAspects.add( Aspect.MECHANISM, 2 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList vriAspects = new AspectList(); + vriAspects.add(Aspect.AURA, 5); + vriAspects.add(Aspect.ENERGY, 4); + vriAspects.add(Aspect.VOID, 3); + vriAspects.add(Aspect.MECHANISM, 2); - // Set the icon - ItemStack vriIcon = AEPartsEnum.VisInterface.getStack(); + // Set the icon + ItemStack vriIcon = AEPartsEnum.VisInterface.getStack(); - // Set the pages - ResearchPage[] vriPages = new ResearchPage[] { new ResearchPage( ResearchTypes.VIS_RELAY_INTERFACE.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.PART_VIS_INTERFACE ), - new ResearchPage( ResearchTypes.VIS_RELAY_INTERFACE.getPageName( 2 ) ), - new ResearchPage( ResearchTypes.VIS_RELAY_INTERFACE.getPageName( 3 ) ) }; - - // Create the vis relay interface research - ResearchTypes.VIS_RELAY_INTERFACE.createResearchItem( vriAspects, ResearchRegistry.COMPLEXITY_MEDIUM, vriIcon, vriPages ); - ResearchTypes.VIS_RELAY_INTERFACE.researchItem.setParents( this.getFirstValidParentKey( false ), PseudoResearchTypes.VISPOWER.getKey() ); - ResearchTypes.VIS_RELAY_INTERFACE.researchItem.setParentsHidden( "VISPOWER" ); - ResearchTypes.VIS_RELAY_INTERFACE.researchItem.registerResearchItem(); - } + // Set the pages + ResearchPage[] vriPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.VIS_RELAY_INTERFACE.getPageName(1)), + new ResearchPage(RecipeRegistry.PART_VIS_INTERFACE), + new ResearchPage(ResearchTypes.VIS_RELAY_INTERFACE.getPageName(2)), + new ResearchPage(ResearchTypes.VIS_RELAY_INTERFACE.getPageName(3)) + }; + // Create the vis relay interface research + ResearchTypes.VIS_RELAY_INTERFACE.createResearchItem( + vriAspects, ResearchRegistry.COMPLEXITY_MEDIUM, vriIcon, vriPages); + ResearchTypes.VIS_RELAY_INTERFACE.researchItem.setParents( + this.getFirstValidParentKey(false), PseudoResearchTypes.VISPOWER.getKey()); + ResearchTypes.VIS_RELAY_INTERFACE.researchItem.setParentsHidden("VISPOWER"); + ResearchTypes.VIS_RELAY_INTERFACE.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/FeatureWrenchFocus.java b/src/main/java/thaumicenergistics/common/features/FeatureWrenchFocus.java index 0274fc22..1bd6c2da 100644 --- a/src/main/java/thaumicenergistics/common/features/FeatureWrenchFocus.java +++ b/src/main/java/thaumicenergistics/common/features/FeatureWrenchFocus.java @@ -21,85 +21,90 @@ import thaumicenergistics.common.registries.ResearchRegistry.ResearchTypes; * @author Nividica * */ -public class FeatureWrenchFocus - extends ThEThaumcraftResearchFeature -{ - public FeatureWrenchFocus() - { - super( ResearchTypes.FOCUS_WRENCH.getKey() ); - } +public class FeatureWrenchFocus extends ThEThaumcraftResearchFeature { + public FeatureWrenchFocus() { + super(ResearchTypes.FOCUS_WRENCH.getKey()); + } - @Override - protected boolean checkConfigs( final IThEConfig theConfig ) - { - // Depends on quartz tools - if( !AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzTools ) ) - { - return false; - } + @Override + protected boolean checkConfigs(final IThEConfig theConfig) { + // Depends on quartz tools + if (!AEConfig.instance.isFeatureEnabled(AEFeature.CertusQuartzTools)) { + return false; + } - // Depends on quartz wrench - if( !AEConfig.instance.isFeatureEnabled( AEFeature.QuartzWrench ) ) - { - return false; - } + // Depends on quartz wrench + if (!AEConfig.instance.isFeatureEnabled(AEFeature.QuartzWrench)) { + return false; + } - return theConfig.enableWrenchFocus(); - } + return theConfig.enableWrenchFocus(); + } - @Override - protected Object[] getItemReqs( final CommonDependantItems cdi ) - { - return new Object[] { cdi.CertusWrench }; - } + @Override + protected Object[] getItemReqs(final CommonDependantItems cdi) { + return new Object[] {cdi.CertusWrench}; + } - @Override - protected ThEThaumcraftResearchFeature getParentFeature() - { - return null; - } + @Override + protected ThEThaumcraftResearchFeature getParentFeature() { + return null; + } - @Override - protected void registerCrafting( final CommonDependantItems cdi ) - { - // My items - ItemStack WrenchFocus = ThEApi.instance().items().WandFocusAEWrench.getStack(); + @Override + protected void registerCrafting(final CommonDependantItems cdi) { + // My items + ItemStack WrenchFocus = ThEApi.instance().items().WandFocusAEWrench.getStack(); - // Wrench focus - AspectList wrenchAspects = new AspectList(); - wrenchAspects.add( Aspect.AIR, 10 ); - wrenchAspects.add( Aspect.FIRE, 10 ); - RecipeRegistry.ITEM_WRENCH_FOCUS = ThaumcraftApi.addArcaneCraftingRecipe( this.researchKey, WrenchFocus, - wrenchAspects, - new Object[] { "ANF", "NWN", "FNA", 'A', cdi.AirShard, 'F', cdi.FireShard, 'N', cdi.NetherQuartz, 'W', cdi.CertusWrench } ); - } + // Wrench focus + AspectList wrenchAspects = new AspectList(); + wrenchAspects.add(Aspect.AIR, 10); + wrenchAspects.add(Aspect.FIRE, 10); + RecipeRegistry.ITEM_WRENCH_FOCUS = + ThaumcraftApi.addArcaneCraftingRecipe(this.researchKey, WrenchFocus, wrenchAspects, new Object[] { + "ANF", + "NWN", + "FNA", + 'A', + cdi.AirShard, + 'F', + cdi.FireShard, + 'N', + cdi.NetherQuartz, + 'W', + cdi.CertusWrench + }); + } - @Override - protected void registerPseudoParents() - { - PseudoResearchTypes.FOCUSFIRE.registerPsudeoResearch(); - } + @Override + protected void registerPseudoParents() { + PseudoResearchTypes.FOCUSFIRE.registerPsudeoResearch(); + } - @Override - protected void registerResearch() - { - // Set the research aspects - AspectList focusAspects = new AspectList(); - focusAspects.add( Aspect.MECHANISM, 6 ); - focusAspects.add( Aspect.TOOL, 5 ); - focusAspects.add( Aspect.MAGIC, 3 ); + @Override + protected void registerResearch() { + // Set the research aspects + AspectList focusAspects = new AspectList(); + focusAspects.add(Aspect.MECHANISM, 6); + focusAspects.add(Aspect.TOOL, 5); + focusAspects.add(Aspect.MAGIC, 3); - // Set the icon - ItemStack focusIcon = ThEApi.instance().items().WandFocusAEWrench.getStack(); + // Set the icon + ItemStack focusIcon = ThEApi.instance().items().WandFocusAEWrench.getStack(); - // Set the pages - ResearchPage[] focusPages = new ResearchPage[] { new ResearchPage( ResearchTypes.FOCUS_WRENCH.getPageName( 1 ) ), - new ResearchPage( RecipeRegistry.ITEM_WRENCH_FOCUS ) }; - - // Create the research - ResearchTypes.FOCUS_WRENCH.createResearchItem( focusAspects, ResearchRegistry.COMPLEXITY_SMALL, focusIcon, focusPages ); - ResearchTypes.FOCUS_WRENCH.researchItem.setParents( PseudoResearchTypes.FOCUSFIRE.getKey() ).setSecondary(); - ResearchTypes.FOCUS_WRENCH.researchItem.registerResearchItem(); - } + // Set the pages + ResearchPage[] focusPages = new ResearchPage[] { + new ResearchPage(ResearchTypes.FOCUS_WRENCH.getPageName(1)), + new ResearchPage(RecipeRegistry.ITEM_WRENCH_FOCUS) + }; + // Create the research + ResearchTypes.FOCUS_WRENCH.createResearchItem( + focusAspects, ResearchRegistry.COMPLEXITY_SMALL, focusIcon, focusPages); + ResearchTypes.FOCUS_WRENCH + .researchItem + .setParents(PseudoResearchTypes.FOCUSFIRE.getKey()) + .setSecondary(); + ResearchTypes.FOCUS_WRENCH.researchItem.registerResearchItem(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/ThEDependencyFeatureBase.java b/src/main/java/thaumicenergistics/common/features/ThEDependencyFeatureBase.java index aeda9142..bee4d394 100644 --- a/src/main/java/thaumicenergistics/common/features/ThEDependencyFeatureBase.java +++ b/src/main/java/thaumicenergistics/common/features/ThEDependencyFeatureBase.java @@ -13,82 +13,70 @@ import thaumicenergistics.common.registries.FeatureRegistry; * @author Nividica * */ -public abstract class ThEDependencyFeatureBase - extends ThEFeatureBase -{ - /** - * True if the requirements have been checked. - */ - private boolean hasCheckedReqs = false; +public abstract class ThEDependencyFeatureBase extends ThEFeatureBase { + /** + * True if the requirements have been checked. + */ + private boolean hasCheckedReqs = false; - public ThEDependencyFeatureBase() - { - // Disabled by default - super( false ); - } + public ThEDependencyFeatureBase() { + // Disabled by default + super(false); + } - /** - * Ensures that all the required items are present. - * - * @param items - * @return - */ - private final boolean checkItemReqs( final Object[] items ) - { - // Are there no item reqs? - if( items == null ) - { - return true; - } + /** + * Ensures that all the required items are present. + * + * @param items + * @return + */ + private final boolean checkItemReqs(final Object[] items) { + // Are there no item reqs? + if (items == null) { + return true; + } - // Check all requirements - for( Object item : items ) - { - if( item == null ) - { - // Something is null, feature can not be enabled. - return false; - } - } + // Check all requirements + for (Object item : items) { + if (item == null) { + // Something is null, feature can not be enabled. + return false; + } + } - return true; - } + return true; + } - /** - * Checks if this feature can be enabled based on ThE, TC and/or AE configs. - */ - protected abstract boolean checkConfigs( @Nonnull IThEConfig theConfig ); + /** + * Checks if this feature can be enabled based on ThE, TC and/or AE configs. + */ + protected abstract boolean checkConfigs(@Nonnull IThEConfig theConfig); - /** - * Gets the features required items. - * - * @return - */ - @Nullable - protected abstract Object[] getItemReqs( CommonDependantItems cdi ); + /** + * Gets the features required items. + * + * @return + */ + @Nullable + protected abstract Object[] getItemReqs(CommonDependantItems cdi); - @Override - protected void registerAdditional() - { - } + @Override + protected void registerAdditional() {} - /** - * Evaluates the dependencies of the feature and enables it if possible. - * - * @param cdi - */ - @Override - public boolean isAvailable() - { - if( !this.hasCheckedReqs ) - { - // Ask for the features config settings and required items - this.available = this.checkConfigs( ThEApi.instance().config() ) && - this.checkItemReqs( this.getItemReqs( FeatureRegistry.instance().cdi ) ); - this.hasCheckedReqs = true; - } - - return super.isAvailable(); - } + /** + * Evaluates the dependencies of the feature and enables it if possible. + * + * @param cdi + */ + @Override + public boolean isAvailable() { + if (!this.hasCheckedReqs) { + // Ask for the features config settings and required items + this.available = this.checkConfigs(ThEApi.instance().config()) + && this.checkItemReqs(this.getItemReqs(FeatureRegistry.instance().cdi)); + this.hasCheckedReqs = true; + } + return super.isAvailable(); + } } diff --git a/src/main/java/thaumicenergistics/common/features/ThEFeatureBase.java b/src/main/java/thaumicenergistics/common/features/ThEFeatureBase.java index 96be6c79..4c2f1477 100644 --- a/src/main/java/thaumicenergistics/common/features/ThEFeatureBase.java +++ b/src/main/java/thaumicenergistics/common/features/ThEFeatureBase.java @@ -6,70 +6,64 @@ package thaumicenergistics.common.features; * @author Nividica * */ -public abstract class ThEFeatureBase -{ +public abstract class ThEFeatureBase { - /** - * Has the feature been called to register itself? - */ - private boolean hasRegistered = false; + /** + * Has the feature been called to register itself? + */ + private boolean hasRegistered = false; - /** - * Is the feature available. - */ - protected boolean available = false; + /** + * Is the feature available. + */ + protected boolean available = false; - /** - * Creates the feature. - * - * @param initiallyAvailable - */ - public ThEFeatureBase( final boolean initiallyAvailable ) - { - this.available = initiallyAvailable; - } + /** + * Creates the feature. + * + * @param initiallyAvailable + */ + public ThEFeatureBase(final boolean initiallyAvailable) { + this.available = initiallyAvailable; + } - /** - * Registers any additional features of this feature. - */ - protected abstract void registerAdditional(); + /** + * Registers any additional features of this feature. + */ + protected abstract void registerAdditional(); - /** - * Registers the features crafting recipes, if it has any. - * - * @param cdi - */ - protected abstract void registerCrafting( final CommonDependantItems cdi ); + /** + * Registers the features crafting recipes, if it has any. + * + * @param cdi + */ + protected abstract void registerCrafting(final CommonDependantItems cdi); - /** - * Is the feature available? - * - * @return - */ - public boolean isAvailable() - { - return this.available; - } + /** + * Is the feature available? + * + * @return + */ + public boolean isAvailable() { + return this.available; + } - /** - * Asks the feature to register itself. - * - * @param cdi - */ - public final void registerFeature( final CommonDependantItems cdi ) - { - // Is the feature enabled and has not yet been registered? - if( this.isAvailable() && !this.hasRegistered ) - { - // Register crafting recipe(s) - this.registerCrafting( cdi ); + /** + * Asks the feature to register itself. + * + * @param cdi + */ + public final void registerFeature(final CommonDependantItems cdi) { + // Is the feature enabled and has not yet been registered? + if (this.isAvailable() && !this.hasRegistered) { + // Register crafting recipe(s) + this.registerCrafting(cdi); - // Register anything else - this.registerAdditional(); - - // Mark that this feature has been registered - this.hasRegistered = true; - } - } + // Register anything else + this.registerAdditional(); + // Mark that this feature has been registered + this.hasRegistered = true; + } + } } diff --git a/src/main/java/thaumicenergistics/common/features/ThEThaumcraftResearchFeature.java b/src/main/java/thaumicenergistics/common/features/ThEThaumcraftResearchFeature.java index ebef6c33..d852b3fd 100644 --- a/src/main/java/thaumicenergistics/common/features/ThEThaumcraftResearchFeature.java +++ b/src/main/java/thaumicenergistics/common/features/ThEThaumcraftResearchFeature.java @@ -9,78 +9,68 @@ import javax.annotation.Nullable; * @author Nividica * */ -public abstract class ThEThaumcraftResearchFeature - extends ThEDependencyFeatureBase -{ - /** - * The research key for this research. - */ - public final String researchKey; +public abstract class ThEThaumcraftResearchFeature extends ThEDependencyFeatureBase { + /** + * The research key for this research. + */ + public final String researchKey; - /** - * Creates the feature with the specified research key. - * - * @param parent - */ - public ThEThaumcraftResearchFeature( @Nonnull final String researchKey ) - { - this.researchKey = researchKey; - } + /** + * Creates the feature with the specified research key. + * + * @param parent + */ + public ThEThaumcraftResearchFeature(@Nonnull final String researchKey) { + this.researchKey = researchKey; + } - /** - * Gets the parent for this feature, if there is one. - * - * @return - */ - @Nullable - protected abstract ThEThaumcraftResearchFeature getParentFeature(); + /** + * Gets the parent for this feature, if there is one. + * + * @return + */ + @Nullable + protected abstract ThEThaumcraftResearchFeature getParentFeature(); - @Override - protected void registerAdditional() - { - // Call super - super.registerAdditional(); + @Override + protected void registerAdditional() { + // Call super + super.registerAdditional(); - // Register Thaumcraft research. - this.registerResearch(); + // Register Thaumcraft research. + this.registerResearch(); - // Register pseudo parents - this.registerPseudoParents(); - } + // Register pseudo parents + this.registerPseudoParents(); + } - /** - * If the research item has any pseudo parents, register them here. - */ - protected abstract void registerPseudoParents(); + /** + * If the research item has any pseudo parents, register them here. + */ + protected abstract void registerPseudoParents(); - /** - * Registers the research with Thaumcraft, if it has any. - */ - protected abstract void registerResearch(); + /** + * Registers the research with Thaumcraft, if it has any. + */ + protected abstract void registerResearch(); - /** - * Gets the research key of the first valid parent that can be found. - * If the feature in question is not enabled, it will pass the call to its - * parent. - * - * @param includeSelf - * @return - */ - public final String getFirstValidParentKey( final boolean includeSelf ) - { - if( this.isAvailable() && includeSelf ) - { - return this.researchKey; - } - else if( this.getParentFeature() != null ) - { - // Pass to parent - return this.getParentFeature().getFirstValidParentKey( true ); - } - else - { - // No parent - return ""; - } - } + /** + * Gets the research key of the first valid parent that can be found. + * If the feature in question is not enabled, it will pass the call to its + * parent. + * + * @param includeSelf + * @return + */ + public final String getFirstValidParentKey(final boolean includeSelf) { + if (this.isAvailable() && includeSelf) { + return this.researchKey; + } else if (this.getParentFeature() != null) { + // Pass to parent + return this.getParentFeature().getFirstValidParentKey(true); + } else { + // No parent + return ""; + } + } } diff --git a/src/main/java/thaumicenergistics/common/fluids/GaseousEssentia.java b/src/main/java/thaumicenergistics/common/fluids/GaseousEssentia.java index 5ff68fd9..2d05b50c 100644 --- a/src/main/java/thaumicenergistics/common/fluids/GaseousEssentia.java +++ b/src/main/java/thaumicenergistics/common/fluids/GaseousEssentia.java @@ -18,166 +18,143 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public class GaseousEssentia - extends Fluid - implements IThEEssentiaGas -{ - /** - * List of all created gasses. - */ - public static final LinkedHashMap gasList = new LinkedHashMap(); +public class GaseousEssentia extends Fluid implements IThEEssentiaGas { + /** + * List of all created gasses. + */ + public static final LinkedHashMap gasList = new LinkedHashMap(); - /** - * The aspect the gas is based off of. - */ - private Aspect associatedAspect; + /** + * The aspect the gas is based off of. + */ + private Aspect associatedAspect; - /** - * Creates the gas. - * - * @param gasName - * Name of the gas displayed to the user - * @param aspect - * The aspect the gas is based off of. - */ - private GaseousEssentia( final String gasName, final Aspect aspect ) - { - // Pass to super - super( gasName ); + /** + * Creates the gas. + * + * @param gasName + * Name of the gas displayed to the user + * @param aspect + * The aspect the gas is based off of. + */ + private GaseousEssentia(final String gasName, final Aspect aspect) { + // Pass to super + super(gasName); - // Set the aspect - this.associatedAspect = aspect; + // Set the aspect + this.associatedAspect = aspect; - // Gas slightly glows - this.setLuminosity( 7 ); + // Gas slightly glows + this.setLuminosity(7); - // Negative density, it floats away! - this.setDensity( -4 ); + // Negative density, it floats away! + this.setDensity(-4); - // Flow speed, 3x slower than water - this.setViscosity( 3000 ); + // Flow speed, 3x slower than water + this.setViscosity(3000); - // This is a gas, adjusts the render pass. - this.setGaseous( true ); + // This is a gas, adjusts the render pass. + this.setGaseous(true); + } - } + /** + * Creates a gas based on the specified aspect + * + * @param aspect + */ + private static void create(final Aspect aspect) { + // Ensure this has not already been register + if (gasList.containsKey(aspect)) { + // Return the existing fluid + return; + } - /** - * Creates a gas based on the specified aspect - * - * @param aspect - */ - private static void create( final Aspect aspect ) - { - // Ensure this has not already been register - if( gasList.containsKey( aspect ) ) - { - // Return the existing fluid - return; - } + // Create the name + String gasName = "gaseous" + aspect.getTag() + "essentia"; - // Create the name - String gasName = "gaseous" + aspect.getTag() + "essentia"; + // Create the fluid + GaseousEssentia newGas = new GaseousEssentia(gasName, aspect); - // Create the fluid - GaseousEssentia newGas = new GaseousEssentia( gasName, aspect ); + // Register the fluid + if (FluidRegistry.registerFluid(newGas)) { + // Add to the list + gasList.put(aspect, newGas); - // Register the fluid - if( FluidRegistry.registerFluid( newGas ) ) - { - // Add to the list - gasList.put( aspect, newGas ); + // Log info + // ThELog.info( "Created fluid for aspect %s.", aspect.getTag() ); + } else { + // Log a warning + ThELog.warning("Unable to register '%s' as fluid.", aspect.getTag()); + } + } - // Log info - // ThELog.info( "Created fluid for aspect %s.", aspect.getTag() ); - } - else - { - // Log a warning - ThELog.warning( "Unable to register '%s' as fluid.", aspect.getTag() ); - } + /** + * Gets the gas form of the specified aspect + * + * @param aspect + * @return + */ + public static GaseousEssentia getGasFromAspect(final Aspect aspect) { + return GaseousEssentia.gasList.get(aspect); + } - } + /** + * Called from load to register all gas types with the game. + */ + public static void registerGases() { + // Create a gas for each essentia type + for (Entry aspectType : Aspect.aspects.entrySet()) { + // Get the aspect + Aspect aspect = aspectType.getValue(); - /** - * Gets the gas form of the specified aspect - * - * @param aspect - * @return - */ - public static GaseousEssentia getGasFromAspect( final Aspect aspect ) - { - return GaseousEssentia.gasList.get( aspect ); - } + // Create and register + GaseousEssentia.create(aspect); + } + } - /** - * Called from load to register all gas types with the game. - */ - public static void registerGases() - { - // Create a gas for each essentia type - for( Entry aspectType : Aspect.aspects.entrySet() ) - { - // Get the aspect - Aspect aspect = aspectType.getValue(); + /** + * Get the aspect this gas is based off of. + * + * @return + */ + @Override + public Aspect getAspect() { + return this.associatedAspect; + } - // Create and register - GaseousEssentia.create( aspect ); - } + /** + * Gets the color of the gas. + */ + @Override + public int getColor() { + if (this.associatedAspect != null) { + return this.associatedAspect.getColor(); + } - } + return super.getColor(); + } - /** - * Get the aspect this gas is based off of. - * - * @return - */ - @Override - public Aspect getAspect() - { - return this.associatedAspect; - } + @Override + public IIcon getFlowingIcon() { + return BlockTextureManager.GASEOUS_ESSENTIA.getTexture(); + } - /** - * Gets the color of the gas. - */ - @Override - public int getColor() - { - if( this.associatedAspect != null ) - { - return this.associatedAspect.getColor(); - } + @Deprecated + @Override + public String getLocalizedName() { + return this.getLocalizedName(null); + } - return super.getColor(); - } - - @Override - public IIcon getFlowingIcon() - { - return BlockTextureManager.GASEOUS_ESSENTIA.getTexture(); - } - - @Deprecated - @Override - public String getLocalizedName() - { - return this.getLocalizedName( null ); - } - - /** - * Gets the localized version of the gasses name. - */ - @Override - public String getLocalizedName( final FluidStack stack ) - { - return this.associatedAspect.getName() + " " + ThEStrings.Fluid_GaseousEssentia.getLocalized(); - } - - @Override - public IIcon getStillIcon() - { - return BlockTextureManager.GASEOUS_ESSENTIA.getTexture(); - } + /** + * Gets the localized version of the gasses name. + */ + @Override + public String getLocalizedName(final FluidStack stack) { + return this.associatedAspect.getName() + " " + ThEStrings.Fluid_GaseousEssentia.getLocalized(); + } + @Override + public IIcon getStillIcon() { + return BlockTextureManager.GASEOUS_ESSENTIA.getTexture(); + } } diff --git a/src/main/java/thaumicenergistics/common/grid/AEPartGridBlock.java b/src/main/java/thaumicenergistics/common/grid/AEPartGridBlock.java index 4ba6cb19..13c50fa8 100644 --- a/src/main/java/thaumicenergistics/common/grid/AEPartGridBlock.java +++ b/src/main/java/thaumicenergistics/common/grid/AEPartGridBlock.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.grid; -import java.util.EnumSet; import appeng.api.networking.*; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.security.ISecurityGrid; @@ -10,6 +9,7 @@ import appeng.api.storage.IMEMonitor; import appeng.api.storage.data.IAEItemStack; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; +import java.util.EnumSet; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; import thaumicenergistics.api.grid.IEssentiaGrid; @@ -22,222 +22,194 @@ import thaumicenergistics.common.parts.ThEPartBase; * @author Nividica * */ -public class AEPartGridBlock - implements IGridBlock -{ - /** - * The part using this gridblock. - */ - protected ThEPartBase part; +public class AEPartGridBlock implements IGridBlock { + /** + * The part using this gridblock. + */ + protected ThEPartBase part; - /** - * Create the gridblock for the specified part. - * - * @param part - */ - public AEPartGridBlock( final ThEPartBase part ) - { - this.part = part; - } + /** + * Create the gridblock for the specified part. + * + * @param part + */ + public AEPartGridBlock(final ThEPartBase part) { + this.part = part; + } - @Override - public EnumSet getConnectableSides() - { - return EnumSet.noneOf( ForgeDirection.class ); - } + @Override + public EnumSet getConnectableSides() { + return EnumSet.noneOf(ForgeDirection.class); + } - public IEnergyGrid getEnergyGrid() - { - // Get the grid - IGrid grid = this.getGrid(); + public IEnergyGrid getEnergyGrid() { + // Get the grid + IGrid grid = this.getGrid(); - // Ensure we have a grid - if( grid == null ) - { - return null; - } + // Ensure we have a grid + if (grid == null) { + return null; + } - // Return the energy grid - return grid.getCache( IEnergyGrid.class ); - } + // Return the energy grid + return grid.getCache(IEnergyGrid.class); + } - /** - * Returns the essentia monitor for the current grid. - * - * @return - */ - public IMEEssentiaMonitor getEssentiaMonitor() - { - // Get the grid. - IGrid grid = this.getGrid(); + /** + * Returns the essentia monitor for the current grid. + * + * @return + */ + public IMEEssentiaMonitor getEssentiaMonitor() { + // Get the grid. + IGrid grid = this.getGrid(); - // Ensure there is a grid - if( grid == null ) - { - return null; - } + // Ensure there is a grid + if (grid == null) { + return null; + } - // Get the essentia monitor from the cache. - return (IMEEssentiaMonitor)grid.getCache( IEssentiaGrid.class ); - } + // Get the essentia monitor from the cache. + return (IMEEssentiaMonitor) grid.getCache(IEssentiaGrid.class); + } - /** - * Return that we require a channel to function. - */ - @Override - public EnumSet getFlags() - { - return EnumSet.of( GridFlags.REQUIRE_CHANNEL ); - } + /** + * Return that we require a channel to function. + */ + @Override + public EnumSet getFlags() { + return EnumSet.of(GridFlags.REQUIRE_CHANNEL); + } - public final IGrid getGrid() - { - // Get the grid node - IGridNode node = this.part.getGridNode(); + public final IGrid getGrid() { + // Get the grid node + IGridNode node = this.part.getGridNode(); - // Ensure we have a node - if( node != null ) - { - // Get the grid - return node.getGrid(); - } + // Ensure we have a node + if (node != null) { + // Get the grid + return node.getGrid(); + } - return null; - } + return null; + } - /** - * Returns the color of the grid. - */ - @Override - public AEColor getGridColor() - { - // Return transparent. - return AEColor.Transparent; - } + /** + * Returns the color of the grid. + */ + @Override + public AEColor getGridColor() { + // Return transparent. + return AEColor.Transparent; + } - /** - * Gets how much power the part is using. - */ - @Override - public double getIdlePowerUsage() - { - return this.part.getIdlePowerUsage(); - } + /** + * Gets how much power the part is using. + */ + @Override + public double getIdlePowerUsage() { + return this.part.getIdlePowerUsage(); + } - /** - * Gets the AE item monitor for the grid. - * - * @return Monitor if valid grid, null otherwise. - */ - public IMEMonitor getItemMonitor() - { - // Get the storage grid - IStorageGrid storageGrid = this.getStorageGrid(); + /** + * Gets the AE item monitor for the grid. + * + * @return Monitor if valid grid, null otherwise. + */ + public IMEMonitor getItemMonitor() { + // Get the storage grid + IStorageGrid storageGrid = this.getStorageGrid(); - // Do we have a storage grid? - if( storageGrid == null ) - { - return null; - } + // Do we have a storage grid? + if (storageGrid == null) { + return null; + } - // Return the storage grid's item monitor. - return storageGrid.getItemInventory(); - } + // Return the storage grid's item monitor. + return storageGrid.getItemInventory(); + } - /** - * Gets the location of the part. - */ - @Override - public DimensionalCoord getLocation() - { - return this.part.getLocation(); - } + /** + * Gets the location of the part. + */ + @Override + public DimensionalCoord getLocation() { + return this.part.getLocation(); + } - /** - * Gets the part - */ - @Override - public IGridHost getMachine() - { - return this.part; - } + /** + * Gets the part + */ + @Override + public IGridHost getMachine() { + return this.part; + } - /** - * Gets the an itemstack based on the parts state. - */ - @Override - public ItemStack getMachineRepresentation() - { - return this.part.getItemStack( PartItemStack.Network ); - } + /** + * Gets the an itemstack based on the parts state. + */ + @Override + public ItemStack getMachineRepresentation() { + return this.part.getItemStack(PartItemStack.Network); + } - /** - * Gets the security grid - * - * @return - */ - public ISecurityGrid getSecurityGrid() - { - // Get the grid. - IGrid grid = this.getGrid(); + /** + * Gets the security grid + * + * @return + */ + public ISecurityGrid getSecurityGrid() { + // Get the grid. + IGrid grid = this.getGrid(); - // Do we have a grid? - if( grid == null ) - { - return null; - } + // Do we have a grid? + if (grid == null) { + return null; + } - // Get the security grid from the cache. - return (ISecurityGrid)grid.getCache( ISecurityGrid.class ); - } + // Get the security grid from the cache. + return (ISecurityGrid) grid.getCache(ISecurityGrid.class); + } - /** - * Gets the storage grid. - * - * @return - */ - public IStorageGrid getStorageGrid() - { - // Get the grid. - IGrid grid = this.getGrid(); + /** + * Gets the storage grid. + * + * @return + */ + public IStorageGrid getStorageGrid() { + // Get the grid. + IGrid grid = this.getGrid(); - // Do we have a grid? - if( grid == null ) - { - return null; - } + // Do we have a grid? + if (grid == null) { + return null; + } - // Get the storage grid from the cache. - return (IStorageGrid)grid.getCache( IStorageGrid.class ); - } + // Get the storage grid from the cache. + return (IStorageGrid) grid.getCache(IStorageGrid.class); + } - @Override - public void gridChanged() - { - // Ignored - } + @Override + public void gridChanged() { + // Ignored + } - /** - * Parts are not world accessable - */ - @Override - public boolean isWorldAccessible() - { - return false; - } + /** + * Parts are not world accessable + */ + @Override + public boolean isWorldAccessible() { + return false; + } - @Override - public void onGridNotification( final GridNotification notification ) - { - // Ignored - } - - /** - * Called to update the grid and the channels used. - */ - @Override - public final void setNetworkStatus( final IGrid grid, final int usedChannels ) - { - } + @Override + public void onGridNotification(final GridNotification notification) { + // Ignored + } + /** + * Called to update the grid and the channels used. + */ + @Override + public final void setNetworkStatus(final IGrid grid, final int usedChannels) {} } diff --git a/src/main/java/thaumicenergistics/common/grid/CraftingAspect_ItemWatcher.java b/src/main/java/thaumicenergistics/common/grid/CraftingAspect_ItemWatcher.java index 5ed2f327..c58795cd 100644 --- a/src/main/java/thaumicenergistics/common/grid/CraftingAspect_ItemWatcher.java +++ b/src/main/java/thaumicenergistics/common/grid/CraftingAspect_ItemWatcher.java @@ -6,41 +6,35 @@ import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEItemStack; import thaumicenergistics.common.items.ItemCraftingAspect; -class CraftingAspect_ItemWatcher - implements IMEMonitorHandlerReceiver -{ +class CraftingAspect_ItemWatcher implements IMEMonitorHandlerReceiver { - private final GridEssentiaCache gridCache; + private final GridEssentiaCache gridCache; - public CraftingAspect_ItemWatcher( final GridEssentiaCache gridCache ) - { - this.gridCache = gridCache; - } + public CraftingAspect_ItemWatcher(final GridEssentiaCache gridCache) { + this.gridCache = gridCache; + } - @Override - public boolean isValid( final Object verificationToken ) - { - return this.gridCache.internalGrid == verificationToken; - } + @Override + public boolean isValid(final Object verificationToken) { + return this.gridCache.internalGrid == verificationToken; + } - @Override - public void onListUpdate() - { - // Ignored - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - for( IAEItemStack stack : change ) - { - // Is the stack craftable, has NBT tag, and is a crafting aspect? - if( stack.isCraftable() && stack.hasTagCompound() && ( stack.getItem() instanceof ItemCraftingAspect ) ) - { - this.gridCache.markForUpdate(); - break; - } - } - } + @Override + public void onListUpdate() { + // Ignored + } + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource) { + for (IAEItemStack stack : change) { + // Is the stack craftable, has NBT tag, and is a crafting aspect? + if (stack.isCraftable() && stack.hasTagCompound() && (stack.getItem() instanceof ItemCraftingAspect)) { + this.gridCache.markForUpdate(); + break; + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/grid/EssentiaMonitor.java b/src/main/java/thaumicenergistics/common/grid/EssentiaMonitor.java index 291a4a43..25929616 100644 --- a/src/main/java/thaumicenergistics/common/grid/EssentiaMonitor.java +++ b/src/main/java/thaumicenergistics/common/grid/EssentiaMonitor.java @@ -1,9 +1,5 @@ package thaumicenergistics.common.grid; -import java.lang.ref.WeakReference; -import java.util.*; -import java.util.Map.Entry; -import com.google.common.collect.ImmutableList; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.networking.energy.IEnergyGrid; @@ -13,6 +9,10 @@ import appeng.api.storage.IMEMonitor; import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import com.google.common.collect.ImmutableList; +import java.lang.ref.WeakReference; +import java.util.*; +import java.util.Map.Entry; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IMEEssentiaMonitor; import thaumicenergistics.api.grid.IMEEssentiaMonitorReceiver; @@ -29,690 +29,632 @@ import thaumicenergistics.common.storage.EssentiaRepo; * @author Nividica * */ -public class EssentiaMonitor - implements IMEEssentiaMonitor, IMEMonitorHandlerReceiver -{ - /** - * The amount of power required to transfer 1 essentia. - */ - public static final double AE_PER_ESSENTIA = 0.3; - - /** - * Objects who wish to be notified of any changes. - */ - protected final HashMap listeners; - - /** - * The grids fluid monitor. - */ - protected IMEMonitor fluidMonitor; - - /** - * The grids energy manager. - */ - protected IEnergyGrid energyGrid; - - /** - * Collection backed by the cache that shows the essentia amounts in the network. Is created the first time it is needed.
- * Any changes to the cache are reflected in the view. - */ - private Collection cacheView; - - /** - * Used to validate the state of the fluid listener, can not be null - */ - private WeakReference token; - - /** - * Cache of essentia. - */ - private final IEssentiaRepo cache; - - /** - * When true the full storage list needs to be pulled to update the cache. - */ - protected boolean cacheNeedsUpdate = false; - - public EssentiaMonitor() - { - // Create the cache - this.cache = new EssentiaRepo(); - - // Create the listeners table - this.listeners = new HashMap(); - } - - /** - * Wraps the specified fluid monitor and energy grid. - * - * @param fluidMonitor - * Fluid monitor to listen to - * @param energyGrid - * Energy grid to extract power from - * @param validationToken - * Used to validate the state of the fluid listener, can not be null - */ - public EssentiaMonitor( final IMEMonitor fluidMonitor, final IEnergyGrid energyGrid, final Object validationToken ) - { - // Call default constructor - this(); - - // Call wrap - this.wrap( fluidMonitor, energyGrid, validationToken ); - } - - /** - * Mirror method of the injectEssentia. Used to defer power calculations, because the simulation is not always accurate, and Essentia gas should - * not be stored in partial amounts. - * - * @param aspect - * @param amount - * @param mode - * @param source - * @return Amount that was not injected - */ - private long injectEssentiaSafely( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, - final GaseousEssentia essentiaGas ) - { - // Create the fluid request - IAEFluidStack fluidRequest = EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( essentiaGas, amount ); - - // Inject fluid - IAEFluidStack fluidRejected = this.fluidMonitor.injectItems( fluidRequest, mode, source ); - - // Was any rejected? - if( ( fluidRejected != null ) && ( fluidRejected.getStackSize() > 0 ) ) - { - if( fluidRejected.getStackSize() == fluidRequest.getStackSize() ) - { - // All essentia was rejected - return amount; - } - - // Calculate the adjusted amount, essentia gas can not be stored in partial units - long rejectedAdjustedAmount = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( fluidRejected.getStackSize() ); - return rejectedAdjustedAmount; - } - - // All essentia was accepted. - return 0; - } - - /** - * Notifies all listeners of the specified changes. - * - * @param changes - */ - private void notifyListeners( final List changes ) - { - // Get an immutable copy - ImmutableList changeList = ImmutableList.copyOf( changes ); - - // Get the listener iterator - Iterator> entryIterator = this.listeners.entrySet().iterator(); - - // Inform all listeners of the changes - while( entryIterator.hasNext() ) - { - // Get the listener - Entry entry = entryIterator.next(); - - // Validate the token - if( entry.getKey().isValid( entry.getValue() ) ) - { - // Valid token - entry.getKey().postChange( this, changeList ); - } - else - { - // Invalid token, remove from listener list - entryIterator.remove(); - } - } - } - - private boolean setAspectCraftability( final Aspect aspect, final boolean isCraftable, final boolean doNotify ) - { - // Get the aspect stack - IAspectStack stack = this.cache.getOrDefault( aspect, null ); - - boolean changesMade = false; - - // Not stored? - if( stack == null ) - { - // If the cache doesn't have this aspect, and its not craftable then there is nothing to do - if( isCraftable ) - { - // Put it in the cache - this.cache.postChange( aspect, 0, true ); - - // Set changes made - changesMade = true; - } - } - else - { - // Is stored, but is stack size 0 and setting to not craftable? - if( stack.isEmpty() && ( !isCraftable ) ) - { - // Remove the stack - this.cache.remove( aspect ); - - // Set changes made - changesMade = true; - } - // Is it changing? - else if( stack.getCraftable() != isCraftable ) - { - // Set craftability - stack.setCraftable( isCraftable ); - - // Set changes made - changesMade = true; - } - } - - // Do notify? - if( doNotify && changesMade && ( this.listeners.size() > 0 ) ) - { - // Create the change - ArrayList changes = new ArrayList(); - - // Add the aspect - changes.add( new AspectStack( aspect, 0, isCraftable ) ); - - // Notify - this.notifyListeners( changes ); - } - - return changesMade; - } - - /** - * Sets if the aspect is craftable. - * - * @param aspect - * @param isCraftable - */ - protected void setAspectCraftability( final Aspect aspect, final boolean isCraftable ) - { - this.setAspectCraftability( aspect, isCraftable, true ); - } - - /** - * Sets each aspect as craftable. - * - * @param aspects - */ - protected void setCraftableAspects( final HashSet aspects ) - { - // Create the changes - ArrayList changes = new ArrayList(); - - // Set each aspect - for( Aspect aspect : aspects ) - { - // Was the crafting status changed? - if( this.setAspectCraftability( aspect, true, false ) ) - { - // Add the aspect - changes.add( new AspectStack( aspect, 0, true ) ); - } - } - - // Notify listeners? - if( ( changes.size() > 0 ) && ( this.listeners.size() > 0 ) ) - { - // Notify - this.notifyListeners( changes ); - } - } - - /** - * Updates the cache to match the contents of the network and updates any - * listeners of the changes. - */ - @SuppressWarnings("null") - protected void updateCacheToMatchNetwork() - { - // Changes made to the cache - List aspectChanges = null; - - // The currently stored aspects - Set previousAspects = null; - - // Are there any listeners? - boolean hasListeners = ( this.listeners.size() > 0 ); - if( hasListeners ) - { - // Create the change trackers - aspectChanges = new ArrayList(); - previousAspects = new HashSet(); - previousAspects.addAll( this.cache.aspectSet() ); - } - else - { - // Can safely clear the cache - this.cache.clear(); - } - - // Is the network powerd? - if( this.energyGrid.isNetworkPowered() ) - { - - // Get the list of fluids in the network - IItemList fluidStackList = this.fluidMonitor.getStorageList(); - - // Loop over all fluids - for( IAEFluidStack fluidStack : fluidStackList ) - { - // Ensure the fluid is an essentia gas - if( !( fluidStack.getFluid() instanceof GaseousEssentia ) ) - { - // Not an essentia gas. - continue; - } - - // Get the gas aspect - Aspect aspect = ( (GaseousEssentia)fluidStack.getFluid() ).getAspect(); - - // Calculate the new amount - Long newAmount = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( fluidStack.getStackSize() ); - - // Update the cache - IAspectStack prevStack = this.cache.setAspect( aspect, newAmount, false ); - - // Are there any listeners? - if( hasListeners ) - { - // Remove from the previous mapping - previousAspects.remove( aspect ); - - // Calculate the difference - long diff = ( newAmount - ( prevStack != null ? prevStack.getStackSize() : 0 ) ); - - if( diff != 0 ) - { - // Add to the changes - aspectChanges.add( new AspectStack( aspect, diff ) ); - } - } - } - } - - // Are there any listeners? - if( hasListeners ) - { - // Anything left in the previous mapping is no longer present in the network - for( Aspect aspect : previousAspects ) - { - aspectChanges.add( new AspectStack( aspect, -this.cache.remove( aspect ).getStackSize(), false ) ); - } - - // Notify listeners - this.notifyListeners( aspectChanges ); - } - - // Mark the cache as valid - this.cacheNeedsUpdate = false; - - } - - @Override - public void addListener( final IMEEssentiaMonitorReceiver listener, final Object verificationToken ) - { - if( verificationToken == null ) - { - throw new NullPointerException( "Verification token can not be null" ); - } - - // If this is the first listener, and the cache is out of sync, it needs to be updated first - if( ( this.listeners.size() == 0 ) && ( this.cacheNeedsUpdate ) ) - { - this.updateCacheToMatchNetwork(); - } - - this.listeners.put( listener, verificationToken ); - } - - /** - * Detaches from the fluid monitor. - * Note that the monitor is no longer valid from this point forward. - */ - public void detach() - { - if( this.fluidMonitor != null ) - { - this.fluidMonitor.removeListener( this ); - this.token = null; - } - } - - @Override - public long extractEssentia( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, final boolean powered ) - { - // Ensure the aspect is not null, and the amount is > 0 - if( ( aspect == null ) || ( amount <= 0 ) ) - { - // Invalid arguments - return 0; - } - - // Get the gas form of the essentia - GaseousEssentia essentiaGas; - - // Ensure there is a gas form of the aspect. - if( ( essentiaGas = GaseousEssentia.getGasFromAspect( aspect ) ) == null ) - { - // Unregistered aspect :( - return 0; - } - - if( powered ) - { - // Simulate power extraction - double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; - double powerReceived = this.energyGrid.extractAEPower( powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - // Was enough power extracted? - if( powerReceived < powerRequest ) - { - // Not enough power - return 0; - } - } - - // Create the fluid request - IAEFluidStack fluidRequest = EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( essentiaGas, amount ); - - // Attempt the extraction - IAEFluidStack fluidReceived = this.fluidMonitor.extractItems( fluidRequest, mode, source ); - - // Was any fluid received? - if( ( fluidReceived == null ) || ( fluidReceived.getStackSize() <= 0 ) ) - { - // Fluid not found. - return 0; - } - - // Convert the received fluid into an aspect stack - long extractedAmount = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( fluidReceived.getStackSize() ); - - // Extract power if modulating - if( ( powered ) && ( mode == Actionable.MODULATE ) ) - { - this.energyGrid.extractAEPower( EssentiaMonitor.AE_PER_ESSENTIA * extractedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG ); - } - - return extractedAmount; - - } - - @Override - public long getEssentiaAmount( final Aspect aspect ) - { - if( !this.energyGrid.isNetworkPowered() ) - { - return 0; - } - - // Does the cache need to be updated? - if( this.cacheNeedsUpdate ) - { - // Update the cache - this.updateCacheToMatchNetwork(); - } - - // Does the cache have this aspect? - if( this.cache.containsAspect( aspect ) ) - { - // Return the amount - return this.cache.get( aspect ).getStackSize(); - } - - // Aspect not stored - return 0; - } - - @Override - public Collection getEssentiaList() - { - if( !this.energyGrid.isNetworkPowered() ) - { - return new ArrayList(); - } - - // Does the cache need to be updated? - if( this.cacheNeedsUpdate ) - { - this.updateCacheToMatchNetwork(); - } - - // Does the view need to be created? - if( this.cacheView == null ) - { - this.cacheView = Collections.unmodifiableCollection( this.cache.getAll() ); - } - - return this.cacheView; - } - - @Override - public long injectEssentia( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, final boolean powered ) - { - // Ensure the aspect is not null, and the amount is > 0 - if( ( aspect == null ) || ( amount <= 0 ) ) - { - // Invalid arguments - return amount; - } - - // Get the gas form of the essentia - GaseousEssentia essentiaGas; - - // Ensure there is a gas form of the aspect. - if( ( essentiaGas = GaseousEssentia.getGasFromAspect( aspect ) ) == null ) - { - // Unregistered aspect :( - return amount; - } - - // Simulate the injection - long injectedAmount = amount; - long rejectedAmount = this.injectEssentiaSafely( aspect, injectedAmount, Actionable.SIMULATE, source, essentiaGas ); - injectedAmount -= rejectedAmount; - - // Was all rejected? - if( injectedAmount == 0 ) - { - return amount; - } - - // Is this a powered injection? - if( powered ) - { - // Simulate power extraction - double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount; - double powerReceived = this.energyGrid.extractAEPower( powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - // Was enough power extracted? - if( powerReceived < powerRequest ) - { - // Not enough power - return amount; - } - } - - // Modulating? - if( mode == Actionable.MODULATE ) - { - // Inject - rejectedAmount = this.injectEssentiaSafely( aspect, injectedAmount, Actionable.MODULATE, source, essentiaGas ); - injectedAmount -= rejectedAmount; - - // Adjust and extract power - if( powered ) - { - double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount; - this.energyGrid.extractAEPower( powerRequest, Actionable.MODULATE, PowerMultiplier.CONFIG ); - } - } - - return amount - injectedAmount; - } - - @Override - public boolean isValid( final Object verificationToken ) - { - // Has a token been assigned? - if( this.token != null ) - { - // Does the token match? - if( this.token.equals( verificationToken ) ) - { - // Does the token still exist? - Object vToken = this.token.get(); - if( vToken != null ) - { - // Return true - return true; - } - } - } - - return false; - } - - @Override - public void onListUpdate() - { - // Mark that the cache needs to be updated - this.cacheNeedsUpdate = true; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable fluidChanges, - final BaseActionSource actionSource ) - { - // Ensure the cache is up to date - if( this.cacheNeedsUpdate ) - { - // No use updating an out of sync cache - return; - - /* - * Note: this should never happen if there are listeners. As the cache will be updated when a list update occurs. - * If any changes occur between a call to onListUpdate() and onUpdateTick(), those changes will be ignored until the cache is updated. - */ - } - - // Ensure there was a change - if( fluidChanges == null ) - { - return; - } - - // True if there are any listeners - boolean hasListeners = ( this.listeners.size() > 0 ); - - // Changes made to the cache. - List aspectChanges = null; - - // Search the changes for essentia gas - for( IAEFluidStack change : fluidChanges ) - { - // Is the change an essentia gas? - if( ( change.getFluid() instanceof GaseousEssentia ) ) - { - // Get the aspect - Aspect aspect = ( (GaseousEssentia)change.getFluid() ).getAspect(); - - // Calculate the difference - long changeAmount = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( change.getStackSize() ); - - // Update the cache - IAspectStack previous = this.cache.postChange( aspect, changeAmount, null ); - - // Add to the changes - if( hasListeners ) - { - // Create the change list if needed - if( aspectChanges == null ) - { - aspectChanges = new ArrayList(); - } - - // Was there a previous stack? - IAspectStack changeStack; - if( previous != null ) - { - // Re-use it, as it is no longer associated with anything - // Plus, it carries the crafting info. - changeStack = previous; - previous.setStackSize( changeAmount ); - } - else - { - // Create a new stack - changeStack = new AspectStack( aspect, changeAmount ); - } - - // Add the change - aspectChanges.add( changeStack ); - } - } - } - - // Notify any listeners - if( ( aspectChanges != null ) && ( aspectChanges.size() > 0 ) ) - { - this.notifyListeners( aspectChanges ); - } - - } - - @Override - public void removeListener( final IMEEssentiaMonitorReceiver listener ) - { - this.listeners.remove( listener ); - } - - /** - * Wraps the specified fluid monitor and energy grid. - * - * @param fluidMonitor - * Fluid monitor to listen to - * @param energyGrid - * Energy grid to extract power from - * @param validationToken - * Used to validate the state of the fluid listener, can not be null - */ - public void wrap( final IMEMonitor fluidMonitor, final IEnergyGrid energyGrid, final Object validationToken ) - { - // Ensure the token is not null - if( validationToken != null ) - { - // Set the token - this.token = new WeakReference( validationToken ); - } - else - { - // Throw exception - throw new NullPointerException( "Validation Token Can Not Be Null" ); - } - - // Set the fluid monitor - this.fluidMonitor = fluidMonitor; - - // Set the energy grid - this.energyGrid = energyGrid; - - // Add listener - this.fluidMonitor.addListener( this, this.token ); - - // Mark that the cache needs to be updated - this.cacheNeedsUpdate = true; - } - +public class EssentiaMonitor implements IMEEssentiaMonitor, IMEMonitorHandlerReceiver { + /** + * The amount of power required to transfer 1 essentia. + */ + public static final double AE_PER_ESSENTIA = 0.3; + + /** + * Objects who wish to be notified of any changes. + */ + protected final HashMap listeners; + + /** + * The grids fluid monitor. + */ + protected IMEMonitor fluidMonitor; + + /** + * The grids energy manager. + */ + protected IEnergyGrid energyGrid; + + /** + * Collection backed by the cache that shows the essentia amounts in the network. Is created the first time it is needed.
+ * Any changes to the cache are reflected in the view. + */ + private Collection cacheView; + + /** + * Used to validate the state of the fluid listener, can not be null + */ + private WeakReference token; + + /** + * Cache of essentia. + */ + private final IEssentiaRepo cache; + + /** + * When true the full storage list needs to be pulled to update the cache. + */ + protected boolean cacheNeedsUpdate = false; + + public EssentiaMonitor() { + // Create the cache + this.cache = new EssentiaRepo(); + + // Create the listeners table + this.listeners = new HashMap(); + } + + /** + * Wraps the specified fluid monitor and energy grid. + * + * @param fluidMonitor + * Fluid monitor to listen to + * @param energyGrid + * Energy grid to extract power from + * @param validationToken + * Used to validate the state of the fluid listener, can not be null + */ + public EssentiaMonitor( + final IMEMonitor fluidMonitor, final IEnergyGrid energyGrid, final Object validationToken) { + // Call default constructor + this(); + + // Call wrap + this.wrap(fluidMonitor, energyGrid, validationToken); + } + + /** + * Mirror method of the injectEssentia. Used to defer power calculations, because the simulation is not always accurate, and Essentia gas should + * not be stored in partial amounts. + * + * @param aspect + * @param amount + * @param mode + * @param source + * @return Amount that was not injected + */ + private long injectEssentiaSafely( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final GaseousEssentia essentiaGas) { + // Create the fluid request + IAEFluidStack fluidRequest = + EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits(essentiaGas, amount); + + // Inject fluid + IAEFluidStack fluidRejected = this.fluidMonitor.injectItems(fluidRequest, mode, source); + + // Was any rejected? + if ((fluidRejected != null) && (fluidRejected.getStackSize() > 0)) { + if (fluidRejected.getStackSize() == fluidRequest.getStackSize()) { + // All essentia was rejected + return amount; + } + + // Calculate the adjusted amount, essentia gas can not be stored in partial units + long rejectedAdjustedAmount = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(fluidRejected.getStackSize()); + return rejectedAdjustedAmount; + } + + // All essentia was accepted. + return 0; + } + + /** + * Notifies all listeners of the specified changes. + * + * @param changes + */ + private void notifyListeners(final List changes) { + // Get an immutable copy + ImmutableList changeList = ImmutableList.copyOf(changes); + + // Get the listener iterator + Iterator> entryIterator = + this.listeners.entrySet().iterator(); + + // Inform all listeners of the changes + while (entryIterator.hasNext()) { + // Get the listener + Entry entry = entryIterator.next(); + + // Validate the token + if (entry.getKey().isValid(entry.getValue())) { + // Valid token + entry.getKey().postChange(this, changeList); + } else { + // Invalid token, remove from listener list + entryIterator.remove(); + } + } + } + + private boolean setAspectCraftability(final Aspect aspect, final boolean isCraftable, final boolean doNotify) { + // Get the aspect stack + IAspectStack stack = this.cache.getOrDefault(aspect, null); + + boolean changesMade = false; + + // Not stored? + if (stack == null) { + // If the cache doesn't have this aspect, and its not craftable then there is nothing to do + if (isCraftable) { + // Put it in the cache + this.cache.postChange(aspect, 0, true); + + // Set changes made + changesMade = true; + } + } else { + // Is stored, but is stack size 0 and setting to not craftable? + if (stack.isEmpty() && (!isCraftable)) { + // Remove the stack + this.cache.remove(aspect); + + // Set changes made + changesMade = true; + } + // Is it changing? + else if (stack.getCraftable() != isCraftable) { + // Set craftability + stack.setCraftable(isCraftable); + + // Set changes made + changesMade = true; + } + } + + // Do notify? + if (doNotify && changesMade && (this.listeners.size() > 0)) { + // Create the change + ArrayList changes = new ArrayList(); + + // Add the aspect + changes.add(new AspectStack(aspect, 0, isCraftable)); + + // Notify + this.notifyListeners(changes); + } + + return changesMade; + } + + /** + * Sets if the aspect is craftable. + * + * @param aspect + * @param isCraftable + */ + protected void setAspectCraftability(final Aspect aspect, final boolean isCraftable) { + this.setAspectCraftability(aspect, isCraftable, true); + } + + /** + * Sets each aspect as craftable. + * + * @param aspects + */ + protected void setCraftableAspects(final HashSet aspects) { + // Create the changes + ArrayList changes = new ArrayList(); + + // Set each aspect + for (Aspect aspect : aspects) { + // Was the crafting status changed? + if (this.setAspectCraftability(aspect, true, false)) { + // Add the aspect + changes.add(new AspectStack(aspect, 0, true)); + } + } + + // Notify listeners? + if ((changes.size() > 0) && (this.listeners.size() > 0)) { + // Notify + this.notifyListeners(changes); + } + } + + /** + * Updates the cache to match the contents of the network and updates any + * listeners of the changes. + */ + @SuppressWarnings("null") + protected void updateCacheToMatchNetwork() { + // Changes made to the cache + List aspectChanges = null; + + // The currently stored aspects + Set previousAspects = null; + + // Are there any listeners? + boolean hasListeners = (this.listeners.size() > 0); + if (hasListeners) { + // Create the change trackers + aspectChanges = new ArrayList(); + previousAspects = new HashSet(); + previousAspects.addAll(this.cache.aspectSet()); + } else { + // Can safely clear the cache + this.cache.clear(); + } + + // Is the network powerd? + if (this.energyGrid.isNetworkPowered()) { + + // Get the list of fluids in the network + IItemList fluidStackList = this.fluidMonitor.getStorageList(); + + // Loop over all fluids + for (IAEFluidStack fluidStack : fluidStackList) { + // Ensure the fluid is an essentia gas + if (!(fluidStack.getFluid() instanceof GaseousEssentia)) { + // Not an essentia gas. + continue; + } + + // Get the gas aspect + Aspect aspect = ((GaseousEssentia) fluidStack.getFluid()).getAspect(); + + // Calculate the new amount + Long newAmount = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(fluidStack.getStackSize()); + + // Update the cache + IAspectStack prevStack = this.cache.setAspect(aspect, newAmount, false); + + // Are there any listeners? + if (hasListeners) { + // Remove from the previous mapping + previousAspects.remove(aspect); + + // Calculate the difference + long diff = (newAmount - (prevStack != null ? prevStack.getStackSize() : 0)); + + if (diff != 0) { + // Add to the changes + aspectChanges.add(new AspectStack(aspect, diff)); + } + } + } + } + + // Are there any listeners? + if (hasListeners) { + // Anything left in the previous mapping is no longer present in the network + for (Aspect aspect : previousAspects) { + aspectChanges.add( + new AspectStack(aspect, -this.cache.remove(aspect).getStackSize(), false)); + } + + // Notify listeners + this.notifyListeners(aspectChanges); + } + + // Mark the cache as valid + this.cacheNeedsUpdate = false; + } + + @Override + public void addListener(final IMEEssentiaMonitorReceiver listener, final Object verificationToken) { + if (verificationToken == null) { + throw new NullPointerException("Verification token can not be null"); + } + + // If this is the first listener, and the cache is out of sync, it needs to be updated first + if ((this.listeners.size() == 0) && (this.cacheNeedsUpdate)) { + this.updateCacheToMatchNetwork(); + } + + this.listeners.put(listener, verificationToken); + } + + /** + * Detaches from the fluid monitor. + * Note that the monitor is no longer valid from this point forward. + */ + public void detach() { + if (this.fluidMonitor != null) { + this.fluidMonitor.removeListener(this); + this.token = null; + } + } + + @Override + public long extractEssentia( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final boolean powered) { + // Ensure the aspect is not null, and the amount is > 0 + if ((aspect == null) || (amount <= 0)) { + // Invalid arguments + return 0; + } + + // Get the gas form of the essentia + GaseousEssentia essentiaGas; + + // Ensure there is a gas form of the aspect. + if ((essentiaGas = GaseousEssentia.getGasFromAspect(aspect)) == null) { + // Unregistered aspect :( + return 0; + } + + if (powered) { + // Simulate power extraction + double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; + double powerReceived = + this.energyGrid.extractAEPower(powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + // Was enough power extracted? + if (powerReceived < powerRequest) { + // Not enough power + return 0; + } + } + + // Create the fluid request + IAEFluidStack fluidRequest = + EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits(essentiaGas, amount); + + // Attempt the extraction + IAEFluidStack fluidReceived = this.fluidMonitor.extractItems(fluidRequest, mode, source); + + // Was any fluid received? + if ((fluidReceived == null) || (fluidReceived.getStackSize() <= 0)) { + // Fluid not found. + return 0; + } + + // Convert the received fluid into an aspect stack + long extractedAmount = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(fluidReceived.getStackSize()); + + // Extract power if modulating + if ((powered) && (mode == Actionable.MODULATE)) { + this.energyGrid.extractAEPower( + EssentiaMonitor.AE_PER_ESSENTIA * extractedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG); + } + + return extractedAmount; + } + + @Override + public long getEssentiaAmount(final Aspect aspect) { + if (!this.energyGrid.isNetworkPowered()) { + return 0; + } + + // Does the cache need to be updated? + if (this.cacheNeedsUpdate) { + // Update the cache + this.updateCacheToMatchNetwork(); + } + + // Does the cache have this aspect? + if (this.cache.containsAspect(aspect)) { + // Return the amount + return this.cache.get(aspect).getStackSize(); + } + + // Aspect not stored + return 0; + } + + @Override + public Collection getEssentiaList() { + if (!this.energyGrid.isNetworkPowered()) { + return new ArrayList(); + } + + // Does the cache need to be updated? + if (this.cacheNeedsUpdate) { + this.updateCacheToMatchNetwork(); + } + + // Does the view need to be created? + if (this.cacheView == null) { + this.cacheView = Collections.unmodifiableCollection(this.cache.getAll()); + } + + return this.cacheView; + } + + @Override + public long injectEssentia( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final boolean powered) { + // Ensure the aspect is not null, and the amount is > 0 + if ((aspect == null) || (amount <= 0)) { + // Invalid arguments + return amount; + } + + // Get the gas form of the essentia + GaseousEssentia essentiaGas; + + // Ensure there is a gas form of the aspect. + if ((essentiaGas = GaseousEssentia.getGasFromAspect(aspect)) == null) { + // Unregistered aspect :( + return amount; + } + + // Simulate the injection + long injectedAmount = amount; + long rejectedAmount = + this.injectEssentiaSafely(aspect, injectedAmount, Actionable.SIMULATE, source, essentiaGas); + injectedAmount -= rejectedAmount; + + // Was all rejected? + if (injectedAmount == 0) { + return amount; + } + + // Is this a powered injection? + if (powered) { + // Simulate power extraction + double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount; + double powerReceived = + this.energyGrid.extractAEPower(powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + // Was enough power extracted? + if (powerReceived < powerRequest) { + // Not enough power + return amount; + } + } + + // Modulating? + if (mode == Actionable.MODULATE) { + // Inject + rejectedAmount = + this.injectEssentiaSafely(aspect, injectedAmount, Actionable.MODULATE, source, essentiaGas); + injectedAmount -= rejectedAmount; + + // Adjust and extract power + if (powered) { + double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount; + this.energyGrid.extractAEPower(powerRequest, Actionable.MODULATE, PowerMultiplier.CONFIG); + } + } + + return amount - injectedAmount; + } + + @Override + public boolean isValid(final Object verificationToken) { + // Has a token been assigned? + if (this.token != null) { + // Does the token match? + if (this.token.equals(verificationToken)) { + // Does the token still exist? + Object vToken = this.token.get(); + if (vToken != null) { + // Return true + return true; + } + } + } + + return false; + } + + @Override + public void onListUpdate() { + // Mark that the cache needs to be updated + this.cacheNeedsUpdate = true; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable fluidChanges, + final BaseActionSource actionSource) { + // Ensure the cache is up to date + if (this.cacheNeedsUpdate) { + // No use updating an out of sync cache + return; + + /* + * Note: this should never happen if there are listeners. As the cache will be updated when a list update occurs. + * If any changes occur between a call to onListUpdate() and onUpdateTick(), those changes will be ignored until the cache is updated. + */ + } + + // Ensure there was a change + if (fluidChanges == null) { + return; + } + + // True if there are any listeners + boolean hasListeners = (this.listeners.size() > 0); + + // Changes made to the cache. + List aspectChanges = null; + + // Search the changes for essentia gas + for (IAEFluidStack change : fluidChanges) { + // Is the change an essentia gas? + if ((change.getFluid() instanceof GaseousEssentia)) { + // Get the aspect + Aspect aspect = ((GaseousEssentia) change.getFluid()).getAspect(); + + // Calculate the difference + long changeAmount = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(change.getStackSize()); + + // Update the cache + IAspectStack previous = this.cache.postChange(aspect, changeAmount, null); + + // Add to the changes + if (hasListeners) { + // Create the change list if needed + if (aspectChanges == null) { + aspectChanges = new ArrayList(); + } + + // Was there a previous stack? + IAspectStack changeStack; + if (previous != null) { + // Re-use it, as it is no longer associated with anything + // Plus, it carries the crafting info. + changeStack = previous; + previous.setStackSize(changeAmount); + } else { + // Create a new stack + changeStack = new AspectStack(aspect, changeAmount); + } + + // Add the change + aspectChanges.add(changeStack); + } + } + } + + // Notify any listeners + if ((aspectChanges != null) && (aspectChanges.size() > 0)) { + this.notifyListeners(aspectChanges); + } + } + + @Override + public void removeListener(final IMEEssentiaMonitorReceiver listener) { + this.listeners.remove(listener); + } + + /** + * Wraps the specified fluid monitor and energy grid. + * + * @param fluidMonitor + * Fluid monitor to listen to + * @param energyGrid + * Energy grid to extract power from + * @param validationToken + * Used to validate the state of the fluid listener, can not be null + */ + public void wrap( + final IMEMonitor fluidMonitor, final IEnergyGrid energyGrid, final Object validationToken) { + // Ensure the token is not null + if (validationToken != null) { + // Set the token + this.token = new WeakReference(validationToken); + } else { + // Throw exception + throw new NullPointerException("Validation Token Can Not Be Null"); + } + + // Set the fluid monitor + this.fluidMonitor = fluidMonitor; + + // Set the energy grid + this.energyGrid = energyGrid; + + // Add listener + this.fluidMonitor.addListener(this, this.token); + + // Mark that the cache needs to be updated + this.cacheNeedsUpdate = true; + } } diff --git a/src/main/java/thaumicenergistics/common/grid/EssentiaPassThroughMonitor.java b/src/main/java/thaumicenergistics/common/grid/EssentiaPassThroughMonitor.java index f4f1cbc0..e699fb25 100644 --- a/src/main/java/thaumicenergistics/common/grid/EssentiaPassThroughMonitor.java +++ b/src/main/java/thaumicenergistics/common/grid/EssentiaPassThroughMonitor.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.grid; -import java.util.Collection; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.networking.security.BaseActionSource; +import java.util.Collection; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IMEEssentiaMonitor; import thaumicenergistics.api.grid.IMEEssentiaMonitorReceiver; @@ -16,104 +16,102 @@ import thaumicenergistics.api.storage.IAspectStack; * @author Nividica * */ -public class EssentiaPassThroughMonitor - extends EssentiaMonitor -{ - private final IMEEssentiaMonitor internalMonitor; +public class EssentiaPassThroughMonitor extends EssentiaMonitor { + private final IMEEssentiaMonitor internalMonitor; - public EssentiaPassThroughMonitor( final IMEEssentiaMonitor source, final IEnergyGrid energyGrid ) - { - // Call super - super(); + public EssentiaPassThroughMonitor(final IMEEssentiaMonitor source, final IEnergyGrid energyGrid) { + // Call super + super(); - // Set the source - this.internalMonitor = source; + // Set the source + this.internalMonitor = source; - // Set the energy grid - this.energyGrid = energyGrid; - } + // Set the energy grid + this.energyGrid = energyGrid; + } - @Override - public void addListener( final IMEEssentiaMonitorReceiver listener, final Object verificationToken ) - { - this.internalMonitor.addListener( listener, verificationToken ); - } + @Override + public void addListener(final IMEEssentiaMonitorReceiver listener, final Object verificationToken) { + this.internalMonitor.addListener(listener, verificationToken); + } - @Override - public long extractEssentia( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, final boolean powered ) - { - if( powered ) - { - // Simulate power extraction - double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; - double powerReceived = this.energyGrid.extractAEPower( powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG ); + @Override + public long extractEssentia( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final boolean powered) { + if (powered) { + // Simulate power extraction + double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; + double powerReceived = + this.energyGrid.extractAEPower(powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG); - // Was enough power extracted? - if( powerReceived < powerRequest ) - { - // Not enough power - return 0; - } - } + // Was enough power extracted? + if (powerReceived < powerRequest) { + // Not enough power + return 0; + } + } - // Extract - long extractedAmount = this.internalMonitor.extractEssentia( aspect, amount, mode, source, false ); + // Extract + long extractedAmount = this.internalMonitor.extractEssentia(aspect, amount, mode, source, false); - // Extract power if modulating - if( ( extractedAmount > 0 ) && ( powered ) && ( mode == Actionable.MODULATE ) ) - { - this.energyGrid.extractAEPower( EssentiaMonitor.AE_PER_ESSENTIA * extractedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG ); - } + // Extract power if modulating + if ((extractedAmount > 0) && (powered) && (mode == Actionable.MODULATE)) { + this.energyGrid.extractAEPower( + EssentiaMonitor.AE_PER_ESSENTIA * extractedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG); + } - return extractedAmount; - } + return extractedAmount; + } - @Override - public long getEssentiaAmount( final Aspect aspect ) - { - return this.internalMonitor.getEssentiaAmount( aspect ); - } + @Override + public long getEssentiaAmount(final Aspect aspect) { + return this.internalMonitor.getEssentiaAmount(aspect); + } - @Override - public Collection getEssentiaList() - { - return this.internalMonitor.getEssentiaList(); - } + @Override + public Collection getEssentiaList() { + return this.internalMonitor.getEssentiaList(); + } - @Override - public long injectEssentia( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, final boolean powered ) - { - if( powered ) - { - // Simulate power extraction - double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; - double powerReceived = this.energyGrid.extractAEPower( powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG ); + @Override + public long injectEssentia( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final boolean powered) { + if (powered) { + // Simulate power extraction + double powerRequest = EssentiaMonitor.AE_PER_ESSENTIA * amount; + double powerReceived = + this.energyGrid.extractAEPower(powerRequest, Actionable.SIMULATE, PowerMultiplier.CONFIG); - // Was enough power extracted? - if( powerReceived < powerRequest ) - { - // Not enough power - return 0; - } - } + // Was enough power extracted? + if (powerReceived < powerRequest) { + // Not enough power + return 0; + } + } - // Inject - long rejectedAmount = this.internalMonitor.injectEssentia( aspect, amount, mode, source, false ); - long injectedAmount = amount - rejectedAmount; + // Inject + long rejectedAmount = this.internalMonitor.injectEssentia(aspect, amount, mode, source, false); + long injectedAmount = amount - rejectedAmount; - // Extract power if modulating - if( ( injectedAmount > 0 ) && ( powered ) && ( mode == Actionable.MODULATE ) ) - { - this.energyGrid.extractAEPower( EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG ); - } + // Extract power if modulating + if ((injectedAmount > 0) && (powered) && (mode == Actionable.MODULATE)) { + this.energyGrid.extractAEPower( + EssentiaMonitor.AE_PER_ESSENTIA * injectedAmount, Actionable.MODULATE, PowerMultiplier.CONFIG); + } - return rejectedAmount; - } - - @Override - public void removeListener( final IMEEssentiaMonitorReceiver listener ) - { - this.internalMonitor.removeListener( listener ); - } + return rejectedAmount; + } + @Override + public void removeListener(final IMEEssentiaMonitorReceiver listener) { + this.internalMonitor.removeListener(listener); + } } diff --git a/src/main/java/thaumicenergistics/common/grid/EssentiaWatcher.java b/src/main/java/thaumicenergistics/common/grid/EssentiaWatcher.java index 93147a60..153db76a 100644 --- a/src/main/java/thaumicenergistics/common/grid/EssentiaWatcher.java +++ b/src/main/java/thaumicenergistics/common/grid/EssentiaWatcher.java @@ -14,149 +14,125 @@ import thaumicenergistics.api.grid.IEssentiaWatcherHost; * @author Nividica * */ -public class EssentiaWatcher - implements IEssentiaWatcher -{ +public class EssentiaWatcher implements IEssentiaWatcher { - /** - * What aspects are being tracked by this watcher. - */ - private final HashSet trackedAspects; + /** + * What aspects are being tracked by this watcher. + */ + private final HashSet trackedAspects; - /** - * The manager for the cache. - */ - private final EssentiaWatcherManager manager; + /** + * The manager for the cache. + */ + private final EssentiaWatcherManager manager; - /** - * Whom this watcher belongs to. - */ - private final WeakReference host; + /** + * Whom this watcher belongs to. + */ + private final WeakReference host; - public EssentiaWatcher( final EssentiaWatcherManager manager, final IEssentiaWatcherHost host ) - { - this.manager = manager; - this.trackedAspects = new HashSet(); - this.host = new WeakReference( host ); - } + public EssentiaWatcher(final EssentiaWatcherManager manager, final IEssentiaWatcherHost host) { + this.manager = manager; + this.trackedAspects = new HashSet(); + this.host = new WeakReference(host); + } - @Override - public boolean add( final Aspect aspect ) - { - boolean changed = this.trackedAspects.add( aspect ); - if( changed ) - { - // Update the manager - this.manager.onWatcherAddAspect( this, aspect ); - } - return changed; - } + @Override + public boolean add(final Aspect aspect) { + boolean changed = this.trackedAspects.add(aspect); + if (changed) { + // Update the manager + this.manager.onWatcherAddAspect(this, aspect); + } + return changed; + } - @Override - public boolean addAll( final Collection c ) - { - boolean changed = false; - for( Aspect aspect : c ) - { - changed |= this.add( aspect ); - } - return changed; - } + @Override + public boolean addAll(final Collection c) { + boolean changed = false; + for (Aspect aspect : c) { + changed |= this.add(aspect); + } + return changed; + } - @Override - public void clear() - { - if( !this.isEmpty() ) - { - // Update the manager - this.manager.onWatcherCleared( this, this.trackedAspects ); + @Override + public void clear() { + if (!this.isEmpty()) { + // Update the manager + this.manager.onWatcherCleared(this, this.trackedAspects); - // Clear the tracked aspects - this.trackedAspects.clear(); - } - } + // Clear the tracked aspects + this.trackedAspects.clear(); + } + } - @Override - public boolean contains( final Object o ) - { - return this.trackedAspects.contains( o ); - } + @Override + public boolean contains(final Object o) { + return this.trackedAspects.contains(o); + } - @Override - public boolean containsAll( final Collection c ) - { - return this.trackedAspects.containsAll( c ); - } + @Override + public boolean containsAll(final Collection c) { + return this.trackedAspects.containsAll(c); + } - @Override - public IEssentiaWatcherHost getHost() - { - return this.host.get(); - } + @Override + public IEssentiaWatcherHost getHost() { + return this.host.get(); + } - @Override - public boolean isEmpty() - { - return this.trackedAspects.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.trackedAspects.isEmpty(); + } - @Override - public Iterator iterator() - { - return this.trackedAspects.iterator(); - } + @Override + public Iterator iterator() { + return this.trackedAspects.iterator(); + } - @Override - public boolean remove( final Object o ) - { - if( o instanceof Aspect ) - { - boolean changed = this.trackedAspects.remove( o ); - if( changed ) - { - this.manager.onWatcherRemoveAspect( this, (Aspect)o ); - } - return changed; - } - return false; - } + @Override + public boolean remove(final Object o) { + if (o instanceof Aspect) { + boolean changed = this.trackedAspects.remove(o); + if (changed) { + this.manager.onWatcherRemoveAspect(this, (Aspect) o); + } + return changed; + } + return false; + } - @Override - public boolean removeAll( final Collection c ) - { - boolean changed = false; - for( Object aspect : c ) - { - changed |= this.remove( aspect ); - } - return changed; - } + @Override + public boolean removeAll(final Collection c) { + boolean changed = false; + for (Object aspect : c) { + changed |= this.remove(aspect); + } + return changed; + } - /** - * This is not supported. - */ - @Override - public boolean retainAll( final Collection c ) - { - throw new UnsupportedOperationException(); - } + /** + * This is not supported. + */ + @Override + public boolean retainAll(final Collection c) { + throw new UnsupportedOperationException(); + } - @Override - public int size() - { - return this.trackedAspects.size(); - } + @Override + public int size() { + return this.trackedAspects.size(); + } - @Override - public Object[] toArray() - { - return this.trackedAspects.toArray(); - } - - @Override - public T[] toArray( final T[] a ) - { - return this.trackedAspects.toArray( a ); - } + @Override + public Object[] toArray() { + return this.trackedAspects.toArray(); + } + @Override + public T[] toArray(final T[] a) { + return this.trackedAspects.toArray(a); + } } diff --git a/src/main/java/thaumicenergistics/common/grid/EssentiaWatcherManager.java b/src/main/java/thaumicenergistics/common/grid/EssentiaWatcherManager.java index 9a5888c2..e77ee4eb 100644 --- a/src/main/java/thaumicenergistics/common/grid/EssentiaWatcherManager.java +++ b/src/main/java/thaumicenergistics/common/grid/EssentiaWatcherManager.java @@ -1,8 +1,8 @@ package thaumicenergistics.common.grid; +import appeng.api.networking.IGridNode; import java.util.HashMap; import java.util.HashSet; -import appeng.api.networking.IGridNode; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IEssentiaWatcher; import thaumicenergistics.api.grid.IEssentiaWatcherHost; @@ -10,183 +10,160 @@ import thaumicenergistics.api.grid.IMEEssentiaMonitor; import thaumicenergistics.api.grid.IMEEssentiaMonitorReceiver; import thaumicenergistics.api.storage.IAspectStack; -class EssentiaWatcherManager - implements IMEEssentiaMonitorReceiver -{ - /** - * Maps Node->Watcher - */ - private HashMap watchers = new HashMap(); +class EssentiaWatcherManager implements IMEEssentiaMonitorReceiver { + /** + * Maps Node->Watcher + */ + private HashMap watchers = new HashMap(); - /** - * Maps Aspect -> Watchers - */ - private HashMap> watchedAspects = new HashMap>(); + /** + * Maps Aspect -> Watchers + */ + private HashMap> watchedAspects = + new HashMap>(); - /** - * True when the manager is listening for changes. - */ - private boolean isListeningForChanges = false; + /** + * True when the manager is listening for changes. + */ + private boolean isListeningForChanges = false; - private final GridEssentiaCache gridCache; + private final GridEssentiaCache gridCache; - public EssentiaWatcherManager( final GridEssentiaCache gridCache ) - { - this.gridCache = gridCache; - } + public EssentiaWatcherManager(final GridEssentiaCache gridCache) { + this.gridCache = gridCache; + } - /** - * Adds a watcher. - * - * @param node - * @param watcher - */ - public void addWatcher( final IGridNode node, final IEssentiaWatcher watcher ) - { - // Add the watcher - this.watchers.put( node, watcher ); + /** + * Adds a watcher. + * + * @param node + * @param watcher + */ + public void addWatcher(final IGridNode node, final IEssentiaWatcher watcher) { + // Add the watcher + this.watchers.put(node, watcher); - // Is the manager not listening for changes? - if( !this.isListeningForChanges ) - { - // Listen for changes - this.gridCache.addListener( this, this.gridCache.internalGrid ); - this.isListeningForChanges = true; - } - } + // Is the manager not listening for changes? + if (!this.isListeningForChanges) { + // Listen for changes + this.gridCache.addListener(this, this.gridCache.internalGrid); + this.isListeningForChanges = true; + } + } - @Override - public boolean isValid( final Object verificationToken ) - { - return this.isListeningForChanges && ( verificationToken == this.gridCache.internalGrid ); - } + @Override + public boolean isValid(final Object verificationToken) { + return this.isListeningForChanges && (verificationToken == this.gridCache.internalGrid); + } - /** - * Called by watchers when a new aspect is to be tracked. - */ - public void onWatcherAddAspect( final IEssentiaWatcher watcher, final Aspect aspect ) - { - HashSet aWatchers; + /** + * Called by watchers when a new aspect is to be tracked. + */ + public void onWatcherAddAspect(final IEssentiaWatcher watcher, final Aspect aspect) { + HashSet aWatchers; - // Does the set need to be created? - if( !this.watchedAspects.containsKey( aspect ) ) - { - // Create the set - aWatchers = new HashSet(); - this.watchedAspects.put( aspect, aWatchers ); - } - else - { - // Get the set - aWatchers = this.watchedAspects.get( aspect ); - } + // Does the set need to be created? + if (!this.watchedAspects.containsKey(aspect)) { + // Create the set + aWatchers = new HashSet(); + this.watchedAspects.put(aspect, aWatchers); + } else { + // Get the set + aWatchers = this.watchedAspects.get(aspect); + } - // Add the watcher - aWatchers.add( watcher ); - } + // Add the watcher + aWatchers.add(watcher); + } - /** - * Called by watchers just before they are cleared. - * - * @param watcher - * @param previouslyTrackedAspects - */ - public void onWatcherCleared( final IEssentiaWatcher watcher, final HashSet previouslyTrackedAspects ) - { - for( Aspect aspect : previouslyTrackedAspects ) - { - this.onWatcherRemoveAspect( watcher, aspect ); - } - } + /** + * Called by watchers just before they are cleared. + * + * @param watcher + * @param previouslyTrackedAspects + */ + public void onWatcherCleared(final IEssentiaWatcher watcher, final HashSet previouslyTrackedAspects) { + for (Aspect aspect : previouslyTrackedAspects) { + this.onWatcherRemoveAspect(watcher, aspect); + } + } - /** - * Called by watchers when an aspect is no longer to be tracked. - * - * @param watcher - * @param aspect - */ - public void onWatcherRemoveAspect( final IEssentiaWatcher watcher, final Aspect aspect ) - { - // Get the set - HashSet aWatchers = this.watchedAspects.get( aspect ); - if( aWatchers != null ) - { - // Remove the watcher - aWatchers.remove( watcher ); + /** + * Called by watchers when an aspect is no longer to be tracked. + * + * @param watcher + * @param aspect + */ + public void onWatcherRemoveAspect(final IEssentiaWatcher watcher, final Aspect aspect) { + // Get the set + HashSet aWatchers = this.watchedAspects.get(aspect); + if (aWatchers != null) { + // Remove the watcher + aWatchers.remove(watcher); - // Is the set empty? - if( aWatchers.isEmpty() ) - { - // Remove the mapping - this.watchedAspects.remove( aspect ); - } - } - } + // Is the set empty? + if (aWatchers.isEmpty()) { + // Remove the mapping + this.watchedAspects.remove(aspect); + } + } + } - @Override - public void postChange( final IMEEssentiaMonitor fromMonitor, final Iterable changes ) - { - // Fast bail - if( this.watchedAspects.isEmpty() ) - { - return; - } + @Override + public void postChange(final IMEEssentiaMonitor fromMonitor, final Iterable changes) { + // Fast bail + if (this.watchedAspects.isEmpty()) { + return; + } - // Loop over all changes - for( IAspectStack change : changes ) - { - // Is the change being watched for? - if( this.watchedAspects.containsKey( change.getAspect() ) ) - { - // Get the set - HashSet watcherSet = this.watchedAspects.get( change.getAspect() ); + // Loop over all changes + for (IAspectStack change : changes) { + // Is the change being watched for? + if (this.watchedAspects.containsKey(change.getAspect())) { + // Get the set + HashSet watcherSet = this.watchedAspects.get(change.getAspect()); - // Get the full amount in the system - long fullAmount = this.gridCache.getEssentiaAmount( change.getAspect() ); + // Get the full amount in the system + long fullAmount = this.gridCache.getEssentiaAmount(change.getAspect()); - // Update each watcher - for( IEssentiaWatcher watcher : watcherSet ) - { - // Get the watchers host - IEssentiaWatcherHost host = watcher.getHost(); + // Update each watcher + for (IEssentiaWatcher watcher : watcherSet) { + // Get the watchers host + IEssentiaWatcherHost host = watcher.getHost(); - // Update the host - if( host != null ) - { - host.onEssentiaChange( change.getAspect(), fullAmount, change.getStackSize() ); - } - } - } - } - } + // Update the host + if (host != null) { + host.onEssentiaChange(change.getAspect(), fullAmount, change.getStackSize()); + } + } + } + } + } - /** - * Removes a watcher. - * - * @param node - */ - public void removeWatcher( final IGridNode node ) - { - // Get the watcher - IEssentiaWatcher watcher = this.watchers.get( node ); - if( watcher != null ) - { - // Clear the watcher - watcher.clear(); + /** + * Removes a watcher. + * + * @param node + */ + public void removeWatcher(final IGridNode node) { + // Get the watcher + IEssentiaWatcher watcher = this.watchers.get(node); + if (watcher != null) { + // Clear the watcher + watcher.clear(); - // Remove the watcher - this.watchers.remove( node ); + // Remove the watcher + this.watchers.remove(node); - // Is the list empty? - if( this.watchers.isEmpty() ) - { - // Ensure the watched aspects is also empty - this.watchedAspects.clear(); + // Is the list empty? + if (this.watchers.isEmpty()) { + // Ensure the watched aspects is also empty + this.watchedAspects.clear(); - // Stop listening - this.gridCache.removeListener( this ); - this.isListeningForChanges = false; - } - } - } + // Stop listening + this.gridCache.removeListener(this); + this.isListeningForChanges = false; + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/grid/GridEssentiaCache.java b/src/main/java/thaumicenergistics/common/grid/GridEssentiaCache.java index b0eb151a..fb1b1960 100644 --- a/src/main/java/thaumicenergistics/common/grid/GridEssentiaCache.java +++ b/src/main/java/thaumicenergistics/common/grid/GridEssentiaCache.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.grid; -import java.util.HashSet; -import com.google.common.collect.ImmutableSet; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.IGrid; @@ -19,6 +17,8 @@ import appeng.api.storage.IMEMonitor; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.me.cluster.implementations.CraftingCPUCluster; +import com.google.common.collect.ImmutableSet; +import java.util.HashSet; import net.minecraft.item.ItemStack; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IEssentiaGrid; @@ -32,259 +32,230 @@ import thaumicenergistics.common.items.ItemEnum; * @author Nividica * */ -public class GridEssentiaCache - extends EssentiaMonitor - implements IEssentiaGrid -{ +public class GridEssentiaCache extends EssentiaMonitor implements IEssentiaGrid { - /** - * Grid the cache is part of. - */ - final IGrid internalGrid; + /** + * Grid the cache is part of. + */ + final IGrid internalGrid; - /** - * Manages the watchers - */ - private final EssentiaWatcherManager essentiaWatcherManger; + /** + * Manages the watchers + */ + private final EssentiaWatcherManager essentiaWatcherManger; - /** - * The 'result' of essentia crafting operations. - */ - private final ItemStack craftingAspectItem; + /** + * The 'result' of essentia crafting operations. + */ + private final ItemStack craftingAspectItem; - /** - * Watches the item network for essentia related item events. - */ - private final CraftingAspect_ItemWatcher craftingWatcher; + /** + * Watches the item network for essentia related item events. + */ + private final CraftingAspect_ItemWatcher craftingWatcher; - public GridEssentiaCache( final IGrid grid ) - { - // Set the grid - this.internalGrid = grid; + public GridEssentiaCache(final IGrid grid) { + // Set the grid + this.internalGrid = grid; - // Create the watcher manager - this.essentiaWatcherManger = new EssentiaWatcherManager( this ); + // Create the watcher manager + this.essentiaWatcherManger = new EssentiaWatcherManager(this); - // Set the aspect item - this.craftingAspectItem = ItemEnum.CRAFTING_ASPECT.getStack(); + // Set the aspect item + this.craftingAspectItem = ItemEnum.CRAFTING_ASPECT.getStack(); - // Create the crafting watcher - this.craftingWatcher = new CraftingAspect_ItemWatcher( this ); - } + // Create the crafting watcher + this.craftingWatcher = new CraftingAspect_ItemWatcher(this); + } - /** - * Called by the crafting watcher when an update is needed. - */ - void markForUpdate() - { - this.cacheNeedsUpdate = true; - } + /** + * Called by the crafting watcher when an update is needed. + */ + void markForUpdate() { + this.cacheNeedsUpdate = true; + } - /** - * Add in any craftable aspects - */ - @Override - protected void updateCacheToMatchNetwork() - { - // Call super - super.updateCacheToMatchNetwork(); + /** + * Add in any craftable aspects + */ + @Override + protected void updateCacheToMatchNetwork() { + // Call super + super.updateCacheToMatchNetwork(); - // Is the network powered? - if( !this.energyGrid.isNetworkPowered() ) - { - return; - } + // Is the network powered? + if (!this.energyGrid.isNetworkPowered()) { + return; + } - // Get the item monitor - IStorageGrid storage = (IStorageGrid)this.internalGrid.getCache( IStorageGrid.class ); - IMEMonitor itemMonitor = storage.getItemInventory(); + // Get the item monitor + IStorageGrid storage = (IStorageGrid) this.internalGrid.getCache(IStorageGrid.class); + IMEMonitor itemMonitor = storage.getItemInventory(); - // Get stored items - IItemList storedItems = itemMonitor.getStorageList(); - if( ( storedItems == null ) || ( storedItems.size() == 0 ) ) - { - return; - } + // Get stored items + IItemList storedItems = itemMonitor.getStorageList(); + if ((storedItems == null) || (storedItems.size() == 0)) { + return; + } - // Create the aspect list - HashSet craftableAspects = new HashSet(); + // Create the aspect list + HashSet craftableAspects = new HashSet(); - // Check each item for craftability and type - for( IAEItemStack stack : storedItems ) - { - if( stack == null ) - { - continue; - } + // Check each item for craftability and type + for (IAEItemStack stack : storedItems) { + if (stack == null) { + continue; + } - // Is the stack craftable, has NBT tag, and is a crafting aspect? - if( stack.isCraftable() && stack.hasTagCompound() && ( stack.getItem() instanceof ItemCraftingAspect ) ) - { - // Get the aspect - Aspect aspect = ItemCraftingAspect.getAspect( stack.getTagCompound().getNBTTagCompoundCopy() ); - if( aspect != null ) - { - // Add the aspect - craftableAspects.add( aspect ); - } + // Is the stack craftable, has NBT tag, and is a crafting aspect? + if (stack.isCraftable() && stack.hasTagCompound() && (stack.getItem() instanceof ItemCraftingAspect)) { + // Get the aspect + Aspect aspect = + ItemCraftingAspect.getAspect(stack.getTagCompound().getNBTTagCompoundCopy()); + if (aspect != null) { + // Add the aspect + craftableAspects.add(aspect); + } + } + } - } - } + // Anything added? + if (craftableAspects.size() > 0) { + this.setCraftableAspects(craftableAspects); + } + } - // Anything added? - if( craftableAspects.size() > 0 ) - { - this.setCraftableAspects( craftableAspects ); - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + // Does the node wish to watch for changes? + if (machine instanceof IEssentiaWatcherHost) { + // Cast + IEssentiaWatcherHost host = (IEssentiaWatcherHost) machine; - } + // Create the watcher + EssentiaWatcher watcher = new EssentiaWatcher(this.essentiaWatcherManger, host); - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - // Does the node wish to watch for changes? - if( machine instanceof IEssentiaWatcherHost ) - { - // Cast - IEssentiaWatcherHost host = (IEssentiaWatcherHost)machine; + // Add to the watcher manager + this.essentiaWatcherManger.addWatcher(gridNode, watcher); - // Create the watcher - EssentiaWatcher watcher = new EssentiaWatcher( this.essentiaWatcherManger, host ); + // Inform the host it has a watcher + host.updateWatcher(watcher); + } + } - // Add to the watcher manager - this.essentiaWatcherManger.addWatcher( gridNode, watcher ); + @Override + public long injectEssentia( + final Aspect aspect, + final long amount, + final Actionable mode, + final BaseActionSource source, + final boolean powered) { + // Call super + long amountRejected = super.injectEssentia(aspect, amount, mode, source, powered); - // Inform the host it has a watcher - host.updateWatcher( watcher ); - } - } + if ((mode == Actionable.MODULATE) && (amountRejected < amount)) { + // Get the crafting grid + ICraftingGrid craftingGrid = this.internalGrid.getCache(ICraftingGrid.class); - @Override - public long injectEssentia( final Aspect aspect, final long amount, final Actionable mode, final BaseActionSource source, final boolean powered ) - { - // Call super - long amountRejected = super.injectEssentia( aspect, amount, mode, source, powered ); + // Get the CPU list + ImmutableSet cpus = craftingGrid.getCpus(); - if( ( mode == Actionable.MODULATE ) && ( amountRejected < amount ) ) - { - // Get the crafting grid - ICraftingGrid craftingGrid = this.internalGrid.getCache( ICraftingGrid.class ); + // Are there any crafting CPU's? + if (cpus.size() > 0) { + // Set the aspect + ItemCraftingAspect.setAspect(this.craftingAspectItem, aspect); - // Get the CPU list - ImmutableSet cpus = craftingGrid.getCpus(); + // Delay creating this as long as possible + IAEItemStack aspectAEItem = null; - // Are there any crafting CPU's? - if( cpus.size() > 0 ) - { - // Set the aspect - ItemCraftingAspect.setAspect( this.craftingAspectItem, aspect ); + // Set the amounts + long amountToInject = amount - amountRejected; - // Delay creating this as long as possible - IAEItemStack aspectAEItem = null; + // Are any CPU's waiting for this? + for (ICraftingCPU cpu : cpus) { + // Is the cpu crafting, and is it a cluster? + if (cpu.isBusy() && (cpu instanceof CraftingCPUCluster)) { + if (aspectAEItem == null) { + // Create AE version + aspectAEItem = AEApi.instance().storage().createItemStack(this.craftingAspectItem); + aspectAEItem.setStackSize(1); + } - // Set the amounts - long amountToInject = amount - amountRejected; + // Cast + CraftingCPUCluster cluster = (CraftingCPUCluster) cpu; - // Are any CPU's waiting for this? - for( ICraftingCPU cpu : cpus ) - { - // Is the cpu crafting, and is it a cluster? - if( cpu.isBusy() && ( cpu instanceof CraftingCPUCluster ) ) - { - if( aspectAEItem == null ) - { - // Create AE version - aspectAEItem = AEApi.instance().storage().createItemStack( this.craftingAspectItem ); - aspectAEItem.setStackSize( 1 ); - } + // Is the cluster waiting for an aspect item? + if (cluster.isMaking(aspectAEItem)) { + // Not a fan of the loop, but inject items doesn't return anything useful + for (; (amountToInject > 0) && (cluster.isBusy()); --amountToInject) { + // Inject the aspect item + cluster.injectItems(aspectAEItem, mode, source); + } - // Cast - CraftingCPUCluster cluster = (CraftingCPUCluster)cpu; + // Has everything been accounted for? + if (amountToInject == 0) { + // All done + break; + } + } + } + } + } + } - // Is the cluster waiting for an aspect item? - if( cluster.isMaking( aspectAEItem ) ) - { - // Not a fan of the loop, but inject items doesn't return anything useful - for( ; ( amountToInject > 0 ) && ( cluster.isBusy() ); --amountToInject ) - { - // Inject the aspect item - cluster.injectItems( aspectAEItem, mode, source ); - } + return amountRejected; + } - // Has everything been accounted for? - if( amountToInject == 0 ) - { - // All done - break; - } - } - } - } - } - } + @MENetworkEventSubscribe + public void onGridCacheReady(final MENetworkPostCacheConstruction event) { + // Get the storage grid + IStorageGrid storage = (IStorageGrid) this.internalGrid.getCache(IStorageGrid.class); - return amountRejected; - } + // Wrap + this.wrap( + storage.getFluidInventory(), + (IEnergyGrid) this.internalGrid.getCache(IEnergyGrid.class), + this.internalGrid); - @MENetworkEventSubscribe - public void onGridCacheReady( final MENetworkPostCacheConstruction event ) - { - // Get the storage grid - IStorageGrid storage = (IStorageGrid)this.internalGrid.getCache( IStorageGrid.class ); + // Set the crafting watcher + storage.getItemInventory().addListener(this.craftingWatcher, this.internalGrid); + } - // Wrap - this.wrap( storage.getFluidInventory(), (IEnergyGrid)this.internalGrid.getCache( IEnergyGrid.class ), this.internalGrid ); + @Override + public void onJoin(final IGridStorage sourceStorage) { + // Mark that the cache needs to be updated + this.cacheNeedsUpdate = true; + } - // Set the crafting watcher - storage.getItemInventory().addListener( this.craftingWatcher, this.internalGrid ); - } + @Override + public void onSplit(final IGridStorage destinationStorage) {} - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - // Mark that the cache needs to be updated - this.cacheNeedsUpdate = true; - } + @Override + public void onUpdateTick() { + try { + /* + * If the cache is invalid and there are listeners this will update the cache to match the network. + * If there are no listeners the update is deferred until there are listeners, or the cache is accessed. + */ + if (this.cacheNeedsUpdate && (this.listeners.size() > 0)) { + // Update the cache + this.updateCacheToMatchNetwork(); + } + } catch (Exception e) { + // Ignored + } + } - @Override - public void onSplit( final IGridStorage destinationStorage ) - { - } + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { + // Ignored + } - @Override - public void onUpdateTick() - { - try - { - /* - * If the cache is invalid and there are listeners this will update the cache to match the network. - * If there are no listeners the update is deferred until there are listeners, or the cache is accessed. - */ - if( this.cacheNeedsUpdate && ( this.listeners.size() > 0 ) ) - { - // Update the cache - this.updateCacheToMatchNetwork(); - } - } - catch( Exception e ) - { - // Ignored - } - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - // Ignored - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - // Was the node an essentia watcher? - if( machine instanceof IEssentiaWatcherHost ) - { - this.essentiaWatcherManger.removeWatcher( gridNode ); - } - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + // Was the node an essentia watcher? + if (machine instanceof IEssentiaWatcherHost) { + this.essentiaWatcherManger.removeWatcher(gridNode); + } + } } diff --git a/src/main/java/thaumicenergistics/common/grid/WirelessAELink.java b/src/main/java/thaumicenergistics/common/grid/WirelessAELink.java index 2ee765d8..2340ac7d 100644 --- a/src/main/java/thaumicenergistics/common/grid/WirelessAELink.java +++ b/src/main/java/thaumicenergistics/common/grid/WirelessAELink.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.grid; -import java.util.ArrayList; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.implementations.tiles.IWirelessAccessPoint; import appeng.api.networking.IGrid; @@ -21,6 +18,9 @@ import appeng.api.util.DimensionalCoord; import appeng.me.GridException; import appeng.tile.misc.TileSecurity; import appeng.tile.networking.TileWireless; +import java.util.ArrayList; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; @@ -33,457 +33,416 @@ import thaumicenergistics.api.grid.IMEEssentiaMonitor; * @author Nividica * */ -public abstract class WirelessAELink - implements IStorageMonitorable -{ - /** - * The player who owns this link. - */ - protected final EntityPlayer player; +public abstract class WirelessAELink implements IStorageMonitorable { + /** + * The player who owns this link. + */ + protected final EntityPlayer player; - /** - * Encryption key used to access the network. - */ - protected final String encryptionKey; + /** + * Encryption key used to access the network. + */ + protected final String encryptionKey; - /** - * Access point used to communicate with the AE network. - */ - protected IWirelessAccessPoint accessPoint; + /** + * Access point used to communicate with the AE network. + */ + protected IWirelessAccessPoint accessPoint; - /** - * Where in the world is the access point. - */ - protected DimensionalCoord apLocation = null; + /** + * Where in the world is the access point. + */ + protected DimensionalCoord apLocation = null; - /** - * Network source representing the player - */ - protected BaseActionSource actionSource; + /** + * Network source representing the player + */ + protected BaseActionSource actionSource; - public WirelessAELink( final @Nullable EntityPlayer player, @Nonnull final String encryptionKey ) - { - // Set the player - this.player = player; + public WirelessAELink(final @Nullable EntityPlayer player, @Nonnull final String encryptionKey) { + // Set the player + this.player = player; - // Set the enc key - this.encryptionKey = encryptionKey; + // Set the enc key + this.encryptionKey = encryptionKey; - // Link with the AP - this.linkWithNewAP(); - } + // Link with the AP + this.linkWithNewAP(); + } - /** - * Checks if the AP at the specified location and has the specified range, - * is close enough to communicate with. - * - * @param APLocation - * @param APRange - * @param world - * @param x - * @param y - * @param z - * @return - */ - private static boolean isAPInRange( final DimensionalCoord APLocation, final double APRange, final World world, final int x, final int y, - final int z ) - { - // Is the AP in the same world? - if( !APLocation.isInWorld( world ) ) - { - return false; - } + /** + * Checks if the AP at the specified location and has the specified range, + * is close enough to communicate with. + * + * @param APLocation + * @param APRange + * @param world + * @param x + * @param y + * @param z + * @return + */ + private static boolean isAPInRange( + final DimensionalCoord APLocation, + final double APRange, + final World world, + final int x, + final int y, + final int z) { + // Is the AP in the same world? + if (!APLocation.isInWorld(world)) { + return false; + } - // Calculate the square distance - double squareDistance = WirelessAELink.getSquaredDistanceFromAP( APLocation, x, y, z ); + // Calculate the square distance + double squareDistance = WirelessAELink.getSquaredDistanceFromAP(APLocation, x, y, z); - // Return if close enough to use AP - return squareDistance <= ( APRange * APRange ); - } + // Return if close enough to use AP + return squareDistance <= (APRange * APRange); + } - /** - * @param world - * @param x - * @param y - * @param z - * @param grid - * @return - */ - private static ArrayList locateAPsInRange( final World world, final int x, final int y, final int z, final IGrid grid ) - { - // Get all AP's on the grid - IMachineSet accessPoints = grid.getMachines( TileWireless.class ); - if( accessPoints.isEmpty() ) - { - return null; - } + /** + * @param world + * @param x + * @param y + * @param z + * @param grid + * @return + */ + private static ArrayList locateAPsInRange( + final World world, final int x, final int y, final int z, final IGrid grid) { + // Get all AP's on the grid + IMachineSet accessPoints = grid.getMachines(TileWireless.class); + if (accessPoints.isEmpty()) { + return null; + } - // Create the list - ArrayList aps = new ArrayList(); + // Create the list + ArrayList aps = new ArrayList(); - // Loop over AP's and see if any are close enough to communicate with - for( IGridNode APNode : accessPoints ) - { - // Get the AP - IWirelessAccessPoint AP = (IWirelessAccessPoint)APNode.getMachine(); + // Loop over AP's and see if any are close enough to communicate with + for (IGridNode APNode : accessPoints) { + // Get the AP + IWirelessAccessPoint AP = (IWirelessAccessPoint) APNode.getMachine(); - // Is the AP active? - if( AP.isActive() ) - { - // Close enough to the AP? - if( WirelessAELink.isAPInRange( AP.getLocation(), AP.getRange(), world, x, y, z ) ) - { - aps.add( AP ); - } - } - } + // Is the AP active? + if (AP.isActive()) { + // Close enough to the AP? + if (WirelessAELink.isAPInRange(AP.getLocation(), AP.getRange(), world, x, y, z)) { + aps.add(AP); + } + } + } - return aps; - } + return aps; + } - /** - * Returns the squared distance the specified coords are from the Access Point. - * - * @param locationAP - * @param x - * @param y - * @param z - * @return - */ - protected static double getSquaredDistanceFromAP( final DimensionalCoord locationAP, final int x, final int y, final int z ) - { - if( locationAP == null ) - { - return Double.MAX_VALUE; - } + /** + * Returns the squared distance the specified coords are from the Access Point. + * + * @param locationAP + * @param x + * @param y + * @param z + * @return + */ + protected static double getSquaredDistanceFromAP( + final DimensionalCoord locationAP, final int x, final int y, final int z) { + if (locationAP == null) { + return Double.MAX_VALUE; + } - // Calculate the distance from the AP - int dX = locationAP.x - x, dY = locationAP.y - y, dZ = locationAP.z - z; + // Calculate the distance from the AP + int dX = locationAP.x - x, dY = locationAP.y - y, dZ = locationAP.z - z; - // Calculate the square distance - return( ( dX * dX ) + ( dY * dY ) + ( dZ * dZ ) ); - } + // Calculate the square distance + return ((dX * dX) + (dY * dY) + (dZ * dZ)); + } - /** - * Returns an unsorted list of AP's in range. - * - * @param world - * @param x - * @param y - * @param z - * @param encryptionKey - * @return Null on error, list of AP's in range otherwise. - */ - public static ArrayList locateAPsInRange( final World world, final int x, final int y, final int z, - final String encryptionKey ) - { - // Get the encryption key - long encryptionValue; - try - { - encryptionValue = Long.parseLong( encryptionKey ); - } - catch( NumberFormatException e ) - { - // Invalid security key - return null; - } + /** + * Returns an unsorted list of AP's in range. + * + * @param world + * @param x + * @param y + * @param z + * @param encryptionKey + * @return Null on error, list of AP's in range otherwise. + */ + public static ArrayList locateAPsInRange( + final World world, final int x, final int y, final int z, final String encryptionKey) { + // Get the encryption key + long encryptionValue; + try { + encryptionValue = Long.parseLong(encryptionKey); + } catch (NumberFormatException e) { + // Invalid security key + return null; + } - // Get the linked source - Object source = AEApi.instance().registries().locatable().getLocatableBy( encryptionValue ); + // Get the linked source + Object source = AEApi.instance().registries().locatable().getLocatableBy(encryptionValue); - // Ensure it is a security terminal - if( !( source instanceof TileSecurity ) ) - { - // Invalid security terminal - return null; - } + // Ensure it is a security terminal + if (!(source instanceof TileSecurity)) { + // Invalid security terminal + return null; + } - // Get the terminal - TileSecurity securityHost = (TileSecurity)source; + // Get the terminal + TileSecurity securityHost = (TileSecurity) source; - // Get the grid - IGrid grid; - try - { - grid = securityHost.getGridNode( ForgeDirection.UNKNOWN ).getGrid(); - } - catch( Exception e ) - { - // Can not find the grid - return null; - } + // Get the grid + IGrid grid; + try { + grid = securityHost.getGridNode(ForgeDirection.UNKNOWN).getGrid(); + } catch (Exception e) { + // Can not find the grid + return null; + } - return WirelessAELink.locateAPsInRange( world, x, y, z, grid ); - } + return WirelessAELink.locateAPsInRange(world, x, y, z, grid); + } - /** - * Returns an unsorted list of AP's in range. - * - * @param player - * @param encryptionKey - * @return Null on error, list of AP's in range otherwise. - */ - public static ArrayList locateAPsInRangeOfPlayer( final EntityPlayer player, final String encryptionKey ) - { - return WirelessAELink.locateAPsInRange( player.worldObj, - (int)Math.floor( player.posX ), - (int)Math.floor( player.posY ), - (int)Math.floor( player.posZ ), encryptionKey ); - } + /** + * Returns an unsorted list of AP's in range. + * + * @param player + * @param encryptionKey + * @return Null on error, list of AP's in range otherwise. + */ + public static ArrayList locateAPsInRangeOfPlayer( + final EntityPlayer player, final String encryptionKey) { + return WirelessAELink.locateAPsInRange( + player.worldObj, + (int) Math.floor(player.posX), + (int) Math.floor(player.posY), + (int) Math.floor(player.posZ), + encryptionKey); + } - /** - * Checks if the AP is still active and in range. - * - * @return - */ - private boolean isAPInRangeAndActive() - { - // Has AP? - if( this.accessPoint != null ) - { - // Is active? - if( this.accessPoint.isActive() ) - { - // In range? - return WirelessAELink.isAPInRange( this.apLocation, this.accessPoint.getRange(), this.getUserWorld(), - this.getUserPositionX(), this.getUserPositionY(), this.getUserPositionZ() ); - } - } - return false; - } + /** + * Checks if the AP is still active and in range. + * + * @return + */ + private boolean isAPInRangeAndActive() { + // Has AP? + if (this.accessPoint != null) { + // Is active? + if (this.accessPoint.isActive()) { + // In range? + return WirelessAELink.isAPInRange( + this.apLocation, + this.accessPoint.getRange(), + this.getUserWorld(), + this.getUserPositionX(), + this.getUserPositionY(), + this.getUserPositionZ()); + } + } + return false; + } - /** - * Locates the closest AP in range and links with it. - * - * @return True if AP linked with. - */ - private boolean linkWithNewAP() - { - World w = this.getUserWorld(); - int x = this.getUserPositionX(); - int y = this.getUserPositionY(); - int z = this.getUserPositionZ(); + /** + * Locates the closest AP in range and links with it. + * + * @return True if AP linked with. + */ + private boolean linkWithNewAP() { + World w = this.getUserWorld(); + int x = this.getUserPositionX(); + int y = this.getUserPositionY(); + int z = this.getUserPositionZ(); - ArrayList apList = null; + ArrayList apList = null; - try { - IGrid grid = accessPoint != null ? accessPoint.getGrid() : null; - // Get a list of AP's in range - if (grid != null) { - apList = WirelessAELink.locateAPsInRange(w, x, y, z, grid); - } else { - apList = WirelessAELink.locateAPsInRange(w, x, y, z, this.encryptionKey); - } - } catch (GridException ignored) { - // :( - } + try { + IGrid grid = accessPoint != null ? accessPoint.getGrid() : null; + // Get a list of AP's in range + if (grid != null) { + apList = WirelessAELink.locateAPsInRange(w, x, y, z, grid); + } else { + apList = WirelessAELink.locateAPsInRange(w, x, y, z, this.encryptionKey); + } + } catch (GridException ignored) { + // :( + } - // Determine the closest AP - IWirelessAccessPoint closestAP = null; - if( apList != null ) - { - double closestDistance = Double.MAX_VALUE; - for( IWirelessAccessPoint ap : apList ) - { - double dist = WirelessAELink.getSquaredDistanceFromAP( ap.getLocation(), x, y, z ); - if( dist < closestDistance ) - { - closestDistance = dist; - closestAP = ap; - } - } - } + // Determine the closest AP + IWirelessAccessPoint closestAP = null; + if (apList != null) { + double closestDistance = Double.MAX_VALUE; + for (IWirelessAccessPoint ap : apList) { + double dist = WirelessAELink.getSquaredDistanceFromAP(ap.getLocation(), x, y, z); + if (dist < closestDistance) { + closestDistance = dist; + closestAP = ap; + } + } + } - if( closestAP != null ) - { - // Set the closest as the AP to use - this.setAP( closestAP ); - } - else - { - // No valid AP's found - this.accessPoint = null; - } + if (closestAP != null) { + // Set the closest as the AP to use + this.setAP(closestAP); + } else { + // No valid AP's found + this.accessPoint = null; + } - return( this.accessPoint != null ); - } + return (this.accessPoint != null); + } - /** - * Set's the access point used for communication. - * - * @param accessPoint - */ - private void setAP( final IWirelessAccessPoint accessPoint ) - { - // Set the access point - this.accessPoint = accessPoint; + /** + * Set's the access point used for communication. + * + * @param accessPoint + */ + private void setAP(final IWirelessAccessPoint accessPoint) { + // Set the access point + this.accessPoint = accessPoint; - // Get the location of the access point - this.apLocation = this.accessPoint.getLocation(); + // Get the location of the access point + this.apLocation = this.accessPoint.getLocation(); - // Create the action source - if( this.player != null ) - { - this.actionSource = new PlayerSource( this.player, this.accessPoint ); - } - else - { - this.actionSource = new MachineSource( this.accessPoint ); - } - } + // Create the action source + if (this.player != null) { + this.actionSource = new PlayerSource(this.player, this.accessPoint); + } else { + this.actionSource = new MachineSource(this.accessPoint); + } + } - /** - * Return the x position of the user. - * - * @return - */ - protected abstract int getUserPositionX(); + /** + * Return the x position of the user. + * + * @return + */ + protected abstract int getUserPositionX(); - /** - * Return the y position of the user. - * - * @return - */ - protected abstract int getUserPositionY(); + /** + * Return the y position of the user. + * + * @return + */ + protected abstract int getUserPositionY(); - /** - * Return the z position of the user. - * - * @return - */ - protected abstract int getUserPositionZ(); + /** + * Return the z position of the user. + * + * @return + */ + protected abstract int getUserPositionZ(); - /** - * Return the world the user is in. - * - * @return - */ - protected abstract World getUserWorld(); + /** + * Return the world the user is in. + * + * @return + */ + protected abstract World getUserWorld(); - /** - * Is there enough local power to communicate with the AP? - * - * @return - */ - protected abstract boolean hasPowerToCommunicate(); + /** + * Is there enough local power to communicate with the AP? + * + * @return + */ + protected abstract boolean hasPowerToCommunicate(); - public IEnergyGrid getEnergyGrid() - { - // Check AP - if( this.accessPoint == null ) - { - return null; - } + public IEnergyGrid getEnergyGrid() { + // Check AP + if (this.accessPoint == null) { + return null; + } - try - { - // Get the energy grid - return this.accessPoint.getActionableNode().getGrid().getCache( IEnergyGrid.class ); - } - catch( Exception e ) - { - // Ignored - } + try { + // Get the energy grid + return this.accessPoint.getActionableNode().getGrid().getCache(IEnergyGrid.class); + } catch (Exception e) { + // Ignored + } - return null; - } + return null; + } - /** - * Gets the essentia inventory. - * - * @return - */ - public IMEEssentiaMonitor getEssentiaInventory() - { - // Check connectivity - if( ( this.accessPoint == null ) || !this.isConnected() ) - { - return null; - } + /** + * Gets the essentia inventory. + * + * @return + */ + public IMEEssentiaMonitor getEssentiaInventory() { + // Check connectivity + if ((this.accessPoint == null) || !this.isConnected()) { + return null; + } - try - { - // Get the network essentia monitor - return( (IMEEssentiaMonitor)this.accessPoint.getGrid().getCache( IEssentiaGrid.class ) ); - } - catch( Exception e ) - { - return null; - } - } + try { + // Get the network essentia monitor + return ((IMEEssentiaMonitor) this.accessPoint.getGrid().getCache(IEssentiaGrid.class)); + } catch (Exception e) { + return null; + } + } - @Override - public IMEMonitor getFluidInventory() - { - // Check connectivity - if( ( this.accessPoint == null ) || !this.isConnected() ) - { - return null; - } + @Override + public IMEMonitor getFluidInventory() { + // Check connectivity + if ((this.accessPoint == null) || !this.isConnected()) { + return null; + } - try - { - // Get the storage grid - IStorageGrid storageGrid = this.accessPoint.getActionableNode().getGrid().getCache( IStorageGrid.class ); + try { + // Get the storage grid + IStorageGrid storageGrid = + this.accessPoint.getActionableNode().getGrid().getCache(IStorageGrid.class); - // Return the monitor - return storageGrid.getFluidInventory(); - } - catch( Exception e ) - { - // Ignored - } + // Return the monitor + return storageGrid.getFluidInventory(); + } catch (Exception e) { + // Ignored + } - return null; - } + return null; + } - @Override - public IMEMonitor getItemInventory() - { - // Check connectivity - if( ( this.accessPoint == null ) || !this.isConnected() ) - { - return null; - } + @Override + public IMEMonitor getItemInventory() { + // Check connectivity + if ((this.accessPoint == null) || !this.isConnected()) { + return null; + } - try - { - // Get the storage grid - IStorageGrid storageGrid = this.accessPoint.getActionableNode().getGrid().getCache( IStorageGrid.class ); + try { + // Get the storage grid + IStorageGrid storageGrid = + this.accessPoint.getActionableNode().getGrid().getCache(IStorageGrid.class); - // Return the monitor - return storageGrid.getItemInventory(); - } - catch( Exception e ) - { - // Ignored - } + // Return the monitor + return storageGrid.getItemInventory(); + } catch (Exception e) { + // Ignored + } - return null; - } + return null; + } - /** - * Checks if the AP is still connected. - * - * @return - */ - public boolean isConnected() - { - // Is there power? - if( !this.hasPowerToCommunicate() ) - { - return false; - } + /** + * Checks if the AP is still connected. + * + * @return + */ + public boolean isConnected() { + // Is there power? + if (!this.hasPowerToCommunicate()) { + return false; + } - // Is the current AP still good? - if( this.isAPInRangeAndActive() ) - { - // Current AP is still connected. - return true; - } + // Is the current AP still good? + if (this.isAPInRangeAndActive()) { + // Current AP is still connected. + return true; + } - // Attempt to link with a new AP - return this.linkWithNewAP(); - } + // Attempt to link with a new AP + return this.linkWithNewAP(); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/AEHooks.java b/src/main/java/thaumicenergistics/common/integration/AEHooks.java index e6e93fcb..f2a7d623 100644 --- a/src/main/java/thaumicenergistics/common/integration/AEHooks.java +++ b/src/main/java/thaumicenergistics/common/integration/AEHooks.java @@ -3,23 +3,19 @@ package thaumicenergistics.common.integration; import appeng.api.storage.data.IAEItemStack; import thaumicenergistics.common.items.ItemCraftingAspect; -public class AEHooks -{ - /** - * Hook for AE2s GuiMeMonitorable.postUpdate().
- * Returning true will prevent the item from being displayed in GUI's. - * TODO: Expand this into registration list within the API. - * - * @param is - * @return - */ - public static boolean isItemGUIBlacklisted( final IAEItemStack is ) - { - if( is.getItem() instanceof ItemCraftingAspect ) - { - return true; - } - return false; - } - +public class AEHooks { + /** + * Hook for AE2s GuiMeMonitorable.postUpdate().
+ * Returning true will prevent the item from being displayed in GUI's. + * TODO: Expand this into registration list within the API. + * + * @param is + * @return + */ + public static boolean isItemGUIBlacklisted(final IAEItemStack is) { + if (is.getItem() instanceof ItemCraftingAspect) { + return true; + } + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/EssentiaProviderPeripheral.java b/src/main/java/thaumicenergistics/common/integration/EssentiaProviderPeripheral.java index 25bacdb4..15398bbd 100644 --- a/src/main/java/thaumicenergistics/common/integration/EssentiaProviderPeripheral.java +++ b/src/main/java/thaumicenergistics/common/integration/EssentiaProviderPeripheral.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.integration; -import java.lang.ref.WeakReference; -import java.util.*; -import org.apache.commons.lang3.StringUtils; import appeng.api.networking.IGrid; import appeng.me.GridAccessException; import dan200.computercraft.api.lua.ILuaContext; @@ -10,8 +7,11 @@ import dan200.computercraft.api.lua.ILuaObject; import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.peripheral.IComputerAccess; import dan200.computercraft.api.peripheral.IPeripheral; +import java.lang.ref.WeakReference; +import java.util.*; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +import org.apache.commons.lang3.StringUtils; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IEssentiaGrid; import thaumicenergistics.api.grid.IMEEssentiaMonitor; @@ -25,963 +25,851 @@ import thaumicenergistics.common.tiles.TileEssentiaProvider; * @author Nividica * */ -public class EssentiaProviderPeripheral - implements IPeripheral, IEssentiaProviderWatcher -{ - private static enum CCEvents - { - /** - * A watched for aspect has changed amounts. - */ - AspectUpdate (1), - - /** - * The provider has powered on or off. - */ - PowerChange (2), - - /** - * The computer has detached from the peripheral, or the peripheral has detached from the provider. - */ - Detached (3); - - /** - * ID of the event passed into CC - */ - public final int eventID; - - private CCEvents( final int ID ) - { - this.eventID = ID; - } - } - - private static class CCHelpObject - implements ILuaObject - { - /** - * Singleton - */ - private static CCHelpObject INSTANCE; - - /** - * Private constructor - */ - private CCHelpObject() - { - - } - - /** - * Returns the help object. - */ - public static CCHelpObject Instance() - { - if( CCHelpObject.INSTANCE == null ) - { - CCHelpObject.INSTANCE = new CCHelpObject(); - } - - return CCHelpObject.INSTANCE; - } - - @Override - public Object[] callMethod( final ILuaContext context, final int method, final Object[] arguments ) throws LuaException, InterruptedException - { - String helpText = null; - - if( method == 6 ) - { - helpText = "\nEvent name: essentia" + "\nEvent Structure: [Index] [Arg1] [Arg2]\n" + - "\nEssentia Event:[1] [aspectName] [changeAmount]\n" + "Power Event: [2] [true(on)|false(off)]\n" + - "Detach Event: [3]\n" + "\nExample:\n" + "event = { os.pullEvent(\"essentia\") }\n"; - } - else - { - // Determine which method was called. - switch ( CCMethods.VALUES[method] ) - { - case isOnline: - helpText = "\nNo arguments.\n" + "Returns true if the provider is powered on and connected, false otherwise.\n" + "\nExample:\n" + - "if( ep.isOnline() ) then\n"; - break; - - case getAspects: - helpText = "\nNo arguments.\n" + "Returns the name then the amount of each essentia type stored.\n" + - "Note: You will probably want to wrap the results into a table.\n" + "\nExample:\n" + - "essTable = {ep.getAspects()}\n" + "name = essTable[1]\n" + "amount = essTable[2]\n"; - break; - - case getAmount: - helpText = "\nArguments: AspectName1, AspectName2, ...\n" + - "Returns the amount(s) of essentia stored in the system for the specified aspect(s).\n" + "\nExample:\n" + - "ordoAmt = ep.getAmount(\"ordo\")\n" + "ordoAmt, metoAmt = ep.getAmount(\"ordo\",\"meto\")\n"; - break; - - case registerAsWatcher: - helpText = "\nOptional Arguments: AspectName1, AspectName2, ...\n" + - "Registers this computer for essentia events. When essentia amounts on the network changes, this computer will receive a notification event.\n" + - "If aspect arguments are provided, only events for those aspects will be generated. If no arguments are provided, any change will generate an event.\n" + - "Note: Run help.events() for details about the events.\n" + "\nExamples:\n" + "ep.registerAsWatcher()\n" + - "ep.registerAsWatcher(\"ordo\")\n" + "ep.registerAsWatcher(\"ordo\",\"meto\")\n"; - break; - - case unregisterAsWatcher: - helpText = "\nOptional Arguments: AspectName1, AspectName2, ...\n" + "Unregisters this computer for essentia events.\n" + - "If aspect arguments are provided, only unregister for those aspects. If no arguments are provided, unregister for all.\n" + - "\nExamples:\n" + "ep.unregisterAsWatcher()\n" + "ep.unregisterAsWatcher(\"ordo\")\n" + - "ep.unregisterAsWatcher(\"meto\",\"ordo\")\n"; - break; - - case help: - helpText = "\nDisplays help for the following:\n" + StringUtils.join( "()\n", this.getMethodNames() ) + "()\n"; - break; - } - } - - return new Object[] { helpText }; - } - - @Override - public String[] getMethodNames() - { - int staticLen = CCMethods.NAMES.length; - - String[] names = new String[staticLen + 1]; - - System.arraycopy( CCMethods.NAMES, 0, names, 0, staticLen ); - - names[staticLen] = "events"; - - return names; - } - - } - - private static enum CCMethods - { - /** - * Is the provider active and online? - */ - isOnline, - - /** - * Gets the list of aspects stored in the network. - * Stored in pairs of (name,amount) - */ - getAspects, - - /** - * Gets how much of the specified essentias are in the network. - * Args: Param array of aspect names - */ - getAmount, - - /** - * Register for network changes - * Args: aspect names, can be null for all aspects - */ - registerAsWatcher, - - /** - * Unregister for network changes - * Args: aspect names, can be null for all aspects - */ - unregisterAsWatcher, - - /** - * Gets help object. - */ - help; - - /** - * List of methods. - */ - public final static EssentiaProviderPeripheral.CCMethods[] VALUES; - - /** - * List of LUA method names. - */ - public final static String[] NAMES; - - /** - * Static initializer block to ensure VALUES and NAMES maintains order - */ - static - { - // Cache the values - VALUES = CCMethods.values(); - - // Create the array - NAMES = new String[CCMethods.VALUES.length]; - - // Populate the array - for( int i = 0; i < CCMethods.NAMES.length; ++i ) - { - CCMethods.NAMES[i] = CCMethods.VALUES[i].name(); - } - } - } - - private class EssentiaWatcher - implements IMEEssentiaMonitorReceiver - { - - /** - * Computers that are listening for specific updates. - * The Boolean value specifies if the computer is watching for all changes(false) or specific aspects(true) - */ - private final HashMap computerWatchers; - - /** - * A mapping of Aspect->Computer(s). - */ - private final HashMap> aspectWatchers; - - /** - * Computers watching for any change. - */ - private final HashSet anyWatchers; - - /** - * Used to ensure concurrency. - */ - private final Object threadLock = new Object(); - - /** - * True if this is attached to the network monitor. - */ - private boolean isReceving = false; - - public EssentiaWatcher() - { - // Setup the lists - this.computerWatchers = new HashMap(); - this.aspectWatchers = new HashMap>(); - this.anyWatchers = new HashSet(); - } - - /** - * Adds a computer to the watch list, or updates an existing computer's aspects. - * - * @param computer - * Computer to add. - * @param aspectsOfInterest - * Aspects to watch for. Can be null. - * @throws LuaException - * @throws InterruptedException - */ - public void addComputerWatch( final IComputerAccess computer, final Set aspectsOfInterest ) throws LuaException, InterruptedException - { - synchronized( this.threadLock ) - { - // If the computer is already watching? - if( this.computerWatchers.containsKey( computer ) ) - { - // Was it watching for specific aspects? - if( this.computerWatchers.get( computer ) ) - { - // Remove the watches - this.removeComputerWatcher( computer ); - } - } - - // Is the computer watching specific aspects? - boolean specificWatches = false; - if( ( ( aspectsOfInterest != null ) && ( aspectsOfInterest.size() > 0 ) ) ) - { - // Computer has specific watches - specificWatches = true; - - for( Aspect watchAspect : aspectsOfInterest ) - { - // Are there other watchers for this aspect? - if( !this.aspectWatchers.containsKey( watchAspect ) ) - { - // New aspect - this.aspectWatchers.put( watchAspect, new HashSet() ); - } - - // Add to the watch map - this.aspectWatchers.get( watchAspect ).add( computer ); - } - } - else - { - // Computer is watching all aspects - this.anyWatchers.add( computer ); - } - - // Add the computer - this.computerWatchers.put( computer, specificWatches ); - - // Attached to monitor? - if( !this.isReceving ) - { - // Get the monitor - IMEEssentiaMonitor monitor = EssentiaProviderPeripheral.this.getProviderMonitor(); - if( monitor != null ) - { - // Register - try - { - monitor.addListener( this, EssentiaProviderPeripheral.this.getProvider().getProxy().getGrid() ); - - // Mark as receiving - this.isReceving = true; - } - catch( GridAccessException e ) - { - } - } - } - } - } - - @Override - public boolean isValid( final Object verificationToken ) - { - // Assume false - this.isReceving = false; - try - { - IGrid grid = EssentiaProviderPeripheral.this.getProvider().getProxy().getGrid(); - if( verificationToken == grid ) - { - synchronized( this.threadLock ) - { - // Only valid if there are computer watchers - this.isReceving = ( this.computerWatchers.size() > 0 ); - } - } - } - catch( GridAccessException e ) - { - return false; - } - - return this.isReceving; - } - - public void onProviderBroken() - { - synchronized( this.threadLock ) - { - // Clear any watchers - this.anyWatchers.clear(); - this.aspectWatchers.clear(); - this.computerWatchers.clear(); - } - } - - @Override - public void postChange( final IMEEssentiaMonitor fromMonitor, final Iterable changes ) - { - // Ensure the provider is there and active - TileEssentiaProvider provider = EssentiaProviderPeripheral.this.getProvider(); - if( provider == null ) - { - // The provider is no longer valid, clear everything - this.onProviderBroken(); - return; - } - - if( !provider.isActive() ) - { - // Provider is inactive, can't pass events - return; - } - - synchronized( this.threadLock ) - { - Set specificWatchers; - Set invalidWatchers = null; - Object[] ccChange = null; - - // For each change - for( IAspectStack change : changes ) - { - // Are there computers watching for any change? - if( this.anyWatchers.size() > 0 ) - { - // Create the argument - ccChange = new Object[] { change.getAspectName(), change.getStackSize() }; - - for( IComputerAccess computer : this.anyWatchers ) - { - try - { - // Queue the event - EssentiaProviderPeripheral.this.sendEvent( computer, CCEvents.AspectUpdate, ccChange ); - } - catch( Exception e ) - { - // The watcher is no longer valid - if( invalidWatchers == null ) - { - invalidWatchers = new HashSet(); - } - invalidWatchers.add( computer ); - } - } - } - - // Are there computers watching for this specific change? - if( ( specificWatchers = this.aspectWatchers.get( change.getAspect() ) ) != null ) - { - // Create the argument - ccChange = new Object[] { change.getAspectName(), change.getStackSize() }; - - // Update those watchers - for( IComputerAccess computer : specificWatchers ) - { - try - { - // Queue the event - EssentiaProviderPeripheral.this.sendEvent( computer, CCEvents.AspectUpdate, ccChange ); - } - catch( Exception e ) - { - // The watcher is no longer valid - if( invalidWatchers == null ) - { - invalidWatchers = new HashSet(); - } - invalidWatchers.add( computer ); - } - } - } - - } - - // Remove any invalid watchers - if( invalidWatchers != null ) - { - for( IComputerAccess badComputer : invalidWatchers ) - { - this.removeComputerWatcher( badComputer ); - } - } - } - } - - /** - * Removes a computer from the watch list. - * - * @param computer - * @throws LuaException - * @throws InterruptedException - */ - public void removeComputerWatcher( final IComputerAccess computer ) - { - synchronized( this.threadLock ) - { - if( this.computerWatchers.containsKey( computer ) ) - { - // Was the computer watching for specific changes? - if( this.computerWatchers.get( computer ) ) - { - // Remove the mappings - for( Set watchSet : this.aspectWatchers.values() ) - { - watchSet.remove( computer ); - } - } - else - { - // Remove the mapping - this.anyWatchers.remove( computer ); - } - - // Remove the computer - this.computerWatchers.remove( computer ); - } - } - } - } - - /** - * Name of the peripheral. - */ - private static final String CC_PERIPHERAL_NAME = "EssentiaProvider"; - - /** - * Name of the event to pass into CC. - */ - private static final String CC_EVENT_NAME = "essentia"; - - /** - * Maps an aspects name to an Aspect. - */ - private final static Hashtable aspectNameReverseMap = new Hashtable(); - - /** - * What world is the provider in? - */ - private final WeakReference epWorld; - - /** - * Where in the world is the provider? - */ - private final int epX, epY, epZ; - - /** - * Watches the network for essentia changes. - */ - private final EssentiaWatcher watcher; - - /** - * Computers attached to this peripheral. - */ - private final HashSet attachedComputers = new HashSet(); - - /** - * True if the peripheral is listening to the provider. - */ - private boolean isRegisteredAsBlockListener = false; - - public EssentiaProviderPeripheral( final World world, final int x, final int y, final int z ) - { - // Mark the world - this.epWorld = new WeakReference( world ); - - // Mark the position - this.epX = x; - this.epY = y; - this.epZ = z; - - // Create the watcher - this.watcher = new EssentiaWatcher(); - - // Setup the block listener - this.getProvider(); - } - - /** - * Returns how much of an aspect is in the system from its tag. - * - * @param args - * @return - */ - @SuppressWarnings("null") - private Object[] ccGetAmount( final Object[] args ) throws LuaException, InterruptedException - { - // Get the provider - TileEssentiaProvider provider = this.getProvider(); - - // Get the list of aspects - List aspects = this.getAspectsFromArguments( args ); - - // Create the results - Object[] results = new Object[aspects.size()]; - - // Is the provider active? - boolean providerActive = ( provider != null ? provider.isActive() : false ); - - // For aspect, get the amount - for( int index = 0; index < results.length; ++index ) - { - if( providerActive ) - { - // Add the amount to the results - results[index] = provider.getAspectAmountInNetwork( aspects.get( index ) ); - } - else - { - // Provider is offline - results[index] = 0; - } - } - - return results; - } - - /** - * Gets the aspects stored in the network the provider is attached to. - * - * @return - */ - private Object[] ccGetAspects() throws LuaException, InterruptedException - { - - // Attempt to get the monitor - IMEEssentiaMonitor monitor; - if( ( monitor = this.getProviderMonitor() ) == null ) - { - return null; - } - - // Get the list of aspects in the network - Collection essentiaList = monitor.getEssentiaList(); - - // Is there any essentia stored? - if( essentiaList.size() == 0 ) - { - // No essentia stored - return null; - } - - // Create the array - Object[] ccList = new Object[essentiaList.size() * 2]; - - int index = 0; - for( IAspectStack stack : essentiaList ) - { - // Set the name - ccList[index] = stack.getAspectName(); - - // Set the amount - ccList[index + 1] = stack.getStackSize(); - - // Inc the index - index += 2; - } - - return ccList; - - } - - /** - * Returns if the provider is online, or null if the provider is - * invalid. - * - * @return - */ - private Object[] ccGetOnline() throws LuaException, InterruptedException - { - // Return the providers active state - return new Object[] { this.isProviderAvailable() }; - } - - /** - * Registers a computer with the network watcher. - * - * @param computer - * @param args - * @throws LuaException - * @throws InterruptedException - */ - private boolean ccRegisterAsWatcher( final IComputerAccess computer, final Object[] args ) throws LuaException, InterruptedException - { - // No provider - if( !this.isProviderAvailable() ) - { - return false; - } - - // Is the computer watching for specific aspects? - if( ( args != null ) && ( args.length > 0 ) ) - { - // Create the aspect set - HashSet aspects = new HashSet( this.getAspectsFromArguments( args ) ); - - // Register for those aspects - this.watcher.addComputerWatch( computer, aspects ); - } - else - { - // Register for all - this.watcher.addComputerWatch( computer, null ); - } - - return true; - } - - /** - * Gets an aspect based on its friendly name. - * - * @param name - * @return - */ - private Aspect getAspectFromName( final String name ) - { - // Get the name, in lowercase - String aspectName = name.toLowerCase(); - - // Does the map contain this entry? - if( EssentiaProviderPeripheral.aspectNameReverseMap.contains( aspectName ) ) - { - // Get the aspect - return EssentiaProviderPeripheral.aspectNameReverseMap.get( aspectName ); - } - - // Search all aspects - for( Aspect searchAspect : Aspect.aspects.values() ) - { - // Do the names match? - if( searchAspect.getName().equalsIgnoreCase( aspectName ) ) - { - // Update the map - EssentiaProviderPeripheral.aspectNameReverseMap.put( aspectName, searchAspect ); - - // Break the search - return searchAspect; - } - } - - return null; - } - - /** - * Gets a list of aspects based on the arguments passed in from the computer. - * - * @param args - * @return - * @throws LuaException - * @throws InterruptedException - */ - private List getAspectsFromArguments( final Object[] args ) throws LuaException, InterruptedException - { - // Ensure there are arguments - if( ( args == null ) || ( args.length == 0 ) ) - { - throw new LuaException( "Expected argument: AspectName" ); - } - - List results = new ArrayList(); - - // For each argument, attempt to get the aspect - for( Object arg : args ) - { - // Ensure the argument is a string - if( arg instanceof String ) - { - // The aspect to look up - Aspect aspect = this.getAspectFromName( (String)arg ); - - // Was an aspect found? - if( aspect != null ) - { - // Add to the results - results.add( aspect ); - } - else - { - throw new LuaException( String.format( "Invalid aspect name '%s'", arg ) ); - } - } - else - { - throw new LuaException( String.format( "Invalid argument '%s'", arg ) ); - } - } - - return results; - } - - /** - * Returns true if a provider is found, and it is powered up - * - * @return - */ - private boolean isProviderAvailable() - { - TileEssentiaProvider provider = this.getProvider(); - return( provider != null ? provider.isActive() : false ); - } - - /** - * Attempts to get the Essentia Provider - * - * @return - */ - TileEssentiaProvider getProvider() - { - // Attempt to get the world - World world; - if( ( this.epWorld == null ) || ( ( world = this.epWorld.get() ) == null ) ) - { - return null; - } - - // Get the tile entity at the recorded location - TileEntity te = world.getTileEntity( this.epX, this.epY, this.epZ ); - - // Is the entity a provider? - if( te instanceof TileEssentiaProvider ) - { - // Is the peripheral registered as a block watcher? - if( !this.isRegisteredAsBlockListener ) - { - // Register - ( (TileEssentiaProvider)te ).registerBlockWatcher( this ); - this.isRegisteredAsBlockListener = true; - } - - // Return the provider - return (TileEssentiaProvider)te; - } - - return null; - - } - - /** - * Gets the essentia monitor from the provider. - * - * @return - * @throws LuaException - * @throws InterruptedException - */ - IMEEssentiaMonitor getProviderMonitor() throws LuaException, InterruptedException - { - // Get the provider - TileEssentiaProvider provider = this.getProvider(); - - // Is the provider active? - if( !provider.isActive() ) - { - // Inactive - return null; - } - - // Attempt to get the essentia monitor - try - { - return (IMEEssentiaMonitor)provider.getActionableNode().getGrid().getCache( IEssentiaGrid.class ); - } - catch( NullPointerException npe ) - { - // Could not get the monitor - return null; - } - } - - /** - * Sends an event to the specified computer - * - * @param computer - * @param event - * @param additionalData - */ - void sendEvent( final IComputerAccess computer, final CCEvents event, final Object ... additionalData ) - { - // Create the arguments - Object[] args = new Object[( additionalData == null ? 1 : 1 + additionalData.length )]; - - // Set the ID - args[0] = event.eventID; - - // Copy the rest of the data - if( additionalData != null ) - { - System.arraycopy( additionalData, 0, args, 1, additionalData.length ); - } - - computer.queueEvent( EssentiaProviderPeripheral.CC_EVENT_NAME, args ); - } - - @Override - public void attach( final IComputerAccess computer ) - { - // Add to the attach list - this.attachedComputers.add( computer ); - } - - @Override - public Object[] callMethod( final IComputerAccess computer, final ILuaContext context, final int method, final Object[] arguments ) - throws LuaException, InterruptedException - { - Object[] results = null; - - // Determine which method was called. - switch ( CCMethods.VALUES[method] ) - { - case isOnline: - results = this.ccGetOnline(); - break; - - case getAspects: - results = this.ccGetAspects(); - break; - - case getAmount: - results = this.ccGetAmount( arguments ); - break; - - case registerAsWatcher: - results = new Object[] { this.ccRegisterAsWatcher( computer, arguments ) }; - break; - - case unregisterAsWatcher: - this.watcher.removeComputerWatcher( computer ); - results = new Object[] { true }; - break; - case help: - results = new Object[] { CCHelpObject.Instance() }; - break; - } - - return results; - } - - @Override - public void detach( final IComputerAccess computer ) - { - // Remove from the list - this.attachedComputers.remove( computer ); - - // Remove the computer from the watcher - this.watcher.removeComputerWatcher( computer ); - - // Send the detach event - this.sendEvent( computer, CCEvents.Detached ); - } - - @Override - public boolean equals( final IPeripheral other ) - { - return this == other; - } - - @Override - public boolean equals( final Object other ) - { - - return super.equals( other ); - } - - @Override - public String[] getMethodNames() - { - return CCMethods.NAMES; - } - - @Override - public String getType() - { - return EssentiaProviderPeripheral.CC_PERIPHERAL_NAME; - } - - @Override - public int hashCode() - { - return super.hashCode(); - } - - @Override - public void onProviderBroken() - { - // No longer registered - this.isRegisteredAsBlockListener = false; - - // Inform any attached computers that the link is going down - for( IComputerAccess computer : this.attachedComputers ) - { - this.sendEvent( computer, CCEvents.PowerChange, false ); - } - this.watcher.onProviderBroken(); - - } - - @Override - public void onProviderPowerChange( final boolean isOnline ) - { - // Inform computers that the power status changed - for( IComputerAccess computer : this.attachedComputers ) - { - this.sendEvent( computer, CCEvents.PowerChange, isOnline ); - } - } - -} \ No newline at end of file +public class EssentiaProviderPeripheral implements IPeripheral, IEssentiaProviderWatcher { + private static enum CCEvents { + /** + * A watched for aspect has changed amounts. + */ + AspectUpdate(1), + + /** + * The provider has powered on or off. + */ + PowerChange(2), + + /** + * The computer has detached from the peripheral, or the peripheral has detached from the provider. + */ + Detached(3); + + /** + * ID of the event passed into CC + */ + public final int eventID; + + private CCEvents(final int ID) { + this.eventID = ID; + } + } + + private static class CCHelpObject implements ILuaObject { + /** + * Singleton + */ + private static CCHelpObject INSTANCE; + + /** + * Private constructor + */ + private CCHelpObject() {} + + /** + * Returns the help object. + */ + public static CCHelpObject Instance() { + if (CCHelpObject.INSTANCE == null) { + CCHelpObject.INSTANCE = new CCHelpObject(); + } + + return CCHelpObject.INSTANCE; + } + + @Override + public Object[] callMethod(final ILuaContext context, final int method, final Object[] arguments) + throws LuaException, InterruptedException { + String helpText = null; + + if (method == 6) { + helpText = "\nEvent name: essentia" + "\nEvent Structure: [Index] [Arg1] [Arg2]\n" + + "\nEssentia Event:[1] [aspectName] [changeAmount]\n" + + "Power Event: [2] [true(on)|false(off)]\n" + "Detach Event: [3]\n" + + "\nExample:\n" + "event = { os.pullEvent(\"essentia\") }\n"; + } else { + // Determine which method was called. + switch (CCMethods.VALUES[method]) { + case isOnline: + helpText = "\nNo arguments.\n" + + "Returns true if the provider is powered on and connected, false otherwise.\n" + + "\nExample:\n" + "if( ep.isOnline() ) then\n"; + break; + + case getAspects: + helpText = + "\nNo arguments.\n" + "Returns the name then the amount of each essentia type stored.\n" + + "Note: You will probably want to wrap the results into a table.\n" + + "\nExample:\n" + "essTable = {ep.getAspects()}\n" + + "name = essTable[1]\n" + "amount = essTable[2]\n"; + break; + + case getAmount: + helpText = "\nArguments: AspectName1, AspectName2, ...\n" + + "Returns the amount(s) of essentia stored in the system for the specified aspect(s).\n" + + "\nExample:\n" + "ordoAmt = ep.getAmount(\"ordo\")\n" + + "ordoAmt, metoAmt = ep.getAmount(\"ordo\",\"meto\")\n"; + break; + + case registerAsWatcher: + helpText = "\nOptional Arguments: AspectName1, AspectName2, ...\n" + + "Registers this computer for essentia events. When essentia amounts on the network changes, this computer will receive a notification event.\n" + + "If aspect arguments are provided, only events for those aspects will be generated. If no arguments are provided, any change will generate an event.\n" + + "Note: Run help.events() for details about the events.\n" + + "\nExamples:\n" + "ep.registerAsWatcher()\n" + "ep.registerAsWatcher(\"ordo\")\n" + + "ep.registerAsWatcher(\"ordo\",\"meto\")\n"; + break; + + case unregisterAsWatcher: + helpText = "\nOptional Arguments: AspectName1, AspectName2, ...\n" + + "Unregisters this computer for essentia events.\n" + + "If aspect arguments are provided, only unregister for those aspects. If no arguments are provided, unregister for all.\n" + + "\nExamples:\n" + + "ep.unregisterAsWatcher()\n" + "ep.unregisterAsWatcher(\"ordo\")\n" + + "ep.unregisterAsWatcher(\"meto\",\"ordo\")\n"; + break; + + case help: + helpText = "\nDisplays help for the following:\n" + + StringUtils.join("()\n", this.getMethodNames()) + "()\n"; + break; + } + } + + return new Object[] {helpText}; + } + + @Override + public String[] getMethodNames() { + int staticLen = CCMethods.NAMES.length; + + String[] names = new String[staticLen + 1]; + + System.arraycopy(CCMethods.NAMES, 0, names, 0, staticLen); + + names[staticLen] = "events"; + + return names; + } + } + + private static enum CCMethods { + /** + * Is the provider active and online? + */ + isOnline, + + /** + * Gets the list of aspects stored in the network. + * Stored in pairs of (name,amount) + */ + getAspects, + + /** + * Gets how much of the specified essentias are in the network. + * Args: Param array of aspect names + */ + getAmount, + + /** + * Register for network changes + * Args: aspect names, can be null for all aspects + */ + registerAsWatcher, + + /** + * Unregister for network changes + * Args: aspect names, can be null for all aspects + */ + unregisterAsWatcher, + + /** + * Gets help object. + */ + help; + + /** + * List of methods. + */ + public static final EssentiaProviderPeripheral.CCMethods[] VALUES; + + /** + * List of LUA method names. + */ + public static final String[] NAMES; + + /** + * Static initializer block to ensure VALUES and NAMES maintains order + */ + static { + // Cache the values + VALUES = CCMethods.values(); + + // Create the array + NAMES = new String[CCMethods.VALUES.length]; + + // Populate the array + for (int i = 0; i < CCMethods.NAMES.length; ++i) { + CCMethods.NAMES[i] = CCMethods.VALUES[i].name(); + } + } + } + + private class EssentiaWatcher implements IMEEssentiaMonitorReceiver { + + /** + * Computers that are listening for specific updates. + * The Boolean value specifies if the computer is watching for all changes(false) or specific aspects(true) + */ + private final HashMap computerWatchers; + + /** + * A mapping of Aspect->Computer(s). + */ + private final HashMap> aspectWatchers; + + /** + * Computers watching for any change. + */ + private final HashSet anyWatchers; + + /** + * Used to ensure concurrency. + */ + private final Object threadLock = new Object(); + + /** + * True if this is attached to the network monitor. + */ + private boolean isReceving = false; + + public EssentiaWatcher() { + // Setup the lists + this.computerWatchers = new HashMap(); + this.aspectWatchers = new HashMap>(); + this.anyWatchers = new HashSet(); + } + + /** + * Adds a computer to the watch list, or updates an existing computer's aspects. + * + * @param computer + * Computer to add. + * @param aspectsOfInterest + * Aspects to watch for. Can be null. + * @throws LuaException + * @throws InterruptedException + */ + public void addComputerWatch(final IComputerAccess computer, final Set aspectsOfInterest) + throws LuaException, InterruptedException { + synchronized (this.threadLock) { + // If the computer is already watching? + if (this.computerWatchers.containsKey(computer)) { + // Was it watching for specific aspects? + if (this.computerWatchers.get(computer)) { + // Remove the watches + this.removeComputerWatcher(computer); + } + } + + // Is the computer watching specific aspects? + boolean specificWatches = false; + if (((aspectsOfInterest != null) && (aspectsOfInterest.size() > 0))) { + // Computer has specific watches + specificWatches = true; + + for (Aspect watchAspect : aspectsOfInterest) { + // Are there other watchers for this aspect? + if (!this.aspectWatchers.containsKey(watchAspect)) { + // New aspect + this.aspectWatchers.put(watchAspect, new HashSet()); + } + + // Add to the watch map + this.aspectWatchers.get(watchAspect).add(computer); + } + } else { + // Computer is watching all aspects + this.anyWatchers.add(computer); + } + + // Add the computer + this.computerWatchers.put(computer, specificWatches); + + // Attached to monitor? + if (!this.isReceving) { + // Get the monitor + IMEEssentiaMonitor monitor = EssentiaProviderPeripheral.this.getProviderMonitor(); + if (monitor != null) { + // Register + try { + monitor.addListener( + this, + EssentiaProviderPeripheral.this + .getProvider() + .getProxy() + .getGrid()); + + // Mark as receiving + this.isReceving = true; + } catch (GridAccessException e) { + } + } + } + } + } + + @Override + public boolean isValid(final Object verificationToken) { + // Assume false + this.isReceving = false; + try { + IGrid grid = + EssentiaProviderPeripheral.this.getProvider().getProxy().getGrid(); + if (verificationToken == grid) { + synchronized (this.threadLock) { + // Only valid if there are computer watchers + this.isReceving = (this.computerWatchers.size() > 0); + } + } + } catch (GridAccessException e) { + return false; + } + + return this.isReceving; + } + + public void onProviderBroken() { + synchronized (this.threadLock) { + // Clear any watchers + this.anyWatchers.clear(); + this.aspectWatchers.clear(); + this.computerWatchers.clear(); + } + } + + @Override + public void postChange(final IMEEssentiaMonitor fromMonitor, final Iterable changes) { + // Ensure the provider is there and active + TileEssentiaProvider provider = EssentiaProviderPeripheral.this.getProvider(); + if (provider == null) { + // The provider is no longer valid, clear everything + this.onProviderBroken(); + return; + } + + if (!provider.isActive()) { + // Provider is inactive, can't pass events + return; + } + + synchronized (this.threadLock) { + Set specificWatchers; + Set invalidWatchers = null; + Object[] ccChange = null; + + // For each change + for (IAspectStack change : changes) { + // Are there computers watching for any change? + if (this.anyWatchers.size() > 0) { + // Create the argument + ccChange = new Object[] {change.getAspectName(), change.getStackSize()}; + + for (IComputerAccess computer : this.anyWatchers) { + try { + // Queue the event + EssentiaProviderPeripheral.this.sendEvent(computer, CCEvents.AspectUpdate, ccChange); + } catch (Exception e) { + // The watcher is no longer valid + if (invalidWatchers == null) { + invalidWatchers = new HashSet(); + } + invalidWatchers.add(computer); + } + } + } + + // Are there computers watching for this specific change? + if ((specificWatchers = this.aspectWatchers.get(change.getAspect())) != null) { + // Create the argument + ccChange = new Object[] {change.getAspectName(), change.getStackSize()}; + + // Update those watchers + for (IComputerAccess computer : specificWatchers) { + try { + // Queue the event + EssentiaProviderPeripheral.this.sendEvent(computer, CCEvents.AspectUpdate, ccChange); + } catch (Exception e) { + // The watcher is no longer valid + if (invalidWatchers == null) { + invalidWatchers = new HashSet(); + } + invalidWatchers.add(computer); + } + } + } + } + + // Remove any invalid watchers + if (invalidWatchers != null) { + for (IComputerAccess badComputer : invalidWatchers) { + this.removeComputerWatcher(badComputer); + } + } + } + } + + /** + * Removes a computer from the watch list. + * + * @param computer + * @throws LuaException + * @throws InterruptedException + */ + public void removeComputerWatcher(final IComputerAccess computer) { + synchronized (this.threadLock) { + if (this.computerWatchers.containsKey(computer)) { + // Was the computer watching for specific changes? + if (this.computerWatchers.get(computer)) { + // Remove the mappings + for (Set watchSet : this.aspectWatchers.values()) { + watchSet.remove(computer); + } + } else { + // Remove the mapping + this.anyWatchers.remove(computer); + } + + // Remove the computer + this.computerWatchers.remove(computer); + } + } + } + } + + /** + * Name of the peripheral. + */ + private static final String CC_PERIPHERAL_NAME = "EssentiaProvider"; + + /** + * Name of the event to pass into CC. + */ + private static final String CC_EVENT_NAME = "essentia"; + + /** + * Maps an aspects name to an Aspect. + */ + private static final Hashtable aspectNameReverseMap = new Hashtable(); + + /** + * What world is the provider in? + */ + private final WeakReference epWorld; + + /** + * Where in the world is the provider? + */ + private final int epX, epY, epZ; + + /** + * Watches the network for essentia changes. + */ + private final EssentiaWatcher watcher; + + /** + * Computers attached to this peripheral. + */ + private final HashSet attachedComputers = new HashSet(); + + /** + * True if the peripheral is listening to the provider. + */ + private boolean isRegisteredAsBlockListener = false; + + public EssentiaProviderPeripheral(final World world, final int x, final int y, final int z) { + // Mark the world + this.epWorld = new WeakReference(world); + + // Mark the position + this.epX = x; + this.epY = y; + this.epZ = z; + + // Create the watcher + this.watcher = new EssentiaWatcher(); + + // Setup the block listener + this.getProvider(); + } + + /** + * Returns how much of an aspect is in the system from its tag. + * + * @param args + * @return + */ + @SuppressWarnings("null") + private Object[] ccGetAmount(final Object[] args) throws LuaException, InterruptedException { + // Get the provider + TileEssentiaProvider provider = this.getProvider(); + + // Get the list of aspects + List aspects = this.getAspectsFromArguments(args); + + // Create the results + Object[] results = new Object[aspects.size()]; + + // Is the provider active? + boolean providerActive = (provider != null ? provider.isActive() : false); + + // For aspect, get the amount + for (int index = 0; index < results.length; ++index) { + if (providerActive) { + // Add the amount to the results + results[index] = provider.getAspectAmountInNetwork(aspects.get(index)); + } else { + // Provider is offline + results[index] = 0; + } + } + + return results; + } + + /** + * Gets the aspects stored in the network the provider is attached to. + * + * @return + */ + private Object[] ccGetAspects() throws LuaException, InterruptedException { + + // Attempt to get the monitor + IMEEssentiaMonitor monitor; + if ((monitor = this.getProviderMonitor()) == null) { + return null; + } + + // Get the list of aspects in the network + Collection essentiaList = monitor.getEssentiaList(); + + // Is there any essentia stored? + if (essentiaList.size() == 0) { + // No essentia stored + return null; + } + + // Create the array + Object[] ccList = new Object[essentiaList.size() * 2]; + + int index = 0; + for (IAspectStack stack : essentiaList) { + // Set the name + ccList[index] = stack.getAspectName(); + + // Set the amount + ccList[index + 1] = stack.getStackSize(); + + // Inc the index + index += 2; + } + + return ccList; + } + + /** + * Returns if the provider is online, or null if the provider is + * invalid. + * + * @return + */ + private Object[] ccGetOnline() throws LuaException, InterruptedException { + // Return the providers active state + return new Object[] {this.isProviderAvailable()}; + } + + /** + * Registers a computer with the network watcher. + * + * @param computer + * @param args + * @throws LuaException + * @throws InterruptedException + */ + private boolean ccRegisterAsWatcher(final IComputerAccess computer, final Object[] args) + throws LuaException, InterruptedException { + // No provider + if (!this.isProviderAvailable()) { + return false; + } + + // Is the computer watching for specific aspects? + if ((args != null) && (args.length > 0)) { + // Create the aspect set + HashSet aspects = new HashSet(this.getAspectsFromArguments(args)); + + // Register for those aspects + this.watcher.addComputerWatch(computer, aspects); + } else { + // Register for all + this.watcher.addComputerWatch(computer, null); + } + + return true; + } + + /** + * Gets an aspect based on its friendly name. + * + * @param name + * @return + */ + private Aspect getAspectFromName(final String name) { + // Get the name, in lowercase + String aspectName = name.toLowerCase(); + + // Does the map contain this entry? + if (EssentiaProviderPeripheral.aspectNameReverseMap.contains(aspectName)) { + // Get the aspect + return EssentiaProviderPeripheral.aspectNameReverseMap.get(aspectName); + } + + // Search all aspects + for (Aspect searchAspect : Aspect.aspects.values()) { + // Do the names match? + if (searchAspect.getName().equalsIgnoreCase(aspectName)) { + // Update the map + EssentiaProviderPeripheral.aspectNameReverseMap.put(aspectName, searchAspect); + + // Break the search + return searchAspect; + } + } + + return null; + } + + /** + * Gets a list of aspects based on the arguments passed in from the computer. + * + * @param args + * @return + * @throws LuaException + * @throws InterruptedException + */ + private List getAspectsFromArguments(final Object[] args) throws LuaException, InterruptedException { + // Ensure there are arguments + if ((args == null) || (args.length == 0)) { + throw new LuaException("Expected argument: AspectName"); + } + + List results = new ArrayList(); + + // For each argument, attempt to get the aspect + for (Object arg : args) { + // Ensure the argument is a string + if (arg instanceof String) { + // The aspect to look up + Aspect aspect = this.getAspectFromName((String) arg); + + // Was an aspect found? + if (aspect != null) { + // Add to the results + results.add(aspect); + } else { + throw new LuaException(String.format("Invalid aspect name '%s'", arg)); + } + } else { + throw new LuaException(String.format("Invalid argument '%s'", arg)); + } + } + + return results; + } + + /** + * Returns true if a provider is found, and it is powered up + * + * @return + */ + private boolean isProviderAvailable() { + TileEssentiaProvider provider = this.getProvider(); + return (provider != null ? provider.isActive() : false); + } + + /** + * Attempts to get the Essentia Provider + * + * @return + */ + TileEssentiaProvider getProvider() { + // Attempt to get the world + World world; + if ((this.epWorld == null) || ((world = this.epWorld.get()) == null)) { + return null; + } + + // Get the tile entity at the recorded location + TileEntity te = world.getTileEntity(this.epX, this.epY, this.epZ); + + // Is the entity a provider? + if (te instanceof TileEssentiaProvider) { + // Is the peripheral registered as a block watcher? + if (!this.isRegisteredAsBlockListener) { + // Register + ((TileEssentiaProvider) te).registerBlockWatcher(this); + this.isRegisteredAsBlockListener = true; + } + + // Return the provider + return (TileEssentiaProvider) te; + } + + return null; + } + + /** + * Gets the essentia monitor from the provider. + * + * @return + * @throws LuaException + * @throws InterruptedException + */ + IMEEssentiaMonitor getProviderMonitor() throws LuaException, InterruptedException { + // Get the provider + TileEssentiaProvider provider = this.getProvider(); + + // Is the provider active? + if (!provider.isActive()) { + // Inactive + return null; + } + + // Attempt to get the essentia monitor + try { + return (IMEEssentiaMonitor) provider.getActionableNode().getGrid().getCache(IEssentiaGrid.class); + } catch (NullPointerException npe) { + // Could not get the monitor + return null; + } + } + + /** + * Sends an event to the specified computer + * + * @param computer + * @param event + * @param additionalData + */ + void sendEvent(final IComputerAccess computer, final CCEvents event, final Object... additionalData) { + // Create the arguments + Object[] args = new Object[(additionalData == null ? 1 : 1 + additionalData.length)]; + + // Set the ID + args[0] = event.eventID; + + // Copy the rest of the data + if (additionalData != null) { + System.arraycopy(additionalData, 0, args, 1, additionalData.length); + } + + computer.queueEvent(EssentiaProviderPeripheral.CC_EVENT_NAME, args); + } + + @Override + public void attach(final IComputerAccess computer) { + // Add to the attach list + this.attachedComputers.add(computer); + } + + @Override + public Object[] callMethod( + final IComputerAccess computer, final ILuaContext context, final int method, final Object[] arguments) + throws LuaException, InterruptedException { + Object[] results = null; + + // Determine which method was called. + switch (CCMethods.VALUES[method]) { + case isOnline: + results = this.ccGetOnline(); + break; + + case getAspects: + results = this.ccGetAspects(); + break; + + case getAmount: + results = this.ccGetAmount(arguments); + break; + + case registerAsWatcher: + results = new Object[] {this.ccRegisterAsWatcher(computer, arguments)}; + break; + + case unregisterAsWatcher: + this.watcher.removeComputerWatcher(computer); + results = new Object[] {true}; + break; + case help: + results = new Object[] {CCHelpObject.Instance()}; + break; + } + + return results; + } + + @Override + public void detach(final IComputerAccess computer) { + // Remove from the list + this.attachedComputers.remove(computer); + + // Remove the computer from the watcher + this.watcher.removeComputerWatcher(computer); + + // Send the detach event + this.sendEvent(computer, CCEvents.Detached); + } + + @Override + public boolean equals(final IPeripheral other) { + return this == other; + } + + @Override + public boolean equals(final Object other) { + + return super.equals(other); + } + + @Override + public String[] getMethodNames() { + return CCMethods.NAMES; + } + + @Override + public String getType() { + return EssentiaProviderPeripheral.CC_PERIPHERAL_NAME; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public void onProviderBroken() { + // No longer registered + this.isRegisteredAsBlockListener = false; + + // Inform any attached computers that the link is going down + for (IComputerAccess computer : this.attachedComputers) { + this.sendEvent(computer, CCEvents.PowerChange, false); + } + this.watcher.onProviderBroken(); + } + + @Override + public void onProviderPowerChange(final boolean isOnline) { + // Inform computers that the power status changed + for (IComputerAccess computer : this.attachedComputers) { + this.sendEvent(computer, CCEvents.PowerChange, isOnline); + } + } +} diff --git a/src/main/java/thaumicenergistics/common/integration/IEssentiaProviderWatcher.java b/src/main/java/thaumicenergistics/common/integration/IEssentiaProviderWatcher.java index 549b6ace..caedc2d3 100644 --- a/src/main/java/thaumicenergistics/common/integration/IEssentiaProviderWatcher.java +++ b/src/main/java/thaumicenergistics/common/integration/IEssentiaProviderWatcher.java @@ -6,15 +6,14 @@ package thaumicenergistics.common.integration; * @author Nividica * */ -public interface IEssentiaProviderWatcher -{ - /** - * Called when the provider is broken. - */ - public void onProviderBroken(); +public interface IEssentiaProviderWatcher { + /** + * Called when the provider is broken. + */ + public void onProviderBroken(); - /** - * Called when the providers power state changes. - */ - public void onProviderPowerChange( boolean isOnline ); + /** + * Called when the providers power state changes. + */ + public void onProviderPowerChange(boolean isOnline); } diff --git a/src/main/java/thaumicenergistics/common/integration/IWailaSource.java b/src/main/java/thaumicenergistics/common/integration/IWailaSource.java index 56d3a776..5793fe7e 100644 --- a/src/main/java/thaumicenergistics/common/integration/IWailaSource.java +++ b/src/main/java/thaumicenergistics/common/integration/IWailaSource.java @@ -8,12 +8,11 @@ import java.util.List; * @author Nividica * */ -public interface IWailaSource -{ - /** - * Add's information to a Waila tooltip. - * - * @param tooltip - */ - void addWailaInformation( List tooltip ); +public interface IWailaSource { + /** + * Add's information to a Waila tooltip. + * + * @param tooltip + */ + void addWailaInformation(List tooltip); } diff --git a/src/main/java/thaumicenergistics/common/integration/IntegrationCore.java b/src/main/java/thaumicenergistics/common/integration/IntegrationCore.java index 78fdf840..17e9ea19 100644 --- a/src/main/java/thaumicenergistics/common/integration/IntegrationCore.java +++ b/src/main/java/thaumicenergistics/common/integration/IntegrationCore.java @@ -18,129 +18,116 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public final class IntegrationCore -{ - /** - * Class path to all integration modules - */ - private static final String CLASS_PATH = ThaumicEnergistics.MOD_ID + ".common.integration.Module"; +public final class IntegrationCore { + /** + * Class path to all integration modules + */ + private static final String CLASS_PATH = ThaumicEnergistics.MOD_ID + ".common.integration.Module"; - /** - * Module ID for Waila - */ - private static final String MODID_WAILA = "Waila"; + /** + * Module ID for Waila + */ + private static final String MODID_WAILA = "Waila"; - /** - * Module ID for NEI - */ - private static final String MODID_NEI = "NEI"; + /** + * Module ID for NEI + */ + private static final String MODID_NEI = "NEI"; - /** - * Module ID for ExtraCells2 - */ - private static final String MODID_EC2 = "EC2"; + /** + * Module ID for ExtraCells2 + */ + private static final String MODID_EC2 = "EC2"; - /** - * Module ID for ComputerCraft - */ - private static final String MODID_CC = "CC"; + /** + * Module ID for ComputerCraft + */ + private static final String MODID_CC = "CC"; - @SideOnly(Side.CLIENT) - private static void integrateWithClientMods() - { - // Integrate with version checker - IntegrationCore.integrateWithVersionChecker(); + @SideOnly(Side.CLIENT) + private static void integrateWithClientMods() { + // Integrate with version checker + IntegrationCore.integrateWithVersionChecker(); - // Integrate with NEI - IntegrationCore.integrateWithMod( IntegrationCore.MODID_NEI ); + // Integrate with NEI + IntegrationCore.integrateWithMod(IntegrationCore.MODID_NEI); - // Integrate with Waila - IntegrationCore.integrateWithMod( IntegrationCore.MODID_WAILA ); - } + // Integrate with Waila + IntegrationCore.integrateWithMod(IntegrationCore.MODID_WAILA); + } - /** - * Integrates with the specified mod if it exists - * - * @param modID - */ - private static void integrateWithMod( final String modID ) - { - try - { - // Attempt to get the module - Class module = Class.forName( IntegrationCore.CLASS_PATH + modID ); + /** + * Integrates with the specified mod if it exists + * + * @param modID + */ + private static void integrateWithMod(final String modID) { + try { + // Attempt to get the module + Class module = Class.forName(IntegrationCore.CLASS_PATH + modID); - // Instantiate it - module.newInstance(); + // Instantiate it + module.newInstance(); - // Log success - ThELog.info( "Successfully integrated with %s", modID ); - } - catch( Throwable e ) - { + // Log success + ThELog.info("Successfully integrated with %s", modID); + } catch (Throwable e) { - // Log failure - ThELog.info( "Skipping integration with %s", modID ); - } - } + // Log failure + ThELog.info("Skipping integration with %s", modID); + } + } - /** - * Integrates with version checker - */ - private static void integrateWithVersionChecker() - { - // Create the tag - NBTTagCompound tag = new NBTTagCompound(); + /** + * Integrates with version checker + */ + private static void integrateWithVersionChecker() { + // Create the tag + NBTTagCompound tag = new NBTTagCompound(); - // Set the project name - tag.setString( "curseProjectName", "223666-thaumic-energistics" ); + // Set the project name + tag.setString("curseProjectName", "223666-thaumic-energistics"); - // Set the file name - tag.setString( "curseFilenameParser", "thaumicenergistics-[].jar" ); + // Set the file name + tag.setString("curseFilenameParser", "thaumicenergistics-[].jar"); - // Set the mod name - tag.setString( "modDisplayName", "Thaumic Energistics" ); + // Set the mod name + tag.setString("modDisplayName", "Thaumic Energistics"); - // Send to version checker - FMLInterModComms.sendRuntimeMessage( ThaumicEnergistics.MOD_ID, "VersionChecker", "addCurseCheck", tag ); + // Send to version checker + FMLInterModComms.sendRuntimeMessage(ThaumicEnergistics.MOD_ID, "VersionChecker", "addCurseCheck", tag); + } - } + /** + * Integrate with all modules + */ + public static void init() { + long startTime = ThELog.beginSection("Integration"); + try { + // Is client side? + if (EffectiveSide.isClientSide()) { + // Integrate with client mods + IntegrationCore.integrateWithClientMods(); + } - /** - * Integrate with all modules - */ - public static void init() - { - long startTime = ThELog.beginSection( "Integration" ); - try - { - // Is client side? - if( EffectiveSide.isClientSide() ) - { - // Integrate with client mods - IntegrationCore.integrateWithClientMods(); - } + // Integrate with EC2 if blacklisting enabled + if (ThEApi.instance().config().blacklistEssentiaFluidInExtraCells()) { + IntegrationCore.integrateWithMod(IntegrationCore.MODID_EC2); + } - // Integrate with EC2 if blacklisting enabled - if( ThEApi.instance().config().blacklistEssentiaFluidInExtraCells() ) - { - IntegrationCore.integrateWithMod( IntegrationCore.MODID_EC2 ); - } + // Integrate with computer craft + IntegrationCore.integrateWithMod(IntegrationCore.MODID_CC); - // Integrate with computer craft - IntegrationCore.integrateWithMod( IntegrationCore.MODID_CC ); + // Send a message to Thaumic Tinkerer to blacklist the essentia provider from its CC support + FMLInterModComms.sendMessage("ThaumicTinkerer", "AddCCBlacklist", TileEssentiaProvider.class.getName()); - // Send a message to Thaumic Tinkerer to blacklist the essentia provider from its CC support - FMLInterModComms.sendMessage( "ThaumicTinkerer", "AddCCBlacklist", TileEssentiaProvider.class.getName() ); + } catch (Throwable e) { + } - } - catch( Throwable e ) - { - } + // Register the Arcane Assembler for upgrades + Upgrades.SPEED.registerItem( + ThEApi.instance().blocks().ArcaneAssembler.getStack(), BlockArcaneAssembler.MAX_SPEED_UPGRADES); - // Register the Arcane Assembler for upgrades - Upgrades.SPEED.registerItem( ThEApi.instance().blocks().ArcaneAssembler.getStack(), BlockArcaneAssembler.MAX_SPEED_UPGRADES ); - - ThELog.endSection( "Integration", startTime ); - } + ThELog.endSection("Integration", startTime); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/ModuleCC.java b/src/main/java/thaumicenergistics/common/integration/ModuleCC.java index 65b6b64e..8027d4c2 100644 --- a/src/main/java/thaumicenergistics/common/integration/ModuleCC.java +++ b/src/main/java/thaumicenergistics/common/integration/ModuleCC.java @@ -13,43 +13,33 @@ import thaumicenergistics.common.tiles.TileEssentiaProvider; * @author Nividica * */ -public class ModuleCC -{ - public static class ThEPeripherals - implements IPeripheralProvider - { +public class ModuleCC { + public static class ThEPeripherals implements IPeripheralProvider { - @Override - public IPeripheral getPeripheral( final World world, final int x, final int y, final int z, final int side ) - { - try - { - // Get the tile entity at that position - TileEntity te = world.getTileEntity( x, y, z ); + @Override + public IPeripheral getPeripheral(final World world, final int x, final int y, final int z, final int side) { + try { + // Get the tile entity at that position + TileEntity te = world.getTileEntity(x, y, z); - // Is the entity an Essentia Provider? - if( te instanceof TileEssentiaProvider ) - { - // Create the peripheral - return new EssentiaProviderPeripheral( world, x, y, z ); - } - } - catch( Exception e ) - { - // Silently ignore - } + // Is the entity an Essentia Provider? + if (te instanceof TileEssentiaProvider) { + // Create the peripheral + return new EssentiaProviderPeripheral(world, x, y, z); + } + } catch (Exception e) { + // Silently ignore + } - return null; - } + return null; + } + } - } - - /** - * Integrates with CC - */ - public ModuleCC() - { - // Create and register the handler - ComputerCraftAPI.registerPeripheralProvider( new ThEPeripherals() ); - } + /** + * Integrates with CC + */ + public ModuleCC() { + // Create and register the handler + ComputerCraftAPI.registerPeripheralProvider(new ThEPeripherals()); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/ModuleEC2.java b/src/main/java/thaumicenergistics/common/integration/ModuleEC2.java index 497e2678..290dcd74 100644 --- a/src/main/java/thaumicenergistics/common/integration/ModuleEC2.java +++ b/src/main/java/thaumicenergistics/common/integration/ModuleEC2.java @@ -10,31 +10,28 @@ import thaumicenergistics.common.fluids.GaseousEssentia; * @author Nividica * */ -public class ModuleEC2 -{ +public class ModuleEC2 { - public ModuleEC2() throws Exception - { - // Is blacklisting enabled? - if( ThEApi.instance().config().blacklistEssentiaFluidInExtraCells() ) - { - // Get the API - Class ECApi_Class = Class.forName( "extracells.api.ECApi" ); + public ModuleEC2() throws Exception { + // Is blacklisting enabled? + if (ThEApi.instance().config().blacklistEssentiaFluidInExtraCells()) { + // Get the API + Class ECApi_Class = Class.forName("extracells.api.ECApi"); - // Get the 'instance' method - Method ECApi_instance = ECApi_Class.getDeclaredMethod( "instance" ); + // Get the 'instance' method + Method ECApi_instance = ECApi_Class.getDeclaredMethod("instance"); - // Invoke the 'instance' method - Object ECApi = ECApi_instance.invoke( null ); + // Invoke the 'instance' method + Object ECApi = ECApi_instance.invoke(null); - // Get the blacklist methods - Method addFluidToShowBlacklist = ECApi.getClass().getDeclaredMethod( "addFluidToShowBlacklist", Class.class ); - Method addFluidToStorageBlacklist = ECApi.getClass().getDeclaredMethod( "addFluidToStorageBlacklist", Class.class ); - - // Invoke the blacklist methods - addFluidToShowBlacklist.invoke( ECApi, GaseousEssentia.class ); - addFluidToStorageBlacklist.invoke( ECApi, GaseousEssentia.class ); - } - } + // Get the blacklist methods + Method addFluidToShowBlacklist = ECApi.getClass().getDeclaredMethod("addFluidToShowBlacklist", Class.class); + Method addFluidToStorageBlacklist = + ECApi.getClass().getDeclaredMethod("addFluidToStorageBlacklist", Class.class); + // Invoke the blacklist methods + addFluidToShowBlacklist.invoke(ECApi, GaseousEssentia.class); + addFluidToStorageBlacklist.invoke(ECApi, GaseousEssentia.class); + } + } } diff --git a/src/main/java/thaumicenergistics/common/integration/ModuleNEI.java b/src/main/java/thaumicenergistics/common/integration/ModuleNEI.java index 3a9c020d..842fe018 100644 --- a/src/main/java/thaumicenergistics/common/integration/ModuleNEI.java +++ b/src/main/java/thaumicenergistics/common/integration/ModuleNEI.java @@ -1,11 +1,5 @@ package thaumicenergistics.common.integration; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; import appeng.util.Platform; import codechicken.nei.PositionedStack; import codechicken.nei.api.API; @@ -13,6 +7,12 @@ import codechicken.nei.api.INEIGuiAdapter; import codechicken.nei.api.IOverlayHandler; import codechicken.nei.api.IStackPositioner; import codechicken.nei.recipe.IRecipeHandler; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; @@ -32,261 +32,250 @@ import thaumicenergistics.common.network.packet.server.Packet_S_NEIRecipe; * @author Nividica * */ -public class ModuleNEI -{ +public class ModuleNEI { - /** - * Base class for handling item overlays. - * - * @author Nividica - * - */ - static class ACTOverlayHandler implements IOverlayHandler - { - /** - * Called when the user has shift-clicked the [?] button in NEI - */ - @Override - public final void overlayRecipe( final GuiContainer gui, final IRecipeHandler recipeHandler, final int recipeIndex, final boolean shift ) - { - try - { - // Ensure the gui is correct - if( gui instanceof GuiArcaneCraftingTerminal ) - { - List ingredients = recipeHandler.getIngredientStacks( recipeIndex ); + /** + * Base class for handling item overlays. + * + * @author Nividica + * + */ + static class ACTOverlayHandler implements IOverlayHandler { + /** + * Called when the user has shift-clicked the [?] button in NEI + */ + @Override + public final void overlayRecipe( + final GuiContainer gui, + final IRecipeHandler recipeHandler, + final int recipeIndex, + final boolean shift) { + try { + // Ensure the gui is correct + if (gui instanceof GuiArcaneCraftingTerminal) { + List ingredients = recipeHandler.getIngredientStacks(recipeIndex); - NBTTagCompound recipe = new NBTTagCompound(); - for( PositionedStack ingredient : ingredients ) - { - if( ( ingredient == null ) || ( ingredient.item == null ) || ( ingredient.item.getItem() == null ) ) - continue; - addIngredientToItems( ingredient, recipe, false ); - } - if (testSize(recipe, 32*1024)) - { - recipe = new NBTTagCompound(); - for( PositionedStack ingredient : ingredients ) - { - if( ( ingredient == null ) || ( ingredient.item == null ) || ( ingredient.item.getItem() == null ) ) - continue; - addIngredientToItems( ingredient, recipe, true ); - } - } - Packet_S_NEIRecipe packet = new Packet_S_NEIRecipe(); - packet.setRecipe(recipe); - packet.player = Minecraft.getMinecraft().thePlayer; + NBTTagCompound recipe = new NBTTagCompound(); + for (PositionedStack ingredient : ingredients) { + if ((ingredient == null) || (ingredient.item == null) || (ingredient.item.getItem() == null)) + continue; + addIngredientToItems(ingredient, recipe, false); + } + if (testSize(recipe, 32 * 1024)) { + recipe = new NBTTagCompound(); + for (PositionedStack ingredient : ingredients) { + if ((ingredient == null) + || (ingredient.item == null) + || (ingredient.item.getItem() == null)) continue; + addIngredientToItems(ingredient, recipe, true); + } + } + Packet_S_NEIRecipe packet = new Packet_S_NEIRecipe(); + packet.setRecipe(recipe); + packet.player = Minecraft.getMinecraft().thePlayer; - NetworkHandler.sendPacketToServer( packet ); - } - } - catch( Exception e ) - { - // Silently ignored. - } - } + NetworkHandler.sendPacketToServer(packet); + } + } catch (Exception e) { + // Silently ignored. + } + } - /** - * Reduces regular slot offsets to 0, 1, or 2 - */ - private static final int REGULAR_SLOT_INDEX_DIVISOR = 18; + /** + * Reduces regular slot offsets to 0, 1, or 2 + */ + private static final int REGULAR_SLOT_INDEX_DIVISOR = 18; - /** - * Reduces arcane slot Y offsets to 0,1, or 2 - */ - private static final int ARCANE_SLOTY_INDEX_DIVISOR = 20; + /** + * Reduces arcane slot Y offsets to 0,1, or 2 + */ + private static final int ARCANE_SLOTY_INDEX_DIVISOR = 20; - /** - * If true incoming ingredients are from ThaumcraftNEIPlugin - */ - private final boolean isArcaneHandler; + /** + * If true incoming ingredients are from ThaumcraftNEIPlugin + */ + private final boolean isArcaneHandler; - /** - * Creates the handler. - * - * @param isArcane - * Set to true for arcane recipes - */ - public ACTOverlayHandler( final boolean isArcane ) - { - this.isArcaneHandler = isArcane; - } + /** + * Creates the handler. + * + * @param isArcane + * Set to true for arcane recipes + */ + public ACTOverlayHandler(final boolean isArcane) { + this.isArcaneHandler = isArcane; + } - private void packIngredient(NBTTagCompound recipe, int slotIndex, PositionedStack positionedStack, boolean limited) throws IOException - { - final NBTTagList tags = new NBTTagList(); - final List list = new LinkedList<>(); + private void packIngredient( + NBTTagCompound recipe, int slotIndex, PositionedStack positionedStack, boolean limited) + throws IOException { + final NBTTagList tags = new NBTTagList(); + final List list = new LinkedList<>(); - // prefer pure crystals. - for( int x = 0; x < positionedStack.items.length; x++ ) - { - if( Platform.isRecipePrioritized( positionedStack.items[x] ) ) - { - list.add( 0, positionedStack.items[x] ); - } - else - { - list.add( positionedStack.items[x] ); - } - } + // prefer pure crystals. + for (int x = 0; x < positionedStack.items.length; x++) { + if (Platform.isRecipePrioritized(positionedStack.items[x])) { + list.add(0, positionedStack.items[x]); + } else { + list.add(positionedStack.items[x]); + } + } - for( final ItemStack is : list ) - { - final NBTTagCompound tag = new NBTTagCompound(); - is.writeToNBT( tag ); - tags.appendTag( tag ); - if (limited) - { - final NBTTagCompound test = new NBTTagCompound(); - test.setTag( "#" + slotIndex, tags ); - if (testSize(test, 3*1024)) - break; - } - } - recipe.setTag( "#" + slotIndex, tags ); - } - // if the packet becomes too large, limit each slot contents to 3k - protected boolean testSize(final NBTTagCompound recipe, int limit) throws IOException - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream outputStream = new DataOutputStream( bytes ); - CompressedStreamTools.writeCompressed( recipe, outputStream ); - return bytes.size() > limit; - } + for (final ItemStack is : list) { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT(tag); + tags.appendTag(tag); + if (limited) { + final NBTTagCompound test = new NBTTagCompound(); + test.setTag("#" + slotIndex, tags); + if (testSize(test, 3 * 1024)) break; + } + } + recipe.setTag("#" + slotIndex, tags); + } + // if the packet becomes too large, limit each slot contents to 3k + protected boolean testSize(final NBTTagCompound recipe, int limit) throws IOException { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream(bytes); + CompressedStreamTools.writeCompressed(recipe, outputStream); + return bytes.size() > limit; + } - private boolean addArcaneCraftingItems( final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) throws IOException - { - // Calculate the slot positions - int slotX = (int)Math.round( ingredient.relx / (double)ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR ) - 3; - int slotY = (int)Math.round( ingredient.rely / (double)ACTOverlayHandler.ARCANE_SLOTY_INDEX_DIVISOR ) - 2; + private boolean addArcaneCraftingItems(final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) + throws IOException { + // Calculate the slot positions + int slotX = (int) Math.round(ingredient.relx / (double) ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR) - 3; + int slotY = (int) Math.round(ingredient.rely / (double) ACTOverlayHandler.ARCANE_SLOTY_INDEX_DIVISOR) - 2; - // Ignore the 'aspects' - if( slotY >= 3 ) - { - return false; - } + // Ignore the 'aspects' + if (slotY >= 3) { + return false; + } - // Roundoff fix - if( slotX == 3 ) - { - slotX = 2; - } + // Roundoff fix + if (slotX == 3) { + slotX = 2; + } - // Calculate the slot index - int slotIndex = slotX + ( slotY * 3 ); + // Calculate the slot index + int slotIndex = slotX + (slotY * 3); - // Bounds check the index - if( ( slotIndex < 0 ) || ( slotIndex > 9 ) ) - { - // Invalid slot - return false; - } + // Bounds check the index + if ((slotIndex < 0) || (slotIndex > 9)) { + // Invalid slot + return false; + } - // Add the item to the list - packIngredient(recipe, slotIndex, ingredient, limited); + // Add the item to the list + packIngredient(recipe, slotIndex, ingredient, limited); - return true; - } + return true; + } - private boolean addRegularCraftingItems( final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) throws IOException - { - // Calculate the slot positions - int slotX = ( ingredient.relx - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_X ) / ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; - int slotY = ( ingredient.rely - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_Y ) / ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; + private boolean addRegularCraftingItems( + final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) throws IOException { + // Calculate the slot positions + int slotX = (ingredient.relx - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_X) + / ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; + int slotY = (ingredient.rely - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_Y) + / ACTOverlayHandler.REGULAR_SLOT_INDEX_DIVISOR; - // Calculate the slot index - int slotIndex = slotX + ( slotY * 3 ); + // Calculate the slot index + int slotIndex = slotX + (slotY * 3); - // Add the item to the list - packIngredient(recipe, slotIndex, ingredient, limited); + // Add the item to the list + packIngredient(recipe, slotIndex, ingredient, limited); - return true; - } + return true; + } - protected boolean addIngredientToItems( final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) throws IOException - { - return isArcaneHandler ? addArcaneCraftingItems( ingredient, recipe, limited ) : addRegularCraftingItems( ingredient, recipe, limited ); - } - } + protected boolean addIngredientToItems(final PositionedStack ingredient, NBTTagCompound recipe, boolean limited) + throws IOException { + return isArcaneHandler + ? addArcaneCraftingItems(ingredient, recipe, limited) + : addRegularCraftingItems(ingredient, recipe, limited); + } + } - /** - * Corrects the slot positions so that NEI can find and render them. - * - * @author Nividica - * - */ - public static class ACTSlotPositioner - implements IStackPositioner - { + /** + * Corrects the slot positions so that NEI can find and render them. + * + * @author Nividica + * + */ + public static class ACTSlotPositioner implements IStackPositioner { - @Override - public ArrayList positionStacks( final ArrayList stacks ) - { - // Adjust the position of the ghost stacks to match the crafting grid slots - for( PositionedStack ps : stacks ) - { - // Ensure there is a stack - if( ps != null ) - { - // Adjust it's position - ps.relx += ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_X_POS - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_X; - ps.rely += ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_Y_POS - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_Y; - } - } + @Override + public ArrayList positionStacks(final ArrayList stacks) { + // Adjust the position of the ghost stacks to match the crafting grid slots + for (PositionedStack ps : stacks) { + // Ensure there is a stack + if (ps != null) { + // Adjust it's position + ps.relx += ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_X_POS + - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_X; + ps.rely += ContainerPartArcaneCraftingTerminal.CRAFTING_SLOT_Y_POS + - ModuleNEI.NEI_REGULAR_SLOT_OFFSET_Y; + } + } - return stacks; - } + return stacks; + } + } - } + static class NEIGuiHandler extends INEIGuiAdapter { + @Override + public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { + if (gui instanceof ThEBaseGui && draggedStack != null && draggedStack.getItem() != null) { + ((ThEBaseGui) gui).draggedStack = draggedStack; + draggedStack.stackSize = 0; + } - static class NEIGuiHandler extends INEIGuiAdapter { - @Override - public boolean handleDragNDrop(GuiContainer gui, int mousex, int mousey, ItemStack draggedStack, int button) { - if (gui instanceof ThEBaseGui && draggedStack != null && draggedStack.getItem() != null) { - ((ThEBaseGui) gui).draggedStack = draggedStack; - draggedStack.stackSize = 0; - } + return super.handleDragNDrop(gui, mousex, mousey, draggedStack, button); + } + } - return super.handleDragNDrop(gui, mousex, mousey, draggedStack, button); - } - } + /** + * Starting X offset for slots in NEI + */ + static final int NEI_REGULAR_SLOT_OFFSET_X = 25; - /** - * Starting X offset for slots in NEI - */ - static final int NEI_REGULAR_SLOT_OFFSET_X = 25; + /** + * Starting Y offset for slots in NEI + */ + static final int NEI_REGULAR_SLOT_OFFSET_Y = 6; - /** - * Starting Y offset for slots in NEI - */ - static final int NEI_REGULAR_SLOT_OFFSET_Y = 6; + /** + * Integrates with Not Enough Items + * + * @throws Exception + */ + public ModuleNEI() throws Exception { + // Register the ACT overlays + API.registerGuiOverlay( + thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, "crafting", new ACTSlotPositioner()); - /** - * Integrates with Not Enough Items - * - * @throws Exception - */ - public ModuleNEI() throws Exception - { - // Register the ACT overlays - API.registerGuiOverlay( thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, "crafting", new ACTSlotPositioner()); + // Create the regular overlay handler + ACTOverlayHandler craftingOverlayHandler = new ACTOverlayHandler(false); - // Create the regular overlay handler - ACTOverlayHandler craftingOverlayHandler = new ACTOverlayHandler(false); + // Create the arcane overlay handler + ACTOverlayHandler arcaneOverlayHandler = new ACTOverlayHandler(true); - // Create the arcane overlay handler - ACTOverlayHandler arcaneOverlayHandler = new ACTOverlayHandler(true); + // Register the handlers + API.registerGuiOverlayHandler( + thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, craftingOverlayHandler, "crafting"); + API.registerGuiOverlayHandler( + thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, + arcaneOverlayHandler, + "arcaneshapedrecipes"); + API.registerGuiOverlayHandler( + thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, + arcaneOverlayHandler, + "arcaneshapelessrecipes"); - // Register the handlers - API.registerGuiOverlayHandler( thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, craftingOverlayHandler, "crafting" ); - API.registerGuiOverlayHandler( thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, arcaneOverlayHandler, "arcaneshapedrecipes" ); - API.registerGuiOverlayHandler( thaumicenergistics.client.gui.GuiArcaneCraftingTerminal.class, arcaneOverlayHandler, "arcaneshapelessrecipes" ); - - API.registerNEIGuiHandler(new NEIGuiHandler()); - - // Hide the crafting aspect item - API.hideItem( ItemEnum.CRAFTING_ASPECT.getStack() ); - - } + API.registerNEIGuiHandler(new NEIGuiHandler()); + // Hide the crafting aspect item + API.hideItem(ItemEnum.CRAFTING_ASPECT.getStack()); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/ModuleWaila.java b/src/main/java/thaumicenergistics/common/integration/ModuleWaila.java index b08110e9..408567c3 100644 --- a/src/main/java/thaumicenergistics/common/integration/ModuleWaila.java +++ b/src/main/java/thaumicenergistics/common/integration/ModuleWaila.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.integration; -import java.util.List; import cpw.mods.fml.common.event.FMLInterModComms; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -21,93 +21,97 @@ import thaumicenergistics.common.tiles.TileEssentiaVibrationChamber; * @author Nividica * */ -public class ModuleWaila - implements IWailaDataProvider -{ +public class ModuleWaila implements IWailaDataProvider { - /** - * Singleton - */ - public static ModuleWaila INSTANCE; + /** + * Singleton + */ + public static ModuleWaila INSTANCE; - /** - * Attempts to integrate with Waila - */ - public ModuleWaila() - { - // Set the singleton - ModuleWaila.INSTANCE = this; + /** + * Attempts to integrate with Waila + */ + public ModuleWaila() { + // Set the singleton + ModuleWaila.INSTANCE = this; - // Register with Waila - FMLInterModComms.sendMessage( "Waila", "register", ModuleWaila.class.getCanonicalName() + ".callbackRegister" ); - } + // Register with Waila + FMLInterModComms.sendMessage("Waila", "register", ModuleWaila.class.getCanonicalName() + ".callbackRegister"); + } - /** - * Called by Waila to register our hooks. - * - * @param registrar - */ - public static void callbackRegister( final IWailaRegistrar registrar ) - { - // Register the providers - registrar.registerBodyProvider( ModuleWaila.INSTANCE, AbstractBlockProviderBase.class ); + /** + * Called by Waila to register our hooks. + * + * @param registrar + */ + public static void callbackRegister(final IWailaRegistrar registrar) { + // Register the providers + registrar.registerBodyProvider(ModuleWaila.INSTANCE, AbstractBlockProviderBase.class); - // Register the assembler - registrar.registerBodyProvider( ModuleWaila.INSTANCE, BlockArcaneAssembler.class ); + // Register the assembler + registrar.registerBodyProvider(ModuleWaila.INSTANCE, BlockArcaneAssembler.class); - // Register the vibration chamber - registrar.registerBodyProvider( ModuleWaila.INSTANCE, TileEssentiaVibrationChamber.class ); - } + // Register the vibration chamber + registrar.registerBodyProvider(ModuleWaila.INSTANCE, TileEssentiaVibrationChamber.class); + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity tileEntity, final NBTTagCompound data, final World world, - final int x, final int y, final int z ) - { - // Ignored - return data; - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity tileEntity, + final NBTTagCompound data, + final World world, + final int x, + final int y, + final int z) { + // Ignored + return data; + } - /** - * Changes the body of the Waila message. - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List tooltip, final IWailaDataAccessor accessor, - final IWailaConfigHandler config ) - { - // Get the tile entity - TileEntity tileEntity = accessor.getTileEntity(); + /** + * Changes the body of the Waila message. + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List tooltip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + // Get the tile entity + TileEntity tileEntity = accessor.getTileEntity(); - // Does the tile implement the tooltip method? - if( tileEntity instanceof IWailaSource ) - { - // Add the info - ( (IWailaSource)tileEntity ).addWailaInformation( tooltip ); - } + // Does the tile implement the tooltip method? + if (tileEntity instanceof IWailaSource) { + // Add the info + ((IWailaSource) tileEntity).addWailaInformation(tooltip); + } - return tooltip; - } + return tooltip; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currenttip, final IWailaDataAccessor accessor, - final IWailaConfigHandler config ) - { - // Ignored - return currenttip; - } + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currenttip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + // Ignored + return currenttip; + } - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - // Ignored - return null; - } - - @Override - public List getWailaTail( final ItemStack itemStack, final List currenttip, final IWailaDataAccessor accessor, - final IWailaConfigHandler config ) - { - // Ignored - return currenttip; - } + @Override + public ItemStack getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + // Ignored + return null; + } + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currenttip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config) { + // Ignored + return currenttip; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/ArcaneCraftingPattern.java b/src/main/java/thaumicenergistics/common/integration/tc/ArcaneCraftingPattern.java index acc63d26..24e71259 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/ArcaneCraftingPattern.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/ArcaneCraftingPattern.java @@ -1,13 +1,13 @@ package thaumicenergistics.common.integration.tc; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Objects; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Objects; +import javax.annotation.Nullable; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -18,805 +18,697 @@ import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.common.items.ItemEldritchObject; -public class ArcaneCraftingPattern - implements ICraftingPatternDetails -{ - private static final String NBTKEY_INGREDIENT_NUM = "input#", NBTKEY_RESULT = "output", NBTKEY_INGREDIENT_TYPE = "ThE_crafting_type", - NBTKEY_ARRAY_SIZE = "size"; - private static final int NBTKEY_ARRAYTYPE = 2, NBTKEY_ITEMTYPE = 1; - - private static final int GRID_SIZE = 9; - - /** - * Aspects required. - */ - protected AspectList aspects; - - /** - * Ingredients. - */ - protected Object[] ingredients = new Object[ArcaneCraftingPattern.GRID_SIZE]; - - /** - * Crafting result. - */ - protected IAEItemStack result; - - /** - * The knowledge core this pattern belongs to. - */ - protected ItemStack knowledgeCoreHost; - - /** - * Cached array of required aspects - */ - protected Aspect[] cachedAspects; - - /** - * Ingredients as AE itemstacks. - */ - protected IAEItemStack[] ingredientsAE = null; - - /** - * List of all output items, results + containers - */ - protected IAEItemStack[] allResults = null; - - /** - * True if the recipe is valid. - */ - protected boolean isValid = false; - - /** - * - * @param knowledgeCore - * @param aspects - * @param craftingResult - * @param craftingIngredients - */ - public ArcaneCraftingPattern( final ItemStack knowledgeCore, final AspectList aspects, final ItemStack craftingResult, - final Object[] craftingIngredients ) - { - // Set the core - this.knowledgeCoreHost = knowledgeCore; - - // Set the aspects - this.aspects = aspects.copy(); - - // Set the result - this.result = AEApi.instance().storage().createItemStack( craftingResult ); - - // Set the ingredients - boolean hasAtLeastOneValidInput = false; - for( int index = 0; ( ( index < this.ingredients.length ) && ( index < craftingIngredients.length ) ); ++index ) - { - // Get the next ingredient - Object nextIng = craftingIngredients[index]; - - // Add to the ingredients if not null - if( nextIng != null ) - { - this.ingredients[index] = nextIng; - hasAtLeastOneValidInput = true; - } - } - - // Set validity - this.setPatternValidity( ( this.aspects.size() > 0 ) && ( this.result != null ) && hasAtLeastOneValidInput ); - - // Ensure AE result and ingredients are populated - this.setupAEResults(); - } - - /** - * - * @param knowledgeCore - * @param data - */ - public ArcaneCraftingPattern( @Nullable final ItemStack knowledgeCore, final NBTTagCompound data ) - { - // Set the host - this.knowledgeCoreHost = knowledgeCore; - - // Create the aspect list - this.aspects = new AspectList(); - - // Read the data - this.readFromNBT( data ); - - // Ensure AE result and ingredients are populated - this.setupAEResults(); - } - - /** - * Checks if one item can be substituted for another. - * - * @param target - * @param input - * @return - */ - private static boolean canSubItem( final ItemStack target, final ItemStack input ) - { - // Do the itemstacks directly match? - if( ItemStack.areItemStacksEqual( target, input ) ) - { - return true; - } - - if( target.getItem() != input.getItem() ) - { - // Mismatched items - return false; - } - // Items match - - // NBT data present? - if( target.hasTagCompound() ) - { - // Do the tags match? - if( !ThaumcraftApiHelper.areItemStackTagsEqualForCrafting( input, target ) ) - { - // Tags do not match - return false; - } - // Tags equal - } - - // Does the item damage mean something besides damaged? - if( !target.isItemStackDamageable() ) - { - return( ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE ) || ( target.getItemDamage() == input.getItemDamage() ) ); - } - - // Items match, has no tag or tags match, and damage is damage - return true; - } - - /** - * Checks if the input item can be substituted for the target - * - * @param target - * @param input - * @return - */ - public static boolean canSubstitueFor( final Object target, final ItemStack input ) - { - // What type is the ingredient? - if( target instanceof ItemStack ) - { - // Cast to itemstack - return ArcaneCraftingPattern.canSubItem( (ItemStack)target, input ); - } - else if( target instanceof ArrayList ) - { - // Cast to list - ArrayList items = (ArrayList)target; - - // Check each item - for( ItemStack item : items ) - { - if( ArcaneCraftingPattern.canSubItem( item, input ) ) - { - return true; - } - } - - } - - // Unknown type - return false; - } - - /** - * Converts the itemlist into it's AE counterpart - */ - private void setupAEIngredientList() - { - this.ingredientsAE = new AEItemStack[ArcaneCraftingPattern.GRID_SIZE]; - - for( int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; ++index ) - { - // Get the ingredient - Object ing = this.ingredients[index]; - - // Check for null - if( ing == null ) - { - this.ingredientsAE[index] = null; - continue; - } - - // Itemstack? - if( ing instanceof ItemStack ) - { - this.ingredientsAE[index] = AEApi.instance().storage().createItemStack( (ItemStack)ing ); - } - // Array - else if( ing instanceof ArrayList ) - { - // Use the first ingredient - ItemStack firstIng = ( (ArrayList)ing ).get( 0 ); - - this.ingredientsAE[index] = AEApi.instance().storage().createItemStack( firstIng ); - } - } - } - - /** - * Sets up all results, including container items. - */ - private void setupAEResults() - { - // Ensure the ingredient list is made - if( this.ingredientsAE == null ) - { - this.setupAEIngredientList(); - } - - ArrayList results = new ArrayList(); - - // Add any container items - for( IAEItemStack stack : this.ingredientsAE ) - { - if( stack == null ) - { - continue; - } - - // Container? - if( stack.getItem().hasContainerItem( stack.getItemStack() ) ) - { - results.add( AEApi.instance().storage().createItemStack( stack.getItem().getContainerItem( stack.getItemStack() ) ) ); - } - - // Multiplier? - else if( stack.getStackSize() > 1 ) - { - results.add( stack.copy().setStackSize( stack.getStackSize() - 1 ) ); - } - // Primordial Pearl? - else if( ( stack.getItem() instanceof ItemEldritchObject ) && ( stack.getItemDamage() == 3 ) ) - { - results.add( stack ); - } - - } - - // Add result - results.add( this.result ); - - // Set the outputs - this.allResults = results.toArray( new IAEItemStack[results.size()] ); - } - - protected void setPatternValidity( final boolean valid ) - { - // Set - this.isValid = valid; - - if( !valid ) - { - // Clear all items. - this.result = null; - this.ingredientsAE = null; - for( int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; ++index ) - { - this.ingredients[index] = null; - } - - // Clear aspects - this.aspects = new AspectList(); - this.cachedAspects = null; - } - } - - @Override - public boolean canSubstitute() - { - return true; - } - - /** - * This includes container items. - * - * @return - */ - public IAEItemStack[] getAllResults() - { - if( this.allResults == null ) - { - this.setupAEResults(); - } - return this.allResults; - } - - public void updateInventory(InventoryCrafting table) - { - if (this.ingredientsAE == null) - this.ingredientsAE = new AEItemStack[ArcaneCraftingPattern.GRID_SIZE]; - boolean inventoryUnchanged = true; - for (int i = 0; i < 9; ++i) - { - ItemStack s = table.getStackInSlot(i); - if (s == null) - { - if (ingredientsAE[i] == null) - continue; - inventoryUnchanged = false; - ingredientsAE[i] = null; - } - else - { - AEItemStack aestack = (AEItemStack)AEApi.instance().storage().createItemStack(s); - if (ingredientsAE[i] == null || ingredientsAE[i].hashCode() != aestack.hashCode()) - { - ingredientsAE[i] = aestack; - inventoryUnchanged = false; - } - } - } - if (!inventoryUnchanged) - setupAEResults(); - } - - /** - * Returns the aspect cost for the specified aspect. - * - * @return - */ - public int getAspectCost( final Aspect aspect ) - { - return this.aspects.getAmount( aspect ); - } - - /** - * Returns a cached array of the required aspects for this pattern. - * - * @return - */ - public Aspect[] getCachedAspects() - { - if( this.cachedAspects == null ) - { - this.cachedAspects = this.aspects.getAspects(); - } - - return this.cachedAspects; - } - - @Override - public IAEItemStack[] getCondensedInputs() - { - // Create a temp array - ArrayList cond = new ArrayList(); - - if( this.ingredientsAE == null ) - { - this.setupAEIngredientList(); - } - - // Add non-null ingredients - for( int index = 0; index < this.ingredientsAE.length; index++ ) - { - if( this.ingredientsAE[index] != null ) - { - cond.add( this.ingredientsAE[index] ); - } - } - - // Return the ingredients - return cond.toArray( new IAEItemStack[cond.size()] ); - } - - @Override - public IAEItemStack[] getCondensedOutputs() - { - // Is the result null? - if( this.result == null ) - { - // Return empty array - return new IAEItemStack[0]; - } - - return new IAEItemStack[] { this.result }; - } - - @Override - public IAEItemStack[] getInputs() - { - if( this.ingredientsAE == null ) - { - this.setupAEIngredientList(); - } - - return this.ingredientsAE; - } - - @Override - public ItemStack getOutput( final InventoryCrafting craftingInv, final World world ) - { - return this.result.getItemStack(); - } - - @Override - public IAEItemStack[] getOutputs() - { - return new IAEItemStack[] { this.result }; - } - - @Override - public ItemStack getPattern() - { - return this.knowledgeCoreHost; - } - - @Override - public int getPriority() - { - return 0; - } - - /** - * Returns the result of the craft. - * - * @return - */ - public IAEItemStack getResult() - { - return this.result; - } - - @Override - public boolean isCraftable() - { - // Returning false prevents substitutions. - return true; - } - - /** - * True if the recipe is valid. - * - * @return - */ - public boolean isPatternValid() - { - return this.isValid; - } - - @Override - public boolean isValidItemForSlot( final int slotIndex, final ItemStack input, final World world ) - { - // Get the ingredient - Object ing = this.ingredients[slotIndex]; - - // Ensure nothing is null - if( ( ing == null ) || ( input == null ) || ( input.getItem() == null ) ) - { - // Null detected - return false; - } - - return ArcaneCraftingPattern.canSubstitueFor( ing, input ); - - } - - public void readFromNBT( final NBTTagCompound data ) - { - // Sanity check. - if( data == null ) - { - return; - } - - // Assume the recipe is valid - this.setPatternValidity( true ); - - // Read the aspects - this.aspects.readFromNBT( data ); - - // Validate aspects - if( this.aspects.size() == 0 ) - { - this.setPatternValidity( false ); - return; - } - - // Read ingredients - for( int slotNumber = 0; ( this.isValid && ( slotNumber < ArcaneCraftingPattern.GRID_SIZE ) ); slotNumber++ ) - { - // Is there an ingredient for this slot? - if( !data.hasKey( ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + slotNumber ) ) - { - // No ingredient - continue; - } - - // Get the tag - NBTTagCompound ingData = data.getCompoundTag( ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + slotNumber ); - - // Validate the tag - if( ( ingData == null ) || ( ingData.hasNoTags() ) ) - { - // Invalid tag - this.setPatternValidity( false ); - return; - } - - // Does the tag have a type? - if( !ingData.hasKey( ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE ) ) - { - // Old AE tag - try - { - // Load the AE stack - IAEItemStack ingAE = AEItemStack.loadItemStackFromNBT( ingData ); - - // Null check - if( ingAE == null ) - { - this.setPatternValidity( false ); - return; - } - - // Get the item stack - ItemStack ing = ingAE.getItemStack(); - - // Null check - if( ing == null ) - { - this.setPatternValidity( false ); - return; - } - - // Set the stack - this.ingredients[slotNumber] = ing; - } - catch( Exception e ) - { - // Recipe is invalid. - this.setPatternValidity( false ); - return; - } - continue; - } - - // What type is the tag? - int type = ingData.getInteger( ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE ); - - // Itemstack - if( type == ArcaneCraftingPattern.NBTKEY_ITEMTYPE ) - { - try - { - // Get the item - ItemStack ing = ItemStack.loadItemStackFromNBT( ingData ); - - // Null check - if( ing == null ) - { - this.setPatternValidity( false ); - return; - } - - // Set the stack - this.ingredients[slotNumber] = ing; - } - catch( Exception e ) - { - this.setPatternValidity( false ); - return; - } - } - // Array - else if( type == ArcaneCraftingPattern.NBTKEY_ARRAYTYPE ) - { - // Create the list - ArrayList itemList = new ArrayList(); - - // Has count? - if( !ingData.hasKey( ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE ) ) - { - this.setPatternValidity( false ); - return; - } - - // Get the count - int count = ingData.getInteger( ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE ); - - for( int arrayIndex = 0; arrayIndex < count; ++arrayIndex ) - { - // Get the subtag - NBTTagCompound subTag = ingData.getCompoundTag( ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + arrayIndex ); - - if( ( subTag == null ) || ( subTag.hasNoTags() ) ) - { - // Ignore invalid entry - continue; - } - - try - { - // Load the stack - ItemStack stack = ItemStack.loadItemStackFromNBT( subTag ); - if( stack != null ) - { - itemList.add( stack ); - } - } - catch( Exception e ) - { - // Ignore invalid items - } - } - - // Were any items loaded? - if( itemList.size() == 0 ) - { - this.setPatternValidity( false ); - return; - } - - // Set the ingredient to the list - this.ingredients[slotNumber] = itemList; - } - else - { - // Unknown type - this.setPatternValidity( false ); - return; - } - - } - - // Read the result - if( data.hasKey( ArcaneCraftingPattern.NBTKEY_RESULT ) ) - { - // Get the result - NBTTagCompound resultData = data.getCompoundTag( ArcaneCraftingPattern.NBTKEY_RESULT ); - - // Validate - if( ( resultData == null ) || ( resultData.hasNoTags() ) ) - { - this.setPatternValidity( false ); - return; - } - - try - { - // Get result item - this.result = AEItemStack.loadItemStackFromNBT( resultData ); - - // Check item - if( this.result == null ) - { - this.setPatternValidity( false ); - return; - } - } - catch( Exception e ) - { - this.setPatternValidity( false ); - return; - } - } - } - - /** - * Sets the knowledge core. - * - * @param knowledgeCore - */ - public void setKnowledgeCore( final ItemStack knowledgeCore ) - { - this.knowledgeCoreHost = knowledgeCore; - } - - @Override - public void setPriority( final int priority ) - { - // Ignored. - } - - /** - * Write's the pattern to the NBT tag. - * - * @param data - * @return - */ - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - // Write the aspects - this.aspects.writeToNBT( data ); - - // Write the ingredients - for( int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; index++ ) - { - // Ensure it is not null - if( this.ingredients[index] == null ) - { - continue; - } - - // Get the ingredient - Object ing = this.ingredients[index]; - - // Create the tag - NBTTagCompound ingData = new NBTTagCompound(); - - // What type is the ingredient? - if( ing instanceof IAEItemStack ) - { - // Write the ingredient data - ( (IAEItemStack)ing ).getItemStack().writeToNBT( ingData ); - ingData.setInteger( ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ITEMTYPE ); - } - else if( ing instanceof ItemStack ) - { - ( (ItemStack)ing ).writeToNBT( ingData ); - ingData.setInteger( ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ITEMTYPE ); - } - else if( ing instanceof ArrayList ) - { - // Cast to array list - ArrayList ingList = (ArrayList)ing; - - // Set type and count - ingData.setInteger( ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ARRAYTYPE ); - ingData.setInteger( ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE, ingList.size() ); - - // Add each item - for( int i = 0; i < ingList.size(); ++i ) - { - // Create a new tag - NBTTagCompound subTag = new NBTTagCompound(); - - // Write the item - ingList.get( i ).writeToNBT( subTag ); - - // Add the sub tag - ingData.setTag( ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + i, subTag ); - } - - } - - // Write into the main data tag - if( !ingData.hasNoTags() ) - { - data.setTag( ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + index, ingData ); - } - - } - - // Write the result - NBTTagCompound outData = new NBTTagCompound(); - this.result.writeToNBT( outData ); - data.setTag( ArcaneCraftingPattern.NBTKEY_RESULT, outData ); - - return data; - } - - // Custom equality so AE may see the same recipe as the same pattern - // Allows AE to parallel if multiple assemblers with this recipe are available - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ArcaneCraftingPattern that = (ArcaneCraftingPattern) o; - - if (isValid != that.isValid) return false; - if (!Objects.equals(result, that.result)) return false; - if (!Arrays.equals(ingredientsAE, that.ingredientsAE)) return false; - return Arrays.equals(allResults, that.allResults); - } - - @Override - public int hashCode() { - int hash = result != null ? result.hashCode() : 0; - hash = 31 * hash + Arrays.hashCode(ingredientsAE); - hash = 31 * hash + Arrays.hashCode(allResults); - hash = 31 * hash + (isValid ? 1 : 0); - return hash; - } - +public class ArcaneCraftingPattern implements ICraftingPatternDetails { + private static final String NBTKEY_INGREDIENT_NUM = "input#", + NBTKEY_RESULT = "output", + NBTKEY_INGREDIENT_TYPE = "ThE_crafting_type", + NBTKEY_ARRAY_SIZE = "size"; + private static final int NBTKEY_ARRAYTYPE = 2, NBTKEY_ITEMTYPE = 1; + + private static final int GRID_SIZE = 9; + + /** + * Aspects required. + */ + protected AspectList aspects; + + /** + * Ingredients. + */ + protected Object[] ingredients = new Object[ArcaneCraftingPattern.GRID_SIZE]; + + /** + * Crafting result. + */ + protected IAEItemStack result; + + /** + * The knowledge core this pattern belongs to. + */ + protected ItemStack knowledgeCoreHost; + + /** + * Cached array of required aspects + */ + protected Aspect[] cachedAspects; + + /** + * Ingredients as AE itemstacks. + */ + protected IAEItemStack[] ingredientsAE = null; + + /** + * List of all output items, results + containers + */ + protected IAEItemStack[] allResults = null; + + /** + * True if the recipe is valid. + */ + protected boolean isValid = false; + + /** + * + * @param knowledgeCore + * @param aspects + * @param craftingResult + * @param craftingIngredients + */ + public ArcaneCraftingPattern( + final ItemStack knowledgeCore, + final AspectList aspects, + final ItemStack craftingResult, + final Object[] craftingIngredients) { + // Set the core + this.knowledgeCoreHost = knowledgeCore; + + // Set the aspects + this.aspects = aspects.copy(); + + // Set the result + this.result = AEApi.instance().storage().createItemStack(craftingResult); + + // Set the ingredients + boolean hasAtLeastOneValidInput = false; + for (int index = 0; ((index < this.ingredients.length) && (index < craftingIngredients.length)); ++index) { + // Get the next ingredient + Object nextIng = craftingIngredients[index]; + + // Add to the ingredients if not null + if (nextIng != null) { + this.ingredients[index] = nextIng; + hasAtLeastOneValidInput = true; + } + } + + // Set validity + this.setPatternValidity((this.aspects.size() > 0) && (this.result != null) && hasAtLeastOneValidInput); + + // Ensure AE result and ingredients are populated + this.setupAEResults(); + } + + /** + * + * @param knowledgeCore + * @param data + */ + public ArcaneCraftingPattern(@Nullable final ItemStack knowledgeCore, final NBTTagCompound data) { + // Set the host + this.knowledgeCoreHost = knowledgeCore; + + // Create the aspect list + this.aspects = new AspectList(); + + // Read the data + this.readFromNBT(data); + + // Ensure AE result and ingredients are populated + this.setupAEResults(); + } + + /** + * Checks if one item can be substituted for another. + * + * @param target + * @param input + * @return + */ + private static boolean canSubItem(final ItemStack target, final ItemStack input) { + // Do the itemstacks directly match? + if (ItemStack.areItemStacksEqual(target, input)) { + return true; + } + + if (target.getItem() != input.getItem()) { + // Mismatched items + return false; + } + // Items match + + // NBT data present? + if (target.hasTagCompound()) { + // Do the tags match? + if (!ThaumcraftApiHelper.areItemStackTagsEqualForCrafting(input, target)) { + // Tags do not match + return false; + } + // Tags equal + } + + // Does the item damage mean something besides damaged? + if (!target.isItemStackDamageable()) { + return ((target.getItemDamage() == OreDictionary.WILDCARD_VALUE) + || (target.getItemDamage() == input.getItemDamage())); + } + + // Items match, has no tag or tags match, and damage is damage + return true; + } + + /** + * Checks if the input item can be substituted for the target + * + * @param target + * @param input + * @return + */ + public static boolean canSubstitueFor(final Object target, final ItemStack input) { + // What type is the ingredient? + if (target instanceof ItemStack) { + // Cast to itemstack + return ArcaneCraftingPattern.canSubItem((ItemStack) target, input); + } else if (target instanceof ArrayList) { + // Cast to list + ArrayList items = (ArrayList) target; + + // Check each item + for (ItemStack item : items) { + if (ArcaneCraftingPattern.canSubItem(item, input)) { + return true; + } + } + } + + // Unknown type + return false; + } + + /** + * Converts the itemlist into it's AE counterpart + */ + private void setupAEIngredientList() { + this.ingredientsAE = new AEItemStack[ArcaneCraftingPattern.GRID_SIZE]; + + for (int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; ++index) { + // Get the ingredient + Object ing = this.ingredients[index]; + + // Check for null + if (ing == null) { + this.ingredientsAE[index] = null; + continue; + } + + // Itemstack? + if (ing instanceof ItemStack) { + this.ingredientsAE[index] = AEApi.instance().storage().createItemStack((ItemStack) ing); + } + // Array + else if (ing instanceof ArrayList) { + // Use the first ingredient + ItemStack firstIng = ((ArrayList) ing).get(0); + + this.ingredientsAE[index] = AEApi.instance().storage().createItemStack(firstIng); + } + } + } + + /** + * Sets up all results, including container items. + */ + private void setupAEResults() { + // Ensure the ingredient list is made + if (this.ingredientsAE == null) { + this.setupAEIngredientList(); + } + + ArrayList results = new ArrayList(); + + // Add any container items + for (IAEItemStack stack : this.ingredientsAE) { + if (stack == null) { + continue; + } + + // Container? + if (stack.getItem().hasContainerItem(stack.getItemStack())) { + results.add(AEApi.instance() + .storage() + .createItemStack(stack.getItem().getContainerItem(stack.getItemStack()))); + } + + // Multiplier? + else if (stack.getStackSize() > 1) { + results.add(stack.copy().setStackSize(stack.getStackSize() - 1)); + } + // Primordial Pearl? + else if ((stack.getItem() instanceof ItemEldritchObject) && (stack.getItemDamage() == 3)) { + results.add(stack); + } + } + + // Add result + results.add(this.result); + + // Set the outputs + this.allResults = results.toArray(new IAEItemStack[results.size()]); + } + + protected void setPatternValidity(final boolean valid) { + // Set + this.isValid = valid; + + if (!valid) { + // Clear all items. + this.result = null; + this.ingredientsAE = null; + for (int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; ++index) { + this.ingredients[index] = null; + } + + // Clear aspects + this.aspects = new AspectList(); + this.cachedAspects = null; + } + } + + @Override + public boolean canSubstitute() { + return true; + } + + /** + * This includes container items. + * + * @return + */ + public IAEItemStack[] getAllResults() { + if (this.allResults == null) { + this.setupAEResults(); + } + return this.allResults; + } + + public void updateInventory(InventoryCrafting table) { + if (this.ingredientsAE == null) this.ingredientsAE = new AEItemStack[ArcaneCraftingPattern.GRID_SIZE]; + boolean inventoryUnchanged = true; + for (int i = 0; i < 9; ++i) { + ItemStack s = table.getStackInSlot(i); + if (s == null) { + if (ingredientsAE[i] == null) continue; + inventoryUnchanged = false; + ingredientsAE[i] = null; + } else { + AEItemStack aestack = (AEItemStack) AEApi.instance().storage().createItemStack(s); + if (ingredientsAE[i] == null || ingredientsAE[i].hashCode() != aestack.hashCode()) { + ingredientsAE[i] = aestack; + inventoryUnchanged = false; + } + } + } + if (!inventoryUnchanged) setupAEResults(); + } + + /** + * Returns the aspect cost for the specified aspect. + * + * @return + */ + public int getAspectCost(final Aspect aspect) { + return this.aspects.getAmount(aspect); + } + + /** + * Returns a cached array of the required aspects for this pattern. + * + * @return + */ + public Aspect[] getCachedAspects() { + if (this.cachedAspects == null) { + this.cachedAspects = this.aspects.getAspects(); + } + + return this.cachedAspects; + } + + @Override + public IAEItemStack[] getCondensedInputs() { + // Create a temp array + ArrayList cond = new ArrayList(); + + if (this.ingredientsAE == null) { + this.setupAEIngredientList(); + } + + // Add non-null ingredients + for (int index = 0; index < this.ingredientsAE.length; index++) { + if (this.ingredientsAE[index] != null) { + cond.add(this.ingredientsAE[index]); + } + } + + // Return the ingredients + return cond.toArray(new IAEItemStack[cond.size()]); + } + + @Override + public IAEItemStack[] getCondensedOutputs() { + // Is the result null? + if (this.result == null) { + // Return empty array + return new IAEItemStack[0]; + } + + return new IAEItemStack[] {this.result}; + } + + @Override + public IAEItemStack[] getInputs() { + if (this.ingredientsAE == null) { + this.setupAEIngredientList(); + } + + return this.ingredientsAE; + } + + @Override + public ItemStack getOutput(final InventoryCrafting craftingInv, final World world) { + return this.result.getItemStack(); + } + + @Override + public IAEItemStack[] getOutputs() { + return new IAEItemStack[] {this.result}; + } + + @Override + public ItemStack getPattern() { + return this.knowledgeCoreHost; + } + + @Override + public int getPriority() { + return 0; + } + + /** + * Returns the result of the craft. + * + * @return + */ + public IAEItemStack getResult() { + return this.result; + } + + @Override + public boolean isCraftable() { + // Returning false prevents substitutions. + return true; + } + + /** + * True if the recipe is valid. + * + * @return + */ + public boolean isPatternValid() { + return this.isValid; + } + + @Override + public boolean isValidItemForSlot(final int slotIndex, final ItemStack input, final World world) { + // Get the ingredient + Object ing = this.ingredients[slotIndex]; + + // Ensure nothing is null + if ((ing == null) || (input == null) || (input.getItem() == null)) { + // Null detected + return false; + } + + return ArcaneCraftingPattern.canSubstitueFor(ing, input); + } + + public void readFromNBT(final NBTTagCompound data) { + // Sanity check. + if (data == null) { + return; + } + + // Assume the recipe is valid + this.setPatternValidity(true); + + // Read the aspects + this.aspects.readFromNBT(data); + + // Validate aspects + if (this.aspects.size() == 0) { + this.setPatternValidity(false); + return; + } + + // Read ingredients + for (int slotNumber = 0; (this.isValid && (slotNumber < ArcaneCraftingPattern.GRID_SIZE)); slotNumber++) { + // Is there an ingredient for this slot? + if (!data.hasKey(ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + slotNumber)) { + // No ingredient + continue; + } + + // Get the tag + NBTTagCompound ingData = data.getCompoundTag(ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + slotNumber); + + // Validate the tag + if ((ingData == null) || (ingData.hasNoTags())) { + // Invalid tag + this.setPatternValidity(false); + return; + } + + // Does the tag have a type? + if (!ingData.hasKey(ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE)) { + // Old AE tag + try { + // Load the AE stack + IAEItemStack ingAE = AEItemStack.loadItemStackFromNBT(ingData); + + // Null check + if (ingAE == null) { + this.setPatternValidity(false); + return; + } + + // Get the item stack + ItemStack ing = ingAE.getItemStack(); + + // Null check + if (ing == null) { + this.setPatternValidity(false); + return; + } + + // Set the stack + this.ingredients[slotNumber] = ing; + } catch (Exception e) { + // Recipe is invalid. + this.setPatternValidity(false); + return; + } + continue; + } + + // What type is the tag? + int type = ingData.getInteger(ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE); + + // Itemstack + if (type == ArcaneCraftingPattern.NBTKEY_ITEMTYPE) { + try { + // Get the item + ItemStack ing = ItemStack.loadItemStackFromNBT(ingData); + + // Null check + if (ing == null) { + this.setPatternValidity(false); + return; + } + + // Set the stack + this.ingredients[slotNumber] = ing; + } catch (Exception e) { + this.setPatternValidity(false); + return; + } + } + // Array + else if (type == ArcaneCraftingPattern.NBTKEY_ARRAYTYPE) { + // Create the list + ArrayList itemList = new ArrayList(); + + // Has count? + if (!ingData.hasKey(ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE)) { + this.setPatternValidity(false); + return; + } + + // Get the count + int count = ingData.getInteger(ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE); + + for (int arrayIndex = 0; arrayIndex < count; ++arrayIndex) { + // Get the subtag + NBTTagCompound subTag = + ingData.getCompoundTag(ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + arrayIndex); + + if ((subTag == null) || (subTag.hasNoTags())) { + // Ignore invalid entry + continue; + } + + try { + // Load the stack + ItemStack stack = ItemStack.loadItemStackFromNBT(subTag); + if (stack != null) { + itemList.add(stack); + } + } catch (Exception e) { + // Ignore invalid items + } + } + + // Were any items loaded? + if (itemList.size() == 0) { + this.setPatternValidity(false); + return; + } + + // Set the ingredient to the list + this.ingredients[slotNumber] = itemList; + } else { + // Unknown type + this.setPatternValidity(false); + return; + } + } + + // Read the result + if (data.hasKey(ArcaneCraftingPattern.NBTKEY_RESULT)) { + // Get the result + NBTTagCompound resultData = data.getCompoundTag(ArcaneCraftingPattern.NBTKEY_RESULT); + + // Validate + if ((resultData == null) || (resultData.hasNoTags())) { + this.setPatternValidity(false); + return; + } + + try { + // Get result item + this.result = AEItemStack.loadItemStackFromNBT(resultData); + + // Check item + if (this.result == null) { + this.setPatternValidity(false); + return; + } + } catch (Exception e) { + this.setPatternValidity(false); + return; + } + } + } + + /** + * Sets the knowledge core. + * + * @param knowledgeCore + */ + public void setKnowledgeCore(final ItemStack knowledgeCore) { + this.knowledgeCoreHost = knowledgeCore; + } + + @Override + public void setPriority(final int priority) { + // Ignored. + } + + /** + * Write's the pattern to the NBT tag. + * + * @param data + * @return + */ + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + // Write the aspects + this.aspects.writeToNBT(data); + + // Write the ingredients + for (int index = 0; index < ArcaneCraftingPattern.GRID_SIZE; index++) { + // Ensure it is not null + if (this.ingredients[index] == null) { + continue; + } + + // Get the ingredient + Object ing = this.ingredients[index]; + + // Create the tag + NBTTagCompound ingData = new NBTTagCompound(); + + // What type is the ingredient? + if (ing instanceof IAEItemStack) { + // Write the ingredient data + ((IAEItemStack) ing).getItemStack().writeToNBT(ingData); + ingData.setInteger(ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ITEMTYPE); + } else if (ing instanceof ItemStack) { + ((ItemStack) ing).writeToNBT(ingData); + ingData.setInteger(ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ITEMTYPE); + } else if (ing instanceof ArrayList) { + // Cast to array list + ArrayList ingList = (ArrayList) ing; + + // Set type and count + ingData.setInteger( + ArcaneCraftingPattern.NBTKEY_INGREDIENT_TYPE, ArcaneCraftingPattern.NBTKEY_ARRAYTYPE); + ingData.setInteger(ArcaneCraftingPattern.NBTKEY_ARRAY_SIZE, ingList.size()); + + // Add each item + for (int i = 0; i < ingList.size(); ++i) { + // Create a new tag + NBTTagCompound subTag = new NBTTagCompound(); + + // Write the item + ingList.get(i).writeToNBT(subTag); + + // Add the sub tag + ingData.setTag(ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + i, subTag); + } + } + + // Write into the main data tag + if (!ingData.hasNoTags()) { + data.setTag(ArcaneCraftingPattern.NBTKEY_INGREDIENT_NUM + index, ingData); + } + } + + // Write the result + NBTTagCompound outData = new NBTTagCompound(); + this.result.writeToNBT(outData); + data.setTag(ArcaneCraftingPattern.NBTKEY_RESULT, outData); + + return data; + } + + // Custom equality so AE may see the same recipe as the same pattern + // Allows AE to parallel if multiple assemblers with this recipe are available + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ArcaneCraftingPattern that = (ArcaneCraftingPattern) o; + + if (isValid != that.isValid) return false; + if (!Objects.equals(result, that.result)) return false; + if (!Arrays.equals(ingredientsAE, that.ingredientsAE)) return false; + return Arrays.equals(allResults, that.allResults); + } + + @Override + public int hashCode() { + int hash = result != null ? result.hashCode() : 0; + hash = 31 * hash + Arrays.hashCode(ingredientsAE); + hash = 31 * hash + Arrays.hashCode(allResults); + hash = 31 * hash + (isValid ? 1 : 0); + return hash; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/ArcaneRecipeHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/ArcaneRecipeHelper.java index 09d859d8..f6fe0dae 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/ArcaneRecipeHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/ArcaneRecipeHelper.java @@ -8,126 +8,121 @@ import thaumcraft.api.aspects.AspectList; import thaumcraft.api.crafting.IArcaneRecipe; import thaumcraft.common.tiles.TileMagicWorkbench; -public class ArcaneRecipeHelper -{ - /** - * Singleton. - */ - public static final ArcaneRecipeHelper INSTANCE = new ArcaneRecipeHelper(); +public class ArcaneRecipeHelper { + /** + * Singleton. + */ + public static final ArcaneRecipeHelper INSTANCE = new ArcaneRecipeHelper(); - /** - * Private constructor. - */ - private ArcaneRecipeHelper() - { - // Intentionally Empty - } + /** + * Private constructor. + */ + private ArcaneRecipeHelper() { + // Intentionally Empty + } - /** - * Creates a workbench with its crafting grid set to match the source - * inventory. - * - * @param sourceInventory - * @param firstSlotIndex - * @param gridSize - * @return - */ - public TileMagicWorkbench createBridgeInventory( final IInventory sourceInventory, final int firstSlotIndex, final int gridSize ) - { - // Create a new workbench tile - TileMagicWorkbench workbenchTile = new TileMagicWorkbench(); + /** + * Creates a workbench with its crafting grid set to match the source + * inventory. + * + * @param sourceInventory + * @param firstSlotIndex + * @param gridSize + * @return + */ + public TileMagicWorkbench createBridgeInventory( + final IInventory sourceInventory, final int firstSlotIndex, final int gridSize) { + // Create a new workbench tile + TileMagicWorkbench workbenchTile = new TileMagicWorkbench(); - // Load the workbench inventory - for( int slotIndex = 0; slotIndex < gridSize; slotIndex++ ) - { - // Set the slot - workbenchTile.setInventorySlotContentsSoftly( slotIndex, sourceInventory.getStackInSlot( slotIndex + firstSlotIndex ) ); - } + // Load the workbench inventory + for (int slotIndex = 0; slotIndex < gridSize; slotIndex++) { + // Set the slot + workbenchTile.setInventorySlotContentsSoftly( + slotIndex, sourceInventory.getStackInSlot(slotIndex + firstSlotIndex)); + } - return workbenchTile; - } + return workbenchTile; + } - /** - * Searches for a matching arcane crafting recipe - * - * @param sourceInventory - * @param firstSlotIndex - * @param gridSize - * @param player - * @return - */ - public IArcaneRecipe findMatchingArcaneResult( final IInventory sourceInventory, final int firstSlotIndex, final int gridSize, - final EntityPlayer player ) - { - // Create a the workbench - TileMagicWorkbench workbenchTile = this.createBridgeInventory( sourceInventory, firstSlotIndex, gridSize ); + /** + * Searches for a matching arcane crafting recipe + * + * @param sourceInventory + * @param firstSlotIndex + * @param gridSize + * @param player + * @return + */ + public IArcaneRecipe findMatchingArcaneResult( + final IInventory sourceInventory, final int firstSlotIndex, final int gridSize, final EntityPlayer player) { + // Create a the workbench + TileMagicWorkbench workbenchTile = this.createBridgeInventory(sourceInventory, firstSlotIndex, gridSize); - IArcaneRecipe arcaneRecipe = null; + IArcaneRecipe arcaneRecipe = null; - // Loop through all arcane crafting recipes - for( Object currentRecipe : ThaumcraftApi.getCraftingRecipes() ) - { - // Is the current recipe an arcane one? - if( currentRecipe instanceof IArcaneRecipe ) - { - // Does the recipe have a match? - if( ( (IArcaneRecipe)currentRecipe ).matches( workbenchTile, player.worldObj, player ) ) - { - // Found a match, stop searching - arcaneRecipe = (IArcaneRecipe)currentRecipe; + // Loop through all arcane crafting recipes + for (Object currentRecipe : ThaumcraftApi.getCraftingRecipes()) { + // Is the current recipe an arcane one? + if (currentRecipe instanceof IArcaneRecipe) { + // Does the recipe have a match? + if (((IArcaneRecipe) currentRecipe).matches(workbenchTile, player.worldObj, player)) { + // Found a match, stop searching + arcaneRecipe = (IArcaneRecipe) currentRecipe; - break; - } - } - } + break; + } + } + } - // Return the result - return arcaneRecipe; - } + // Return the result + return arcaneRecipe; + } - /** - * Gets the base aspect cost of this recipe. Can return null. - * - * @param sourceInventory - * @param firstSlotIndex - * @param gridSize - * @param recipe - * @return - */ - public AspectList getRecipeAspectCost( final IInventory sourceInventory, final int firstSlotIndex, final int gridSize, - final IArcaneRecipe recipe ) - { - // Ensure the recipe is valid - if( recipe == null ) - { - return null; - } + /** + * Gets the base aspect cost of this recipe. Can return null. + * + * @param sourceInventory + * @param firstSlotIndex + * @param gridSize + * @param recipe + * @return + */ + public AspectList getRecipeAspectCost( + final IInventory sourceInventory, + final int firstSlotIndex, + final int gridSize, + final IArcaneRecipe recipe) { + // Ensure the recipe is valid + if (recipe == null) { + return null; + } - AspectList al = recipe.getAspects( this.createBridgeInventory( sourceInventory, firstSlotIndex, gridSize ) ); - // some mods (e.g. Gadomancy) return null on inventory check - if (al == null) - al = recipe.getAspects(); - return al; - } + AspectList al = recipe.getAspects(this.createBridgeInventory(sourceInventory, firstSlotIndex, gridSize)); + // some mods (e.g. Gadomancy) return null on inventory check + if (al == null) al = recipe.getAspects(); + return al; + } - /** - * Gets the item that results from this recipe. Can be null. - * - * @param sourceInventory - * @param firstSlotIndex - * @param gridSize - * @param recipe - * @return - */ - public ItemStack getRecipeOutput( final IInventory sourceInventory, final int firstSlotIndex, final int gridSize, final IArcaneRecipe recipe ) - { - // Ensure the recipe is valid - if( recipe == null ) - { - return null; - } - - return recipe.getCraftingResult( this.createBridgeInventory( sourceInventory, firstSlotIndex, gridSize ) ); - } + /** + * Gets the item that results from this recipe. Can be null. + * + * @param sourceInventory + * @param firstSlotIndex + * @param gridSize + * @param recipe + * @return + */ + public ItemStack getRecipeOutput( + final IInventory sourceInventory, + final int firstSlotIndex, + final int gridSize, + final IArcaneRecipe recipe) { + // Ensure the recipe is valid + if (recipe == null) { + return null; + } + return recipe.getCraftingResult(this.createBridgeInventory(sourceInventory, firstSlotIndex, gridSize)); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/AspectHooks.java b/src/main/java/thaumicenergistics/common/integration/tc/AspectHooks.java index 1bbbee61..4de0e48f 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/AspectHooks.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/AspectHooks.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.integration.tc; -import java.util.HashMap; import cpw.mods.fml.common.ModContainer; +import java.util.HashMap; import thaumcraft.api.aspects.Aspect; /** @@ -10,27 +10,24 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public class AspectHooks -{ +public class AspectHooks { - /** - * TODO: Make private and provide wrapper for name or unknown - * Maps an aspect -> mod. - */ - public static final HashMap aspectToMod = new HashMap(); + /** + * TODO: Make private and provide wrapper for name or unknown + * Maps an aspect -> mod. + */ + public static final HashMap aspectToMod = new HashMap(); - /** - * Called from the constructor. - * - * @param aspect - */ - public static void hook_AspectInit( final Aspect aspect ) - { - // Get the mod - ModContainer mod = cpw.mods.fml.common.Loader.instance().activeModContainer(); - - // Add to the map - aspectToMod.put( aspect, mod ); - } + /** + * Called from the constructor. + * + * @param aspect + */ + public static void hook_AspectInit(final Aspect aspect) { + // Get the mod + ModContainer mod = cpw.mods.fml.common.Loader.instance().activeModContainer(); + // Add to the map + aspectToMod.put(aspect, mod); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/DigiVisSourceData.java b/src/main/java/thaumicenergistics/common/integration/tc/DigiVisSourceData.java index f87911d7..bca5276e 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/DigiVisSourceData.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/DigiVisSourceData.java @@ -1,11 +1,11 @@ package thaumicenergistics.common.integration.tc; -import java.lang.ref.WeakReference; -import javax.annotation.Nonnull; import appeng.api.networking.IGrid; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.util.DimensionalCoord; +import java.lang.ref.WeakReference; +import javax.annotation.Nonnull; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -14,376 +14,337 @@ import net.minecraftforge.common.util.ForgeDirection; import thaumicenergistics.api.grid.IDigiVisSource; import thaumicenergistics.common.registries.ThEStrings; -public class DigiVisSourceData -{ - private static final String NBT_KEY_HAS_DATA = "hasData"; - private static final String NBT_KEY_DATA = "data"; - private static final String NBT_KEY_UID = "uid"; +public class DigiVisSourceData { + private static final String NBT_KEY_HAS_DATA = "hasData"; + private static final String NBT_KEY_DATA = "data"; + private static final String NBT_KEY_UID = "uid"; - public static final String SOURCE_UNLOC_NAME = ThEStrings.Gui_DigiVisSource.getUnlocalized(); + public static final String SOURCE_UNLOC_NAME = ThEStrings.Gui_DigiVisSource.getUnlocalized(); - /** - * True if there is data. - */ - private boolean hasData = false; + /** + * True if there is data. + */ + private boolean hasData = false; - /** - * World the source is in. - */ - private int worldID; + /** + * World the source is in. + */ + private int worldID; - /** - * X position of the source. - */ - private int x; + /** + * X position of the source. + */ + private int x; - /** - * Y position of the source. - */ - private int y; + /** + * Y position of the source. + */ + private int y; - /** - * Z position of the source. - */ - private int z; + /** + * Z position of the source. + */ + private int z; - /** - * Side the part is attached to. - */ - private ForgeDirection side; + /** + * Side the part is attached to. + */ + private ForgeDirection side; - /** - * ID of the source. - */ - private long UID; + /** + * ID of the source. + */ + private long UID; - /** - * Cached reference to source. - */ - private WeakReference digiVisSource; + /** + * Cached reference to source. + */ + private WeakReference digiVisSource; - /** - * Creates the info, setting that there is no data - */ - public DigiVisSourceData() - { - this.clearData(); - } + /** + * Creates the info, setting that there is no data + */ + public DigiVisSourceData() { + this.clearData(); + } - /** - * Creates the data from a digivis source. - * - * @param digiVisSource - */ - public DigiVisSourceData( final IDigiVisSource digiVisSource ) - { - // Init the data fields. - this.clearData(); + /** + * Creates the data from a digivis source. + * + * @param digiVisSource + */ + public DigiVisSourceData(final IDigiVisSource digiVisSource) { + // Init the data fields. + this.clearData(); - // Ensure there is a source. - if( digiVisSource == null ) - { - // No source - return; - } + // Ensure there is a source. + if (digiVisSource == null) { + // No source + return; + } - // Get the source location - DimensionalCoord sourceLocation = digiVisSource.getLocation(); + // Get the source location + DimensionalCoord sourceLocation = digiVisSource.getLocation(); - // Get the world id - this.worldID = sourceLocation.getWorld().provider.dimensionId; + // Get the world id + this.worldID = sourceLocation.getWorld().provider.dimensionId; - // Get the x,y,z - this.x = sourceLocation.x; - this.y = sourceLocation.y; - this.z = sourceLocation.z; + // Get the x,y,z + this.x = sourceLocation.x; + this.y = sourceLocation.y; + this.z = sourceLocation.z; - // Get the side - this.side = digiVisSource.getSide(); + // Get the side + this.side = digiVisSource.getSide(); - // Get the UID - this.UID = digiVisSource.getUID(); + // Get the UID + this.UID = digiVisSource.getUID(); - // Set that we have data - this.hasData = true; - } + // Set that we have data + this.hasData = true; + } - /** - * Gets the vis source. - * - * @return - */ - private IDigiVisSource getSource( final boolean forceUpdate ) - { - // Do we have any data to load from? - if( this.hasData ) - { - // Do we have an source cached? - IDigiVisSource vInt = this.digiVisSource.get(); - if( forceUpdate || ( vInt == null ) ) - { - // Attempt to get the source - this.refreshCache(); + /** + * Gets the vis source. + * + * @return + */ + private IDigiVisSource getSource(final boolean forceUpdate) { + // Do we have any data to load from? + if (this.hasData) { + // Do we have an source cached? + IDigiVisSource vInt = this.digiVisSource.get(); + if (forceUpdate || (vInt == null)) { + // Attempt to get the source + this.refreshCache(); - // Return it if cached - return this.digiVisSource.get(); - } + // Return it if cached + return this.digiVisSource.get(); + } - // Return the cached - return vInt; + // Return the cached + return vInt; + } - } + // Nothing to load + return null; + } - // Nothing to load - return null; - } + private void refreshCache() { + // Clear the reference + this.digiVisSource.clear(); + IDigiVisSource visSource = null; - private void refreshCache() - { - // Clear the reference - this.digiVisSource.clear(); - IDigiVisSource visSource = null; + try { + // Get the world + World world = DimensionManager.getWorld(this.worldID); - try - { - // Get the world - World world = DimensionManager.getWorld( this.worldID ); + // Ensure the world is not null + if (world == null) { + return; + } - // Ensure the world is not null - if( world == null ) - { - return; - } + // Get the tile + TileEntity tile = world.getTileEntity(this.x, this.y, this.z); - // Get the tile - TileEntity tile = world.getTileEntity( this.x, this.y, this.z ); + // Ensure we got a tile + if (tile == null) { + return; + } - // Ensure we got a tile - if( tile == null ) - { - return; - } + // Is the source a block? + if (this.side.equals(ForgeDirection.UNKNOWN)) { + // Ensure the block is a source + if (!(tile instanceof IDigiVisSource)) { + return; + } - // Is the source a block? - if( this.side.equals( ForgeDirection.UNKNOWN ) ) - { - // Ensure the block is a source - if( !( tile instanceof IDigiVisSource ) ) - { - return; - } + // Get the source + visSource = (IDigiVisSource) tile; + } else { + // Ensure the tile is a part host + if (!(tile instanceof IPartHost)) { + return; + } - // Get the source - visSource = (IDigiVisSource)tile; - } - else - { - // Ensure the tile is a part host - if( !( tile instanceof IPartHost ) ) - { - return; - } + // Get the part from the host + IPart part = ((IPartHost) tile).getPart(this.side); - // Get the part from the host - IPart part = ( (IPartHost)tile ).getPart( this.side ); + // Ensure we got the part, and it is a vis source + if (!(part instanceof IDigiVisSource)) { + return; + } - // Ensure we got the part, and it is a vis source - if( !( part instanceof IDigiVisSource ) ) - { - return; - } + // Cast to the source + visSource = (IDigiVisSource) part; + } - // Cast to the source - visSource = (IDigiVisSource)part; - } + // Check the UID + if (visSource.getUID() == this.UID) { + // Set the source + this.digiVisSource = new WeakReference(visSource); + } + } catch (Exception e) { + } + } - // Check the UID - if( visSource.getUID() == this.UID ) - { - // Set the source - this.digiVisSource = new WeakReference( visSource ); - } - } - catch( Exception e ) - { - } - } + private IDigiVisSource tryGetSource(@Nonnull final IGrid destinationGrid, final boolean forceUpdate) { + IDigiVisSource source = null; + try { + // Get this source + source = this.getSource(forceUpdate); + if (source != null) { + // Get the source grid + IGrid sourceGrid = source.getGrid(); - private IDigiVisSource tryGetSource( @Nonnull final IGrid destinationGrid, final boolean forceUpdate ) - { - IDigiVisSource source = null; - try - { - // Get this source - source = this.getSource( forceUpdate ); - if( source != null ) - { - // Get the source grid - IGrid sourceGrid = source.getGrid(); + // Do the grids NOT match? + if ((sourceGrid == null) || !destinationGrid.equals(sourceGrid)) { + // Grid mismatch + source = null; + } + } - // Do the grids NOT match? - if( ( sourceGrid == null ) || !destinationGrid.equals( sourceGrid ) ) - { - // Grid mismatch - source = null; - } - } + } catch (Exception e) { + } - } - catch( Exception e ) - { - } + return source; + } - return source; - } + /** + * Erases all data + */ + public void clearData() { + this.hasData = false; + this.worldID = -1; + this.x = 0; + this.y = 0; + this.z = 0; + this.side = ForgeDirection.UNKNOWN; + this.UID = 0; + this.digiVisSource = new WeakReference(null); + } - /** - * Erases all data - */ - public void clearData() - { - this.hasData = false; - this.worldID = -1; - this.x = 0; - this.y = 0; - this.z = 0; - this.side = ForgeDirection.UNKNOWN; - this.UID = 0; - this.digiVisSource = new WeakReference( null ); - } + /** + * True if there is data. + * + * @return + */ + public boolean hasSourceData() { + return this.hasData; + } - /** - * True if there is data. - * - * @return - */ - public boolean hasSourceData() - { - return this.hasData; - } + /** + * Reads the info directly from the tag. + * + * @param tag + */ + public void readFromNBT(final NBTTagCompound tag) { + // Clear all existing data + this.clearData(); - /** - * Reads the info directly from the tag. - * - * @param tag - */ - public void readFromNBT( final NBTTagCompound tag ) - { - // Clear all existing data - this.clearData(); + // Ensure the tag is not null + if (tag == null) { + return; + } - // Ensure the tag is not null - if( tag == null ) - { - return; - } + // Is there data present in the tag? + if (tag.getBoolean(DigiVisSourceData.NBT_KEY_HAS_DATA)) { + // Ensure the required tags are present + if (!tag.hasKey(DigiVisSourceData.NBT_KEY_UID) || !tag.hasKey(DigiVisSourceData.NBT_KEY_DATA)) { + // Missing required data + return; + } - // Is there data present in the tag? - if( tag.getBoolean( DigiVisSourceData.NBT_KEY_HAS_DATA ) ) - { - // Ensure the required tags are present - if( !tag.hasKey( DigiVisSourceData.NBT_KEY_UID ) || !tag.hasKey( DigiVisSourceData.NBT_KEY_DATA ) ) - { - // Missing required data - return; - } + // Load the info + int[] info = tag.getIntArray(DigiVisSourceData.NBT_KEY_DATA); - // Load the info - int[] info = tag.getIntArray( DigiVisSourceData.NBT_KEY_DATA ); + // Ensure the info contains the expected number of items + if (info.length < 5) { + // Invalid number of items + return; + } - // Ensure the info contains the expected number of items - if( info.length < 5 ) - { - // Invalid number of items - return; - } + // Set each item + this.worldID = info[0]; + this.x = info[1]; + this.y = info[2]; + this.z = info[3]; + this.side = ForgeDirection.getOrientation(info[4]); - // Set each item - this.worldID = info[0]; - this.x = info[1]; - this.y = info[2]; - this.z = info[3]; - this.side = ForgeDirection.getOrientation( info[4] ); + // Read the uid + this.UID = tag.getLong(DigiVisSourceData.NBT_KEY_UID); - // Read the uid - this.UID = tag.getLong( DigiVisSourceData.NBT_KEY_UID ); + // Mark there is data + this.hasData = true; + } + } - // Mark there is data - this.hasData = true; - } - } + /** + * Reads the info from the data tag. + * + * @param data + * @param name + */ + public void readFromNBT(final NBTTagCompound data, final String name) { + this.readFromNBT(data.getCompoundTag(name)); + } - /** - * Reads the info from the data tag. - * - * @param data - * @param name - */ - public void readFromNBT( final NBTTagCompound data, final String name ) - { - this.readFromNBT( data.getCompoundTag( name ) ); - } + /** + * Verifies that the source exists, is active, and that the + * source and destination grid's are the same. + * + * @param destinationGrid + * + * @return Return's the source if valid, null otherwise. + */ + public IDigiVisSource tryGetSource(final IGrid destinationGrid) { + IDigiVisSource source = null; - /** - * Verifies that the source exists, is active, and that the - * source and destination grid's are the same. - * - * @param destinationGrid - * - * @return Return's the source if valid, null otherwise. - */ - public IDigiVisSource tryGetSource( final IGrid destinationGrid ) - { - IDigiVisSource source = null; + // Ensure the destination grid is not null + if (destinationGrid != null) { + // Get the cached source + source = this.tryGetSource(destinationGrid, false); + if (source == null) { + // Force a refresh + source = this.tryGetSource(destinationGrid, true); + } + } + return source; + } - // Ensure the destination grid is not null - if( destinationGrid != null ) - { - // Get the cached source - source = this.tryGetSource( destinationGrid, false ); - if( source == null ) - { - // Force a refresh - source = this.tryGetSource( destinationGrid, true ); - } - } - return source; - } + /** + * Creates a new NBT tag and writes the data into it + * + * @return + */ + public NBTTagCompound writeToNBT() { + // Create the tag + NBTTagCompound tag = new NBTTagCompound(); - /** - * Creates a new NBT tag and writes the data into it - * - * @return - */ - public NBTTagCompound writeToNBT() - { - // Create the tag - NBTTagCompound tag = new NBTTagCompound(); + // Write if we have data + tag.setBoolean(DigiVisSourceData.NBT_KEY_HAS_DATA, this.hasData); - // Write if we have data - tag.setBoolean( DigiVisSourceData.NBT_KEY_HAS_DATA, this.hasData ); + if (this.hasData) { + // Write the data + tag.setIntArray( + DigiVisSourceData.NBT_KEY_DATA, + new int[] {this.worldID, this.x, this.y, this.z, this.side.ordinal()}); - if( this.hasData ) - { - // Write the data - tag.setIntArray( DigiVisSourceData.NBT_KEY_DATA, new int[] { this.worldID, this.x, this.y, this.z, this.side.ordinal() } ); + // Write the uid + tag.setLong(DigiVisSourceData.NBT_KEY_UID, this.UID); + } - // Write the uid - tag.setLong( DigiVisSourceData.NBT_KEY_UID, this.UID ); - } + return tag; + } - return tag; - } - - /** - * Writes the info into the data tag. - * - * @param data - * @param name - */ - public void writeToNBT( final NBTTagCompound data, final String name ) - { - // Write into the data tag - data.setTag( name, this.writeToNBT() ); - } + /** + * Writes the info into the data tag. + * + * @param data + * @param name + */ + public void writeToNBT(final NBTTagCompound data, final String name) { + // Write into the data tag + data.setTag(name, this.writeToNBT()); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaConversionHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaConversionHelper.java index bd316684..028d3170 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaConversionHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaConversionHelper.java @@ -14,116 +14,105 @@ import thaumicenergistics.common.storage.AspectStack; * @author Nividica * */ -public final class EssentiaConversionHelper -{ - /** - * Singleton - */ - public static final EssentiaConversionHelper INSTANCE = new EssentiaConversionHelper(); +public final class EssentiaConversionHelper { + /** + * Singleton + */ + public static final EssentiaConversionHelper INSTANCE = new EssentiaConversionHelper(); - /** - * Private constructor - */ - private EssentiaConversionHelper() - { + /** + * Private constructor + */ + private EssentiaConversionHelper() {} - } + /** + * Converts an AE fluid stack into an AspectStack. + * + * @param fluidStack + * @return Aspect stack if converted, null otherwise. + */ + public AspectStack convertAEFluidStackToAspectStack(final IAEFluidStack fluidStack) { + // Is the fluid an essentia gas? + if (fluidStack.getFluid() instanceof GaseousEssentia) { + // Create an aspect stack to match the fluid + return new AspectStack( + ((GaseousEssentia) fluidStack.getFluid()).getAspect(), + this.convertFluidAmountToEssentiaAmount(fluidStack.getStackSize())); + } - /** - * Converts an AE fluid stack into an AspectStack. - * - * @param fluidStack - * @return Aspect stack if converted, null otherwise. - */ - public AspectStack convertAEFluidStackToAspectStack( final IAEFluidStack fluidStack ) - { - // Is the fluid an essentia gas? - if( fluidStack.getFluid() instanceof GaseousEssentia ) - { - // Create an aspect stack to match the fluid - return new AspectStack( ( (GaseousEssentia)fluidStack.getFluid() ).getAspect(), this.convertFluidAmountToEssentiaAmount( fluidStack - .getStackSize() ) ); - } + return null; + } - return null; - } + /** + * Converts an essentia amount into a fluid amount(mb). + * + * @param essentiaAmount + * @return + */ + public long convertEssentiaAmountToFluidAmount(final long essentiaAmount) { + return essentiaAmount * ThaumicEnergistics.config.conversionMultiplier(); + } - /** - * Converts an essentia amount into a fluid amount(mb). - * - * @param essentiaAmount - * @return - */ - public long convertEssentiaAmountToFluidAmount( final long essentiaAmount ) - { - return essentiaAmount * ThaumicEnergistics.config.conversionMultiplier(); - } + /** + * Converts a fluid amount(mb) into an essentia amount. + * + * @param fluidAmount + * @return + */ + public long convertFluidAmountToEssentiaAmount(final long fluidAmount) { + return fluidAmount / ThaumicEnergistics.config.conversionMultiplier(); + } - /** - * Converts a fluid amount(mb) into an essentia amount. - * - * @param fluidAmount - * @return - */ - public long convertFluidAmountToEssentiaAmount( final long fluidAmount ) - { - return fluidAmount / ThaumicEnergistics.config.conversionMultiplier(); - } + /** + * Creates an AE fluid stack from the specified essentia gas. This will + * convert the specified amount from essentia units to fluid units(mb). + * + * @param Aspect + * @param essentiaAmount + * @return + */ + public IAEFluidStack createAEFluidStackInEssentiaUnits(final Aspect aspect, final long essentiaAmount) { + GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect(aspect); - /** - * Creates an AE fluid stack from the specified essentia gas. This will - * convert the specified amount from essentia units to fluid units(mb). - * - * @param Aspect - * @param essentiaAmount - * @return - */ - public IAEFluidStack createAEFluidStackInEssentiaUnits( final Aspect aspect, final long essentiaAmount ) - { - GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect( aspect ); + if (essentiaGas == null) { + return null; + } - if( essentiaGas == null ) - { - return null; - } + return this.createAEFluidStackInFluidUnits( + essentiaGas, this.convertEssentiaAmountToFluidAmount(essentiaAmount)); + } - return this.createAEFluidStackInFluidUnits( essentiaGas, this.convertEssentiaAmountToFluidAmount( essentiaAmount ) ); - } + /** + * Creates an AE fluid stack from the specified essentia gas. This will + * convert the specified amount from essentia units to fluid units(mb). + * + * @param essentiaGas + * @param essentiaAmount + * @return + */ + public IAEFluidStack createAEFluidStackInEssentiaUnits( + final GaseousEssentia essentiaGas, final long essentiaAmount) { + return this.createAEFluidStackInFluidUnits( + essentiaGas, this.convertEssentiaAmountToFluidAmount(essentiaAmount)); + } - /** - * Creates an AE fluid stack from the specified essentia gas. This will - * convert the specified amount from essentia units to fluid units(mb). - * - * @param essentiaGas - * @param essentiaAmount - * @return - */ - public IAEFluidStack createAEFluidStackInEssentiaUnits( final GaseousEssentia essentiaGas, final long essentiaAmount ) - { - return this.createAEFluidStackInFluidUnits( essentiaGas, this.convertEssentiaAmountToFluidAmount( essentiaAmount ) ); - } + /** + * Creates an AE fluid stack from the specified essentia gas with the amount + * specified. + * + * @param essentiaGas + * @param fluidAmount + * @return + */ + public IAEFluidStack createAEFluidStackInFluidUnits(final GaseousEssentia essentiaGas, final long fluidAmount) { + IAEFluidStack ret = null; + try { + ret = AEApi.instance().storage().createFluidStack(new FluidStack(essentiaGas, 1)); - /** - * Creates an AE fluid stack from the specified essentia gas with the amount - * specified. - * - * @param essentiaGas - * @param fluidAmount - * @return - */ - public IAEFluidStack createAEFluidStackInFluidUnits( final GaseousEssentia essentiaGas, final long fluidAmount ) - { - IAEFluidStack ret = null; - try - { - ret = AEApi.instance().storage().createFluidStack( new FluidStack( essentiaGas, 1 ) ); + ret.setStackSize(fluidAmount); + } catch (Exception e) { + } - ret.setStackSize( fluidAmount ); - } - catch( Exception e ) - { - } - - return ret; - } + return ret; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaItemContainerHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaItemContainerHelper.java index 6e30bca1..e5c27d9c 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaItemContainerHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaItemContainerHelper.java @@ -3,10 +3,10 @@ package thaumicenergistics.common.integration.tc; import com.djgiannuzz.thaumcraftneiplugin.items.ItemAspect; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Optional; -import org.apache.commons.lang3.tuple.ImmutablePair; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import org.apache.commons.lang3.tuple.ImmutablePair; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumcraft.api.aspects.IEssentiaContainerItem; @@ -33,917 +33,806 @@ import thaumicenergistics.common.tiles.abstraction.TileEVCBase; * @author Nividica * */ -public final class EssentiaItemContainerHelper -{ - public enum AspectItemType - { - /** - * Unknown item, or non-whitelisted container - */ - Invalid, - - /** - * Whitelisted container. - */ - EssentiaContainer, - - /** - * Warded jar label. - */ - JarLabel, - - /** - * Crystallized essentia. - */ - CrystallizedEssentia, - - /** - * Wispy Essence. - */ - WispEssence, - - /** - * {@link com.djgiannuzz.thaumcraftneiplugin.items.ItemAspect} - */ - ItemAspect; - } - - /** - * Singleton - */ - public static final EssentiaItemContainerHelper INSTANCE = new EssentiaItemContainerHelper(); - - /** - * NBT key used to get the aspect of a jar's label. - */ - private static final String JAR_LABEL_NBT_KEY = "AspectFilter"; - - /** - * Standard Thaumcraft jar capacity. - */ - private static final int JAR_CAPACITY = 64; - - /** - * Standard Thaumcraft phial capacity. - */ - private static final int PHIAL_CAPACITY = 8; - - /** - * Cache of the item permissions. - */ - private IThETransportPermissions perms; - - /** - * Private constructor - */ - private EssentiaItemContainerHelper() - { - this.perms = ThEApi.instance().transportPermissions(); - } - - /** - * Gets the first aspect contained in the IEssentiaContainerItem. Ignores the whitelist. - * - * @param itemStack - * @return - */ - private Aspect getAspectFromAnyContainerItem( final ItemStack itemStack ) - { - // Is it a container? - if( itemStack.getItem() instanceof IEssentiaContainerItem ) - { - // Get the list of aspects from the container - AspectList aspectList = ( (IEssentiaContainerItem)itemStack.getItem() ).getAspects( itemStack ); - - // Is there are list? - if( aspectList != null ) - { - // Return the aspect contained - return aspectList.getAspects()[0]; - } - } - - return null; - } - - /** - * Returns an itemstack with a single empty jar - * - * @param metadata - * @return - */ - public ItemStack createEmptyJar( final int metadata ) - { - // Create and return the jar - return new ItemStack( ConfigBlocks.blockJar, 1, metadata ); - } - - /** - * Returns an itemstack with a single empty phial - * - * @return - */ - public ItemStack createEmptyPhial() - { - // Create and return the phial - return new ItemStack( ConfigItems.itemEssence, 1, 0 ); - } - - /** - * Returns an itemstack with a single filled jar. - * - * @param aspect - * @param amount - * @param metadata - * @param withLabel - * @return - */ - public ItemStack createFilledJar( final Aspect aspect, int amount, final int metadata, final boolean withLabel ) - { - - ItemStack jar; - - // If there is no aspect, or it would be empty with no label - if( ( aspect == null ) || ( ( amount <= 0 ) && !withLabel ) ) - { - // Create an empty jar - jar = this.createEmptyJar( metadata ); - } - else - { - // Create an empty fillable jar - jar = new ItemStack( ConfigItems.itemJarFilled, 1, metadata ); - - // Are we putting any essentia in the jar? - if( amount > 0 ) - { - // Is there too much to fit in a jar? - if( amount > EssentiaItemContainerHelper.JAR_CAPACITY ) - { - // Reduce to the max a jar can hold - amount = EssentiaItemContainerHelper.JAR_CAPACITY; - } - - // Set the aspect and amount - ( (ItemJarFilled)jar.getItem() ).setAspects( jar, new AspectList().add( aspect, amount ) ); - } - - // Are we putting a label on it? - if( withLabel ) - { - this.setJarLabel( jar, aspect ); - } - } - - // Return the jar - return jar; - } - - /** - * Returns an itemstack with a single filled phial. - * - * @param aspect - * @return - */ - public ItemStack createFilledPhial( final Aspect aspect ) - { - if( aspect == null ) - { - return this.createEmptyPhial(); - } - - // Create the phial - ItemStack phial = new ItemStack( ConfigItems.itemEssence, 1, 1 ); - - // Set it's aspect - ( (ItemEssence)phial.getItem() ).setAspects( phial, new AspectList().add( aspect, EssentiaItemContainerHelper.PHIAL_CAPACITY ) ); - - return phial; - } - - /** - * Returns true if the jar has a label, false if it does not. - * - * @param jar - * @return - */ - public boolean doesJarHaveLabel( final ItemStack jar ) - { - // If the jar's label aspect is not null, there is a label - return( this.getJarLabelAspect( jar ) != null ); - } - - /** - * Extracts essentia from the specified container using the - * aspect and amount specified by the AspectStack. - * - * @param container - * @param aspectStack - * @return - */ - public ImmutablePair extractFromContainer( final ItemStack container, final IAspectStack aspectStack ) - { - // Ensure it is a container - if( this.getItemType( container ) != AspectItemType.EssentiaContainer ) - { - return null; - } - - // Get the item in the stack - Item containerItem = container.getItem(); - - // Get the info about the container - IThEEssentiaContainerPermission info = this.getContainerInfo( containerItem, container.getItemDamage() ); - - // Ensure we got info - if( info == null ) - { - return null; - } - - // Get the aspect in the container - AspectList aspectList = ( (IEssentiaContainerItem)containerItem ).getAspects( container ); - - // Does the container have the aspect we are wanting to extract? - if( aspectStack.getAspect() != aspectList.getAspects()[0] ) - { - return null; - } - - // Get how much is stored in the container - int containerAmountStored = aspectList.getAmount( aspectStack.getAspect() ); - - // Is there any stored in the container? - if( containerAmountStored <= 0 ) - { - return null; - } - - // Copy the amount we want to drain - int amountToDrain = (int)aspectStack.getStackSize(); - - // Can this container do partial fills? - if( !info.canHoldPartialAmount() ) - { - // Ensure the request is for the containers capacity - if( amountToDrain < info.maximumCapacity() ) - { - // Can not partially drain this container - return null; - } - else if( amountToDrain > info.maximumCapacity() ) - { - // Drain is to much, reduce to preset capacity - amountToDrain = info.maximumCapacity(); - } - } - else - { - // Is the amount we want more than is in the container? - if( amountToDrain > containerAmountStored ) - { - // Adjust the amount to how much is in the container - amountToDrain = containerAmountStored; - } - } - - ItemStack resultStack = null; - - // Did we completely drain the container? - if( ( amountToDrain == containerAmountStored ) || ( amountToDrain == info.maximumCapacity() ) ) - { - // Is this a phial? - if( containerItem instanceof ItemEssence ) - { - // Create an empty phial for the output - resultStack = this.createEmptyPhial(); - } - else if( containerItem instanceof ItemJarFilled ) - { - // Was the jar labeled? - if( this.doesJarHaveLabel( container ) ) - { - // Create an empty labeled jar - resultStack = this.createFilledJar( aspectStack.getAspect(), 0, container.getItemDamage(), true ); - } - else - { - // Create an empty jar for the output - resultStack = this.createEmptyJar( container.getItemDamage() ); - } - } - - } - - // Have we already set the result stack? - if( resultStack == null ) - { - // Make a copy of the container - resultStack = container.copy(); - - // Reduce the list amount - aspectList.remove( aspectStack.getAspect(), amountToDrain ); - - // Set the stored amount - ( (IEssentiaContainerItem)resultStack.getItem() ).setAspects( resultStack, aspectList ); - } - - return new ImmutablePair( amountToDrain, resultStack ); - - } - - /** - * Extracts essentia from the specified container using the - * aspect in the container, and the amount(in essentia units). - * - * @param container - * @param drainAmount_EU - * @return - */ - public ImmutablePair extractFromContainer( final ItemStack container, final int drainAmount_EU ) - { - // Ensure the container is valid - if( container == null ) - { - return null; - } - - // Create an aspect stack based on whats in the container - IAspectStack stack = new AspectStack( this.getAspectInContainer( container ), drainAmount_EU ); - - // Extract - return this.extractFromContainer( container, stack ); - } - - /** - * Gets the aspect on the label. - * Can return null. - * - * @param label - * @return - */ - public Aspect getAspectFromLabel( final ItemStack label ) - { - // Ensure the item is a label - if( this.getItemType( label ) != AspectItemType.JarLabel ) - { - return null; - } - - // Get the item - ItemResource rLabel = (ItemResource)label.getItem(); - - // Get the aspects - AspectList aspects = rLabel.getAspects( label ); - - // Ensure there is an aspect to get - if( ( aspects == null ) || ( aspects.size() == 0 ) ) - { - return null; - } - - // Return the aspect - return aspects.getAspects()[0]; - } - - /** - * Returns the aspect in the container, or null if empty or invalid container. - * - * @param itemStack - * @return - */ - public Aspect getAspectInContainer( final ItemStack itemStack ) - { - // Ensure the item is a valid container - if( this.getItemType( itemStack ) == AspectItemType.EssentiaContainer ) - { - return this.getAspectFromAnyContainerItem( itemStack ); - } - - return null; - } - - /** - * Gets an {@link AspectStack} representing the essentia and - * amount in the container. - * - * @param container - * @return AspectStack can read container, null otherwise. - */ - public IAspectStack getAspectStackFromContainer( final ItemStack container ) - { - // Get the aspect of the essentia in the container - Aspect aspect = this.getAspectInContainer( container ); - - // Did we get an aspect? - if( aspect == null ) - { - return null; - } - - // get the amount stored in the container - int stored = this.getContainerStoredAmount( container ); - - return new AspectStack( aspect, stored ); - } - - /** - * Gets the maximum amount the specified container can hold - * - * @param container - * @return - */ - public int getContainerCapacity( final ItemStack container ) - { - // Is the container not null? - if( container != null ) - { - // Get the item from the stack - Item containerItem = container.getItem(); - - // Get the info about the container - IThEEssentiaContainerPermission info = this.getContainerInfo( containerItem, container.getItemDamage() ); - - // Did we get any info? - if( info != null ) - { - return info.maximumCapacity(); - } - } - - return 0; - } - - /** - * Gets the information about the container as it was registered to the - * whitelist. - * - * @param item - * @param metadata - * @return - */ - public IThEEssentiaContainerPermission getContainerInfo( final Item item, final int metadata ) - { - // Is the item not null? - if( item != null ) - { - return this.perms.getEssentiaContainerInfo( item.getClass(), metadata ); - } - - return null; - } - - /** - * Gets the information about the container as it was registered to the - * whitelist. - * - * @param itemstack - * @return - */ - public IThEEssentiaContainerPermission getContainerInfo( final ItemStack itemStack ) - { - // Is the itemstack not null? - if( itemStack != null ) - { - return this.perms.getEssentiaContainerInfo( itemStack.getItem().getClass(), itemStack.getItemDamage() ); - } - - return null; - } - - /** - * Gets the amount stored in the container. - * - * @param container - * @return - */ - public int getContainerStoredAmount( final ItemStack container ) - { - // Is the container valid? - if( ( container != null ) && ( container.getItem() instanceof IEssentiaContainerItem ) ) - { - // Is the container whitelisted? - if( this.isContainerWhitelisted( container ) ) - { - // Get the aspect list from the container - AspectList storedList = ( (IEssentiaContainerItem)container.getItem() ).getAspects( container ); - - // Is there a list? - if( storedList == null ) - { - return 0; - } - - // Return the amount - return storedList.getAmount( storedList.getAspects()[0] ); - } - } - return 0; - } - - /** - * Returns the aspect of of the specified item. This method supports jars, jar labels and crystallized essentia. - * This should not be used to validate a container. - * - * @param itemStack - * @return Aspect if container has one, null otherwise. - */ - public Aspect getFilterAspectFromItem( final ItemStack itemStack ) - { - // Get the type - AspectItemType type = this.getItemType( itemStack ); - - switch ( type ) - { - case JarLabel: - return this.getAspectFromLabel( itemStack ); - - case CrystallizedEssentia: - case EssentiaContainer: - case WispEssence: - return this.getAspectFromAnyContainerItem( itemStack ); - - case ItemAspect: - return this.getAspectFromItemAspect(itemStack); - - case Invalid: - break; - - } - - return null; - } - - /** - * Gets the aspect type of the item. - * - * @param itemStack - * @return - */ - public AspectItemType getItemType( final ItemStack itemStack ) - { - // Ensure the stack is not null - if( itemStack != null ) - { - // Get the item - Item item = itemStack.getItem(); - - // Ensure the item is not null - if( item != null ) - { - - // Valid container? - if( this.isContainerWhitelisted( itemStack ) ) - { - return AspectItemType.EssentiaContainer; - } - // IEssentiaContainerItem? - else if( item instanceof IEssentiaContainerItem ) - { - - // Crystallized Essentia? - if( item instanceof ItemCrystalEssence ) - { - return AspectItemType.CrystallizedEssentia; - } - - // Wisp essence? - if( item instanceof ItemWispEssence ) - { - return AspectItemType.WispEssence; - } - } - - // Label? - if( ( item instanceof ItemResource ) && ( itemStack.getItemDamage() == 13 ) ) - { - return AspectItemType.JarLabel; - } - - // ItemAspect? - if (Loader.isModLoaded("thaumcraftneiplugin") && item instanceof ItemAspect) { - return AspectItemType.ItemAspect; - } - } - - } - - return AspectItemType.Invalid; - } - - /** - * Gets the aspect represented by a jar's label. - * - * @param jar - * @return - */ - public Aspect getJarLabelAspect( final ItemStack jar ) - { - Aspect labelAspect = null; - - // Ensure it is a jar - if( jar.getItem() instanceof ItemJarFilled ) - { - // Does the jar have a label? - if( ( jar.hasTagCompound() ) && ( jar.stackTagCompound.hasKey( EssentiaItemContainerHelper.JAR_LABEL_NBT_KEY ) ) ) - { - // Get the aspect tag from the NBT - String tag = jar.stackTagCompound.getString( EssentiaItemContainerHelper.JAR_LABEL_NBT_KEY ); - - // Set the label aspect - labelAspect = Aspect.getAspect( tag ); - } - } - - return labelAspect; - - } - - /** - * Creates a copy of the container filled with the additional gas. - * - * @param container - * @param aspectStack - * @return The amount that was inject, and the new container. - */ - public ImmutablePair injectIntoContainer( final ItemStack container, final IAspectStack aspectStack ) - { - // Is the item an essentia container? - if( this.getItemType( container ) != AspectItemType.EssentiaContainer ) - { - return null; - } - - // Get the container item - Item containerItem = container.getItem(); - if( containerItem == null ) - { - // Invalid item - return null; - } - - // Is the container a labeled jar? - if( containerItem instanceof ItemJarFilled ) - { - if( this.doesJarHaveLabel( container ) ) - { - // Does the label match the aspect we are going to fill - // with? - if( aspectStack.getAspect() != this.getJarLabelAspect( container ) ) - { - // Aspect does not match the jar's label - return null; - } - } - } - // Is the container restricted? - else if( containerItem instanceof IRestrictedEssentiaContainerItem ) - { - // Ensure the container accepts this essentia - if( !( ( (IRestrictedEssentiaContainerItem)containerItem ).acceptsAspect( aspectStack.getAspect() ) ) ) - { - // Not acceptable - return null; - } - } - - // Get the info about the container - IThEEssentiaContainerPermission info = this.getContainerInfo( containerItem, container.getItemDamage() ); - - // Ensure we got the info - if( info == null ) - { - return null; - } - - // Get how much essentia is in the container - int containerAmountStored = this.getContainerStoredAmount( container ); - - // Calculate how much remaining storage is in the container - int remainaingStorage = info.maximumCapacity() - containerAmountStored; - - // Is there any room left in the container? - if( remainaingStorage <= 0 ) - { - return null; - } - - // Set the amount to fill - int amountToFill = (int)aspectStack.getStackSize(); - - // Can this container do partial fills? - if( !info.canHoldPartialAmount() ) - { - // Ensure the request is for the containers capacity - if( amountToFill < info.maximumCapacity() ) - { - // Can not partially fill this container - return null; - } - else if( amountToFill > info.maximumCapacity() ) - { - // Drain is to much, reduce to preset capacity - amountToFill = info.maximumCapacity(); - } - } - else - { - // Would the resulting amount be more than the container can hold? - if( amountToFill > ( containerAmountStored + info.maximumCapacity() ) ) - { - // Adjust the amount - amountToFill = info.maximumCapacity() - containerAmountStored; - } - } - - ItemStack resultStack = null; - - // Is this a phial? - if( containerItem instanceof ItemEssence ) - { - // Create a new phial - resultStack = this.createFilledPhial( aspectStack.getAspect() ); - } - // Is it an empty jar? - else if( containerItem instanceof BlockJarItem ) - { - // Create a fillable jar - resultStack = this.createFilledJar( aspectStack.getAspect(), amountToFill, container.getItemDamage(), false ); - } - - // Have we already set the result? - if( resultStack == null ) - { - // Get the currently stored list. - AspectList aspectList = ( (IEssentiaContainerItem)containerItem ).getAspects( container ); - - // Is the containers list null? - if( aspectList == null ) - { - // Create a new aspect list - aspectList = new AspectList(); - } - // Does the list have anything in it? - else if( aspectList.size() > 0 ) - { - // Does the stored aspect match the aspect to inject? - if( aspectStack.getAspect() != aspectList.getAspects()[0] ) - { - // Don't mix aspects - return null; - } - } - - // Increase the list amount - aspectList.add( aspectStack.getAspect(), amountToFill ); - - // Make a copy of the request - resultStack = container.copy(); - - // Set the stored amount - ( (IEssentiaContainerItem)resultStack.getItem() ).setAspects( resultStack, aspectList ); - } - - return new ImmutablePair( amountToFill, resultStack ); - } - - /** - * Checks if the specified itemstack represents an empty container. - * - * @param container - * @return - */ - public boolean isContainerEmpty( final ItemStack container ) - { - return( this.getContainerStoredAmount( container ) == 0 ); - } - - /** - * Checks if the specified itemstack represents a non-empty container. - * - * @param container - * @return - */ - public boolean isContainerFilled( final ItemStack container ) - { - - return( this.getContainerStoredAmount( container ) > 0 ); - } - - /** - * Quick check to see if the item is whitelisted. - * - * @param item - * @param metadata - * @return - */ - public boolean isContainerWhitelisted( final Item container, final int metadata ) - { - return this.getContainerInfo( container, metadata ) != null; - } - - /** - * Quick check to see if the itemstack is whitelisted. - * - * @param item - * @return - */ - public boolean isContainerWhitelisted( final ItemStack container ) - { - return this.getContainerInfo( container ) != null; - } - - /** - * Setup the standard white list - */ - public void registerDefaultContainers() - { - // Phials - this.perms.addEssentiaContainerItemToTransportPermissions( ItemEssence.class, PHIAL_CAPACITY, 0, false ); - this.perms.addEssentiaContainerItemToTransportPermissions( ItemEssence.class, PHIAL_CAPACITY, 1, false ); - - // Filled jar - this.perms.addEssentiaContainerItemToTransportPermissions( ItemJarFilled.class, JAR_CAPACITY, 0, true ); - - // Void jar - this.perms.addEssentiaContainerItemToTransportPermissions( ItemJarFilled.class, JAR_CAPACITY, 3, true ); - - // Vibration chamber - this.perms.addEssentiaContainerItemToTransportPermissions( ItemBlockEssentiaVibrationChamber.class, TileEVCBase.MAX_ESSENTIA_STORED, 0, - true ); - } - - /** - * Sets the specified jar's label. - * - * @param jar - * @param OverrideAspect - * Override existing label and use this aspect. Can be null to use existing - * label. - * @return The specified itemstack. - */ - public ItemStack setJarLabel( final ItemStack jar, final Aspect OverrideAspect ) - { - // Ensure it is a jar - if( jar.getItem() instanceof ItemJarFilled ) - { - Aspect labelAspect; - - // Are we overriding the aspect? - if( OverrideAspect != null ) - { - labelAspect = OverrideAspect; - } - else - { - labelAspect = this.getFilterAspectFromItem( jar ); - } - - // Ensure we have an aspect to set - if( labelAspect != null ) - { - // Does the jar have a compound tag? - if( !jar.hasTagCompound() ) - { - // Create a new compound tag - jar.stackTagCompound = new NBTTagCompound(); - } - - // Set the label - jar.stackTagCompound.setString( "AspectFilter", labelAspect.getTag() ); - } - - } - - return jar; - } - - /** - * Sets a labels aspect - * - * @param label - * The itemstack is modified. - * @param aspect - */ - public void setLabelAspect( final ItemStack label, final Aspect aspect ) - { - // Ensure the item is a label - if( this.getItemType( label ) != AspectItemType.JarLabel ) - { - return; - } - - // Get the item - ItemResource rLabel = (ItemResource)label.getItem(); - - // Create the aspects - AspectList aspects = new AspectList(); - aspects.add( aspect, 1 ); - - // Set the aspect - rLabel.setAspects( label, aspects ); - - } +public final class EssentiaItemContainerHelper { + public enum AspectItemType { + /** + * Unknown item, or non-whitelisted container + */ + Invalid, + + /** + * Whitelisted container. + */ + EssentiaContainer, + + /** + * Warded jar label. + */ + JarLabel, + + /** + * Crystallized essentia. + */ + CrystallizedEssentia, + + /** + * Wispy Essence. + */ + WispEssence, + + /** + * {@link com.djgiannuzz.thaumcraftneiplugin.items.ItemAspect} + */ + ItemAspect; + } + + /** + * Singleton + */ + public static final EssentiaItemContainerHelper INSTANCE = new EssentiaItemContainerHelper(); + + /** + * NBT key used to get the aspect of a jar's label. + */ + private static final String JAR_LABEL_NBT_KEY = "AspectFilter"; + + /** + * Standard Thaumcraft jar capacity. + */ + private static final int JAR_CAPACITY = 64; + + /** + * Standard Thaumcraft phial capacity. + */ + private static final int PHIAL_CAPACITY = 8; + + /** + * Cache of the item permissions. + */ + private IThETransportPermissions perms; + + /** + * Private constructor + */ + private EssentiaItemContainerHelper() { + this.perms = ThEApi.instance().transportPermissions(); + } + + /** + * Gets the first aspect contained in the IEssentiaContainerItem. Ignores the whitelist. + * + * @param itemStack + * @return + */ + private Aspect getAspectFromAnyContainerItem(final ItemStack itemStack) { + // Is it a container? + if (itemStack.getItem() instanceof IEssentiaContainerItem) { + // Get the list of aspects from the container + AspectList aspectList = ((IEssentiaContainerItem) itemStack.getItem()).getAspects(itemStack); + + // Is there are list? + if (aspectList != null) { + // Return the aspect contained + return aspectList.getAspects()[0]; + } + } + + return null; + } + + /** + * Returns an itemstack with a single empty jar + * + * @param metadata + * @return + */ + public ItemStack createEmptyJar(final int metadata) { + // Create and return the jar + return new ItemStack(ConfigBlocks.blockJar, 1, metadata); + } + + /** + * Returns an itemstack with a single empty phial + * + * @return + */ + public ItemStack createEmptyPhial() { + // Create and return the phial + return new ItemStack(ConfigItems.itemEssence, 1, 0); + } + + /** + * Returns an itemstack with a single filled jar. + * + * @param aspect + * @param amount + * @param metadata + * @param withLabel + * @return + */ + public ItemStack createFilledJar(final Aspect aspect, int amount, final int metadata, final boolean withLabel) { + + ItemStack jar; + + // If there is no aspect, or it would be empty with no label + if ((aspect == null) || ((amount <= 0) && !withLabel)) { + // Create an empty jar + jar = this.createEmptyJar(metadata); + } else { + // Create an empty fillable jar + jar = new ItemStack(ConfigItems.itemJarFilled, 1, metadata); + + // Are we putting any essentia in the jar? + if (amount > 0) { + // Is there too much to fit in a jar? + if (amount > EssentiaItemContainerHelper.JAR_CAPACITY) { + // Reduce to the max a jar can hold + amount = EssentiaItemContainerHelper.JAR_CAPACITY; + } + + // Set the aspect and amount + ((ItemJarFilled) jar.getItem()).setAspects(jar, new AspectList().add(aspect, amount)); + } + + // Are we putting a label on it? + if (withLabel) { + this.setJarLabel(jar, aspect); + } + } + + // Return the jar + return jar; + } + + /** + * Returns an itemstack with a single filled phial. + * + * @param aspect + * @return + */ + public ItemStack createFilledPhial(final Aspect aspect) { + if (aspect == null) { + return this.createEmptyPhial(); + } + + // Create the phial + ItemStack phial = new ItemStack(ConfigItems.itemEssence, 1, 1); + + // Set it's aspect + ((ItemEssence) phial.getItem()) + .setAspects(phial, new AspectList().add(aspect, EssentiaItemContainerHelper.PHIAL_CAPACITY)); + + return phial; + } + + /** + * Returns true if the jar has a label, false if it does not. + * + * @param jar + * @return + */ + public boolean doesJarHaveLabel(final ItemStack jar) { + // If the jar's label aspect is not null, there is a label + return (this.getJarLabelAspect(jar) != null); + } + + /** + * Extracts essentia from the specified container using the + * aspect and amount specified by the AspectStack. + * + * @param container + * @param aspectStack + * @return + */ + public ImmutablePair extractFromContainer( + final ItemStack container, final IAspectStack aspectStack) { + // Ensure it is a container + if (this.getItemType(container) != AspectItemType.EssentiaContainer) { + return null; + } + + // Get the item in the stack + Item containerItem = container.getItem(); + + // Get the info about the container + IThEEssentiaContainerPermission info = this.getContainerInfo(containerItem, container.getItemDamage()); + + // Ensure we got info + if (info == null) { + return null; + } + + // Get the aspect in the container + AspectList aspectList = ((IEssentiaContainerItem) containerItem).getAspects(container); + + // Does the container have the aspect we are wanting to extract? + if (aspectStack.getAspect() != aspectList.getAspects()[0]) { + return null; + } + + // Get how much is stored in the container + int containerAmountStored = aspectList.getAmount(aspectStack.getAspect()); + + // Is there any stored in the container? + if (containerAmountStored <= 0) { + return null; + } + + // Copy the amount we want to drain + int amountToDrain = (int) aspectStack.getStackSize(); + + // Can this container do partial fills? + if (!info.canHoldPartialAmount()) { + // Ensure the request is for the containers capacity + if (amountToDrain < info.maximumCapacity()) { + // Can not partially drain this container + return null; + } else if (amountToDrain > info.maximumCapacity()) { + // Drain is to much, reduce to preset capacity + amountToDrain = info.maximumCapacity(); + } + } else { + // Is the amount we want more than is in the container? + if (amountToDrain > containerAmountStored) { + // Adjust the amount to how much is in the container + amountToDrain = containerAmountStored; + } + } + + ItemStack resultStack = null; + + // Did we completely drain the container? + if ((amountToDrain == containerAmountStored) || (amountToDrain == info.maximumCapacity())) { + // Is this a phial? + if (containerItem instanceof ItemEssence) { + // Create an empty phial for the output + resultStack = this.createEmptyPhial(); + } else if (containerItem instanceof ItemJarFilled) { + // Was the jar labeled? + if (this.doesJarHaveLabel(container)) { + // Create an empty labeled jar + resultStack = this.createFilledJar(aspectStack.getAspect(), 0, container.getItemDamage(), true); + } else { + // Create an empty jar for the output + resultStack = this.createEmptyJar(container.getItemDamage()); + } + } + } + + // Have we already set the result stack? + if (resultStack == null) { + // Make a copy of the container + resultStack = container.copy(); + + // Reduce the list amount + aspectList.remove(aspectStack.getAspect(), amountToDrain); + + // Set the stored amount + ((IEssentiaContainerItem) resultStack.getItem()).setAspects(resultStack, aspectList); + } + + return new ImmutablePair(amountToDrain, resultStack); + } + + /** + * Extracts essentia from the specified container using the + * aspect in the container, and the amount(in essentia units). + * + * @param container + * @param drainAmount_EU + * @return + */ + public ImmutablePair extractFromContainer(final ItemStack container, final int drainAmount_EU) { + // Ensure the container is valid + if (container == null) { + return null; + } + + // Create an aspect stack based on whats in the container + IAspectStack stack = new AspectStack(this.getAspectInContainer(container), drainAmount_EU); + + // Extract + return this.extractFromContainer(container, stack); + } + + /** + * Gets the aspect on the label. + * Can return null. + * + * @param label + * @return + */ + public Aspect getAspectFromLabel(final ItemStack label) { + // Ensure the item is a label + if (this.getItemType(label) != AspectItemType.JarLabel) { + return null; + } + + // Get the item + ItemResource rLabel = (ItemResource) label.getItem(); + + // Get the aspects + AspectList aspects = rLabel.getAspects(label); + + // Ensure there is an aspect to get + if ((aspects == null) || (aspects.size() == 0)) { + return null; + } + + // Return the aspect + return aspects.getAspects()[0]; + } + + /** + * Returns the aspect in the container, or null if empty or invalid container. + * + * @param itemStack + * @return + */ + public Aspect getAspectInContainer(final ItemStack itemStack) { + // Ensure the item is a valid container + if (this.getItemType(itemStack) == AspectItemType.EssentiaContainer) { + return this.getAspectFromAnyContainerItem(itemStack); + } + + return null; + } + + /** + * Gets an {@link AspectStack} representing the essentia and + * amount in the container. + * + * @param container + * @return AspectStack can read container, null otherwise. + */ + public IAspectStack getAspectStackFromContainer(final ItemStack container) { + // Get the aspect of the essentia in the container + Aspect aspect = this.getAspectInContainer(container); + + // Did we get an aspect? + if (aspect == null) { + return null; + } + + // get the amount stored in the container + int stored = this.getContainerStoredAmount(container); + + return new AspectStack(aspect, stored); + } + + /** + * Gets the maximum amount the specified container can hold + * + * @param container + * @return + */ + public int getContainerCapacity(final ItemStack container) { + // Is the container not null? + if (container != null) { + // Get the item from the stack + Item containerItem = container.getItem(); + + // Get the info about the container + IThEEssentiaContainerPermission info = this.getContainerInfo(containerItem, container.getItemDamage()); + + // Did we get any info? + if (info != null) { + return info.maximumCapacity(); + } + } + + return 0; + } + + /** + * Gets the information about the container as it was registered to the + * whitelist. + * + * @param item + * @param metadata + * @return + */ + public IThEEssentiaContainerPermission getContainerInfo(final Item item, final int metadata) { + // Is the item not null? + if (item != null) { + return this.perms.getEssentiaContainerInfo(item.getClass(), metadata); + } + + return null; + } + + /** + * Gets the information about the container as it was registered to the + * whitelist. + * + * @param itemstack + * @return + */ + public IThEEssentiaContainerPermission getContainerInfo(final ItemStack itemStack) { + // Is the itemstack not null? + if (itemStack != null) { + return this.perms.getEssentiaContainerInfo(itemStack.getItem().getClass(), itemStack.getItemDamage()); + } + + return null; + } + + /** + * Gets the amount stored in the container. + * + * @param container + * @return + */ + public int getContainerStoredAmount(final ItemStack container) { + // Is the container valid? + if ((container != null) && (container.getItem() instanceof IEssentiaContainerItem)) { + // Is the container whitelisted? + if (this.isContainerWhitelisted(container)) { + // Get the aspect list from the container + AspectList storedList = ((IEssentiaContainerItem) container.getItem()).getAspects(container); + + // Is there a list? + if (storedList == null) { + return 0; + } + + // Return the amount + return storedList.getAmount(storedList.getAspects()[0]); + } + } + return 0; + } + + /** + * Returns the aspect of of the specified item. This method supports jars, jar labels and crystallized essentia. + * This should not be used to validate a container. + * + * @param itemStack + * @return Aspect if container has one, null otherwise. + */ + public Aspect getFilterAspectFromItem(final ItemStack itemStack) { + // Get the type + AspectItemType type = this.getItemType(itemStack); + + switch (type) { + case JarLabel: + return this.getAspectFromLabel(itemStack); + + case CrystallizedEssentia: + case EssentiaContainer: + case WispEssence: + return this.getAspectFromAnyContainerItem(itemStack); + + case ItemAspect: + return this.getAspectFromItemAspect(itemStack); + + case Invalid: + break; + } + + return null; + } + + /** + * Gets the aspect type of the item. + * + * @param itemStack + * @return + */ + public AspectItemType getItemType(final ItemStack itemStack) { + // Ensure the stack is not null + if (itemStack != null) { + // Get the item + Item item = itemStack.getItem(); + + // Ensure the item is not null + if (item != null) { + + // Valid container? + if (this.isContainerWhitelisted(itemStack)) { + return AspectItemType.EssentiaContainer; + } + // IEssentiaContainerItem? + else if (item instanceof IEssentiaContainerItem) { + + // Crystallized Essentia? + if (item instanceof ItemCrystalEssence) { + return AspectItemType.CrystallizedEssentia; + } + + // Wisp essence? + if (item instanceof ItemWispEssence) { + return AspectItemType.WispEssence; + } + } + + // Label? + if ((item instanceof ItemResource) && (itemStack.getItemDamage() == 13)) { + return AspectItemType.JarLabel; + } + + // ItemAspect? + if (Loader.isModLoaded("thaumcraftneiplugin") && item instanceof ItemAspect) { + return AspectItemType.ItemAspect; + } + } + } + + return AspectItemType.Invalid; + } + + /** + * Gets the aspect represented by a jar's label. + * + * @param jar + * @return + */ + public Aspect getJarLabelAspect(final ItemStack jar) { + Aspect labelAspect = null; + + // Ensure it is a jar + if (jar.getItem() instanceof ItemJarFilled) { + // Does the jar have a label? + if ((jar.hasTagCompound()) + && (jar.stackTagCompound.hasKey(EssentiaItemContainerHelper.JAR_LABEL_NBT_KEY))) { + // Get the aspect tag from the NBT + String tag = jar.stackTagCompound.getString(EssentiaItemContainerHelper.JAR_LABEL_NBT_KEY); + + // Set the label aspect + labelAspect = Aspect.getAspect(tag); + } + } + + return labelAspect; + } + + /** + * Creates a copy of the container filled with the additional gas. + * + * @param container + * @param aspectStack + * @return The amount that was inject, and the new container. + */ + public ImmutablePair injectIntoContainer( + final ItemStack container, final IAspectStack aspectStack) { + // Is the item an essentia container? + if (this.getItemType(container) != AspectItemType.EssentiaContainer) { + return null; + } + + // Get the container item + Item containerItem = container.getItem(); + if (containerItem == null) { + // Invalid item + return null; + } + + // Is the container a labeled jar? + if (containerItem instanceof ItemJarFilled) { + if (this.doesJarHaveLabel(container)) { + // Does the label match the aspect we are going to fill + // with? + if (aspectStack.getAspect() != this.getJarLabelAspect(container)) { + // Aspect does not match the jar's label + return null; + } + } + } + // Is the container restricted? + else if (containerItem instanceof IRestrictedEssentiaContainerItem) { + // Ensure the container accepts this essentia + if (!(((IRestrictedEssentiaContainerItem) containerItem).acceptsAspect(aspectStack.getAspect()))) { + // Not acceptable + return null; + } + } + + // Get the info about the container + IThEEssentiaContainerPermission info = this.getContainerInfo(containerItem, container.getItemDamage()); + + // Ensure we got the info + if (info == null) { + return null; + } + + // Get how much essentia is in the container + int containerAmountStored = this.getContainerStoredAmount(container); + + // Calculate how much remaining storage is in the container + int remainaingStorage = info.maximumCapacity() - containerAmountStored; + + // Is there any room left in the container? + if (remainaingStorage <= 0) { + return null; + } + + // Set the amount to fill + int amountToFill = (int) aspectStack.getStackSize(); + + // Can this container do partial fills? + if (!info.canHoldPartialAmount()) { + // Ensure the request is for the containers capacity + if (amountToFill < info.maximumCapacity()) { + // Can not partially fill this container + return null; + } else if (amountToFill > info.maximumCapacity()) { + // Drain is to much, reduce to preset capacity + amountToFill = info.maximumCapacity(); + } + } else { + // Would the resulting amount be more than the container can hold? + if (amountToFill > (containerAmountStored + info.maximumCapacity())) { + // Adjust the amount + amountToFill = info.maximumCapacity() - containerAmountStored; + } + } + + ItemStack resultStack = null; + + // Is this a phial? + if (containerItem instanceof ItemEssence) { + // Create a new phial + resultStack = this.createFilledPhial(aspectStack.getAspect()); + } + // Is it an empty jar? + else if (containerItem instanceof BlockJarItem) { + // Create a fillable jar + resultStack = this.createFilledJar(aspectStack.getAspect(), amountToFill, container.getItemDamage(), false); + } + + // Have we already set the result? + if (resultStack == null) { + // Get the currently stored list. + AspectList aspectList = ((IEssentiaContainerItem) containerItem).getAspects(container); + + // Is the containers list null? + if (aspectList == null) { + // Create a new aspect list + aspectList = new AspectList(); + } + // Does the list have anything in it? + else if (aspectList.size() > 0) { + // Does the stored aspect match the aspect to inject? + if (aspectStack.getAspect() != aspectList.getAspects()[0]) { + // Don't mix aspects + return null; + } + } + + // Increase the list amount + aspectList.add(aspectStack.getAspect(), amountToFill); + + // Make a copy of the request + resultStack = container.copy(); + + // Set the stored amount + ((IEssentiaContainerItem) resultStack.getItem()).setAspects(resultStack, aspectList); + } + + return new ImmutablePair(amountToFill, resultStack); + } + + /** + * Checks if the specified itemstack represents an empty container. + * + * @param container + * @return + */ + public boolean isContainerEmpty(final ItemStack container) { + return (this.getContainerStoredAmount(container) == 0); + } + + /** + * Checks if the specified itemstack represents a non-empty container. + * + * @param container + * @return + */ + public boolean isContainerFilled(final ItemStack container) { + + return (this.getContainerStoredAmount(container) > 0); + } + + /** + * Quick check to see if the item is whitelisted. + * + * @param item + * @param metadata + * @return + */ + public boolean isContainerWhitelisted(final Item container, final int metadata) { + return this.getContainerInfo(container, metadata) != null; + } + + /** + * Quick check to see if the itemstack is whitelisted. + * + * @param item + * @return + */ + public boolean isContainerWhitelisted(final ItemStack container) { + return this.getContainerInfo(container) != null; + } + + /** + * Setup the standard white list + */ + public void registerDefaultContainers() { + // Phials + this.perms.addEssentiaContainerItemToTransportPermissions(ItemEssence.class, PHIAL_CAPACITY, 0, false); + this.perms.addEssentiaContainerItemToTransportPermissions(ItemEssence.class, PHIAL_CAPACITY, 1, false); + + // Filled jar + this.perms.addEssentiaContainerItemToTransportPermissions(ItemJarFilled.class, JAR_CAPACITY, 0, true); + + // Void jar + this.perms.addEssentiaContainerItemToTransportPermissions(ItemJarFilled.class, JAR_CAPACITY, 3, true); + + // Vibration chamber + this.perms.addEssentiaContainerItemToTransportPermissions( + ItemBlockEssentiaVibrationChamber.class, TileEVCBase.MAX_ESSENTIA_STORED, 0, true); + } + + /** + * Sets the specified jar's label. + * + * @param jar + * @param OverrideAspect + * Override existing label and use this aspect. Can be null to use existing + * label. + * @return The specified itemstack. + */ + public ItemStack setJarLabel(final ItemStack jar, final Aspect OverrideAspect) { + // Ensure it is a jar + if (jar.getItem() instanceof ItemJarFilled) { + Aspect labelAspect; + + // Are we overriding the aspect? + if (OverrideAspect != null) { + labelAspect = OverrideAspect; + } else { + labelAspect = this.getFilterAspectFromItem(jar); + } + + // Ensure we have an aspect to set + if (labelAspect != null) { + // Does the jar have a compound tag? + if (!jar.hasTagCompound()) { + // Create a new compound tag + jar.stackTagCompound = new NBTTagCompound(); + } + + // Set the label + jar.stackTagCompound.setString("AspectFilter", labelAspect.getTag()); + } + } + + return jar; + } + + /** + * Sets a labels aspect + * + * @param label + * The itemstack is modified. + * @param aspect + */ + public void setLabelAspect(final ItemStack label, final Aspect aspect) { + // Ensure the item is a label + if (this.getItemType(label) != AspectItemType.JarLabel) { + return; + } + + // Get the item + ItemResource rLabel = (ItemResource) label.getItem(); + + // Create the aspects + AspectList aspects = new AspectList(); + aspects.add(aspect, 1); + + // Set the aspect + rLabel.setAspects(label, aspects); + } /** * Get the aspect of the ItemAspect. @@ -951,9 +840,8 @@ public final class EssentiaItemContainerHelper * @param itemStack * @return */ - @Optional.Method(modid = "thaumcraftneiplugin") - public Aspect getAspectFromItemAspect(ItemStack itemStack){ + @Optional.Method(modid = "thaumcraftneiplugin") + public Aspect getAspectFromItemAspect(ItemStack itemStack) { return ItemAspect.getAspects(itemStack).getAspects()[0]; } - } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTileContainerHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTileContainerHelper.java index d70565ea..1b51eec9 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTileContainerHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTileContainerHelper.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.integration.tc; +import appeng.api.config.Actionable; +import appeng.api.storage.data.IAEFluidStack; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; -import appeng.api.config.Actionable; -import appeng.api.storage.data.IAEFluidStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import thaumcraft.api.aspects.Aspect; @@ -26,367 +26,371 @@ import thaumicenergistics.common.tiles.abstraction.TileEVCBase; * */ public final class EssentiaTileContainerHelper { - /** - * Singleton - */ - public static final EssentiaTileContainerHelper INSTANCE = new EssentiaTileContainerHelper(); + /** + * Singleton + */ + public static final EssentiaTileContainerHelper INSTANCE = new EssentiaTileContainerHelper(); - /** - * Cache the permission class - */ - public final IThETransportPermissions perms = ThEApi.instance().transportPermissions(); + /** + * Cache the permission class + */ + public final IThETransportPermissions perms = ThEApi.instance().transportPermissions(); - /** - * Extracts essentia from a container based on the specified fluid stack - * type and amount. - * - * @param container - * @param request - * @param mode - * @return - */ - public FluidStack extractFromContainer(final IAspectContainer container, final FluidStack request, final Actionable mode) { - // Ensure there is a request - if ((request == null) || (request.getFluid() == null) || (request.amount == 0)) { - // No request - return null; - } + /** + * Extracts essentia from a container based on the specified fluid stack + * type and amount. + * + * @param container + * @param request + * @param mode + * @return + */ + public FluidStack extractFromContainer( + final IAspectContainer container, final FluidStack request, final Actionable mode) { + // Ensure there is a request + if ((request == null) || (request.getFluid() == null) || (request.amount == 0)) { + // No request + return null; + } - // Get the fluid - Fluid fluid = request.getFluid(); + // Get the fluid + Fluid fluid = request.getFluid(); - // Ensure it is a gas - if (!(fluid instanceof GaseousEssentia)) { - // Not a gas - return null; - } + // Ensure it is a gas + if (!(fluid instanceof GaseousEssentia)) { + // Not a gas + return null; + } - // Get the gas's aspect - Aspect gasAspect = ((GaseousEssentia) fluid).getAspect(); + // Get the gas's aspect + Aspect gasAspect = ((GaseousEssentia) fluid).getAspect(); - // Get the amount to extract - long amountToDrain_EU = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(request.amount); + // Get the amount to extract + long amountToDrain_EU = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(request.amount); - // Extract - long extractedAmount_EU = this.extractFromContainer(container, (int) amountToDrain_EU, gasAspect, mode); + // Extract + long extractedAmount_EU = this.extractFromContainer(container, (int) amountToDrain_EU, gasAspect, mode); - // Was any extracted? - if (extractedAmount_EU <= 0) { - // None extracted - return null; - } + // Was any extracted? + if (extractedAmount_EU <= 0) { + // None extracted + return null; + } - // Return the extracted amount - return new FluidStack(fluid, (int) EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(extractedAmount_EU)); - } + // Return the extracted amount + return new FluidStack( + fluid, (int) EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(extractedAmount_EU)); + } - /** - * Extracts the specified aspect and amount from the container. - * - * @param container - * @param amountToDrain - * @param aspectToDrain - * @param mode - * @return The amount extracted. - */ - public long extractFromContainer(final IAspectContainer container, int amountToDrain, final Aspect aspectToDrain, final Actionable mode) { + /** + * Extracts the specified aspect and amount from the container. + * + * @param container + * @param amountToDrain + * @param aspectToDrain + * @param mode + * @return The amount extracted. + */ + public long extractFromContainer( + final IAspectContainer container, int amountToDrain, final Aspect aspectToDrain, final Actionable mode) { - // Is the request empty? - if (amountToDrain == 0) { - // Empty request - return 0; - } + // Is the request empty? + if (amountToDrain == 0) { + // Empty request + return 0; + } - // Is the container whitelisted? - if (!this.perms.canExtractFromAspectContainerTile(container)) { - // Not whitelisted - return 0; - } + // Is the container whitelisted? + if (!this.perms.canExtractFromAspectContainerTile(container)) { + // Not whitelisted + return 0; + } - // Get how much is in the container - int containerAmount = container.getAspects().getAmount(aspectToDrain); + // Get how much is in the container + int containerAmount = container.getAspects().getAmount(aspectToDrain); - // Is the container empty? - if (containerAmount == 0) { - // Empty container, or does not contain the wanted aspect - return 0; - } - // Is the drain for more than is in the container? - if (amountToDrain > containerAmount) { - amountToDrain = containerAmount; - } + // Is the container empty? + if (containerAmount == 0) { + // Empty container, or does not contain the wanted aspect + return 0; + } + // Is the drain for more than is in the container? + if (amountToDrain > containerAmount) { + amountToDrain = containerAmount; + } - // Are we really draining, or just simulating? - if (mode == Actionable.MODULATE) { - if (!container.takeFromContainer(aspectToDrain, amountToDrain)) - return 0; - } + // Are we really draining, or just simulating? + if (mode == Actionable.MODULATE) { + if (!container.takeFromContainer(aspectToDrain, amountToDrain)) return 0; + } - // Return how much was drained - return amountToDrain; - } + // Return how much was drained + return amountToDrain; + } - /** - * Returns the aspect of the essentia in the container. - * - * @param container - * @return - */ - public Aspect getAspectInContainer(final IAspectContainer container) { - // Get the aspect list from the container - IAspectStack containerStack = this.getAspectStackFromContainer(container); + /** + * Returns the aspect of the essentia in the container. + * + * @param container + * @return + */ + public Aspect getAspectInContainer(final IAspectContainer container) { + // Get the aspect list from the container + IAspectStack containerStack = this.getAspectStackFromContainer(container); - // Did we get a stack? - if (containerStack == null) { - return null; - } + // Did we get a stack? + if (containerStack == null) { + return null; + } - return containerStack.getAspect(); - } + return containerStack.getAspect(); + } - public IAspectStack getAspectStackFromContainer(final IAspectContainer container) { - // Ensure we have a container - if (container == null) { - return null; - } + public IAspectStack getAspectStackFromContainer(final IAspectContainer container) { + // Ensure we have a container + if (container == null) { + return null; + } - // Get the list of aspects in the container - AspectList aspectList = container.getAspects(); + // Get the list of aspects in the container + AspectList aspectList = container.getAspects(); - if (aspectList == null) { - return null; - } + if (aspectList == null) { + return null; + } - // Create the stack - IAspectStack aspectStack = new AspectStack(); + // Create the stack + IAspectStack aspectStack = new AspectStack(); - // Set the aspect - aspectStack.setAspect(aspectList.getAspectsSortedAmount()[0]); + // Set the aspect + aspectStack.setAspect(aspectList.getAspectsSortedAmount()[0]); - if (!aspectStack.hasAspect()) { - return null; - } + if (!aspectStack.hasAspect()) { + return null; + } - // Set the amount - aspectStack.setStackSize(aspectList.getAmount(aspectStack.getAspect())); + // Set the amount + aspectStack.setStackSize(aspectList.getAmount(aspectStack.getAspect())); - return aspectStack; - } + return aspectStack; + } - /** - * Gets the list of aspects in the container. - * - * @param container - * @return - */ - public List getAspectStacksFromContainer(final IAspectContainer container) { - List stacks = new ArrayList(); + /** + * Gets the list of aspects in the container. + * + * @param container + * @return + */ + public List getAspectStacksFromContainer(final IAspectContainer container) { + List stacks = new ArrayList(); - // Ensure we have a container - if (container == null) { - return stacks; - } + // Ensure we have a container + if (container == null) { + return stacks; + } - // Get the list of aspects in the container - AspectList aspectList = container.getAspects(); + // Get the list of aspects in the container + AspectList aspectList = container.getAspects(); - if (aspectList == null) { - return stacks; - } + if (aspectList == null) { + return stacks; + } - // Populate the list - for (Entry essentia : aspectList.aspects.entrySet()) { - if ((essentia != null) && (essentia.getValue() != 0)) { - stacks.add(new AspectStack(essentia.getKey(), essentia.getValue())); - } - } + // Populate the list + for (Entry essentia : aspectList.aspects.entrySet()) { + if ((essentia != null) && (essentia.getValue() != 0)) { + stacks.add(new AspectStack(essentia.getKey(), essentia.getValue())); + } + } - return stacks; + return stacks; + } - } + /** + * Returns the capacity of the specified container. + * + * @param container + * @return Capacity or -1 if unknown capacity. + */ + public int getContainerCapacity(final IAspectContainer container) { + return this.perms.getAspectContainerTileCapacity(container); + } - /** - * Returns the capacity of the specified container. - * - * @param container - * @return Capacity or -1 if unknown capacity. - */ - public int getContainerCapacity(final IAspectContainer container) { - return this.perms.getAspectContainerTileCapacity(container); - } + public int getContainerStoredAmount(final IAspectContainer container) { + int stored = 0; - public int getContainerStoredAmount(final IAspectContainer container) { - int stored = 0; + // Get the essentia list + for (IAspectStack essentia : this.getAspectStacksFromContainer(container)) { + if (essentia != null) { + stored += (int) essentia.getStackSize(); + } + } - // Get the essentia list - for (IAspectStack essentia : this.getAspectStacksFromContainer(container)) { - if (essentia != null) { - stored += (int) essentia.getStackSize(); - } - } + return stored; + } - return stored; - } + /** + * Attempts to inject essentia into the container. + * Returns the amount that was injected. + * + * @param container + * @param amountToFill + * @param aspectToFill + * @param mode + * @return + */ + public long injectEssentiaIntoContainer( + final IAspectContainer container, int amountToFill, final Aspect aspectToFill, final Actionable mode) { + // Is the container whitelisted? + if (!this.perms.canInjectToAspectContainerTile(container)) { + // Not whitelisted + return 0; + } - /** - * Attempts to inject essentia into the container. - * Returns the amount that was injected. - * - * @param container - * @param amountToFill - * @param aspectToFill - * @param mode - * @return - */ - public long injectEssentiaIntoContainer(final IAspectContainer container, int amountToFill, final Aspect aspectToFill, final Actionable mode) { - // Is the container whitelisted? - if (!this.perms.canInjectToAspectContainerTile(container)) { - // Not whitelisted - return 0; - } + // Get the aspect in the container + IAspectStack storedEssentia = this.getAspectStackFromContainer(container); - // Get the aspect in the container - IAspectStack storedEssentia = this.getAspectStackFromContainer(container); + // Match types on jars + if ((storedEssentia != null) && (container instanceof TileJarFillable)) { + // Do the aspects match? + if (aspectToFill != storedEssentia.getAspect()) { + // Aspects do not match; + return 0; + } + } else if (!(container.doesContainerAccept(aspectToFill))) { + // Container will not accept this aspect + return 0; + } - // Match types on jars - if ((storedEssentia != null) && (container instanceof TileJarFillable)) { - // Do the aspects match? - if (aspectToFill != storedEssentia.getAspect()) { - // Aspects do not match; - return 0; - } - } else if (!(container.doesContainerAccept(aspectToFill))) { - // Container will not accept this aspect - return 0; - } + // Get how much the container can hold + int containerCurrentCapacity = this.getContainerCapacity(container) - this.getContainerStoredAmount(container); - // Get how much the container can hold - int containerCurrentCapacity = this.getContainerCapacity(container) - this.getContainerStoredAmount(container); + // Is there more to fill than the container will hold? + if (amountToFill > containerCurrentCapacity) { + amountToFill = containerCurrentCapacity; + } - // Is there more to fill than the container will hold? - if (amountToFill > containerCurrentCapacity) { - amountToFill = containerCurrentCapacity; - } + // Are we really filling, or simulating? + if (mode == Actionable.MODULATE) { + // Attempt to inject the full amount + int remaining = container.addToContainer(aspectToFill, amountToFill); - // Are we really filling, or simulating? - if (mode == Actionable.MODULATE) { - // Attempt to inject the full amount - int remaining = container.addToContainer(aspectToFill, amountToFill); + // Subtract any that could not be injected + amountToFill -= remaining; + } - // Subtract any that could not be injected - amountToFill -= remaining; - } + return amountToFill; + } - return amountToFill; - } + /** + * Attempts to inject the fluid into the container. + * Returns the amount that was injected in milibuckets. + * + * @param container + * @param fluidStack + * @param mode + * @return + */ + public long injectFluidIntoContainer( + final IAspectContainer container, final IAEFluidStack fluidStack, final Actionable mode) { + // Do we have an input? + if (fluidStack == null) { + // No input + return 0; + } - /** - * Attempts to inject the fluid into the container. - * Returns the amount that was injected in milibuckets. - * - * @param container - * @param fluidStack - * @param mode - * @return - */ - public long injectFluidIntoContainer(final IAspectContainer container, final IAEFluidStack fluidStack, final Actionable mode) { - // Do we have an input? - if (fluidStack == null) { - // No input - return 0; - } + // Is the container whitelisted? + if (!this.perms.canInjectToAspectContainerTile(container)) { + // Not whitelisted + return 0; + } - // Is the container whitelisted? - if (!this.perms.canInjectToAspectContainerTile(container)) { - // Not whitelisted - return 0; - } + // Get the fluid. + Fluid fluid = fluidStack.getFluid(); - // Get the fluid. - Fluid fluid = fluidStack.getFluid(); + // Ensure it is a gas + if (!(fluid instanceof GaseousEssentia)) { + // Not essentia gas + return 0; + } - // Ensure it is a gas - if (!(fluid instanceof GaseousEssentia)) { - // Not essentia gas - return 0; - } + // Get the aspect of the gas + Aspect gasAspect = ((GaseousEssentia) fluid).getAspect(); - // Get the aspect of the gas - Aspect gasAspect = ((GaseousEssentia) fluid).getAspect(); + // Get the amount to fill + long amountToFill = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(fluidStack.getStackSize()); - // Get the amount to fill - long amountToFill = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(fluidStack.getStackSize()); + // Inject + long injectedAmount_EU = this.injectEssentiaIntoContainer(container, (int) amountToFill, gasAspect, mode); - // Inject - long injectedAmount_EU = this.injectEssentiaIntoContainer(container, (int) amountToFill, gasAspect, mode); + return EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(injectedAmount_EU); + } - return EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(injectedAmount_EU); - } + /** + * Setup the standard white list + */ + public void registerDefaultContainers() { + // Alembic + this.perms.addAspectContainerTileToExtractPermissions(TileAlembic.class, 32); - /** - * Setup the standard white list - */ - public void registerDefaultContainers() { - // Alembic - this.perms.addAspectContainerTileToExtractPermissions(TileAlembic.class, 32); + // Centrifuge + this.perms.addAspectContainerTileToExtractPermissions(TileCentrifuge.class, 0); - // Centrifuge - this.perms.addAspectContainerTileToExtractPermissions(TileCentrifuge.class, 0); + // Jars + this.perms.addAspectContainerTileToBothPermissions(TileJarFillable.class, 64); + this.perms.addAspectContainerTileToBothPermissions(TileJarFillableVoid.class, 64); - // Jars - this.perms.addAspectContainerTileToBothPermissions(TileJarFillable.class, 64); - this.perms.addAspectContainerTileToBothPermissions(TileJarFillableVoid.class, 64); + // Essentia buffer + this.perms.addAspectContainerTileToExtractPermissions(TileTubeBuffer.class, 8); + this.perms.addAspectContainerTileToInjectPermissions(TileTubeBuffer.class, 8); - // Essentia buffer - this.perms.addAspectContainerTileToExtractPermissions(TileTubeBuffer.class, 8); - this.perms.addAspectContainerTileToInjectPermissions(TileTubeBuffer.class, 8); + // Essentia reservoir + this.perms.addAspectContainerTileToBothPermissions(TileEssentiaReservoir.class, 256); - // Essentia reservoir - this.perms.addAspectContainerTileToBothPermissions(TileEssentiaReservoir.class, 256); + // Advanced alchemical furnace + this.perms.addAspectContainerTileToExtractPermissions(TileAlchemyFurnaceAdvancedNozzle.class, 0); - // Advanced alchemical furnace - this.perms.addAspectContainerTileToExtractPermissions(TileAlchemyFurnaceAdvancedNozzle.class, 0); + // Essentia vibration chamber + this.perms.addAspectContainerTileToInjectPermissions( + TileEssentiaVibrationChamber.class, TileEVCBase.MAX_ESSENTIA_STORED); - // Essentia vibration chamber - this.perms.addAspectContainerTileToInjectPermissions(TileEssentiaVibrationChamber.class, TileEVCBase.MAX_ESSENTIA_STORED); - - try { - Class c = Class.forName("flaxbeard.thaumicexploration.tile.TileEntityTrashJar"); - this.perms.addAspectContainerTileToInjectPermissions(c, 64); - c = Class.forName("flaxbeard.thaumicexploration.tile.TileEntityBoundJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 64); - } catch (Exception ignored) { - } - try { - Class c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileRemoteJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 64); - c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileStickyJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 64); - } catch (Exception ignored) { - } - try { - // Essentia condenser does not directly implement IAspectContainer, so this may fail if used w/o Automagy - Class c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileEssentiaCompressor"); - this.perms.addAspectContainerTileToBothPermissions(c, 64); - } catch (Exception ignored) { - } - try { - // I hope some day Kekztech jars will have a namespace - Class c = Class.forName("common.tileentities.TE_IchorJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 4096); - c = Class.forName("common.tileentities.TE_IchorVoidJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 4096); - c = Class.forName("common.tileentities.TE_ThaumiumReinforcedJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 256); - c = Class.forName("common.tileentities.TE_ThaumiumReinforcedVoidJar"); - this.perms.addAspectContainerTileToBothPermissions(c, 256); - } catch (Exception ignored) { - } - try { - Class c = Class.forName("tuhljin.automagy.tiles.TileEntityJarCreative"); - this.perms.addAspectContainerTileToBothPermissions(c, 1<<31); - } catch (Exception ignored) { - } - - } + try { + Class c = Class.forName("flaxbeard.thaumicexploration.tile.TileEntityTrashJar"); + this.perms.addAspectContainerTileToInjectPermissions(c, 64); + c = Class.forName("flaxbeard.thaumicexploration.tile.TileEntityBoundJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 64); + } catch (Exception ignored) { + } + try { + Class c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileRemoteJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 64); + c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileStickyJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 64); + } catch (Exception ignored) { + } + try { + // Essentia condenser does not directly implement IAspectContainer, so this may fail if used w/o Automagy + Class c = Class.forName("makeo.gadomancy.common.blocks.tiles.TileEssentiaCompressor"); + this.perms.addAspectContainerTileToBothPermissions(c, 64); + } catch (Exception ignored) { + } + try { + // I hope some day Kekztech jars will have a namespace + Class c = Class.forName("common.tileentities.TE_IchorJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 4096); + c = Class.forName("common.tileentities.TE_IchorVoidJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 4096); + c = Class.forName("common.tileentities.TE_ThaumiumReinforcedJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 256); + c = Class.forName("common.tileentities.TE_ThaumiumReinforcedVoidJar"); + this.perms.addAspectContainerTileToBothPermissions(c, 256); + } catch (Exception ignored) { + } + try { + Class c = Class.forName("tuhljin.automagy.tiles.TileEntityJarCreative"); + this.perms.addAspectContainerTileToBothPermissions(c, 1 << 31); + } catch (Exception ignored) { + } + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTransportHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTransportHelper.java index 3d8b4aef..91244887 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTransportHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/EssentiaTransportHelper.java @@ -8,93 +8,89 @@ import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.IEssentiaTransport; import thaumicenergistics.api.tiles.IEssentiaTransportWithSimulate; -public class EssentiaTransportHelper -{ - /** - * Instance. - */ - public static final EssentiaTransportHelper INSTANCE = new EssentiaTransportHelper(); +public class EssentiaTransportHelper { + /** + * Instance. + */ + public static final EssentiaTransportHelper INSTANCE = new EssentiaTransportHelper(); - /** - * Private constructor. - */ - private EssentiaTransportHelper() - { - // Intentionally Empty - } + /** + * Private constructor. + */ + private EssentiaTransportHelper() { + // Intentionally Empty + } - public void takeEssentiaFromTransportNeighbors( final IEssentiaTransportWithSimulate destination, final World world, final int x, final int y, - final int z ) - { - // Null checks - if( ( destination == null ) || ( world == null ) ) - { - return; - } + public void takeEssentiaFromTransportNeighbors( + final IEssentiaTransportWithSimulate destination, + final World world, + final int x, + final int y, + final int z) { + // Null checks + if ((destination == null) || (world == null)) { + return; + } - // For each side - for( ForgeDirection destinationSide : ForgeDirection.VALID_DIRECTIONS ) - { - // Can the destination accept essentia from this side? - if( !destination.canInputFrom( destinationSide ) ) - { - // Destination can not accept essentia from this side - continue; - } + // For each side + for (ForgeDirection destinationSide : ForgeDirection.VALID_DIRECTIONS) { + // Can the destination accept essentia from this side? + if (!destination.canInputFrom(destinationSide)) { + // Destination can not accept essentia from this side + continue; + } - // Get the source - TileEntity sourceTile = world.getTileEntity( destinationSide.offsetX + x, destinationSide.offsetY + y, destinationSide.offsetZ + z ); + // Get the source + TileEntity sourceTile = world.getTileEntity( + destinationSide.offsetX + x, destinationSide.offsetY + y, destinationSide.offsetZ + z); - // Ensure the source is a transport - if( !( sourceTile instanceof IEssentiaTransport ) ) - { - // Invalid source - continue; - } + // Ensure the source is a transport + if (!(sourceTile instanceof IEssentiaTransport)) { + // Invalid source + continue; + } - // Cast - IEssentiaTransport source = (IEssentiaTransport)sourceTile; + // Cast + IEssentiaTransport source = (IEssentiaTransport) sourceTile; - // Get the opposite direction - ForgeDirection sourceSide = destinationSide.getOpposite(); + // Get the opposite direction + ForgeDirection sourceSide = destinationSide.getOpposite(); - // Can the source output to this side? - if( !source.canOutputTo( sourceSide ) ) - { - // Source can not output to this side - continue; - } + // Can the source output to this side? + if (!source.canOutputTo(sourceSide)) { + // Source can not output to this side + continue; + } - // Does the source have any essentia to give? - if( source.getEssentiaAmount( sourceSide ) <= 0 ) - { - // No essentia from this side - continue; - } + // Does the source have any essentia to give? + if (source.getEssentiaAmount(sourceSide) <= 0) { + // No essentia from this side + continue; + } - // Does the destination have enough suction? - int dSuck = destination.getSuctionAmount( destinationSide ); - if( ( dSuck < source.getMinimumSuction() ) || ( dSuck < source.getSuctionAmount( sourceSide ) ) ) - { - // Destination does not have enough suction. - continue; - } + // Does the destination have enough suction? + int dSuck = destination.getSuctionAmount(destinationSide); + if ((dSuck < source.getMinimumSuction()) || (dSuck < source.getSuctionAmount(sourceSide))) { + // Destination does not have enough suction. + continue; + } - // Get the source aspect - Aspect sourceAspect = source.getEssentiaType( sourceSide ); - if( sourceAspect == null ) - { - // Invalid aspect - continue; - } - - // Simulate an injection - if( destination.addEssentia( sourceAspect, 1, destinationSide, Actionable.SIMULATE ) == 1 ) - { - // Inject - destination.addEssentia( sourceAspect, source.takeEssentia( sourceAspect, 1, sourceSide ), destinationSide, Actionable.MODULATE ); - } - } - } + // Get the source aspect + Aspect sourceAspect = source.getEssentiaType(sourceSide); + if (sourceAspect == null) { + // Invalid aspect + continue; + } + // Simulate an injection + if (destination.addEssentia(sourceAspect, 1, destinationSide, Actionable.SIMULATE) == 1) { + // Inject + destination.addEssentia( + sourceAspect, + source.takeEssentia(sourceAspect, 1, sourceSide), + destinationSide, + Actionable.MODULATE); + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/GolemCoreType.java b/src/main/java/thaumicenergistics/common/integration/tc/GolemCoreType.java index 4432729c..4fb8d5c9 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/GolemCoreType.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/GolemCoreType.java @@ -2,54 +2,49 @@ package thaumicenergistics.common.integration.tc; import javax.annotation.Nullable; -public enum GolemCoreType -{ - Fill (0), - Empty (1), - Gather (2), - Harvest (3), - Guard (4), - Liquid (5), - Essentia (6), - Lumber (7), - Use (8), - Butcher (9), - Sorting (10), - Fish (11); +public enum GolemCoreType { + Fill(0), + Empty(1), + Gather(2), + Harvest(3), + Guard(4), + Liquid(5), + Essentia(6), + Lumber(7), + Use(8), + Butcher(9), + Sorting(10), + Fish(11); - /** - * Array of cores sorted by ID. - */ - public static final GolemCoreType allCores[]; - static - { - GolemCoreType[] values = GolemCoreType.values(); + /** + * Array of cores sorted by ID. + */ + public static final GolemCoreType allCores[]; - // Setup the array - allCores = new GolemCoreType[values.length]; - for( GolemCoreType core : values ) - { - allCores[core.coreID] = core; - } - } + static { + GolemCoreType[] values = GolemCoreType.values(); - /** - * Thaumcraft core ID - */ - public final byte coreID; + // Setup the array + allCores = new GolemCoreType[values.length]; + for (GolemCoreType core : values) { + allCores[core.coreID] = core; + } + } - private GolemCoreType( final int ID ) - { - this.coreID = (byte)ID; - } + /** + * Thaumcraft core ID + */ + public final byte coreID; - @Nullable - public static GolemCoreType getCoreByID( final byte ID ) - { - if( ( ID >= 0 ) && ( ID < allCores.length ) ) - { - return allCores[ID]; - } - return null; - } + private GolemCoreType(final int ID) { + this.coreID = (byte) ID; + } + + @Nullable + public static GolemCoreType getCoreByID(final byte ID) { + if ((ID >= 0) && (ID < allCores.length)) { + return allCores[ID]; + } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/GolemHooks.java b/src/main/java/thaumicenergistics/common/integration/tc/GolemHooks.java index 61ed8388..6b1cf91e 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/GolemHooks.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/GolemHooks.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.integration.tc; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import java.util.HashMap; import java.util.HashSet; import javax.annotation.Nonnull; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -24,708 +24,602 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class GolemHooks -{ - private static class DummyHookHandler - implements IGolemHookHandler - { - - public DummyHookHandler() - { - } - - @Override - public void addDefaultSyncEntries( final IGolemHookSyncRegistry syncRegistry ) - { - - } - - @Override - public void bellLeftClicked( final EntityGolemBase golem, final Object handlerData, final ItemStack itemGolemPlacer, - final EntityPlayer player, final boolean dismantled, - final Side side ) - { - - } - - @Override - public InteractionLevel canHandleInteraction( final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, - final Side side ) - { - return InteractionLevel.NoInteraction; - } - - @Override - public Object customInteraction( final EntityGolemBase golem, final Object handlerData, final IGolemHookSyncRegistry syncData, - final EntityPlayer player, final Side side ) - { - return null; - } - - @Override - public void golemTick( final EntityGolemBase golem, final Object serverHandlerData, final IGolemHookSyncRegistry syncData ) - { - } - - @Override - public boolean needsDynamicUpdates() - { - return false; - } - - @Override - public boolean needsRenderer() - { - return false; - } - - @Override - public Object readEntityFromNBT( final EntityGolemBase golem, final NBTTagCompound nbtTag ) - { - return null; - } - - @Override - public void renderGolem( final EntityGolemBase golem, final Object clientHandlerData, final double x, final double y, final double z, - final float partialElaspsedTick ) - { - - } - - @Override - public Object setupGolem( final EntityGolemBase golem, final Object handlerData, final IGolemHookSyncRegistry syncData, final Side side ) - { - return null; - } - - @Override - public Object spawnGolemFromItemStack( final EntityGolemBase golem, final ItemStack itemGolemPlacer, final Side side ) - { - return null; - } - - @Override - public Object syncDataChanged( final IGolemHookSyncRegistry syncData, final Object clientHandlerData ) - { - return null; - } - - @Override - public void writeEntityNBT( final EntityGolemBase golem, final Object serverHandlerData, final NBTTagCompound nbtTag ) - { - - } - - } - - /** - * ID of the datawatcher field. - */ - private static int DATAWATCHER_ID = -1; - - /** - * Default sync values. - */ - private static final GolemSyncRegistry defaultSyncRegistry = new GolemSyncRegistry(); - - /** - * Internal handler used to track sync data. - */ - private static final DummyHookHandler internalHandler = new DummyHookHandler(); - - /** - * All hook handlers - */ - protected static final HashSet registeredHandlers = new HashSet(); - - /** - * Handlers that need to be called during tick event. - */ - protected static final HashSet dynamicHandlers = new HashSet(); - - /** - * Handlers that need to be called during render. - */ - protected static final HashSet renderHandlers = new HashSet(); - - /** - * Logs an exception when it occurs. - * - * @param hook - * @param handler - * @param e - */ - private static void logCaughtException( final String hook, final IGolemHookHandler handler, final Exception e ) - { - if( handler != null ) - { - if( e != null ) - { - ThELog.warning( "Caught Exception During call to '" + hook + "' for handler '%s':", handler.getClass().getCanonicalName() ); - ThELog.warning( e.toString() ); - } - else - { - ThELog.warning( "Caught Unknown Exception During call to '" + hook + "' for handler '%s'", handler.getClass().getCanonicalName() ); - } - } - else if( e != null ) - { - ThELog.warning( "Caught Exception During call to null handler '" + hook + "':" ); - ThELog.warning( e.toString() ); - } - else - { - ThELog.warning( "Caught Unknown Exception During call to null handler '" + hook + "'" ); - } - - } - - /** - * Hook for ItemGolemBell.onLeftClickEntity - * - * @param golem - * @param dropped - * @param player - * @param golemHandlerData - */ - public static void hook_Bell_OnLeftClickGolem( final EntityGolemBase golem, final ItemStack dropped, final EntityPlayer player, - final HashMap golemHandlerData ) - { - // Get the dismantled status - boolean dismantled = player.isSneaking(); - Side side = EffectiveSide.side(); - - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - try - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - - // Call handler - - handler.bellLeftClicked( golem, handlerData, dropped, player, dismantled, side ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "onBellLeftClick", handler, e ); - } - - } - - } - - /** - * Hook for EntityGolemBase.customInteraction - * - * @param golem - * @param player - * @param golemHandlerData - * @return - */ - public static boolean hook_CustomInteraction( final EntityGolemBase golem, final EntityPlayer player, - final HashMap golemHandlerData ) - { - GolemSyncRegistry syncRegistry = ( (GolemSyncRegistry)golemHandlerData.get( GolemHooks.internalHandler ) ); - - boolean needsSync = false; - boolean needsSetup = false; - boolean skipGUI = false; - InteractionLevel handlerLevel; - - Side side = EffectiveSide.side(); - - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - - // Call handler - try - { - handlerLevel = handler.canHandleInteraction( golem, handlerData, player, side ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "canHandleInteraction", handler, e ); - continue; - } - - switch ( handlerLevel ) - { - case NoInteraction: - continue; - - case BasicInteraction: - break; - - case SyncInteraction: - needsSync = true; - break; - - case FullInteraction: - needsSync = true; - needsSetup = true; - break; - } - - // Handled, dont show the GUI - skipGUI = true; - - boolean hadData = ( handlerData != null ); - try - { - handlerData = handler.customInteraction( golem, handlerData, syncRegistry, player, side ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "customInteraction", handler, e ); - continue; - } - - // Update golem - if( handlerData == null ) - { - if( hadData ) - { - golemHandlerData.remove( handler ); - } - } - else - { - golemHandlerData.put( handler, handlerData ); - } - - } - - if( side == Side.SERVER ) - { - if( needsSetup ) - { - golem.setupGolem(); - } - if( needsSync ) - { - syncRegistry.markDirty(); - } - } - - return skipGUI; - } - - /** - * Hook for EntityGolemBase.entityInit - * - * @param golem - * @param golemHandlerData - */ - public static void hook_EntityInit( final EntityGolemBase golem, final HashMap golemHandlerData ) - { - // Create a new sync registry - GolemSyncRegistry localRegistry = new GolemSyncRegistry(); - localRegistry.copyDefaults( GolemHooks.defaultSyncRegistry ); - - // Add to the handlers - golemHandlerData.put( GolemHooks.internalHandler, localRegistry ); - - // Get the datawatcher - DataWatcher watcher = golem.getDataWatcher(); - - // Has the ID been set? - if( GolemHooks.DATAWATCHER_ID == -1 ) - { - // Set the ID to the next available - for( int i = 4; i < 31; ++i ) - { - try - { - // Add the object - watcher.addObject( GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString() ); - - // Object was added - GolemHooks.DATAWATCHER_ID = i; - return; - } - catch( IllegalArgumentException e ) - { - } - } - - // If execution makes it this far, there were no available ID's :( - GolemHooks.DATAWATCHER_ID = -2; - ThELog.warning( "Golem Hook API is unable to register channel for sync data." ); - return; - } - else if( GolemHooks.DATAWATCHER_ID > 0 ) - { - // Add datawatcher field. - try - { - watcher.addObject( GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString() ); - } - catch( Exception e ) - { - localRegistry.markDirty(); - } - } - } - - /** - * Hook for EntityGolemBase.onEntityUpdate. - * Keeps client handlers updated. - * - * @param golem - * @param golemHandlerData - */ - public static void hook_onEntityUpdate( final EntityGolemBase golem, final HashMap golemHandlerData ) - { - // Get the sync registry - GolemSyncRegistry syncRegistry = (GolemSyncRegistry)golemHandlerData.get( GolemHooks.internalHandler ); - - if( EffectiveSide.isServerSide() ) - { - // Update handlers - for( IGolemHookHandler handler : GolemHooks.dynamicHandlers ) - { - try - { - handler.golemTick( golem, golemHandlerData.get( handler ), syncRegistry ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "golemTick", handler, e ); - } - } - - // Update data watcher - if( syncRegistry.hasChanged() ) - { - if( GolemHooks.DATAWATCHER_ID > 0 ) - { - try - { - golem.getDataWatcher().updateObject( GolemHooks.DATAWATCHER_ID, syncRegistry.mappingsToString() ); - } - catch( NullPointerException e1 ) - { - - try - { - golem.getDataWatcher().addObject( GolemHooks.DATAWATCHER_ID, syncRegistry.mappingsToString() ); - } - catch( Exception e2 ) - { - syncRegistry.markDirty(); - } - } - } - } - return; - } - - if( GolemHooks.DATAWATCHER_ID < 0 ) - { - return; - } - - // Update sync ticks - ++syncRegistry.clientSyncTicks; - - // Have 20 ticks passed? (Roughly a full second if the game is not lagging) - if( syncRegistry.clientSyncTicks >= 30.0f ) - { - // Reset the counter - syncRegistry.clientSyncTicks = 0.0f; - - // Is the data out of sync? - String watcherString; - try - { - watcherString = golem.getDataWatcher().getWatchableObjectString( GolemHooks.DATAWATCHER_ID ); - if( !syncRegistry.hasChanged() && ( watcherString == syncRegistry.lastUpdatedFrom ) ) - { - // Data is in sync - return; - } - } - catch( Exception e ) - { - return; - } - - // Read the sync data, and get the list of handlers to update - HashSet handlersToUpdate = syncRegistry.readFromString( watcherString ); - if( handlersToUpdate == null ) - { - // No handlers to update - return; - } - - // Inform each handler - for( IGolemHookHandler handler : handlersToUpdate ) - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - boolean hadData = ( handlerData != null ); - try - { - // Call handler - handlerData = handler.syncDataChanged( syncRegistry, handlerData ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "onSyncDataChanged", handler, e ); - continue; - } - - // Update golem - if( handlerData == null ) - { - if( hadData ) - { - golemHandlerData.remove( handler ); - } - } - else - { - golemHandlerData.put( handler, handlerData ); - } - } - } - - } - - /** - * Hook for ItemGolemPlacer.spawnCreature - * - * @param golem - * @param itemGolemPlacer - * @param golemHandlerData - */ - public static void hook_Placer_SpawnGolem( final EntityGolemBase golem, final ItemStack itemGolemPlacer, - final HashMap golemHandlerData ) - { - // Ensure the stack has an NBT tag - if( !itemGolemPlacer.hasTagCompound() ) - { - return; - } - Side side = EffectiveSide.side(); - - // Inform each handler - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - try - { - // Call handler - Object handlerData = handler.spawnGolemFromItemStack( golem, itemGolemPlacer, side ); - - // Update golem - if( handlerData != null ) - { - golemHandlerData.put( handler, handlerData ); - } - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "spawnGolemFromItemStack", handler, e ); - } - } - } - - /** - * Hook for EntityGolemBase.readEntityFromNBT - * - * @param golem - * @param golemHandlerData - * @param nbt - */ - public static void hook_ReadEntityFromNBT( final EntityGolemBase golem, final HashMap golemHandlerData, - final NBTTagCompound nbt ) - { - // Inform each handler - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - try - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - - // Call handler - handlerData = handler.readEntityFromNBT( golem, nbt ); - - // Update golem - if( handlerData == null ) - { - golemHandlerData.remove( handler ); - } - else - { - golemHandlerData.put( handler, handlerData ); - } - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "readEntityFromNBT", handler, e ); - } - } - } - - /** - * Hook for RenderGolemBase.render - * - * @param golem - * @param x - * @param y - * @param z - * @param partialElaspsedTick - */ - @SideOnly(Side.CLIENT) - public static void hook_RenderGolem( final EntityGolemBase golem, final HashMap golemHandlerData, final double x, - final double y, final double z, final float partialElaspsedTick ) - { - - // Call each render handler - for( IGolemHookHandler handler : GolemHooks.renderHandlers ) - { - try - { - handler.renderGolem( golem, golemHandlerData.get( handler ), x, y, z, partialElaspsedTick ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "renderGolem", handler, e ); - } - } - - } - - /** - * Hook for EntityGolemBase.setupGolem - * - * @param golem - * @param golemHandlerData - */ - public static void hook_SetupGolem( final EntityGolemBase golem, final HashMap golemHandlerData ) - { - // Get the sync data - GolemSyncRegistry localRegistry = (GolemSyncRegistry)golemHandlerData.get( GolemHooks.internalHandler ); - Side side = EffectiveSide.side(); - - // Inform each handler - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - try - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - boolean hadData = ( handlerData != null ); - - // Call handler - handlerData = handler.setupGolem( golem, handlerData, localRegistry, side ); - - // Update golem - if( handlerData == null ) - { - if( hadData ) - { - golemHandlerData.remove( handler ); - } - } - else - { - golemHandlerData.put( handler, handlerData ); - } - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "setupGolem", handler, e ); - } - } - - // Update data watcher - if( localRegistry.hasChanged() && ( side == Side.SERVER ) && ( GolemHooks.DATAWATCHER_ID > 0 ) ) - { - try - { - golem.getDataWatcher().updateObject( GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString() ); - } - catch( NullPointerException e ) - { - localRegistry.markDirty(); - } - } - } - - /** - * Hook for EntityGolemBase.writeEntityToNBT - * - * @param golem - * @param golemHandlerData - * @param nbt - */ - public static void hook_WriteEntityToNBT( final EntityGolemBase golem, final HashMap golemHandlerData, - final NBTTagCompound nbt ) - { - // Inform each handler - for( IGolemHookHandler handler : GolemHooks.registeredHandlers ) - { - try - { - // Get the current handler data - Object handlerData = golemHandlerData.getOrDefault( handler, null ); - - // Call handler - handler.writeEntityNBT( golem, handlerData, nbt ); - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "writeEntityNBT", handler, e ); - } - } - } - - /** - * Registers a handler. - * - * @param handler - */ - public static void registerHandler( final @Nonnull IGolemHookHandler handler ) - { - // Ensure the required transforms are present. - if( ThECore.golemHooksTransformFailed ) - { - return; - } - - try - { - // Add the handler - GolemHooks.registeredHandlers.add( handler ); - - // Needs render? - if( handler.needsRenderer() ) - { - GolemHooks.renderHandlers.add( handler ); - } - - // Needs tick? - if( handler.needsDynamicUpdates() ) - { - GolemHooks.dynamicHandlers.add( handler ); - } - - // Register sync data - GolemHooks.defaultSyncRegistry.canRegister = true; - handler.addDefaultSyncEntries( GolemHooks.defaultSyncRegistry ); - GolemHooks.defaultSyncRegistry.canRegister = false; - - } - catch( Exception e ) - { - GolemHooks.logCaughtException( "registerHandler", handler, e ); - } - - } +public class GolemHooks { + private static class DummyHookHandler implements IGolemHookHandler { + + public DummyHookHandler() {} + + @Override + public void addDefaultSyncEntries(final IGolemHookSyncRegistry syncRegistry) {} + + @Override + public void bellLeftClicked( + final EntityGolemBase golem, + final Object handlerData, + final ItemStack itemGolemPlacer, + final EntityPlayer player, + final boolean dismantled, + final Side side) {} + + @Override + public InteractionLevel canHandleInteraction( + final EntityGolemBase golem, final Object handlerData, final EntityPlayer player, final Side side) { + return InteractionLevel.NoInteraction; + } + + @Override + public Object customInteraction( + final EntityGolemBase golem, + final Object handlerData, + final IGolemHookSyncRegistry syncData, + final EntityPlayer player, + final Side side) { + return null; + } + + @Override + public void golemTick( + final EntityGolemBase golem, final Object serverHandlerData, final IGolemHookSyncRegistry syncData) {} + + @Override + public boolean needsDynamicUpdates() { + return false; + } + + @Override + public boolean needsRenderer() { + return false; + } + + @Override + public Object readEntityFromNBT(final EntityGolemBase golem, final NBTTagCompound nbtTag) { + return null; + } + + @Override + public void renderGolem( + final EntityGolemBase golem, + final Object clientHandlerData, + final double x, + final double y, + final double z, + final float partialElaspsedTick) {} + + @Override + public Object setupGolem( + final EntityGolemBase golem, + final Object handlerData, + final IGolemHookSyncRegistry syncData, + final Side side) { + return null; + } + + @Override + public Object spawnGolemFromItemStack( + final EntityGolemBase golem, final ItemStack itemGolemPlacer, final Side side) { + return null; + } + + @Override + public Object syncDataChanged(final IGolemHookSyncRegistry syncData, final Object clientHandlerData) { + return null; + } + + @Override + public void writeEntityNBT( + final EntityGolemBase golem, final Object serverHandlerData, final NBTTagCompound nbtTag) {} + } + + /** + * ID of the datawatcher field. + */ + private static int DATAWATCHER_ID = -1; + + /** + * Default sync values. + */ + private static final GolemSyncRegistry defaultSyncRegistry = new GolemSyncRegistry(); + + /** + * Internal handler used to track sync data. + */ + private static final DummyHookHandler internalHandler = new DummyHookHandler(); + + /** + * All hook handlers + */ + protected static final HashSet registeredHandlers = new HashSet(); + + /** + * Handlers that need to be called during tick event. + */ + protected static final HashSet dynamicHandlers = new HashSet(); + + /** + * Handlers that need to be called during render. + */ + protected static final HashSet renderHandlers = new HashSet(); + + /** + * Logs an exception when it occurs. + * + * @param hook + * @param handler + * @param e + */ + private static void logCaughtException(final String hook, final IGolemHookHandler handler, final Exception e) { + if (handler != null) { + if (e != null) { + ThELog.warning( + "Caught Exception During call to '" + hook + "' for handler '%s':", + handler.getClass().getCanonicalName()); + ThELog.warning(e.toString()); + } else { + ThELog.warning( + "Caught Unknown Exception During call to '" + hook + "' for handler '%s'", + handler.getClass().getCanonicalName()); + } + } else if (e != null) { + ThELog.warning("Caught Exception During call to null handler '" + hook + "':"); + ThELog.warning(e.toString()); + } else { + ThELog.warning("Caught Unknown Exception During call to null handler '" + hook + "'"); + } + } + + /** + * Hook for ItemGolemBell.onLeftClickEntity + * + * @param golem + * @param dropped + * @param player + * @param golemHandlerData + */ + public static void hook_Bell_OnLeftClickGolem( + final EntityGolemBase golem, + final ItemStack dropped, + final EntityPlayer player, + final HashMap golemHandlerData) { + // Get the dismantled status + boolean dismantled = player.isSneaking(); + Side side = EffectiveSide.side(); + + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + try { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + + // Call handler + + handler.bellLeftClicked(golem, handlerData, dropped, player, dismantled, side); + } catch (Exception e) { + GolemHooks.logCaughtException("onBellLeftClick", handler, e); + } + } + } + + /** + * Hook for EntityGolemBase.customInteraction + * + * @param golem + * @param player + * @param golemHandlerData + * @return + */ + public static boolean hook_CustomInteraction( + final EntityGolemBase golem, + final EntityPlayer player, + final HashMap golemHandlerData) { + GolemSyncRegistry syncRegistry = ((GolemSyncRegistry) golemHandlerData.get(GolemHooks.internalHandler)); + + boolean needsSync = false; + boolean needsSetup = false; + boolean skipGUI = false; + InteractionLevel handlerLevel; + + Side side = EffectiveSide.side(); + + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + + // Call handler + try { + handlerLevel = handler.canHandleInteraction(golem, handlerData, player, side); + } catch (Exception e) { + GolemHooks.logCaughtException("canHandleInteraction", handler, e); + continue; + } + + switch (handlerLevel) { + case NoInteraction: + continue; + + case BasicInteraction: + break; + + case SyncInteraction: + needsSync = true; + break; + + case FullInteraction: + needsSync = true; + needsSetup = true; + break; + } + + // Handled, dont show the GUI + skipGUI = true; + + boolean hadData = (handlerData != null); + try { + handlerData = handler.customInteraction(golem, handlerData, syncRegistry, player, side); + } catch (Exception e) { + GolemHooks.logCaughtException("customInteraction", handler, e); + continue; + } + + // Update golem + if (handlerData == null) { + if (hadData) { + golemHandlerData.remove(handler); + } + } else { + golemHandlerData.put(handler, handlerData); + } + } + + if (side == Side.SERVER) { + if (needsSetup) { + golem.setupGolem(); + } + if (needsSync) { + syncRegistry.markDirty(); + } + } + + return skipGUI; + } + + /** + * Hook for EntityGolemBase.entityInit + * + * @param golem + * @param golemHandlerData + */ + public static void hook_EntityInit( + final EntityGolemBase golem, final HashMap golemHandlerData) { + // Create a new sync registry + GolemSyncRegistry localRegistry = new GolemSyncRegistry(); + localRegistry.copyDefaults(GolemHooks.defaultSyncRegistry); + + // Add to the handlers + golemHandlerData.put(GolemHooks.internalHandler, localRegistry); + + // Get the datawatcher + DataWatcher watcher = golem.getDataWatcher(); + + // Has the ID been set? + if (GolemHooks.DATAWATCHER_ID == -1) { + // Set the ID to the next available + for (int i = 4; i < 31; ++i) { + try { + // Add the object + watcher.addObject(GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString()); + + // Object was added + GolemHooks.DATAWATCHER_ID = i; + return; + } catch (IllegalArgumentException e) { + } + } + + // If execution makes it this far, there were no available ID's :( + GolemHooks.DATAWATCHER_ID = -2; + ThELog.warning("Golem Hook API is unable to register channel for sync data."); + return; + } else if (GolemHooks.DATAWATCHER_ID > 0) { + // Add datawatcher field. + try { + watcher.addObject(GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString()); + } catch (Exception e) { + localRegistry.markDirty(); + } + } + } + + /** + * Hook for EntityGolemBase.onEntityUpdate. + * Keeps client handlers updated. + * + * @param golem + * @param golemHandlerData + */ + public static void hook_onEntityUpdate( + final EntityGolemBase golem, final HashMap golemHandlerData) { + // Get the sync registry + GolemSyncRegistry syncRegistry = (GolemSyncRegistry) golemHandlerData.get(GolemHooks.internalHandler); + + if (EffectiveSide.isServerSide()) { + // Update handlers + for (IGolemHookHandler handler : GolemHooks.dynamicHandlers) { + try { + handler.golemTick(golem, golemHandlerData.get(handler), syncRegistry); + } catch (Exception e) { + GolemHooks.logCaughtException("golemTick", handler, e); + } + } + + // Update data watcher + if (syncRegistry.hasChanged()) { + if (GolemHooks.DATAWATCHER_ID > 0) { + try { + golem.getDataWatcher().updateObject(GolemHooks.DATAWATCHER_ID, syncRegistry.mappingsToString()); + } catch (NullPointerException e1) { + + try { + golem.getDataWatcher() + .addObject(GolemHooks.DATAWATCHER_ID, syncRegistry.mappingsToString()); + } catch (Exception e2) { + syncRegistry.markDirty(); + } + } + } + } + return; + } + + if (GolemHooks.DATAWATCHER_ID < 0) { + return; + } + + // Update sync ticks + ++syncRegistry.clientSyncTicks; + + // Have 20 ticks passed? (Roughly a full second if the game is not lagging) + if (syncRegistry.clientSyncTicks >= 30.0f) { + // Reset the counter + syncRegistry.clientSyncTicks = 0.0f; + + // Is the data out of sync? + String watcherString; + try { + watcherString = golem.getDataWatcher().getWatchableObjectString(GolemHooks.DATAWATCHER_ID); + if (!syncRegistry.hasChanged() && (watcherString == syncRegistry.lastUpdatedFrom)) { + // Data is in sync + return; + } + } catch (Exception e) { + return; + } + + // Read the sync data, and get the list of handlers to update + HashSet handlersToUpdate = syncRegistry.readFromString(watcherString); + if (handlersToUpdate == null) { + // No handlers to update + return; + } + + // Inform each handler + for (IGolemHookHandler handler : handlersToUpdate) { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + boolean hadData = (handlerData != null); + try { + // Call handler + handlerData = handler.syncDataChanged(syncRegistry, handlerData); + } catch (Exception e) { + GolemHooks.logCaughtException("onSyncDataChanged", handler, e); + continue; + } + + // Update golem + if (handlerData == null) { + if (hadData) { + golemHandlerData.remove(handler); + } + } else { + golemHandlerData.put(handler, handlerData); + } + } + } + } + + /** + * Hook for ItemGolemPlacer.spawnCreature + * + * @param golem + * @param itemGolemPlacer + * @param golemHandlerData + */ + public static void hook_Placer_SpawnGolem( + final EntityGolemBase golem, + final ItemStack itemGolemPlacer, + final HashMap golemHandlerData) { + // Ensure the stack has an NBT tag + if (!itemGolemPlacer.hasTagCompound()) { + return; + } + Side side = EffectiveSide.side(); + + // Inform each handler + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + try { + // Call handler + Object handlerData = handler.spawnGolemFromItemStack(golem, itemGolemPlacer, side); + + // Update golem + if (handlerData != null) { + golemHandlerData.put(handler, handlerData); + } + } catch (Exception e) { + GolemHooks.logCaughtException("spawnGolemFromItemStack", handler, e); + } + } + } + + /** + * Hook for EntityGolemBase.readEntityFromNBT + * + * @param golem + * @param golemHandlerData + * @param nbt + */ + public static void hook_ReadEntityFromNBT( + final EntityGolemBase golem, + final HashMap golemHandlerData, + final NBTTagCompound nbt) { + // Inform each handler + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + try { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + + // Call handler + handlerData = handler.readEntityFromNBT(golem, nbt); + + // Update golem + if (handlerData == null) { + golemHandlerData.remove(handler); + } else { + golemHandlerData.put(handler, handlerData); + } + } catch (Exception e) { + GolemHooks.logCaughtException("readEntityFromNBT", handler, e); + } + } + } + + /** + * Hook for RenderGolemBase.render + * + * @param golem + * @param x + * @param y + * @param z + * @param partialElaspsedTick + */ + @SideOnly(Side.CLIENT) + public static void hook_RenderGolem( + final EntityGolemBase golem, + final HashMap golemHandlerData, + final double x, + final double y, + final double z, + final float partialElaspsedTick) { + + // Call each render handler + for (IGolemHookHandler handler : GolemHooks.renderHandlers) { + try { + handler.renderGolem(golem, golemHandlerData.get(handler), x, y, z, partialElaspsedTick); + } catch (Exception e) { + GolemHooks.logCaughtException("renderGolem", handler, e); + } + } + } + + /** + * Hook for EntityGolemBase.setupGolem + * + * @param golem + * @param golemHandlerData + */ + public static void hook_SetupGolem( + final EntityGolemBase golem, final HashMap golemHandlerData) { + // Get the sync data + GolemSyncRegistry localRegistry = (GolemSyncRegistry) golemHandlerData.get(GolemHooks.internalHandler); + Side side = EffectiveSide.side(); + + // Inform each handler + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + try { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + boolean hadData = (handlerData != null); + + // Call handler + handlerData = handler.setupGolem(golem, handlerData, localRegistry, side); + + // Update golem + if (handlerData == null) { + if (hadData) { + golemHandlerData.remove(handler); + } + } else { + golemHandlerData.put(handler, handlerData); + } + } catch (Exception e) { + GolemHooks.logCaughtException("setupGolem", handler, e); + } + } + + // Update data watcher + if (localRegistry.hasChanged() && (side == Side.SERVER) && (GolemHooks.DATAWATCHER_ID > 0)) { + try { + golem.getDataWatcher().updateObject(GolemHooks.DATAWATCHER_ID, localRegistry.mappingsToString()); + } catch (NullPointerException e) { + localRegistry.markDirty(); + } + } + } + + /** + * Hook for EntityGolemBase.writeEntityToNBT + * + * @param golem + * @param golemHandlerData + * @param nbt + */ + public static void hook_WriteEntityToNBT( + final EntityGolemBase golem, + final HashMap golemHandlerData, + final NBTTagCompound nbt) { + // Inform each handler + for (IGolemHookHandler handler : GolemHooks.registeredHandlers) { + try { + // Get the current handler data + Object handlerData = golemHandlerData.getOrDefault(handler, null); + + // Call handler + handler.writeEntityNBT(golem, handlerData, nbt); + } catch (Exception e) { + GolemHooks.logCaughtException("writeEntityNBT", handler, e); + } + } + } + + /** + * Registers a handler. + * + * @param handler + */ + public static void registerHandler(final @Nonnull IGolemHookHandler handler) { + // Ensure the required transforms are present. + if (ThECore.golemHooksTransformFailed) { + return; + } + + try { + // Add the handler + GolemHooks.registeredHandlers.add(handler); + + // Needs render? + if (handler.needsRenderer()) { + GolemHooks.renderHandlers.add(handler); + } + + // Needs tick? + if (handler.needsDynamicUpdates()) { + GolemHooks.dynamicHandlers.add(handler); + } + + // Register sync data + GolemHooks.defaultSyncRegistry.canRegister = true; + handler.addDefaultSyncEntries(GolemHooks.defaultSyncRegistry); + GolemHooks.defaultSyncRegistry.canRegister = false; + + } catch (Exception e) { + GolemHooks.logCaughtException("registerHandler", handler, e); + } + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/GolemSyncRegistry.java b/src/main/java/thaumicenergistics/common/integration/tc/GolemSyncRegistry.java index c664c23f..804a6769 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/GolemSyncRegistry.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/GolemSyncRegistry.java @@ -1,232 +1,210 @@ package thaumicenergistics.common.integration.tc; +import com.google.common.base.Charsets; import java.io.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; -import com.google.common.base.Charsets; import thaumicenergistics.api.entities.IGolemHookHandler; import thaumicenergistics.api.entities.IGolemHookSyncRegistry; import thaumicenergistics.common.utils.ThELog; -class GolemSyncRegistry - implements IGolemHookSyncRegistry -{ - /** - * Maps ID => Handler - */ - private static final HashMap handlerMappings = new HashMap(); +class GolemSyncRegistry implements IGolemHookSyncRegistry { + /** + * Maps ID => Handler + */ + private static final HashMap handlerMappings = + new HashMap(); - /** - * Maps ID => Data - */ - private final HashMap dataMappings = new HashMap(); + /** + * Maps ID => Data + */ + private final HashMap dataMappings = new HashMap(); - /** - * Next ID - */ - private Integer uuid = Integer.valueOf( 13 ); + /** + * Next ID + */ + private Integer uuid = Integer.valueOf(13); - /** - * True if the data has changed. - */ - private boolean hasDataChanged = false; + /** + * True if the data has changed. + */ + private boolean hasDataChanged = false; - /** - * True if new values can be added. - */ - public boolean canRegister = false; + /** + * True if new values can be added. + */ + public boolean canRegister = false; - /** - * The string that the mappings were read from. - */ - public String lastUpdatedFrom = null; + /** + * The string that the mappings were read from. + */ + public String lastUpdatedFrom = null; - /** - * Tracks the number of ticks since the last sync on the client side. - */ - public float clientSyncTicks = 0.0f; + /** + * Tracks the number of ticks since the last sync on the client side. + */ + public float clientSyncTicks = 0.0f; - public void copyDefaults( final GolemSyncRegistry defaults ) - { - // Clear the maps - this.dataMappings.clear(); + public void copyDefaults(final GolemSyncRegistry defaults) { + // Clear the maps + this.dataMappings.clear(); - // Copy the defaults - this.dataMappings.putAll( defaults.dataMappings ); - this.hasDataChanged = true; - } + // Copy the defaults + this.dataMappings.putAll(defaults.dataMappings); + this.hasDataChanged = true; + } - @Override - public char getSyncCharOrDefault( final int id, final char defaultChar ) - { - return this.dataMappings.getOrDefault( Integer.valueOf( id ), defaultChar ); - } + @Override + public char getSyncCharOrDefault(final int id, final char defaultChar) { + return this.dataMappings.getOrDefault(Integer.valueOf(id), defaultChar); + } - /** - * True if the data has changed since the last sync. - * - * @return - */ - public boolean hasChanged() - { - return this.hasDataChanged; - } + /** + * True if the data has changed since the last sync. + * + * @return + */ + public boolean hasChanged() { + return this.hasDataChanged; + } - /** - * Converts the mappings into a string. - * - * @return - */ - public String mappingsToString() - { - this.hasDataChanged = false; + /** + * Converts the mappings into a string. + * + * @return + */ + public String mappingsToString() { + this.hasDataChanged = false; - // Write the data - try( ByteArrayOutputStream baos = new ByteArrayOutputStream( ( this.dataMappings.size() * 6 ) + 4 ); - DataOutputStream stream = new DataOutputStream( baos ) ) - { + // Write the data + try (ByteArrayOutputStream baos = new ByteArrayOutputStream((this.dataMappings.size() * 6) + 4); + DataOutputStream stream = new DataOutputStream(baos)) { - // Write count - stream.writeInt( this.dataMappings.size() ); + // Write count + stream.writeInt(this.dataMappings.size()); - for( Entry entry : this.dataMappings.entrySet() ) - { - // Write the ID - stream.writeInt( entry.getKey() ); + for (Entry entry : this.dataMappings.entrySet()) { + // Write the ID + stream.writeInt(entry.getKey()); - // Write the char - stream.writeChar( entry.getValue() ); - } - stream.close(); + // Write the char + stream.writeChar(entry.getValue()); + } + stream.close(); - // Return the string - return baos.toString( Charsets.UTF_8.name() ); - } - catch( IOException e ) - { - ThELog.error( e, "Unable to send golem sync data" ); - } + // Return the string + return baos.toString(Charsets.UTF_8.name()); + } catch (IOException e) { + ThELog.error(e, "Unable to send golem sync data"); + } - return ""; - } + return ""; + } - /** - * Marks the registry as needing to be syncd. - */ - public void markDirty() - { - this.hasDataChanged = true; - } + /** + * Marks the registry as needing to be syncd. + */ + public void markDirty() { + this.hasDataChanged = true; + } - /** - * Reads the mappings from a string - * - * @param data - */ - public HashSet readFromString( final String data ) - { - if( ( data == null ) || ( data.length() < 4 ) ) - { - ThELog.warning( "Incomplete golem sync data received" ); - return null; - } + /** + * Reads the mappings from a string + * + * @param data + */ + public HashSet readFromString(final String data) { + if ((data == null) || (data.length() < 4)) { + ThELog.warning("Incomplete golem sync data received"); + return null; + } - HashSet handlersToUpdate = new HashSet(); + HashSet handlersToUpdate = new HashSet(); - // Mark the data as valid - this.hasDataChanged = false; + // Mark the data as valid + this.hasDataChanged = false; - // Save the string - this.lastUpdatedFrom = data; + // Save the string + this.lastUpdatedFrom = data; - // Read the data - try( ByteArrayInputStream bais = new ByteArrayInputStream( data.getBytes( Charsets.UTF_8.name() ) ); - DataInputStream stream = new DataInputStream( bais ); ) - { + // Read the data + try (ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(Charsets.UTF_8.name())); + DataInputStream stream = new DataInputStream(bais); ) { - // Read the count - int count = stream.readInt(); + // Read the count + int count = stream.readInt(); - for( int i = 0; i < count; ++i ) - { - // Read the ID - Integer id = Integer.valueOf( stream.readInt() ); + for (int i = 0; i < count; ++i) { + // Read the ID + Integer id = Integer.valueOf(stream.readInt()); - // Read the char - Character c = Character.valueOf( stream.readChar() ); + // Read the char + Character c = Character.valueOf(stream.readChar()); - // Add to the mapping - this.dataMappings.put( id, c ); + // Add to the mapping + this.dataMappings.put(id, c); - // Mark for update - handlersToUpdate.add( GolemSyncRegistry.handlerMappings.get( id ) ); - } + // Mark for update + handlersToUpdate.add(GolemSyncRegistry.handlerMappings.get(id)); + } - // Close the stream - stream.close(); - } - catch( Exception e ) - { - ThELog.error( e, "Malformed golem sync data received" ); + // Close the stream + stream.close(); + } catch (Exception e) { + ThELog.error(e, "Malformed golem sync data received"); + } - } + // Update handlers + if (!handlersToUpdate.isEmpty()) { + return handlersToUpdate; + } - // Update handlers - if( !handlersToUpdate.isEmpty() ) - { - return handlersToUpdate; - } + return null; + } - return null; - } + @Override + public int registerSyncChar(final IGolemHookHandler handler, final char c) { + if (!this.canRegister) { + throw new UnsupportedOperationException("Can not register new sync data at this location."); + } - @Override - public int registerSyncChar( final IGolemHookHandler handler, final char c ) - { - if( !this.canRegister ) - { - throw new UnsupportedOperationException( "Can not register new sync data at this location." ); - } + // Add the mappings + this.dataMappings.put(this.uuid, Character.valueOf(c)); + GolemSyncRegistry.handlerMappings.put(this.uuid, handler); + this.hasDataChanged = true; - // Add the mappings - this.dataMappings.put( this.uuid, Character.valueOf( c ) ); - GolemSyncRegistry.handlerMappings.put( this.uuid, handler ); - this.hasDataChanged = true; + // Get the id + int id = this.uuid; - // Get the id - int id = this.uuid; + // Increment the uuid + this.uuid = Integer.valueOf(id + 1); - // Increment the uuid - this.uuid = Integer.valueOf( id + 1 ); + return id; + } - return id; - } + @Override + public void updateSyncChar(final IGolemHookHandler handler, final int id, final char c) { + // Get the id + Integer ID = Integer.valueOf(id); - @Override - public void updateSyncChar( final IGolemHookHandler handler, final int id, final char c ) - { - // Get the id - Integer ID = Integer.valueOf( id ); + // Does the map have this id? + if (!this.dataMappings.containsKey(ID)) { + throw new UnsupportedOperationException( + "Unable to update sync byte '" + Integer.toString(id) + "', that ID is not mapped"); + } - // Does the map have this id? - if( !this.dataMappings.containsKey( ID ) ) - { - throw new UnsupportedOperationException( "Unable to update sync byte '" + Integer.toString( id ) + "', that ID is not mapped" ); - } + // Get the registered handler + IGolemHookHandler registeredHandler = handlerMappings.get(ID); + if (registeredHandler != handler) { + throw new UnsupportedOperationException( + "Unable to update sync byte '" + Integer.toString(id) + "', that ID does not belong to you."); + } - // Get the registered handler - IGolemHookHandler registeredHandler = handlerMappings.get( ID ); - if( registeredHandler != handler ) - { - throw new UnsupportedOperationException( "Unable to update sync byte '" + Integer.toString( id ) + "', that ID does not belong to you." ); - } - - // Update - Character newValue = Character.valueOf( c ); - if( this.dataMappings.put( ID, newValue ) != newValue ) - { - this.hasDataChanged = true; - } - } + // Update + Character newValue = Character.valueOf(c); + if (this.dataMappings.put(ID, newValue) != newValue) { + this.hasDataChanged = true; + } + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/GolemUpgradeTypes.java b/src/main/java/thaumicenergistics/common/integration/tc/GolemUpgradeTypes.java index 46854919..c0546802 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/GolemUpgradeTypes.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/GolemUpgradeTypes.java @@ -2,48 +2,43 @@ package thaumicenergistics.common.integration.tc; import javax.annotation.Nullable; -public enum GolemUpgradeTypes -{ - Air (0), - Earth (1), - Fire (2), - Water (3), - Order (4), - Entropy (5); +public enum GolemUpgradeTypes { + Air(0), + Earth(1), + Fire(2), + Water(3), + Order(4), + Entropy(5); - /** - * Array of upgrades sorted by ID. - */ - public static final GolemUpgradeTypes allUpgrades[]; - static - { - GolemUpgradeTypes[] values = GolemUpgradeTypes.values(); + /** + * Array of upgrades sorted by ID. + */ + public static final GolemUpgradeTypes allUpgrades[]; - // Setup the array - allUpgrades = new GolemUpgradeTypes[values.length]; - for( GolemUpgradeTypes upgrade : values ) - { - allUpgrades[upgrade.upgradeID] = upgrade; - } - } + static { + GolemUpgradeTypes[] values = GolemUpgradeTypes.values(); - /** - * Thaumcraft ID for the upgrade. - */ - public final byte upgradeID; + // Setup the array + allUpgrades = new GolemUpgradeTypes[values.length]; + for (GolemUpgradeTypes upgrade : values) { + allUpgrades[upgrade.upgradeID] = upgrade; + } + } - private GolemUpgradeTypes( final int ID ) - { - this.upgradeID = (byte)ID; - } + /** + * Thaumcraft ID for the upgrade. + */ + public final byte upgradeID; - @Nullable - public static GolemUpgradeTypes getUpgradeByID( final byte ID ) - { - if( ( ID >= 0 ) && ( ID < allUpgrades.length ) ) - { - return allUpgrades[ID]; - } - return null; - } + private GolemUpgradeTypes(final int ID) { + this.upgradeID = (byte) ID; + } + + @Nullable + public static GolemUpgradeTypes getUpgradeByID(final byte ID) { + if ((ID >= 0) && (ID < allUpgrades.length)) { + return allUpgrades[ID]; + } + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/MEItemAspectBridgeContainer.java b/src/main/java/thaumicenergistics/common/integration/tc/MEItemAspectBridgeContainer.java index e4b694ae..b0108896 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/MEItemAspectBridgeContainer.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/MEItemAspectBridgeContainer.java @@ -1,14 +1,14 @@ package thaumicenergistics.common.integration.tc; -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.util.Map; -import java.util.Map.Entry; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.eventhandler.EventBus; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Map.Entry; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; @@ -26,130 +26,119 @@ import thaumicenergistics.common.inventory.TheInternalInventory; * */ @SideOnly(Side.CLIENT) -public class MEItemAspectBridgeContainer - extends Container -{ - /** - * Reference to TC's client event handler, which houses the renderAspects - * function I need. - */ - private static WeakReference thaumcraftClientEvents = new WeakReference( null ); +public class MEItemAspectBridgeContainer extends Container { + /** + * Reference to TC's client event handler, which houses the renderAspects + * function I need. + */ + private static WeakReference thaumcraftClientEvents = + new WeakReference(null); - /** - * Internal inventory that mirrors the ME items displayed by the A.C.T - */ - private TheInternalInventory internalInventory; + /** + * Internal inventory that mirrors the ME items displayed by the A.C.T + */ + private TheInternalInventory internalInventory; - /** - * Constructs a pseudo container that TC can use to 'see' the items in the - * ME network. - * - * @param inventorySize - * @throws Exception - * When the TC rendering code can not be found, the bridge will not - * construct. - */ - public MEItemAspectBridgeContainer( final int inventorySize ) throws Exception - { - // Create the inventory - this.internalInventory = new TheInternalInventory( "TC Inventory Bridge", inventorySize, 1 ); + /** + * Constructs a pseudo container that TC can use to 'see' the items in the + * ME network. + * + * @param inventorySize + * @throws Exception + * When the TC rendering code can not be found, the bridge will not + * construct. + */ + public MEItemAspectBridgeContainer(final int inventorySize) throws Exception { + // Create the inventory + this.internalInventory = new TheInternalInventory("TC Inventory Bridge", inventorySize, 1); - // Have we hooked to TC's event handler? - if( MEItemAspectBridgeContainer.thaumcraftClientEvents.get() == null ) - { - // Access the listenerOwners field - Field loField = EventBus.class.getDeclaredField( "listenerOwners" ); - loField.setAccessible( true ); + // Have we hooked to TC's event handler? + if (MEItemAspectBridgeContainer.thaumcraftClientEvents.get() == null) { + // Access the listenerOwners field + Field loField = EventBus.class.getDeclaredField("listenerOwners"); + loField.setAccessible(true); - // Get the owners - Map owners = (Map)loField.get( FMLCommonHandler.instance().bus() ); + // Get the owners + Map owners = (Map) + loField.get(FMLCommonHandler.instance().bus()); - // Attempt to locate TC's event handler - for( Entry set : owners.entrySet() ) - { - Object Owner = set.getKey(); + // Attempt to locate TC's event handler + for (Entry set : owners.entrySet()) { + Object Owner = set.getKey(); - if( Owner instanceof thaumcraft.client.lib.ClientTickEventsFML ) - { - MEItemAspectBridgeContainer.thaumcraftClientEvents = new WeakReference( (ClientTickEventsFML)Owner ); - break; - } - } + if (Owner instanceof thaumcraft.client.lib.ClientTickEventsFML) { + MEItemAspectBridgeContainer.thaumcraftClientEvents = + new WeakReference((ClientTickEventsFML) Owner); + break; + } + } - // Get rid of the references, cause I'm paranoid. - owners = null; - loField = null; + // Get rid of the references, cause I'm paranoid. + owners = null; + loField = null; - // Did we locate it? - if( MEItemAspectBridgeContainer.thaumcraftClientEvents.get() == null ) - { - throw new Exception( "Unable to find TC event handler" ); - } - } + // Did we locate it? + if (MEItemAspectBridgeContainer.thaumcraftClientEvents.get() == null) { + throw new Exception("Unable to find TC event handler"); + } + } + } - } + /** + * Adds a slot to the container. The index and position should perfectly + * match the widgets they represent. + * + * @param index + * @param posX + * @param posY + */ + public void addSlot(final int index, final int posX, final int posY) { + // Create the slot + Slot bridgeSlot = new Slot(this.internalInventory, index, posX, posY); - /** - * Adds a slot to the container. The index and position should perfectly - * match the widgets they represent. - * - * @param index - * @param posX - * @param posY - */ - public void addSlot( final int index, final int posX, final int posY ) - { - // Create the slot - Slot bridgeSlot = new Slot( this.internalInventory, index, posX, posY ); + // Add the slot + this.addSlotToContainer(bridgeSlot); + } - // Add the slot - this.addSlotToContainer( bridgeSlot ); - } + @Override + public boolean canInteractWith(final EntityPlayer p_75145_1_) { + // Ignored + return false; + } - @Override - public boolean canInteractWith( final EntityPlayer p_75145_1_ ) - { - // Ignored - return false; - } + /** + * Calls on TC to render the items aspects. This should only be called from + * a GUI's drawScreen event. + * + * @param gui + * @param player + */ + public void renderAspects(final GuiContainer gui, final EntityPlayer player) { + ClientTickEventsFML tceh = MEItemAspectBridgeContainer.thaumcraftClientEvents.get(); - /** - * Calls on TC to render the items aspects. This should only be called from - * a GUI's drawScreen event. - * - * @param gui - * @param player - */ - public void renderAspects( final GuiContainer gui, final EntityPlayer player ) - { - ClientTickEventsFML tceh = MEItemAspectBridgeContainer.thaumcraftClientEvents.get(); + if (tceh != null) { + // Get the actual container + Container actualContainer = gui.inventorySlots; - if( tceh != null ) - { - // Get the actual container - Container actualContainer = gui.inventorySlots; + // Set the container to this bridge + gui.inventorySlots = this; - // Set the container to this bridge - gui.inventorySlots = this; + // Call render + tceh.renderAspectsInGui(gui, player); - // Call render - tceh.renderAspectsInGui( gui, player ); - - // Re-set the container to the original - gui.inventorySlots = actualContainer; - } - } - - /** - * Sets the itemstack of the slot. When you update a widget, update this as - * well. - * - * @param index - * @param stack - */ - public void setSlot( final int index, final ItemStack stack ) - { - this.getSlot( index ).putStack( stack ); - } + // Re-set the container to the original + gui.inventorySlots = actualContainer; + } + } + /** + * Sets the itemstack of the slot. When you update a widget, update this as + * well. + * + * @param index + * @param stack + */ + public void setSlot(final int index, final ItemStack stack) { + this.getSlot(index).putStack(stack); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/PseudoResearchItem.java b/src/main/java/thaumicenergistics/common/integration/tc/PseudoResearchItem.java index f1f19ff8..4769f7f2 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/PseudoResearchItem.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/PseudoResearchItem.java @@ -9,146 +9,138 @@ import thaumcraft.api.research.ResearchCategories; import thaumcraft.api.research.ResearchItem; import thaumcraft.api.research.ResearchPage; -public class PseudoResearchItem - extends ResearchItem -{ - private ResearchItem realResearch; +public class PseudoResearchItem extends ResearchItem { + private ResearchItem realResearch; - /** - * Icon as itemstack - * - * @param key - * @param category - * @param column - * @param row - * @param icon - */ - private PseudoResearchItem( final String key, final String category, final int column, final int row, final ItemStack icon ) - { - // Call super and create the research item - super( key, category, new AspectList(), column, row, 1, icon ); + /** + * Icon as itemstack + * + * @param key + * @param category + * @param column + * @param row + * @param icon + */ + private PseudoResearchItem( + final String key, final String category, final int column, final int row, final ItemStack icon) { + // Call super and create the research item + super(key, category, new AspectList(), column, row, 1, icon); - // Set as a stub - this.setStub().setHidden(); - } + // Set as a stub + this.setStub().setHidden(); + } - /** - * Icon as resource location - * - * @param key - * @param category - * @param column - * @param row - * @param icon - */ - private PseudoResearchItem( final String key, final String category, final int column, final int row, final ResourceLocation icon ) - { - // Call super and create the research item - super( key, category, new AspectList(), column, row, 1, icon ); + /** + * Icon as resource location + * + * @param key + * @param category + * @param column + * @param row + * @param icon + */ + private PseudoResearchItem( + final String key, final String category, final int column, final int row, final ResourceLocation icon) { + // Call super and create the research item + super(key, category, new AspectList(), column, row, 1, icon); - // Set as a stub - this.setStub().setHidden(); - } + // Set as a stub + this.setStub().setHidden(); + } - /** - * Creates a new pseudo research item. - * - * @param key - * @param category - * @param realKey - * @param realCategory - * @param column - * @param row - * @return - */ - public static PseudoResearchItem newPseudo( final String key, final String category, final String realKey, final String realCategory, - final int column, final int row ) - { - PseudoResearchItem pseudo; + /** + * Creates a new pseudo research item. + * + * @param key + * @param category + * @param realKey + * @param realCategory + * @param column + * @param row + * @return + */ + public static PseudoResearchItem newPseudo( + final String key, + final String category, + final String realKey, + final String realCategory, + final int column, + final int row) { + PseudoResearchItem pseudo; - // Get the actual research item - ResearchItem realResearch = ResearchCategories.researchCategories.get( realCategory ).research.get( realKey ); + // Get the actual research item + ResearchItem realResearch = + ResearchCategories.researchCategories.get(realCategory).research.get(realKey); - // Create the pseudo research - if( realResearch.icon_item != null ) - { - pseudo = new PseudoResearchItem( key, category, column, row, realResearch.icon_item ); - } - else - { - pseudo = new PseudoResearchItem( key, category, column, row, realResearch.icon_resource ); - } + // Create the pseudo research + if (realResearch.icon_item != null) { + pseudo = new PseudoResearchItem(key, category, column, row, realResearch.icon_item); + } else { + pseudo = new PseudoResearchItem(key, category, column, row, realResearch.icon_resource); + } - // Set the real research item - pseudo.realResearch = realResearch; + // Set the real research item + pseudo.realResearch = realResearch; - // Link to the research - pseudo.linkToRealResearch(); + // Link to the research + pseudo.linkToRealResearch(); - return pseudo; - } + return pseudo; + } - /** - * Adds this research as a sibling. - * This will ensure this unlocks when the real research does. - */ - private void linkToRealResearch() - { + /** + * Adds this research as a sibling. + * This will ensure this unlocks when the real research does. + */ + private void linkToRealResearch() { - // Add to the siblings - // Does the original research have any siblings? - if( this.realResearch.siblings == null ) - { - // Add this to the siblings - this.realResearch.setSiblings( this.key ); - } - else - { - // Get the siblings - String[] prevSibs = this.realResearch.siblings; - String[] newSibs = new String[prevSibs.length + 1]; + // Add to the siblings + // Does the original research have any siblings? + if (this.realResearch.siblings == null) { + // Add this to the siblings + this.realResearch.setSiblings(this.key); + } else { + // Get the siblings + String[] prevSibs = this.realResearch.siblings; + String[] newSibs = new String[prevSibs.length + 1]; - // Copy prev into new - System.arraycopy( prevSibs, 0, newSibs, 0, prevSibs.length ); + // Copy prev into new + System.arraycopy(prevSibs, 0, newSibs, 0, prevSibs.length); - // Add this to the siblings - newSibs[prevSibs.length] = this.key; + // Add this to the siblings + newSibs[prevSibs.length] = this.key; - // Re-set the siblings - this.realResearch.setSiblings( newSibs ); - } - } + // Re-set the siblings + this.realResearch.setSiblings(newSibs); + } + } - /** - * Redirect function to get the name of the research from - * the real research. - */ - @SideOnly(Side.CLIENT) - @Override - public String getName() - { - return this.realResearch.getName(); - } + /** + * Redirect function to get the name of the research from + * the real research. + */ + @SideOnly(Side.CLIENT) + @Override + public String getName() { + return this.realResearch.getName(); + } - /** - * Redirect function to get the research pages from the - * real research. - */ - @Override - public ResearchPage[] getPages() - { - return this.realResearch.getPages(); - } - - /** - * Redirect function to get the research text from the - * real research. - */ - @SideOnly(Side.CLIENT) - @Override - public String getText() - { - return this.realResearch.getText(); - } + /** + * Redirect function to get the research pages from the + * real research. + */ + @Override + public ResearchPage[] getPages() { + return this.realResearch.getPages(); + } + /** + * Redirect function to get the research text from the + * real research. + */ + @SideOnly(Side.CLIENT) + @Override + public String getText() { + return this.realResearch.getText(); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/VisCraftingHelper.java b/src/main/java/thaumicenergistics/common/integration/tc/VisCraftingHelper.java index 13196956..5c86252f 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/VisCraftingHelper.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/VisCraftingHelper.java @@ -9,139 +9,127 @@ import thaumcraft.api.aspects.Aspect; import thaumcraft.common.config.ConfigItems; import thaumcraft.common.items.wands.ItemWandCasting; -public class VisCraftingHelper -{ +public class VisCraftingHelper { - public static final VisCraftingHelper INSTANCE = new VisCraftingHelper(); + public static final VisCraftingHelper INSTANCE = new VisCraftingHelper(); - private ItemStack craftingScepter = null; + private ItemStack craftingScepter = null; - /** - * Private constructor - */ - private VisCraftingHelper() - { - // Intentionally Empty - } + /** + * Private constructor + */ + private VisCraftingHelper() { + // Intentionally Empty + } - /** - * Calculates the vis discount for the specified armor slots and aspect. - * - * @param inventory - * @param firstSlotIndex - * @param slotCount - * @param aspect - * @return - */ - public float calculateArmorDiscount( final IInventory inventory, final int firstSlotIndex, final int slotCount, final Aspect aspect ) - { - float discount = 0.0F; + /** + * Calculates the vis discount for the specified armor slots and aspect. + * + * @param inventory + * @param firstSlotIndex + * @param slotCount + * @param aspect + * @return + */ + public float calculateArmorDiscount( + final IInventory inventory, final int firstSlotIndex, final int slotCount, final Aspect aspect) { + float discount = 0.0F; - for( int index = 0; index < slotCount; index++ ) - { - // Get the armor stack - ItemStack armor = inventory.getStackInSlot( firstSlotIndex + index ); + for (int index = 0; index < slotCount; index++) { + // Get the armor stack + ItemStack armor = inventory.getStackInSlot(firstSlotIndex + index); - // Ensure it is valid discount gear - if( ( armor != null ) && ( armor.getItem() instanceof IVisDiscountGear ) ) - { - try - { - // Get the discount - discount += ( ( (IVisDiscountGear)armor.getItem() ).getVisDiscount( armor, null, aspect ) / 100.0F ); - } - catch( Exception e ) - { - } - } - } + // Ensure it is valid discount gear + if ((armor != null) && (armor.getItem() instanceof IVisDiscountGear)) { + try { + // Get the discount + discount += (((IVisDiscountGear) armor.getItem()).getVisDiscount(armor, null, aspect) / 100.0F); + } catch (Exception e) { + } + } + } - return discount; - } + return discount; + } - /** - * Calculates the amount of warp generated from the specified armor slots. - * - * @param inventory - * @param firstSlotIndex - * @param slotCount - * @return - */ - public int calculateArmorWarp( final IInventory inventory, final int firstSlotIndex, final int slotCount ) - { - int warp = 0; + /** + * Calculates the amount of warp generated from the specified armor slots. + * + * @param inventory + * @param firstSlotIndex + * @param slotCount + * @return + */ + public int calculateArmorWarp(final IInventory inventory, final int firstSlotIndex, final int slotCount) { + int warp = 0; - for( int index = 0; index < slotCount; index++ ) - { - // Get the armor stack - ItemStack armor = inventory.getStackInSlot( firstSlotIndex + index ); + for (int index = 0; index < slotCount; index++) { + // Get the armor stack + ItemStack armor = inventory.getStackInSlot(firstSlotIndex + index); - // Ensure it is valid warp gear - if( ( armor != null ) && ( armor.getItem() instanceof IWarpingGear ) ) - { - try - { - // Get the warp - warp += ( (IWarpingGear)armor.getItem() ).getWarp( armor, null ); - } - catch( Exception e ) - { - } - } - } + // Ensure it is valid warp gear + if ((armor != null) && (armor.getItem() instanceof IWarpingGear)) { + try { + // Get the warp + warp += ((IWarpingGear) armor.getItem()).getWarp(armor, null); + } catch (Exception e) { + } + } + } - return warp; - } + return warp; + } - /** - * Gets an itemstack representing a fully charged silverwood and thaumium - * crafting scepter. - * - * @return - */ - public ItemStack getCraftingScepter() - { - if( this.craftingScepter == null ) - { - // Create the item - this.craftingScepter = new ItemStack( ConfigItems.itemWandCasting, 1, 32767 ); + /** + * Gets an itemstack representing a fully charged silverwood and thaumium + * crafting scepter. + * + * @return + */ + public ItemStack getCraftingScepter() { + if (this.craftingScepter == null) { + // Create the item + this.craftingScepter = new ItemStack(ConfigItems.itemWandCasting, 1, 32767); - // Set rod type to thaumium - ( (ItemWandCasting)this.craftingScepter.getItem() ).setCap( this.craftingScepter, ConfigItems.WAND_CAP_THAUMIUM ); + // Set rod type to thaumium + ((ItemWandCasting) this.craftingScepter.getItem()) + .setCap(this.craftingScepter, ConfigItems.WAND_CAP_THAUMIUM); - // Set cap type to silverwood - ( (ItemWandCasting)this.craftingScepter.getItem() ).setRod( this.craftingScepter, ConfigItems.WAND_ROD_SILVERWOOD ); + // Set cap type to silverwood + ((ItemWandCasting) this.craftingScepter.getItem()) + .setRod(this.craftingScepter, ConfigItems.WAND_ROD_SILVERWOOD); - // Set that it is a scepter - this.craftingScepter.setTagInfo( "sceptre", new NBTTagByte( (byte)1 ) ); + // Set that it is a scepter + this.craftingScepter.setTagInfo("sceptre", new NBTTagByte((byte) 1)); - // Max out vis storage - for( Aspect aspect : Aspect.getPrimalAspects() ) - { - ( (ItemWandCasting)this.craftingScepter.getItem() ).addVis( this.craftingScepter, aspect, - ( (ItemWandCasting)this.craftingScepter.getItem() ).getMaxVis( this.craftingScepter ), true ); - } - } + // Max out vis storage + for (Aspect aspect : Aspect.getPrimalAspects()) { + ((ItemWandCasting) this.craftingScepter.getItem()) + .addVis( + this.craftingScepter, + aspect, + ((ItemWandCasting) this.craftingScepter.getItem()).getMaxVis(this.craftingScepter), + true); + } + } - return this.craftingScepter; - } + return this.craftingScepter; + } - /** - * Gets the vis discount given by the crafting scepter for the specified - * aspect. - * - * @param aspect - * @return - */ - public float getScepterVisModifier( final Aspect aspect ) - { - // Ensure the scepter has been created - if( this.craftingScepter == null ) - { - this.getCraftingScepter(); - } - - return ( (ItemWandCasting)this.craftingScepter.getItem() ).getConsumptionModifier( this.craftingScepter, null, aspect, true ); - } + /** + * Gets the vis discount given by the crafting scepter for the specified + * aspect. + * + * @param aspect + * @return + */ + public float getScepterVisModifier(final Aspect aspect) { + // Ensure the scepter has been created + if (this.craftingScepter == null) { + this.getCraftingScepter(); + } + return ((ItemWandCasting) this.craftingScepter.getItem()) + .getConsumptionModifier(this.craftingScepter, null, aspect, true); + } } diff --git a/src/main/java/thaumicenergistics/common/integration/tc/VisProviderProxy.java b/src/main/java/thaumicenergistics/common/integration/tc/VisProviderProxy.java index 313cf567..e60cc87d 100644 --- a/src/main/java/thaumicenergistics/common/integration/tc/VisProviderProxy.java +++ b/src/main/java/thaumicenergistics/common/integration/tc/VisProviderProxy.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.integration.tc; -import java.util.HashSet; import appeng.api.util.DimensionalCoord; +import java.util.HashSet; import net.minecraftforge.common.util.ForgeDirection; import thaumcraft.api.WorldCoordinates; import thaumcraft.api.aspects.Aspect; @@ -10,173 +10,158 @@ import thaumcraft.api.visnet.VisNetHandler; import thaumcraft.common.tiles.TileVisRelay; import thaumicenergistics.common.parts.PartVisInterface; -public class VisProviderProxy - extends TileVisNode -{ - /** - * How far vis can travel from the source. I think >.> - * TODO: Test vis range - */ - private static final int VIS_RANGE = 1; +public class VisProviderProxy extends TileVisNode { + /** + * How far vis can travel from the source. I think >.> + * TODO: Test vis range + */ + private static final int VIS_RANGE = 1; - /** - * Tracks which proxies have been visited during a single call chain. - */ - private static final HashSet visitedProxies = new HashSet<>(); + /** + * Tracks which proxies have been visited during a single call chain. + */ + private static final HashSet visitedProxies = new HashSet<>(); - /** - * The interface associated with this source. - */ - private PartVisInterface visInterface; + /** + * The interface associated with this source. + */ + private PartVisInterface visInterface; - /** - * Where in the world this provider is. - */ - private WorldCoordinates location; + /** + * Where in the world this provider is. + */ + private WorldCoordinates location; - /** - * What vis 'channel' does this node respond on? - */ - private byte attunement = -1; + /** + * What vis 'channel' does this node respond on? + */ + private byte attunement = -1; - public VisProviderProxy( final PartVisInterface parent ) - { - // Set the interface - this.visInterface = parent; + public VisProviderProxy(final PartVisInterface parent) { + // Set the interface + this.visInterface = parent; - // Get the location of the interface - DimensionalCoord aeCoords = this.visInterface.getLocation(); + // Get the location of the interface + DimensionalCoord aeCoords = this.visInterface.getLocation(); - // Get the direction the interface is facing - ForgeDirection face = this.visInterface.getSide(); + // Get the direction the interface is facing + ForgeDirection face = this.visInterface.getSide(); - // Set the subtile's position to just infront of the interface. - this.xCoord = aeCoords.x + face.offsetX; - this.yCoord = aeCoords.y + face.offsetY; - this.zCoord = aeCoords.z + face.offsetZ; - this.worldObj = aeCoords.getWorld(); - this.location = new WorldCoordinates( this.xCoord, this.yCoord, this.zCoord, this.worldObj.provider.dimensionId ); + // Set the subtile's position to just infront of the interface. + this.xCoord = aeCoords.x + face.offsetX; + this.yCoord = aeCoords.y + face.offsetY; + this.zCoord = aeCoords.z + face.offsetZ; + this.worldObj = aeCoords.getWorld(); + this.location = new WorldCoordinates(this.xCoord, this.yCoord, this.zCoord, this.worldObj.provider.dimensionId); + } - } + /** + * Updates should come from the source interface. + */ + @Override + public boolean canUpdate() { + return true; + } - /** - * Updates should come from the source interface. - */ - @Override - public boolean canUpdate() - { - return true; - } + /** + * Attempts to consume vis from the interface. + */ + @Override + public int consumeVis(final Aspect aspect, final int amountRequested) { + // Ensure: This node is valid + // The interface is valid + // The interface is facing a relay + if (this.isInvalid() + || (this.visInterface == null) + || (!this.visInterface.isVisProvider()) + || (this.visInterface.getRelay() == null)) { + return 0; + } - /** - * Attempts to consume vis from the interface. - */ - @Override - public int consumeVis( final Aspect aspect, final int amountRequested ) - { - // Ensure: This node is valid - // The interface is valid - // The interface is facing a relay - if( this.isInvalid() || ( this.visInterface == null ) || ( !this.visInterface.isVisProvider() ) || ( this.visInterface.getRelay() == null ) ) - { - return 0; - } + int amountConsumed = 0; - int amountConsumed = 0; + // Prevent recursion + if (!VisProviderProxy.visitedProxies.contains(this)) { + VisProviderProxy.visitedProxies.add(this); + amountConsumed = this.visInterface.consumeVis(aspect, amountRequested); + VisProviderProxy.visitedProxies.remove(this); + } - // Prevent recursion - if( !VisProviderProxy.visitedProxies.contains( this ) ) - { - VisProviderProxy.visitedProxies.add( this ); - amountConsumed = this.visInterface.consumeVis( aspect, amountRequested ); - VisProviderProxy.visitedProxies.remove( this ); - } + return amountConsumed; + } - return amountConsumed; - } + /** + * Gets the attunement for this source. + */ + @Override + public byte getAttunement() { + return this.attunement; + } - /** - * Gets the attunement for this source. - */ - @Override - public byte getAttunement() - { - return this.attunement; - } + /** + * Returns the location of the interface + */ + @Override + public WorldCoordinates getLocation() { + return this.location; + } - /** - * Returns the location of the interface - */ - @Override - public WorldCoordinates getLocation() - { - return this.location; - } + /** + * How far can vis travel from the interface? + */ + @Override + public int getRange() { + return VisProviderProxy.VIS_RANGE; + } - /** - * How far can vis travel from the interface? - */ - @Override - public int getRange() - { - return VisProviderProxy.VIS_RANGE; - } + /** + * Invalidates the provider. + */ + @Override + public void invalidate() { + this.removeThisNode(); + } - /** - * Invalidates the provider. - */ - @Override - public void invalidate() - { - this.removeThisNode(); - } + /** + * If the interface is a source. + */ + @Override + public boolean isSource() { + return this.visInterface.isVisProvider(); + } - /** - * If the interface is a source. - */ - @Override - public boolean isSource() - { - return this.visInterface.isVisProvider(); - } + @Override + public void updateEntity() { + byte relayAttunement = -1; - @Override - public void updateEntity() - { - byte relayAttunement = -1; + // Is there an interface? + if (this.visInterface != null) { + // Get the relay + TileVisRelay relay = this.visInterface.getRelay(); - // Is there an interface? - if( this.visInterface != null ) - { - // Get the relay - TileVisRelay relay = this.visInterface.getRelay(); + // Is there a relay? + if (relay != null) { + // Get it's attunement + relayAttunement = relay.getAttunement(); + } + } - // Is there a relay? - if( relay != null ) - { - // Get it's attunement - relayAttunement = relay.getAttunement(); - } - } + // Has the attunement changed? + if (this.attunement != relayAttunement) { + // Update our attunement + this.attunement = relayAttunement; - // Has the attunement changed? - if( this.attunement != relayAttunement ) - { - // Update our attunement - this.attunement = relayAttunement; + // Remove the node + this.removeThisNode(); - // Remove the node - this.removeThisNode(); + // Mark for refresh + this.nodeRefresh = true; - // Mark for refresh - this.nodeRefresh = true; - - // Re-register the node - VisNetHandler.addSource( this.worldObj, this ); - } - - // Call super - super.updateEntity(); - } + // Re-register the node + VisNetHandler.addSource(this.worldObj, this); + } + // Call super + super.updateEntity(); + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerDistillationPattern.java b/src/main/java/thaumicenergistics/common/inventory/HandlerDistillationPattern.java index e5c36dbd..cf45054b 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerDistillationPattern.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerDistillationPattern.java @@ -13,203 +13,181 @@ import thaumicenergistics.common.items.ItemCraftingAspect; * @author Nividica * */ -public class HandlerDistillationPattern -{ - /** - * NBT Keys - */ - private static final String NBTKEY_AE_IN = "in", - NBTKEY_AE_OUT = "out", - NBTKEY_AE_ISCRAFTING = "crafting", - NBTKEY_AE_CAN_SUB = "substitute"; +public class HandlerDistillationPattern { + /** + * NBT Keys + */ + private static final String NBTKEY_AE_IN = "in", + NBTKEY_AE_OUT = "out", + NBTKEY_AE_ISCRAFTING = "crafting", + NBTKEY_AE_CAN_SUB = "substitute"; - /** - * Output of the pattern. - * Must be ItemCraftingAspect patterns. - */ - protected ItemStack output = null; + /** + * Output of the pattern. + * Must be ItemCraftingAspect patterns. + */ + protected ItemStack output = null; - /** - * Input of the pattern. - */ - protected ItemStack input = null; + /** + * Input of the pattern. + */ + protected ItemStack input = null; - public void encodePattern( final ItemStack pattern ) - { - // Valid pattern? - if( pattern == null ) - { - return; - } + public void encodePattern(final ItemStack pattern) { + // Valid pattern? + if (pattern == null) { + return; + } - // Check the input & output - if( ( this.input == null ) || ( this.output == null ) ) - { - // No input or output - return; - } + // Check the input & output + if ((this.input == null) || (this.output == null)) { + // No input or output + return; + } - // Create a new tag - NBTTagCompound data = new NBTTagCompound(); + // Create a new tag + NBTTagCompound data = new NBTTagCompound(); - // Write the input - NBTTagList inTags = new NBTTagList(); - inTags.appendTag( this.input.writeToNBT( new NBTTagCompound() ) ); + // Write the input + NBTTagList inTags = new NBTTagList(); + inTags.appendTag(this.input.writeToNBT(new NBTTagCompound())); - // Write the outputs - NBTTagList outTags = new NBTTagList(); - outTags.appendTag( this.output.writeToNBT( new NBTTagCompound() ) ); + // Write the outputs + NBTTagList outTags = new NBTTagList(); + outTags.appendTag(this.output.writeToNBT(new NBTTagCompound())); - // Write the basics - data.setBoolean( NBTKEY_AE_CAN_SUB, false ); - data.setBoolean( NBTKEY_AE_ISCRAFTING, false ); + // Write the basics + data.setBoolean(NBTKEY_AE_CAN_SUB, false); + data.setBoolean(NBTKEY_AE_ISCRAFTING, false); - // Write the lists - data.setTag( NBTKEY_AE_IN, inTags ); - data.setTag( NBTKEY_AE_OUT, outTags ); + // Write the lists + data.setTag(NBTKEY_AE_IN, inTags); + data.setTag(NBTKEY_AE_OUT, outTags); - // Save into the item - pattern.setTagCompound( data ); + // Save into the item + pattern.setTagCompound(data); + } - } + /** + * Returns the input of the pattern. + * May be null. + * + * @return + */ + public ItemStack getInput() { + return this.input; + } - /** - * Returns the input of the pattern. - * May be null. - * - * @return - */ - public ItemStack getInput() - { - return this.input; - } + /** + * Returns the output of the pattern. + * May be null. + * + * @return + */ + public ItemStack getOutput() { + return this.output; + } - /** - * Returns the output of the pattern. - * May be null. - * - * @return - */ - public ItemStack getOutput() - { - return this.output; - } + /** + * Returns true if the current items are valid. + * + * @return + */ + public boolean isValid() { + return ((this.output != null) && (this.input != null)); + } - /** - * Returns true if the current items are valid. - * - * @return - */ - public boolean isValid() - { - return( ( this.output != null ) && ( this.input != null ) ); - } + /** + * Loads the values from the pattern + * + * @param pattern + */ + public void readPattern(final ItemStack pattern) { + // Reset + this.reset(); - /** - * Loads the values from the pattern - * - * @param pattern - */ - public void readPattern( final ItemStack pattern ) - { - // Reset - this.reset(); + // Valid pattern? + if (pattern == null) { + return; + } - // Valid pattern? - if( pattern == null ) - { - return; - } + if (!pattern.hasTagCompound()) { + // Nothing to load + return; + } - if( !pattern.hasTagCompound() ) - { - // Nothing to load - return; - } + // Get the NBT tag + NBTTagCompound data = pattern.getTagCompound(); - // Get the NBT tag - NBTTagCompound data = pattern.getTagCompound(); + // Get the input and output list + NBTTagList inTags = data.getTagList(NBTKEY_AE_IN, NBT.TAG_COMPOUND); + NBTTagList outTags = data.getTagList(NBTKEY_AE_OUT, NBT.TAG_COMPOUND); - // Get the input and output list - NBTTagList inTags = data.getTagList( NBTKEY_AE_IN, NBT.TAG_COMPOUND ); - NBTTagList outTags = data.getTagList( NBTKEY_AE_OUT, NBT.TAG_COMPOUND ); + // Empty check + if ((outTags.tagCount() < 1) || (inTags.tagCount() < 1)) { + // Nothing to load. + return; + } - // Empty check - if( ( outTags.tagCount() < 1 ) || ( inTags.tagCount() < 1 ) ) - { - // Nothing to load. - return; - } + // Read the input and output + this.setOutputItem(ItemStack.loadItemStackFromNBT(outTags.getCompoundTagAt(0))); + this.setInputItem(ItemStack.loadItemStackFromNBT(inTags.getCompoundTagAt(0))); - // Read the input and output - this.setOutputItem( ItemStack.loadItemStackFromNBT( outTags.getCompoundTagAt( 0 ) ) ); - this.setInputItem( ItemStack.loadItemStackFromNBT( inTags.getCompoundTagAt( 0 ) ) ); + // Null check + if ((this.input == null) || (this.output == null)) { + this.reset(); + return; + } + } - // Null check - if( ( this.input == null ) || ( this.output == null ) ) - { - this.reset(); - return; - } + /** + * Resets the helper. + */ + public void reset() { + this.output = null; + this.input = null; + } - } + /** + * Sets the input. + * + * @param inputItem + */ + public void setInputItem(final ItemStack inputItem) { + this.input = inputItem.copy(); + this.input.stackSize = 1; + } - /** - * Resets the helper. - */ - public void reset() - { - this.output = null; - this.input = null; - } + /** + * Sets the output. + * Must be a crafting aspect. + * + * @param outputItem + */ + public void setOutputItem(final ItemStack outputItem) { + // Not valid crafting aspect? + if ((outputItem != null) && !(outputItem.getItem() instanceof ItemCraftingAspect)) { + this.output = null; + } + // Aspect null? + else if (ItemCraftingAspect.getAspect(outputItem) == null) { + this.output = null; + } else { + this.output = outputItem; + } + } - /** - * Sets the input. - * - * @param inputItem - */ - public void setInputItem( final ItemStack inputItem ) - { - this.input = inputItem.copy(); - this.input.stackSize = 1; - } - - /** - * Sets the output. - * Must be a crafting aspect. - * - * @param outputItem - */ - public void setOutputItem( final ItemStack outputItem ) - { - // Not valid crafting aspect? - if( ( outputItem != null ) && !( outputItem.getItem() instanceof ItemCraftingAspect ) ) - { - this.output = null; - } - // Aspect null? - else if( ItemCraftingAspect.getAspect( outputItem ) == null ) - { - this.output = null; - } - else - { - this.output = outputItem; - } - } - - /** - * Sets the input and output items. - * Returns if the recipe is valid or not. - * - * @param inputItem - * @param outputItem - * @return - */ - public boolean setPatternItems( final ItemStack inputItem, final ItemStack outputItem ) - { - this.setInputItem( inputItem ); - this.setOutputItem( outputItem ); - return this.isValid(); - } + /** + * Sets the input and output items. + * Returns if the recipe is valid or not. + * + * @param inputItem + * @param outputItem + * @return + */ + public boolean setPatternItems(final ItemStack inputItem, final ItemStack outputItem) { + this.setInputItem(inputItem); + this.setOutputItem(outputItem); + return this.isValid(); + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusBase.java b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusBase.java index 8613cd54..8b3c2936 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusBase.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusBase.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.inventory; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; @@ -13,6 +11,8 @@ import appeng.api.storage.IMEInventoryHandler; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import java.util.ArrayList; +import java.util.List; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; @@ -27,392 +27,362 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -public abstract class HandlerEssentiaStorageBusBase - implements IMEInventoryHandler -{ +public abstract class HandlerEssentiaStorageBusBase implements IMEInventoryHandler { - /** - * Cache the API instance - */ - protected static final ThEApi TEAPI = ThEApi.instance(); + /** + * Cache the API instance + */ + protected static final ThEApi TEAPI = ThEApi.instance(); - /** - * Storage bus associated with this handler. - */ - protected PartEssentiaStorageBus partStorageBus; + /** + * Storage bus associated with this handler. + */ + protected PartEssentiaStorageBus partStorageBus; - /** - * Controls what operations this bus is allowed to perform. - */ - protected AccessRestriction access; + /** + * Controls what operations this bus is allowed to perform. + */ + protected AccessRestriction access; - /** - * Filtered aspects - */ - protected List filteredAspects = new ArrayList(); + /** + * Filtered aspects + */ + protected List filteredAspects = new ArrayList(); - /** - * When true the filter becomes a blacklist. - */ - protected boolean inverted; + /** + * When true the filter becomes a blacklist. + */ + protected boolean inverted; - /** - * Source of all actions the handler performs. - */ - protected MachineSource machineSource; + /** + * Source of all actions the handler performs. + */ + protected MachineSource machineSource; - /** - * When true excess essentia will be destroyed IF the bus is attached to a - * void - * jar. - */ - private boolean isVoidAllowed = false; + /** + * When true excess essentia will be destroyed IF the bus is attached to a + * void + * jar. + */ + private boolean isVoidAllowed = false; - /** - * Creates the handler. - * - * @param part - */ - public HandlerEssentiaStorageBusBase( final PartEssentiaStorageBus part ) - { - // Set the part - this.partStorageBus = part; + /** + * Creates the handler. + * + * @param part + */ + public HandlerEssentiaStorageBusBase(final PartEssentiaStorageBus part) { + // Set the part + this.partStorageBus = part; - // Set to full read/write access. - this.access = AccessRestriction.READ_WRITE; + // Set to full read/write access. + this.access = AccessRestriction.READ_WRITE; - if( part != null ) - { - // Set the source - this.machineSource = new MachineSource( part ); - } - } + if (part != null) { + // Set the source + this.machineSource = new MachineSource(part); + } + } - /** - * Returns true if there are no filters. - * - * @return - */ - protected boolean allowAny() - { - // Are all filters null? - for( Aspect filteredAspect : this.filteredAspects ) - { - if( filteredAspect != null ) - { - // There is a filter - return false; - } - } + /** + * Returns true if there are no filters. + * + * @return + */ + protected boolean allowAny() { + // Are all filters null? + for (Aspect filteredAspect : this.filteredAspects) { + if (filteredAspect != null) { + // There is a filter + return false; + } + } - // No filters - return true; - } + // No filters + return true; + } - /** - * Verifies that the requested fluidstack to insert/extract is both an - * Essentia Gas and white-listed, or not black-listed. - * - * @param fluidRequest - * @return True if the bus is allowed to transfer the fluid, false if it can - * not. - */ - protected boolean canTransferGas( final GaseousEssentia essentiaGas ) - { - // Can any aspect be transfered? - if( this.allowAny() ) - { - // Allow the transfer - return true; - } + /** + * Verifies that the requested fluidstack to insert/extract is both an + * Essentia Gas and white-listed, or not black-listed. + * + * @param fluidRequest + * @return True if the bus is allowed to transfer the fluid, false if it can + * not. + */ + protected boolean canTransferGas(final GaseousEssentia essentiaGas) { + // Can any aspect be transfered? + if (this.allowAny()) { + // Allow the transfer + return true; + } - /* - * Validate based on if the aspect is filtered and the storage bus is - * inverted. See explanation below. - */ - return( this.filteredAspects.contains( essentiaGas.getAspect() ) != this.inverted ); + /* + * Validate based on if the aspect is filtered and the storage bus is + * inverted. See explanation below. + */ + return (this.filteredAspects.contains(essentiaGas.getAspect()) != this.inverted); - /* - * Truth 'table' ---- Conditions: * isFiltered = true * inverted = false - * Expected outcome: * valid = true Sequence * valid = ( isFiltered == - * !inverted ); * valid = ( true == !false ) * valid = ( true == true ) - * * valid = true - * - * ---- Conditions: * isFiltered = false * inverted = false Expected - * outcome: * valid = false Sequence * valid = ( isFiltered == !inverted - * ); * valid = ( false == !false ) * valid = ( false == true ) * valid - * = false - * - * ---- Conditions: * isFiltered = true * inverted = true Expected - * outcome: * valid = false Sequence * valid = ( isFiltered == !inverted - * ); * valid = ( true == !true ) * valid = ( true == false ) * valid = - * false ---- - * - * Conditions: * isFiltered = false * inverted = true Expected outcome: - * * valid = true Sequence * valid = ( isFiltered == !inverted ); * - * valid = ( false == !true ) * valid = ( false == false ) * valid = - * true ---- - */ - } + /* + * Truth 'table' ---- Conditions: * isFiltered = true * inverted = false + * Expected outcome: * valid = true Sequence * valid = ( isFiltered == + * !inverted ); * valid = ( true == !false ) * valid = ( true == true ) + * * valid = true + * + * ---- Conditions: * isFiltered = false * inverted = false Expected + * outcome: * valid = false Sequence * valid = ( isFiltered == !inverted + * ); * valid = ( false == !false ) * valid = ( false == true ) * valid + * = false + * + * ---- Conditions: * isFiltered = true * inverted = true Expected + * outcome: * valid = false Sequence * valid = ( isFiltered == !inverted + * ); * valid = ( true == !true ) * valid = ( true == false ) * valid = + * false ---- + * + * Conditions: * isFiltered = false * inverted = true Expected outcome: + * * valid = true Sequence * valid = ( isFiltered == !inverted ); * + * valid = ( false == !true ) * valid = ( false == false ) * valid = + * true ---- + */ + } - /** - * Gets the tile entity the storage bus is facing. - * - * @return - */ - protected TileEntity getFaceingTile() - { - // Get the host - TileEntity hostTile = this.partStorageBus.getHostTile(); + /** + * Gets the tile entity the storage bus is facing. + * + * @return + */ + protected TileEntity getFaceingTile() { + // Get the host + TileEntity hostTile = this.partStorageBus.getHostTile(); - // Is there a host? - if( hostTile == null ) - { - // No host. - return null; - } + // Is there a host? + if (hostTile == null) { + // No host. + return null; + } - // Is the host in a loaded world? - if( hostTile.getWorldObj() == null ) - { - // No world. - return null; - } + // Is the host in a loaded world? + if (hostTile.getWorldObj() == null) { + // No world. + return null; + } - // Get what direction of the storage bus. - ForgeDirection orientation = this.partStorageBus.getSide(); + // Get what direction of the storage bus. + ForgeDirection orientation = this.partStorageBus.getSide(); - // Return the tile entity the storage bus is facing. - return hostTile.getWorldObj().getTileEntity( hostTile.xCoord + orientation.offsetX, hostTile.yCoord + orientation.offsetY, - hostTile.zCoord + orientation.offsetZ ); - } + // Return the tile entity the storage bus is facing. + return hostTile.getWorldObj() + .getTileEntity( + hostTile.xCoord + orientation.offsetX, + hostTile.yCoord + orientation.offsetY, + hostTile.zCoord + orientation.offsetZ); + } - /** - * Gets the part that is facing the essentia storage bus. - * - * @param partHost - * @return - */ - protected IPart getFacingPartFromPartHost( final IPartHost partHost ) - { - return partHost.getPart( this.partStorageBus.getSide().getOpposite() ); - } + /** + * Gets the part that is facing the essentia storage bus. + * + * @param partHost + * @return + */ + protected IPart getFacingPartFromPartHost(final IPartHost partHost) { + return partHost.getPart(this.partStorageBus.getSide().getOpposite()); + } - protected boolean hasSecurityPermission() - { - // Is our access restricted to read-only or no access? - if( ( this.access == AccessRestriction.READ ) || ( this.access == AccessRestriction.NO_ACCESS ) ) - { - // Not allowed to insert - return false; - } - return true; - } + protected boolean hasSecurityPermission() { + // Is our access restricted to read-only or no access? + if ((this.access == AccessRestriction.READ) || (this.access == AccessRestriction.NO_ACCESS)) { + // Not allowed to insert + return false; + } + return true; + } - /** - * Checks if the fluid is an essentia gas. - * - * @param fluid - * @return - */ - protected boolean isFluidEssentiaGas( final FluidStack fluid ) - { - // Ensure the request is not null - if( fluid == null ) - { - return false; - } + /** + * Checks if the fluid is an essentia gas. + * + * @param fluid + * @return + */ + protected boolean isFluidEssentiaGas(final FluidStack fluid) { + // Ensure the request is not null + if (fluid == null) { + return false; + } - // Ensure the fluid an essentia gas - return( fluid.getFluid() instanceof GaseousEssentia ); - } + // Ensure the fluid an essentia gas + return (fluid.getFluid() instanceof GaseousEssentia); + } - /** - * Checks if the AE fluidstack is an essentia gas. - * - * @param fluidStack - * @return - */ - protected boolean isFluidEssentiaGas( final IAEFluidStack fluidStack ) - { - // Ensure the request is not null - if( fluidStack == null ) - { - return false; - } + /** + * Checks if the AE fluidstack is an essentia gas. + * + * @param fluidStack + * @return + */ + protected boolean isFluidEssentiaGas(final IAEFluidStack fluidStack) { + // Ensure the request is not null + if (fluidStack == null) { + return false; + } - return this.isFluidEssentiaGas( fluidStack.getFluidStack() ); - } + return this.isFluidEssentiaGas(fluidStack.getFluidStack()); + } - /** - * Lets the host grid know that the storage amount has changed. - * - * @param change - */ - protected void postAlterationToHostGrid( final Iterable change ) - { - try - { - if( this.partStorageBus.getActionableNode().isActive() ) - { - this.partStorageBus.getGridBlock().getStorageGrid().postAlterationOfStoredItems( StorageChannel.FLUIDS, change, this.machineSource ); - } - } - catch( Exception e ) - { + /** + * Lets the host grid know that the storage amount has changed. + * + * @param change + */ + protected void postAlterationToHostGrid(final Iterable change) { + try { + if (this.partStorageBus.getActionableNode().isActive()) { + this.partStorageBus + .getGridBlock() + .getStorageGrid() + .postAlterationOfStoredItems(StorageChannel.FLUIDS, change, this.machineSource); + } + } catch (Exception e) { - } - } + } + } - /** - * Is the specified fluid allowed to be placed in the container? This does - * not take into consideration the amount currently in the container. - */ - @Override - public abstract boolean canAccept( final IAEFluidStack fluidStack ); + /** + * Is the specified fluid allowed to be placed in the container? This does + * not take into consideration the amount currently in the container. + */ + @Override + public abstract boolean canAccept(final IAEFluidStack fluidStack); - /** - * Extracts essentia gas from the attached source. - */ - @Override - public abstract IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource source ); + /** + * Extracts essentia gas from the attached source. + */ + @Override + public abstract IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource source); - /** - * Returns the access restrictions, if any, imposed on the storage bus. - */ - @Override - public AccessRestriction getAccess() - { - return this.access; - } + /** + * Returns the access restrictions, if any, imposed on the storage bus. + */ + @Override + public AccessRestriction getAccess() { + return this.access; + } - /** - * Gets the list of 'fluids' that can be extracted from this storage bus. - */ - @Override - public abstract IItemList getAvailableItems( final IItemList out ); + /** + * Gets the list of 'fluids' that can be extracted from this storage bus. + */ + @Override + public abstract IItemList getAvailableItems(final IItemList out); - /** - * Gets the storage channel for the storage bus. - */ - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } + /** + * Gets the storage channel for the storage bus. + */ + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } - /** - * Gets the priority of the storage bus. - */ - @Override - public int getPriority() - { - return this.partStorageBus.getPriority(); - } + /** + * Gets the priority of the storage bus. + */ + @Override + public int getPriority() { + return this.partStorageBus.getPriority(); + } - /** - * Dunno - */ - @Override - public int getSlot() - { - return 0; - } + /** + * Dunno + */ + @Override + public int getSlot() { + return 0; + } - /** - * Inserts essentia into the source. - * Returns the number of items not added. - */ - @Override - public abstract IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource source ); + /** + * Inserts essentia into the source. + * Returns the number of items not added. + */ + @Override + public abstract IAEFluidStack injectItems( + final IAEFluidStack input, final Actionable mode, final BaseActionSource source); - /** - * Checks if the specified is prioritized. - */ - @Override - public final boolean isPrioritized( final IAEFluidStack fluidStack ) - { - // Ensure the fluid stack is an essentia gas - if( !this.isFluidEssentiaGas( fluidStack ) ) - { - // Not an essentia gas. - return false; - } + /** + * Checks if the specified is prioritized. + */ + @Override + public final boolean isPrioritized(final IAEFluidStack fluidStack) { + // Ensure the fluid stack is an essentia gas + if (!this.isFluidEssentiaGas(fluidStack)) { + // Not an essentia gas. + return false; + } - if( this.inverted ) - { - // no prioritization under blacklist mode - return false; - } + if (this.inverted) { + // no prioritization under blacklist mode + return false; + } - // Is the aspect prioritized? - try - { - return this.filteredAspects.contains( ( (GaseousEssentia)fluidStack.getFluidStack().getFluid() ).getAspect() ); - } - catch( Exception e ) - { - return false; - } - } + // Is the aspect prioritized? + try { + return this.filteredAspects.contains( + ((GaseousEssentia) fluidStack.getFluidStack().getFluid()).getAspect()); + } catch (Exception e) { + return false; + } + } - /** - * Gets if voiding is allowed. - * - * @return - */ - public boolean isVoidAllowed() - { - return this.isVoidAllowed; - } + /** + * Gets if voiding is allowed. + * + * @return + */ + public boolean isVoidAllowed() { + return this.isVoidAllowed; + } - /** - * Called when a neighboring block changes. - * - * @return True if a cell update is needed. - */ - public abstract boolean onNeighborChange(); + /** + * Called when a neighboring block changes. + * + * @return True if a cell update is needed. + */ + public abstract boolean onNeighborChange(); - /** - * Sets if the storage bus filter mode is inverted or not. - * - * @param isInverted - * True = Blacklist, False = Whitelist. - */ - public void setInverted( final boolean isInverted ) - { - this.inverted = isInverted; - } + /** + * Sets if the storage bus filter mode is inverted or not. + * + * @param isInverted + * True = Blacklist, False = Whitelist. + */ + public void setInverted(final boolean isInverted) { + this.inverted = isInverted; + } - /** - * Set's the list of filtered aspects. - * - * @param aspectList - */ - public void setPrioritizedAspects( final List aspectList ) - { - this.filteredAspects = aspectList; - } + /** + * Set's the list of filtered aspects. + * + * @param aspectList + */ + public void setPrioritizedAspects(final List aspectList) { + this.filteredAspects = aspectList; + } - /** - * Sets if the handler can void excess essentia if connected to void jar. - * - * @param - */ - public void setVoidAllowed( final boolean isVoidAllowed ) - { - this.isVoidAllowed = isVoidAllowed; - } + /** + * Sets if the handler can void excess essentia if connected to void jar. + * + * @param + */ + public void setVoidAllowed(final boolean isVoidAllowed) { + this.isVoidAllowed = isVoidAllowed; + } - /** - * Called periodically by the essentia storage bus. - */ - public abstract void tickingRequest( final IGridNode node, final int TicksSinceLastCall ); - - /** - * Is the handler valid for this pass? - */ - @Override - public abstract boolean validForPass( final int pass ); + /** + * Called periodically by the essentia storage bus. + */ + public abstract void tickingRequest(final IGridNode node, final int TicksSinceLastCall); + /** + * Is the handler valid for this pass? + */ + @Override + public abstract boolean validForPass(final int pass); } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusCondenser.java b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusCondenser.java index 13598a81..a56c059f 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusCondenser.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusCondenser.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.inventory; -import com.google.common.collect.ImmutableList; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; @@ -8,6 +7,7 @@ import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; import appeng.tile.misc.TileCondenser; +import com.google.common.collect.ImmutableList; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fluids.FluidStack; import thaumicenergistics.common.fluids.GaseousEssentia; @@ -20,130 +20,116 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -public class HandlerEssentiaStorageBusCondenser - extends HandlerEssentiaStorageBusBase -{ +public class HandlerEssentiaStorageBusCondenser extends HandlerEssentiaStorageBusBase { - private TileCondenser condenser = null; + private TileCondenser condenser = null; - public HandlerEssentiaStorageBusCondenser( final PartEssentiaStorageBus part ) - { - super( part ); - } + public HandlerEssentiaStorageBusCondenser(final PartEssentiaStorageBus part) { + super(part); + } - @Override - public boolean canAccept( final IAEFluidStack fluidStack ) - { - // Ensure there is a condenser - if( this.condenser == null ) - { - return false; - } + @Override + public boolean canAccept(final IAEFluidStack fluidStack) { + // Ensure there is a condenser + if (this.condenser == null) { + return false; + } - // Ensure the bus has security access - if( !this.hasSecurityPermission() ) - { - // The bus does not have security access. - return false; - } + // Ensure the bus has security access + if (!this.hasSecurityPermission()) { + // The bus does not have security access. + return false; + } - // Ensure the fluid is an essentia gas - if( !this.isFluidEssentiaGas( fluidStack ) ) - { - // Not essentia gas. - return false; - } + // Ensure the fluid is an essentia gas + if (!this.isFluidEssentiaGas(fluidStack)) { + // Not essentia gas. + return false; + } - // Ensure we are allowed to transfer this fluid - if( !this.canTransferGas( (GaseousEssentia)fluidStack.getFluid() ) ) - { - /* - * Either: Not on whitelist or is on blacklist - */ - return false; - } + // Ensure we are allowed to transfer this fluid + if (!this.canTransferGas((GaseousEssentia) fluidStack.getFluid())) { + /* + * Either: Not on whitelist or is on blacklist + */ + return false; + } - // Can accept the fluid. - return true; - } + // Can accept the fluid. + return true; + } - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource source ) - { - // Nothing comes out of the condenser. - return null; - } + @Override + public IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource source) { + // Nothing comes out of the condenser. + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - // Nothing is stored in the condenser. - return out; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + // Nothing is stored in the condenser. + return out; + } - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource source ) - { - // Ensure input and output - if( ( this.condenser == null ) || ( input == null ) || ( !this.canAccept( input ) ) ) - { - return input; - } + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource source) { + // Ensure input and output + if ((this.condenser == null) || (input == null) || (!this.canAccept(input))) { + return input; + } - // Ignore if simulation - if( mode == Actionable.SIMULATE ) - { - // Condenser can accept all. - return null; - } + // Ignore if simulation + if (mode == Actionable.SIMULATE) { + // Condenser can accept all. + return null; + } - // Create the fluidstack - IAEFluidStack injectStack = input.copy(); + // Create the fluidstack + IAEFluidStack injectStack = input.copy(); - // Set the amount to the Essentia units, NOT the fluid units - injectStack.setStackSize( 500 * EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( input.getStackSize() ) ); + // Set the amount to the Essentia units, NOT the fluid units + injectStack.setStackSize( + 500 * EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(input.getStackSize())); - // Inject the fluid - this.condenser.fill( this.partStorageBus.getSide().getOpposite(), injectStack.getFluidStack(), ( mode == Actionable.MODULATE ) ); + // Inject the fluid + this.condenser.fill( + this.partStorageBus.getSide().getOpposite(), + injectStack.getFluidStack(), + (mode == Actionable.MODULATE)); - // Update the grid so that it doesn't thing we have stored the voided amount. - this.postAlterationToHostGrid( ImmutableList.of( AEApi.instance().storage() - .createFluidStack( new FluidStack( input.getFluid(), (int) -input.getStackSize() ) ) ) ); + // Update the grid so that it doesn't thing we have stored the voided amount. + this.postAlterationToHostGrid( + ImmutableList.of(AEApi.instance().storage().createFluidStack(new FluidStack(input.getFluid(), (int) + -input.getStackSize())))); - // All fluid accepted. - return null; - } + // All fluid accepted. + return null; + } - @Override - public boolean onNeighborChange() - { - // Get the facing tile - TileEntity te = this.getFaceingTile(); + @Override + public boolean onNeighborChange() { + // Get the facing tile + TileEntity te = this.getFaceingTile(); - // Is it a condenser? - if( te instanceof TileCondenser ) - { - this.condenser = (TileCondenser)te; - } - else - { - this.condenser = null; - } + // Is it a condenser? + if (te instanceof TileCondenser) { + this.condenser = (TileCondenser) te; + } else { + this.condenser = null; + } - // Nothing to update - return false; - } + // Nothing to update + return false; + } - @Override - public void tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - // Ignored. - } - - @Override - public boolean validForPass( final int pass ) - { - return true; - } + @Override + public void tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + // Ignored. + } + @Override + public boolean validForPass(final int pass) { + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusContainer.java b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusContainer.java index 257b3f0d..a451510d 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusContainer.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusContainer.java @@ -1,16 +1,15 @@ package thaumicenergistics.common.inventory; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; - -import appeng.api.networking.IGrid; import appeng.api.config.Actionable; +import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fluids.FluidStack; import thaumcraft.api.aspects.Aspect; @@ -31,561 +30,508 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -class HandlerEssentiaStorageBusContainer - extends HandlerEssentiaStorageBusBase -{ - /** - * Thaumcraft aspect container attracted to the storage bus. - */ - private IAspectContainer aspectContainer; - - /** - * Cached contents of the container. - */ - Hashtable cachedContainerAspects = new Hashtable<>(); - - public HandlerEssentiaStorageBusContainer( final PartEssentiaStorageBus part ) - { - super( part ); - } - - /** - * Adds a list of aspects stacks to a dictionary. - * - * @param essentiaList - */ - private void addListToDictionary( final List essentiaList, final Hashtable dictionary ) - { - // Add each essentia - if( essentiaList != null ) - { - for( IAspectStack stack : essentiaList ) - { - dictionary.put( stack.getAspect(), stack.getStackSize() ); - } - } - } - - /** - * Adjusts the cached aspect amount based on the specified delta. - * Positive diff adds to the amount, negative diff removes from the - * amount. - * - * @param aspect - * @param diff - */ - private void adjustCache( final Aspect aspect, final long diff ) - { - long cachedAmount = 0; - - // Does the cache have this aspect? - if( this.cachedContainerAspects.containsKey( aspect ) ) - { - cachedAmount = this.cachedContainerAspects.get( aspect ); - } - - // Change the amount - long newAmount = cachedAmount + diff; - - // Is there any amount left? - if( newAmount > 0 ) - { - // Update the cache - this.cachedContainerAspects.put( aspect, newAmount ); - } - // None left, was there some? - else if( cachedAmount > 0 ) - { - // Remove from the cache - this.cachedContainerAspects.remove( aspect ); - } - } - - /** - * Gets essentia stored in the container. - */ - private List getContainerEssentia() - { - // Ensure there is a container - if( this.aspectContainer == null ) - { - // No container - return null; - } - - // Ensure the container is whitelisted - if( !TEAPI.transportPermissions().canExtractFromAspectContainerTile( this.aspectContainer ) ) - { - // Not whitelisted - return null; - } - - // Get the essentia and amounts in the container - List containerStacks = EssentiaTileContainerHelper.INSTANCE.getAspectStacksFromContainer( this.aspectContainer ); - - // Ensure there is essentia in the container - if( containerStacks.isEmpty() ) - { - // Empty - return null; - } - - List essentiaList = new ArrayList<>(); - - // Skipping the filter check? - boolean skipFilterCheck = this.allowAny(); - - // Add the essentia - for( IAspectStack essentiaStack : containerStacks ) - { - // Is the aspect in the filter? - if( skipFilterCheck || ( this.filteredAspects.contains( essentiaStack.getAspect() ) != this.inverted ) ) - { - // Convert to fluid - GaseousEssentia gas = GaseousEssentia.getGasFromAspect( essentiaStack.getAspect() ); - - // Is there a fluid form of the aspect? - if( gas != null ) - { - // Add to the list - essentiaList.add( essentiaStack ); - } - } - } - - return essentiaList; - } - - @Override - public boolean canAccept( final IAEFluidStack fluidStack ) - { - // Ensure we have an aspect container - if( this.aspectContainer == null ) - { - // No container - return false; - } - - // Ensure the bus has security access - if( !this.hasSecurityPermission() ) - { - // The bus does not have security access. - return false; - } - - // Ensure the fluid is an essentia gas - if( !this.isFluidEssentiaGas( fluidStack ) ) - { - // Not essentia gas. - return false; - } - - // Ensure the container is whitelisted - if( !( TEAPI.transportPermissions().canInjectToAspectContainerTile( this.aspectContainer ) ) ) - { - // Invalid container - return false; - } - - // Ensure we are allowed to transfer this fluid - if( !this.canTransferGas( (GaseousEssentia)fluidStack.getFluid() ) ) - { - /* - * Either: Not on whitelist or is on blacklist - */ - return false; - } - - // Is the container a reservoir - if( this.aspectContainer instanceof TileEssentiaReservoir ) - { - // Reservoir can accept any type - return true; - } - - // Get the essentia, if any, in the container - IAspectStack containerStack = EssentiaTileContainerHelper.INSTANCE.getAspectStackFromContainer( this.aspectContainer ); - - // Is the container empty? - if( containerStack == null ) - { - // Container is empty, can accept any aspect. - return true; - } - - // Get the gas aspect - Aspect gasAspect = ( (GaseousEssentia)fluidStack.getFluid() ).getAspect(); - - // Does the aspect in the container match the gas aspect? - return gasAspect == containerStack.getAspect(); - } - - /** - * Extracts essentia from the container. - * returns the number of items extracted, null - */ - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource source ) - { - if( ( this.aspectContainer == null ) || ( request == null ) ) - { - // Nothing to drain from, or empty request - return null; - } - - // Ensure the fluid is an essentia gas - if( !this.isFluidEssentiaGas( request ) ) - { - // Not essentia gas fluid. - return null; - } - - // Get the fluid stack from the request - FluidStack toDrain = request.getFluidStack(); - - // Can this gas be transferred? - if( !this.canTransferGas( (GaseousEssentia)toDrain.getFluid() ) ) - { - // Can not transfer this gas. - return null; - } - - // Simulate draining the container - FluidStack drained = EssentiaTileContainerHelper.INSTANCE.extractFromContainer( this.aspectContainer, toDrain, Actionable.SIMULATE ); - - // Was any drained? - if( ( drained == null ) || ( drained.amount == 0 ) ) - { - // None was drained from the container. - return null; - } - - // Convert the drain amount to essentia units - int drainedAmount_EU = (int)EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( drained.amount ); - - // Do we have the power to drain this? - if( !this.partStorageBus.extractPowerForEssentiaTransfer( drainedAmount_EU, Actionable.SIMULATE ) ) - { - // Not enough power - return null; - } - - // Are we modulating? - if( mode == Actionable.MODULATE ) - { - // Extract - EssentiaTileContainerHelper.INSTANCE.extractFromContainer( this.aspectContainer, toDrain, Actionable.MODULATE ); - - // Take power - this.partStorageBus.extractPowerForEssentiaTransfer( drainedAmount_EU, Actionable.MODULATE ); - - // Update cache - this.adjustCache( ( (GaseousEssentia)toDrain.getFluid() ).getAspect(), -drainedAmount_EU ); - } - - // Copy the request - IAEFluidStack extractedFluid = request.copy(); - - // Set the amount extracted - extractedFluid.setStackSize( drained.amount ); - - return extractedFluid; - } - - /** - * Gets the list of fluids from the container. - */ - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( this.aspectContainer != null ) - { - // Get the contents of the container - List essentiaList = this.getContainerEssentia(); - - // Update the cache - this.cachedContainerAspects.clear(); - this.addListToDictionary( essentiaList, this.cachedContainerAspects ); - - if( essentiaList != null ) - { - for( IAspectStack essentia : essentiaList ) - { - // Convert to fluid - GaseousEssentia gas = GaseousEssentia.getGasFromAspect( essentia.getAspect() ); - - // Add to the item list - out.add( EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( gas, essentia.getStackSize() ) ); - } - } - } - - return out; - } - - /** - * Inserts essentia into the container. - * returns the number of items not added. - */ - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource source ) - { - // Ensure input and output - if( ( this.aspectContainer == null ) || ( input == null ) || ( !this.canAccept( input ) ) ) - { - return input; - } - - // Get the fluid stack from the input - FluidStack toFill = input.getFluidStack(); - - // Is void allowed, and we are attached to a void jar? - boolean canVoid = this.isVoidAllowed() && ( this.aspectContainer instanceof TileJarFillableVoid ); - - // How much can be filled, in fluid units - int filled_FU; - - // Can we void any leftovers? - if( canVoid ) - { - // Say that we can take it all - filled_FU = (int)input.getStackSize(); - } - else - { - // Simulate filling the container - filled_FU = (int)EssentiaTileContainerHelper.INSTANCE.injectFluidIntoContainer( this.aspectContainer, input, Actionable.SIMULATE ); - - // Was any filled? - if( filled_FU == 0 ) - { - // Can not inject any. - return input; - } - } - - // Get how much the filled amount is in essentia units - int filled_EU = (int)EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( filled_FU ); - - // Do we have the power to complete this operation? - if( !this.partStorageBus.extractPowerForEssentiaTransfer( filled_EU, Actionable.SIMULATE ) ) - { - // Not enough power - return input; - } - - // Are we modulating? - if( mode == Actionable.MODULATE ) - { - // Inject, and set the actual amount injected - filled_FU = (int)EssentiaTileContainerHelper.INSTANCE.injectFluidIntoContainer( this.aspectContainer, input, Actionable.MODULATE ); - - // Take power for as much as we claimed we could take. - this.partStorageBus.extractPowerForEssentiaTransfer( filled_EU, Actionable.MODULATE ); - - // Convert the actual amount injected into Essentia units. - filled_EU = (int)EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( filled_FU ); - - // Update the cache - this.adjustCache( ( (GaseousEssentia)toFill.getFluid() ).getAspect(), filled_EU ); - } - - // Calculate how much was left over - int remaining_FU = toFill.amount - filled_FU; - - // Did we completely drain the input stack? - if( remaining_FU == 0 ) - { - // Nothing left over - return null; - } - // Are we voiding the remainder? - else if( canVoid ) - { - // Update the grid so that it doesn't thing we have stored the voided amount. - // (actually this doesn't work, since we are inside insertion call stack, so monitor notifications are skipped) - // I left the code here in case someone will want to optimize this again - // this.postAlterationToHostGrid( ImmutableList.of( AEApi.instance().storage() .createFluidStack( new FluidStack( toFill.getFluid(), -remaining_FU ) ) ) ); - // instead we just invalidate essentia cache every time - invalidateGlobalEssentiaCache(); - // Report that we accepted it all. - return null; - } - - // Return what was left over - IAEFluidStack remainingFluid = input.copy(); - remainingFluid.setStackSize( remaining_FU ); - - return remainingFluid; - } - - private void invalidateGlobalEssentiaCache() { - IGridNode node = partStorageBus.getGridNode(); - if( node != null ) - { - IGrid grid = node.getGrid(); - if( grid != null ) - { - GridEssentiaCache globalCache = grid.getCache( IEssentiaGrid.class ); - globalCache.onListUpdate(); - } - } - } - - /** - * Checks if we are still facing a valid container. - * - * @return - */ - @Override - public boolean onNeighborChange() - { - // Get the tile we are facing - TileEntity tileEntity = this.getFaceingTile(); - - // Are we facing an essentia container? - if( tileEntity instanceof IAspectContainer ) - { - // Has the container changed? - if( this.aspectContainer != tileEntity ) - { - // Set the container - this.aspectContainer = (IAspectContainer)tileEntity; - - // Clear the cache - this.cachedContainerAspects.clear(); - - // Container changed - return true; - } - - return false; - } - - // Was the bus facing a container? - if( this.aspectContainer != null ) - { - // Clear the reference - this.aspectContainer = null; - - // Send one last tick - this.tickingRequest( null, 0 ); - - return true; - } - - return false; - } - - /** - * Checks the Thaumcraft container. - */ - @Override - public void tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - // Create the checklist - HashSet aspectsToCheck = new HashSet<>(); - - // Get the current contents of the container - List currentContainerContents = this.getContainerEssentia(); - - // Convert to dictionary - Hashtable currentContainerAspects = new Hashtable<>(); - if( currentContainerContents != null ) - { - this.addListToDictionary( currentContainerContents, currentContainerAspects ); - - // Add the current aspects to check list - aspectsToCheck.addAll( currentContainerAspects.keySet() ); - } - - // Add the cached aspects to check list - aspectsToCheck.addAll( this.cachedContainerAspects.keySet() ); - - // Is there anything to check? - if( aspectsToCheck.size() == 0 ) - { - // Nothing to check. - return; - } - - // Alteration list - List alterations = null; - - // Compare all amounts - for( Aspect aspect : aspectsToCheck ) - { - // Value cached - long cachedAmount = 0; - if( this.cachedContainerAspects.containsKey( aspect ) ) - { - cachedAmount = this.cachedContainerAspects.get( aspect ); - } - - // Current value - long currentAmount = 0; - if( currentContainerAspects.containsKey( aspect ) ) - { - currentAmount = currentContainerAspects.get( aspect ); - } - - // Calculate the difference - long diff = currentAmount - cachedAmount; - - // Do they differ? - if( diff != 0 ) - { - // First alteration? - if( alterations == null ) - { - // Create the list - alterations = new ArrayList<>(); - } - - // Create the alteration - alterations.add( EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( aspect, diff ) ); - - // Update the cache - this.adjustCache( aspect, diff ); - } - } - - // Any alterations? - if( alterations != null ) - { - // Post the changes - this.postAlterationToHostGrid( alterations ); - } - - } - - /** - * Valid for pass 1 if there are filters or the container has stored - * essentia. - * Valid for pass 2 if no filters or stored essentia. - * - * @return - */ - @Override - public boolean validForPass( final int pass ) - { - if( this.aspectContainer != null ) - { - boolean hasFilters = !this.allowAny(); - boolean hasStored = !EssentiaTileContainerHelper.INSTANCE.getAspectStacksFromContainer( this.aspectContainer ).isEmpty(); - - // Is this the priority pass? - if( pass == 1 ) - { - // Valid if has whitelist or container has something in it - return( ( hasFilters && !this.inverted ) || hasStored ); - } - - // Valid if has no filters or is blacklist. - return( !hasFilters || this.inverted ); - - } - - return false; - } +class HandlerEssentiaStorageBusContainer extends HandlerEssentiaStorageBusBase { + /** + * Thaumcraft aspect container attracted to the storage bus. + */ + private IAspectContainer aspectContainer; + + /** + * Cached contents of the container. + */ + Hashtable cachedContainerAspects = new Hashtable<>(); + + public HandlerEssentiaStorageBusContainer(final PartEssentiaStorageBus part) { + super(part); + } + + /** + * Adds a list of aspects stacks to a dictionary. + * + * @param essentiaList + */ + private void addListToDictionary(final List essentiaList, final Hashtable dictionary) { + // Add each essentia + if (essentiaList != null) { + for (IAspectStack stack : essentiaList) { + dictionary.put(stack.getAspect(), stack.getStackSize()); + } + } + } + + /** + * Adjusts the cached aspect amount based on the specified delta. + * Positive diff adds to the amount, negative diff removes from the + * amount. + * + * @param aspect + * @param diff + */ + private void adjustCache(final Aspect aspect, final long diff) { + long cachedAmount = 0; + + // Does the cache have this aspect? + if (this.cachedContainerAspects.containsKey(aspect)) { + cachedAmount = this.cachedContainerAspects.get(aspect); + } + + // Change the amount + long newAmount = cachedAmount + diff; + + // Is there any amount left? + if (newAmount > 0) { + // Update the cache + this.cachedContainerAspects.put(aspect, newAmount); + } + // None left, was there some? + else if (cachedAmount > 0) { + // Remove from the cache + this.cachedContainerAspects.remove(aspect); + } + } + + /** + * Gets essentia stored in the container. + */ + private List getContainerEssentia() { + // Ensure there is a container + if (this.aspectContainer == null) { + // No container + return null; + } + + // Ensure the container is whitelisted + if (!TEAPI.transportPermissions().canExtractFromAspectContainerTile(this.aspectContainer)) { + // Not whitelisted + return null; + } + + // Get the essentia and amounts in the container + List containerStacks = + EssentiaTileContainerHelper.INSTANCE.getAspectStacksFromContainer(this.aspectContainer); + + // Ensure there is essentia in the container + if (containerStacks.isEmpty()) { + // Empty + return null; + } + + List essentiaList = new ArrayList<>(); + + // Skipping the filter check? + boolean skipFilterCheck = this.allowAny(); + + // Add the essentia + for (IAspectStack essentiaStack : containerStacks) { + // Is the aspect in the filter? + if (skipFilterCheck || (this.filteredAspects.contains(essentiaStack.getAspect()) != this.inverted)) { + // Convert to fluid + GaseousEssentia gas = GaseousEssentia.getGasFromAspect(essentiaStack.getAspect()); + + // Is there a fluid form of the aspect? + if (gas != null) { + // Add to the list + essentiaList.add(essentiaStack); + } + } + } + + return essentiaList; + } + + @Override + public boolean canAccept(final IAEFluidStack fluidStack) { + // Ensure we have an aspect container + if (this.aspectContainer == null) { + // No container + return false; + } + + // Ensure the bus has security access + if (!this.hasSecurityPermission()) { + // The bus does not have security access. + return false; + } + + // Ensure the fluid is an essentia gas + if (!this.isFluidEssentiaGas(fluidStack)) { + // Not essentia gas. + return false; + } + + // Ensure the container is whitelisted + if (!(TEAPI.transportPermissions().canInjectToAspectContainerTile(this.aspectContainer))) { + // Invalid container + return false; + } + + // Ensure we are allowed to transfer this fluid + if (!this.canTransferGas((GaseousEssentia) fluidStack.getFluid())) { + /* + * Either: Not on whitelist or is on blacklist + */ + return false; + } + + // Is the container a reservoir + if (this.aspectContainer instanceof TileEssentiaReservoir) { + // Reservoir can accept any type + return true; + } + + // Get the essentia, if any, in the container + IAspectStack containerStack = + EssentiaTileContainerHelper.INSTANCE.getAspectStackFromContainer(this.aspectContainer); + + // Is the container empty? + if (containerStack == null) { + // Container is empty, can accept any aspect. + return true; + } + + // Get the gas aspect + Aspect gasAspect = ((GaseousEssentia) fluidStack.getFluid()).getAspect(); + + // Does the aspect in the container match the gas aspect? + return gasAspect == containerStack.getAspect(); + } + + /** + * Extracts essentia from the container. + * returns the number of items extracted, null + */ + @Override + public IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource source) { + if ((this.aspectContainer == null) || (request == null)) { + // Nothing to drain from, or empty request + return null; + } + + // Ensure the fluid is an essentia gas + if (!this.isFluidEssentiaGas(request)) { + // Not essentia gas fluid. + return null; + } + + // Get the fluid stack from the request + FluidStack toDrain = request.getFluidStack(); + + // Can this gas be transferred? + if (!this.canTransferGas((GaseousEssentia) toDrain.getFluid())) { + // Can not transfer this gas. + return null; + } + + // Simulate draining the container + FluidStack drained = EssentiaTileContainerHelper.INSTANCE.extractFromContainer( + this.aspectContainer, toDrain, Actionable.SIMULATE); + + // Was any drained? + if ((drained == null) || (drained.amount == 0)) { + // None was drained from the container. + return null; + } + + // Convert the drain amount to essentia units + int drainedAmount_EU = + (int) EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(drained.amount); + + // Do we have the power to drain this? + if (!this.partStorageBus.extractPowerForEssentiaTransfer(drainedAmount_EU, Actionable.SIMULATE)) { + // Not enough power + return null; + } + + // Are we modulating? + if (mode == Actionable.MODULATE) { + // Extract + EssentiaTileContainerHelper.INSTANCE.extractFromContainer( + this.aspectContainer, toDrain, Actionable.MODULATE); + + // Take power + this.partStorageBus.extractPowerForEssentiaTransfer(drainedAmount_EU, Actionable.MODULATE); + + // Update cache + this.adjustCache(((GaseousEssentia) toDrain.getFluid()).getAspect(), -drainedAmount_EU); + } + + // Copy the request + IAEFluidStack extractedFluid = request.copy(); + + // Set the amount extracted + extractedFluid.setStackSize(drained.amount); + + return extractedFluid; + } + + /** + * Gets the list of fluids from the container. + */ + @Override + public IItemList getAvailableItems(final IItemList out) { + if (this.aspectContainer != null) { + // Get the contents of the container + List essentiaList = this.getContainerEssentia(); + + // Update the cache + this.cachedContainerAspects.clear(); + this.addListToDictionary(essentiaList, this.cachedContainerAspects); + + if (essentiaList != null) { + for (IAspectStack essentia : essentiaList) { + // Convert to fluid + GaseousEssentia gas = GaseousEssentia.getGasFromAspect(essentia.getAspect()); + + // Add to the item list + out.add(EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( + gas, essentia.getStackSize())); + } + } + } + + return out; + } + + /** + * Inserts essentia into the container. + * returns the number of items not added. + */ + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource source) { + // Ensure input and output + if ((this.aspectContainer == null) || (input == null) || (!this.canAccept(input))) { + return input; + } + + // Get the fluid stack from the input + FluidStack toFill = input.getFluidStack(); + + // Is void allowed, and we are attached to a void jar? + boolean canVoid = this.isVoidAllowed() && (this.aspectContainer instanceof TileJarFillableVoid); + + // How much can be filled, in fluid units + int filled_FU; + + // Can we void any leftovers? + if (canVoid) { + // Say that we can take it all + filled_FU = (int) input.getStackSize(); + } else { + // Simulate filling the container + filled_FU = (int) EssentiaTileContainerHelper.INSTANCE.injectFluidIntoContainer( + this.aspectContainer, input, Actionable.SIMULATE); + + // Was any filled? + if (filled_FU == 0) { + // Can not inject any. + return input; + } + } + + // Get how much the filled amount is in essentia units + int filled_EU = (int) EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(filled_FU); + + // Do we have the power to complete this operation? + if (!this.partStorageBus.extractPowerForEssentiaTransfer(filled_EU, Actionable.SIMULATE)) { + // Not enough power + return input; + } + + // Are we modulating? + if (mode == Actionable.MODULATE) { + // Inject, and set the actual amount injected + filled_FU = (int) EssentiaTileContainerHelper.INSTANCE.injectFluidIntoContainer( + this.aspectContainer, input, Actionable.MODULATE); + + // Take power for as much as we claimed we could take. + this.partStorageBus.extractPowerForEssentiaTransfer(filled_EU, Actionable.MODULATE); + + // Convert the actual amount injected into Essentia units. + filled_EU = (int) EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(filled_FU); + + // Update the cache + this.adjustCache(((GaseousEssentia) toFill.getFluid()).getAspect(), filled_EU); + } + + // Calculate how much was left over + int remaining_FU = toFill.amount - filled_FU; + + // Did we completely drain the input stack? + if (remaining_FU == 0) { + // Nothing left over + return null; + } + // Are we voiding the remainder? + else if (canVoid) { + // Update the grid so that it doesn't thing we have stored the voided amount. + // (actually this doesn't work, since we are inside insertion call stack, so monitor notifications are + // skipped) + // I left the code here in case someone will want to optimize this again + // this.postAlterationToHostGrid( ImmutableList.of( AEApi.instance().storage() .createFluidStack( new + // FluidStack( toFill.getFluid(), -remaining_FU ) ) ) ); + // instead we just invalidate essentia cache every time + invalidateGlobalEssentiaCache(); + // Report that we accepted it all. + return null; + } + + // Return what was left over + IAEFluidStack remainingFluid = input.copy(); + remainingFluid.setStackSize(remaining_FU); + + return remainingFluid; + } + + private void invalidateGlobalEssentiaCache() { + IGridNode node = partStorageBus.getGridNode(); + if (node != null) { + IGrid grid = node.getGrid(); + if (grid != null) { + GridEssentiaCache globalCache = grid.getCache(IEssentiaGrid.class); + globalCache.onListUpdate(); + } + } + } + + /** + * Checks if we are still facing a valid container. + * + * @return + */ + @Override + public boolean onNeighborChange() { + // Get the tile we are facing + TileEntity tileEntity = this.getFaceingTile(); + + // Are we facing an essentia container? + if (tileEntity instanceof IAspectContainer) { + // Has the container changed? + if (this.aspectContainer != tileEntity) { + // Set the container + this.aspectContainer = (IAspectContainer) tileEntity; + + // Clear the cache + this.cachedContainerAspects.clear(); + + // Container changed + return true; + } + + return false; + } + + // Was the bus facing a container? + if (this.aspectContainer != null) { + // Clear the reference + this.aspectContainer = null; + + // Send one last tick + this.tickingRequest(null, 0); + + return true; + } + + return false; + } + + /** + * Checks the Thaumcraft container. + */ + @Override + public void tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + // Create the checklist + HashSet aspectsToCheck = new HashSet<>(); + + // Get the current contents of the container + List currentContainerContents = this.getContainerEssentia(); + + // Convert to dictionary + Hashtable currentContainerAspects = new Hashtable<>(); + if (currentContainerContents != null) { + this.addListToDictionary(currentContainerContents, currentContainerAspects); + + // Add the current aspects to check list + aspectsToCheck.addAll(currentContainerAspects.keySet()); + } + + // Add the cached aspects to check list + aspectsToCheck.addAll(this.cachedContainerAspects.keySet()); + + // Is there anything to check? + if (aspectsToCheck.size() == 0) { + // Nothing to check. + return; + } + + // Alteration list + List alterations = null; + + // Compare all amounts + for (Aspect aspect : aspectsToCheck) { + // Value cached + long cachedAmount = 0; + if (this.cachedContainerAspects.containsKey(aspect)) { + cachedAmount = this.cachedContainerAspects.get(aspect); + } + + // Current value + long currentAmount = 0; + if (currentContainerAspects.containsKey(aspect)) { + currentAmount = currentContainerAspects.get(aspect); + } + + // Calculate the difference + long diff = currentAmount - cachedAmount; + + // Do they differ? + if (diff != 0) { + // First alteration? + if (alterations == null) { + // Create the list + alterations = new ArrayList<>(); + } + + // Create the alteration + alterations.add(EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits(aspect, diff)); + + // Update the cache + this.adjustCache(aspect, diff); + } + } + + // Any alterations? + if (alterations != null) { + // Post the changes + this.postAlterationToHostGrid(alterations); + } + } + + /** + * Valid for pass 1 if there are filters or the container has stored + * essentia. + * Valid for pass 2 if no filters or stored essentia. + * + * @return + */ + @Override + public boolean validForPass(final int pass) { + if (this.aspectContainer != null) { + boolean hasFilters = !this.allowAny(); + boolean hasStored = !EssentiaTileContainerHelper.INSTANCE + .getAspectStacksFromContainer(this.aspectContainer) + .isEmpty(); + + // Is this the priority pass? + if (pass == 1) { + // Valid if has whitelist or container has something in it + return ((hasFilters && !this.inverted) || hasStored); + } + + // Valid if has no filters or is blacklist. + return (!hasFilters || this.inverted); + } + + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusDuality.java b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusDuality.java index 66761960..d10ccf4b 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusDuality.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusDuality.java @@ -20,260 +20,222 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -public class HandlerEssentiaStorageBusDuality - extends HandlerEssentiaStorageBusBase -{ - /** - * The handler that is actually used, can be null. - */ - private HandlerEssentiaStorageBusBase internalHandler; +public class HandlerEssentiaStorageBusDuality extends HandlerEssentiaStorageBusBase { + /** + * The handler that is actually used, can be null. + */ + private HandlerEssentiaStorageBusBase internalHandler; - /** - * Handler used when facing an aspect container. - */ - private HandlerEssentiaStorageBusContainer containerHandler; + /** + * Handler used when facing an aspect container. + */ + private HandlerEssentiaStorageBusContainer containerHandler; - /** - * Handler used when facing an interface. - */ - private HandlerEssentiaStorageBusInterface interfaceHandler; + /** + * Handler used when facing an interface. + */ + private HandlerEssentiaStorageBusInterface interfaceHandler; - /** - * Handler used when facing a condenser. - */ - private HandlerEssentiaStorageBusCondenser condenserHandler; + /** + * Handler used when facing a condenser. + */ + private HandlerEssentiaStorageBusCondenser condenserHandler; - /** - * Creates the handler. - * - * @param part - */ - public HandlerEssentiaStorageBusDuality( final PartEssentiaStorageBus part ) - { - super( part ); - } + /** + * Creates the handler. + * + * @param part + */ + public HandlerEssentiaStorageBusDuality(final PartEssentiaStorageBus part) { + super(part); + } - /** - * Updates the internal handler to match the duality handler. - */ - private void updateInternalHandler() - { - // Ensure there is an internal handler? - if( this.internalHandler != null ) - { - // Set the filtered aspects - this.internalHandler.filteredAspects = this.filteredAspects; + /** + * Updates the internal handler to match the duality handler. + */ + private void updateInternalHandler() { + // Ensure there is an internal handler? + if (this.internalHandler != null) { + // Set the filtered aspects + this.internalHandler.filteredAspects = this.filteredAspects; - // Set inverted - this.internalHandler.inverted = this.inverted; + // Set inverted + this.internalHandler.inverted = this.inverted; - // Set void - this.internalHandler.setVoidAllowed( this.isVoidAllowed() ); - } - } + // Set void + this.internalHandler.setVoidAllowed(this.isVoidAllowed()); + } + } - @Override - public boolean canAccept( final IAEFluidStack fluidStack ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - return this.internalHandler.canAccept( fluidStack ); - } + @Override + public boolean canAccept(final IAEFluidStack fluidStack) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + return this.internalHandler.canAccept(fluidStack); + } - // No handler - return false; - } + // No handler + return false; + } - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource source ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - return this.internalHandler.extractItems( request, mode, source ); - } + @Override + public IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource source) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + return this.internalHandler.extractItems(request, mode, source); + } - // No handler - return null; - } + // No handler + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - return this.internalHandler.getAvailableItems( out ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + return this.internalHandler.getAvailableItems(out); + } - // No handler - return out; - } + // No handler + return out; + } - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource source ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - return this.internalHandler.injectItems( input, mode, source ); - } + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource source) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + return this.internalHandler.injectItems(input, mode, source); + } - // No handler - return input; - } + // No handler + return input; + } - @Override - public boolean onNeighborChange() - { - boolean doUpdate = false; + @Override + public boolean onNeighborChange() { + boolean doUpdate = false; - // What is the storage bus facing? - TileEntity tileEntity = this.getFaceingTile(); + // What is the storage bus facing? + TileEntity tileEntity = this.getFaceingTile(); - HandlerEssentiaStorageBusBase newHandler = null; + HandlerEssentiaStorageBusBase newHandler = null; - // These should be ordered most specific to most generic - if( tileEntity instanceof TileCondenser ) - { - // Create the interface if needed - if( this.condenserHandler == null ) - { - // Create the handler - this.condenserHandler = new HandlerEssentiaStorageBusCondenser( this.partStorageBus ); - } + // These should be ordered most specific to most generic + if (tileEntity instanceof TileCondenser) { + // Create the interface if needed + if (this.condenserHandler == null) { + // Create the handler + this.condenserHandler = new HandlerEssentiaStorageBusCondenser(this.partStorageBus); + } - // Set the new handler - newHandler = this.condenserHandler; + // Set the new handler + newHandler = this.condenserHandler; - } - else if( tileEntity instanceof IAspectContainer ) - { - // Create the container handler if needed - if( this.containerHandler == null ) - { - // Create the handler - this.containerHandler = new HandlerEssentiaStorageBusContainer( this.partStorageBus ); - } + } else if (tileEntity instanceof IAspectContainer) { + // Create the container handler if needed + if (this.containerHandler == null) { + // Create the handler + this.containerHandler = new HandlerEssentiaStorageBusContainer(this.partStorageBus); + } - // Set internal handler to the container handler - newHandler = this.containerHandler; - } - else if( tileEntity instanceof IPartHost ) - { - // Get the part - IPart facingPart = this.getFacingPartFromPartHost( (IPartHost)tileEntity ); + // Set internal handler to the container handler + newHandler = this.containerHandler; + } else if (tileEntity instanceof IPartHost) { + // Get the part + IPart facingPart = this.getFacingPartFromPartHost((IPartHost) tileEntity); - // Is the part a ME interface? - if( facingPart instanceof PartInterface ) - { - // Create the interface handler if needed - if( this.interfaceHandler == null ) - { - // Create the handler - this.interfaceHandler = new HandlerEssentiaStorageBusInterface( this.partStorageBus ); - } + // Is the part a ME interface? + if (facingPart instanceof PartInterface) { + // Create the interface handler if needed + if (this.interfaceHandler == null) { + // Create the handler + this.interfaceHandler = new HandlerEssentiaStorageBusInterface(this.partStorageBus); + } - // Set the internal handler to the interface handler - newHandler = this.interfaceHandler; - } - } - else if( tileEntity instanceof TileInterface ) - { - // Create the interface handler if needed - if( this.interfaceHandler == null ) - { - // Create the handler - this.interfaceHandler = new HandlerEssentiaStorageBusInterface( this.partStorageBus ); - } + // Set the internal handler to the interface handler + newHandler = this.interfaceHandler; + } + } else if (tileEntity instanceof TileInterface) { + // Create the interface handler if needed + if (this.interfaceHandler == null) { + // Create the handler + this.interfaceHandler = new HandlerEssentiaStorageBusInterface(this.partStorageBus); + } - // Set the internal handler to the interface handler - newHandler = this.interfaceHandler; + // Set the internal handler to the interface handler + newHandler = this.interfaceHandler; + } - } + // Has the handler changed? + if (this.internalHandler != newHandler) { + // Was there a previous handler? + if (this.internalHandler != null) { + // Let the old handler know the neighbor changed + this.internalHandler.onNeighborChange(); + } - // Has the handler changed? - if( this.internalHandler != newHandler ) - { - // Was there a previous handler? - if( this.internalHandler != null ) - { - // Let the old handler know the neighbor changed - this.internalHandler.onNeighborChange(); - } + // Set the new handler + this.internalHandler = newHandler; - // Set the new handler - this.internalHandler = newHandler; + // Mark for update + doUpdate = true; + } - // Mark for update - doUpdate = true; - } + // Pass to internal handler + if (this.internalHandler != null) { + // Update it + this.updateInternalHandler(); - // Pass to internal handler - if( this.internalHandler != null ) - { - // Update it - this.updateInternalHandler(); + // Pass to the handler + doUpdate |= this.internalHandler.onNeighborChange(); + } - // Pass to the handler - doUpdate |= this.internalHandler.onNeighborChange(); - } + return doUpdate; + } - return doUpdate; + @Override + public void setInverted(final boolean isInverted) { + this.inverted = isInverted; - } + if (this.internalHandler != null) { + this.internalHandler.setInverted(isInverted); + } + } - @Override - public void setInverted( final boolean isInverted ) - { - this.inverted = isInverted; + @Override + public void setVoidAllowed(final boolean isVoidAllowed) { + // Call super + super.setVoidAllowed(isVoidAllowed); - if( this.internalHandler != null ) - { - this.internalHandler.setInverted( isInverted ); - } - } + // Call handler + if (this.internalHandler != null) { + this.internalHandler.setVoidAllowed(isVoidAllowed); + } + } - @Override - public void setVoidAllowed( final boolean isVoidAllowed ) - { - // Call super - super.setVoidAllowed( isVoidAllowed ); + @Override + public void tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + this.internalHandler.tickingRequest(node, TicksSinceLastCall); + } + } - // Call handler - if( this.internalHandler != null ) - { - this.internalHandler.setVoidAllowed( isVoidAllowed ); - } - } + @Override + public boolean validForPass(final int pass) { + // Ensure we have an internal handler + if (this.internalHandler != null) { + // Pass to handler + return this.internalHandler.validForPass(pass); + } - @Override - public void tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - this.internalHandler.tickingRequest( node, TicksSinceLastCall ); - } - } - - @Override - public boolean validForPass( final int pass ) - { - // Ensure we have an internal handler - if( this.internalHandler != null ) - { - // Pass to handler - return this.internalHandler.validForPass( pass ); - } - - // No handler - return false; - } + // No handler + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusInterface.java b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusInterface.java index f48387b1..c39503da 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusInterface.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerEssentiaStorageBusInterface.java @@ -29,311 +29,269 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -class HandlerEssentiaStorageBusInterface - extends HandlerEssentiaStorageBusBase - implements IMEMonitorHandlerReceiver -{ - /** - * Interface the storage bus is facing. - */ - private ITileStorageMonitorable MEInterface = null; +class HandlerEssentiaStorageBusInterface extends HandlerEssentiaStorageBusBase + implements IMEMonitorHandlerReceiver { + /** + * Interface the storage bus is facing. + */ + private ITileStorageMonitorable MEInterface = null; - /** - * Handler to the interfaces ME grid. - */ - private MEInventoryHandler handler; + /** + * Handler to the interfaces ME grid. + */ + private MEInventoryHandler handler; - /** - * Hashcode of the interface. - */ - private int handlerHash; + /** + * Hashcode of the interface. + */ + private int handlerHash; - /** - * Prevent infinite loops when sub-grid's sub-grid is hosts grid. - * yeah. - */ - private boolean canPostUpdate = true; + /** + * Prevent infinite loops when sub-grid's sub-grid is hosts grid. + * yeah. + */ + private boolean canPostUpdate = true; - /** - * Creates the interface handler. - * - * @param part - */ - public HandlerEssentiaStorageBusInterface( final PartEssentiaStorageBus part ) - { - super( part ); - } + /** + * Creates the interface handler. + * + * @param part + */ + public HandlerEssentiaStorageBusInterface(final PartEssentiaStorageBus part) { + super(part); + } - /** - * Checks if the sub-grid can accept this gas. - */ - @Override - public boolean canAccept( final IAEFluidStack fluidStack ) - { - // Is the fluid an essentia gas? - if( this.isFluidEssentiaGas( fluidStack ) ) - { - // Pass to handler - if( this.handler != null ) - { - return this.handler.canAccept( fluidStack ); - } - } + /** + * Checks if the sub-grid can accept this gas. + */ + @Override + public boolean canAccept(final IAEFluidStack fluidStack) { + // Is the fluid an essentia gas? + if (this.isFluidEssentiaGas(fluidStack)) { + // Pass to handler + if (this.handler != null) { + return this.handler.canAccept(fluidStack); + } + } - return false; - } + return false; + } - /** - * Attempts to extract the gas from the sub-grid. - */ - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource source ) - { - // Is the fluid an essentia gas? - if( this.isFluidEssentiaGas( request ) ) - { - if( this.handler != null ) - { - // Extract the gas - IAEFluidStack extractedGas = this.handler.extractItems( request, mode, source ); + /** + * Attempts to extract the gas from the sub-grid. + */ + @Override + public IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource source) { + // Is the fluid an essentia gas? + if (this.isFluidEssentiaGas(request)) { + if (this.handler != null) { + // Extract the gas + IAEFluidStack extractedGas = this.handler.extractItems(request, mode, source); - return extractedGas; - } - } + return extractedGas; + } + } - return null; - } + return null; + } - /** - * Gets the gases from the sub-grid. - */ - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( this.handler != null ) - { - // Get the subgrids fluids - IItemList subGridFluids = this.handler.getAvailableItems( AEApi.instance().storage().createFluidList() ); + /** + * Gets the gases from the sub-grid. + */ + @Override + public IItemList getAvailableItems(final IItemList out) { + if (this.handler != null) { + // Get the subgrids fluids + IItemList subGridFluids = + this.handler.getAvailableItems(AEApi.instance().storage().createFluidList()); - for( IAEFluidStack fluid : subGridFluids ) - { - // Is the fluid as essentia gas? - if( this.isFluidEssentiaGas( fluid ) ) - { - // Add to the output list - out.add( fluid ); - } - } + for (IAEFluidStack fluid : subGridFluids) { + // Is the fluid as essentia gas? + if (this.isFluidEssentiaGas(fluid)) { + // Add to the output list + out.add(fluid); + } + } + } - } + return out; + } - return out; - } + /** + * Attempts to inject the gas into the sub-network. + */ + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource source) { + // Is the fluid an essentia gas? + if (this.isFluidEssentiaGas(input)) { + if (this.handler != null) { + // Inject the gas + IAEFluidStack remainingGas = this.handler.injectItems(input, mode, source); - /** - * Attempts to inject the gas into the sub-network. - */ - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource source ) - { - // Is the fluid an essentia gas? - if( this.isFluidEssentiaGas( input ) ) - { - if( this.handler != null ) - { - // Inject the gas - IAEFluidStack remainingGas = this.handler.injectItems( input, mode, source ); + return remainingGas; + } + } + return input; + } - return remainingGas; - } - } - return input; - } + /** + * Is the handler still valid for receiving changes? + */ + @Override + public boolean isValid(final Object verificationToken) { + return this.handler == verificationToken; + } - /** - * Is the handler still valid for receiving changes? - */ - @Override - public boolean isValid( final Object verificationToken ) - { - return this.handler == verificationToken; - } + /** + * Sub-grid list changed, we should update. + */ + @Override + public void onListUpdate() { + if (this.canPostUpdate) { + this.canPostUpdate = false; + try { + this.partStorageBus.getGridBlock().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (Exception e) { - /** - * Sub-grid list changed, we should update. - */ - @Override - public void onListUpdate() - { - if( this.canPostUpdate ) - { - this.canPostUpdate = false; - try - { - this.partStorageBus.getGridBlock().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( Exception e ) - { + } + } + } - } - } - } + @Override + public boolean onNeighborChange() { + ITileStorageMonitorable facingInterface = null; - @Override - public boolean onNeighborChange() - { - ITileStorageMonitorable facingInterface = null; + // Get the tile we are facing + TileEntity tileEntity = this.getFaceingTile(); - // Get the tile we are facing - TileEntity tileEntity = this.getFaceingTile(); + // Is the tile a part host? + if (tileEntity instanceof IPartHost) { + // Get the facing part + IPart facingPart = this.getFacingPartFromPartHost((IPartHost) tileEntity); - // Is the tile a part host? - if( tileEntity instanceof IPartHost ) - { - // Get the facing part - IPart facingPart = this.getFacingPartFromPartHost( (IPartHost)tileEntity ); + if (facingPart instanceof PartInterface) { + facingInterface = (ITileStorageMonitorable) facingPart; + } + } + // Is it an interface? + else if (tileEntity instanceof TileInterface) { + facingInterface = (ITileStorageMonitorable) tileEntity; + } - if( facingPart instanceof PartInterface ) - { - facingInterface = (ITileStorageMonitorable)facingPart; - } - } - // Is it an interface? - else if( tileEntity instanceof TileInterface ) - { - facingInterface = (ITileStorageMonitorable)tileEntity; - } + // Is the storage bus facing an interface? + if (facingInterface != null) { + // Get the tile hashcode + int newHandlerHash = Platform.generateTileHash(tileEntity); - // Is the storage bus facing an interface? - if( facingInterface != null ) - { - // Get the tile hashcode - int newHandlerHash = Platform.generateTileHash( tileEntity ); + // Do the hashes match? + if ((this.handlerHash == newHandlerHash) && (this.handlerHash != 0)) { + return false; + } - // Do the hashes match? - if( ( this.handlerHash == newHandlerHash ) && ( this.handlerHash != 0 ) ) - { - return false; - } + // Post cell update to cell network. + try { + this.partStorageBus.getGridBlock().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (Exception e) { - // Post cell update to cell network. - try - { - this.partStorageBus.getGridBlock().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( Exception e ) - { + } - } + // Set the tile hashcode + this.handlerHash = newHandlerHash; - // Set the tile hashcode - this.handlerHash = newHandlerHash; + // Set the interface + this.MEInterface = facingInterface; - // Set the interface - this.MEInterface = facingInterface; + // Clear the old handler. + this.handler = null; - // Clear the old handler. - this.handler = null; + // Get the monitor + IStorageMonitorable monitor = this.MEInterface.getMonitorable( + this.partStorageBus.getSide().getOpposite(), this.machineSource); - // Get the monitor - IStorageMonitorable monitor = this.MEInterface.getMonitorable( this.partStorageBus.getSide().getOpposite(), this.machineSource ); + // Ensure a monitor was retrieved + if (monitor != null) { + // Get the fluid inventory + IMEInventory inv = monitor.getFluidInventory(); - // Ensure a monitor was retrieved - if( monitor != null ) - { - // Get the fluid inventory - IMEInventory inv = monitor.getFluidInventory(); + // Ensure the fluid inventory was retrieved + if (inv != null) { + // Create the handler + this.handler = new MEInventoryHandler(inv, StorageChannel.FLUIDS); - // Ensure the fluid inventory was retrieved - if( inv != null ) - { - // Create the handler - this.handler = new MEInventoryHandler( inv, StorageChannel.FLUIDS ); + // Set the handler properties + this.handler.setBaseAccess(this.getAccess()); + this.handler.setWhitelist(IncludeExclude.WHITELIST); + this.handler.setPriority(this.getPriority()); - // Set the handler properties - this.handler.setBaseAccess( this.getAccess() ); - this.handler.setWhitelist( IncludeExclude.WHITELIST ); - this.handler.setPriority( this.getPriority() ); + // Add the handler as a listener + if (inv instanceof IMEMonitor) { + ((IMEMonitor) inv).addListener(this, this.handler); + } + } + } - // Add the handler as a listener - if( inv instanceof IMEMonitor ) - { - ( (IMEMonitor)inv ).addListener( this, this.handler ); - } - } - } + return true; + } - return true; - } + // Not facing interface + this.handlerHash = 0; + this.MEInterface = null; - // Not facing interface - this.handlerHash = 0; - this.MEInterface = null; + // Was the handler attached to an interface? + if (this.handler != null) { + this.handler = null; + return true; + } - // Was the handler attached to an interface? - if( this.handler != null ) - { - this.handler = null; - return true; - } + return false; + } - return false; - } + /** + * A change occurred in the sub-grid, inform the host grid. + */ + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource) { + try { + IActionHost actionHost = null; - /** - * A change occurred in the sub-grid, inform the host grid. - */ - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - try - { - IActionHost actionHost = null; + // Get the action source + if (actionSource instanceof PlayerSource) { + // From the player source + actionHost = ((PlayerSource) actionSource).via; + } else if (actionSource instanceof MachineSource) { + // From the machine source + actionHost = ((MachineSource) actionSource).via; + } - // Get the action source - if( actionSource instanceof PlayerSource ) - { - // From the player source - actionHost = ( (PlayerSource)actionSource ).via; - } - else if( actionSource instanceof MachineSource ) - { - // From the machine source - actionHost = ( (MachineSource)actionSource ).via; - } + // Ensure there is an action host + if (actionHost != null) { + // Post update if change did not come from host grid, prevents double posting. + if (actionHost.getActionableNode().getGrid() + != this.partStorageBus.getActionableNode().getGrid()) { + // Update the host grid + this.postAlterationToHostGrid(change); + } + } + } catch (Exception e) { - // Ensure there is an action host - if( actionHost != null ) - { - // Post update if change did not come from host grid, prevents double posting. - if( actionHost.getActionableNode().getGrid() != this.partStorageBus.getActionableNode().getGrid() ) - { - // Update the host grid - this.postAlterationToHostGrid( change ); - } - } - } - catch( Exception e ) - { + } + } - } - } + @Override + public void tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + this.canPostUpdate = true; + } - @Override - public void tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - this.canPostUpdate = true; - } - - @Override - public boolean validForPass( final int pass ) - { - if( this.handler != null ) - { - return this.handler.validForPass( pass ); - } - - return false; - } + @Override + public boolean validForPass(final int pass) { + if (this.handler != null) { + return this.handler.validForPass(pass); + } + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCell.java b/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCell.java index 3ce0e6b3..8b52e71d 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCell.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCell.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.inventory; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.ViewItems; @@ -11,6 +9,8 @@ import appeng.api.storage.ISaveProvider; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import java.util.ArrayList; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; @@ -30,945 +30,848 @@ import thaumicenergistics.common.storage.AspectStackComparator.AspectStackCompar * @author Nividica * */ -public class HandlerItemEssentiaCell - implements IMEInventoryHandler -{ - - /** - * NBT Keys - */ - private static final String NBT_ESSENTIA_NUMBER_KEY = "Essentia#", - NBT_SORT_KEY = "SortMode", - NBT_PARTITION_KEY = "Partitions", - NBT_PARTITION_COUNT_KEY = "PartitionCount", - NBT_PARTITION_NUMBER_KEY = "Partition#", - NBT_KEY_VIEW_MODE = "ViewMode"; - - /** - * Controls how many essentia can fit in a single byte. - */ - private static final long ESSENTIA_PER_BYTE = 2; - - /** - * Default sort mode. - */ - private static final AspectStackComparatorMode DEFAULT_SORT_MODE = AspectStackComparatorMode.MODE_ALPHABETIC; - - /** - * Default view mode. - */ - private static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; - - /** - * Stores cell data - */ - private NBTTagCompound cellData; - - /** - * Essentia stored on the cell. - */ - private IAspectStack[] storedEssentia; - - /** - * Total number of essentia types the cell can store. - */ - private int totalTypes; - - /** - * Total number of bytes the cell can store. - */ - protected long totalBytes; - - /** - * Total number of essentia the cell can hold. - */ - protected long totalEssentiaStorage; - - /** - * Number of essentia stored on the cell. - */ - private long usedEssentiaStorage = 0; - - /** - * Sorting mode when used in ME chest. - */ - private AspectStackComparatorMode sortMode = DEFAULT_SORT_MODE; - - /** - * View mode. - */ - private ViewItems viewMode = DEFAULT_VIEW_MODE; - - /** - * Who do we tell we have changed? - * Can be null. - */ - private final ISaveProvider saveProvider; - - /** - * List of aspects this cell can only accept. - */ - protected final ArrayList partitionAspects = new ArrayList(); - - public HandlerItemEssentiaCell( final ItemStack storageStack, final ISaveProvider saveProvider ) - { - // Ensure we have a NBT tag - if( !storageStack.hasTagCompound() ) - { - storageStack.setTagCompound( new NBTTagCompound() ); - } - - // Get the NBT tag - this.cellData = storageStack.getTagCompound(); - - // Get the total types we can store - this.totalTypes = ( (ItemEssentiaCell)ItemEnum.ESSENTIA_CELL.getItem() ).maxTypes( storageStack ); - - // Get the total bytes we can hold - this.totalBytes = ( (ItemEssentiaCell)ItemEnum.ESSENTIA_CELL.getItem() ).maxStorage( storageStack ); - - // Calculate how many essentia we can hold - this.totalEssentiaStorage = this.totalBytes * HandlerItemEssentiaCell.ESSENTIA_PER_BYTE; - - // Setup the storage - this.storedEssentia = new IAspectStack[this.totalTypes]; - - // Set the save provider - this.saveProvider = saveProvider; - - // Read the cell data - this.readCellData(); - } - - /** - * Attempts to add the essentia to the cell - * - * @param aspect - * @param Amount - * @return Amount not stored - */ - private long addEssentiaToCell( final Aspect aspect, final long amount, final Actionable mode ) - { - // Calculate amount to store - long amountToStore = Math.min( amount, this.totalEssentiaStorage - this.usedEssentiaStorage ); - - // Ensure we can store any - if( amountToStore == 0 ) - { - // Cell is full - return amount; - } - - // Get the slot for this aspect - int slotIndex = this.getSlotFor( aspect ); - - // Ensure there is somewhere to put the essentia - if( slotIndex == -1 ) - { - return amount; - } - - // Are we modulating? - if( mode == Actionable.MODULATE ) - { - // Get the slot - IAspectStack stackToAddTo = this.storedEssentia[slotIndex]; - - // Is the slot null? - if( stackToAddTo == null ) - { - // Create the stack - stackToAddTo = new AspectStack( aspect, 0 ); - - // Store it - this.storedEssentia[slotIndex] = stackToAddTo; - } - - // Add to the stack - stackToAddTo.adjustStackSize( amountToStore ); - - // Adjust the used amount - this.usedEssentiaStorage += amountToStore; - - // Write the changes to the data tag - this.writeStorageChanges( slotIndex, stackToAddTo ); - } - - // Return the amount we could not store - return( amount - amountToStore ); - - } - - /** - * Attempts to extract essentia from the cell. - * - * @param aspect - * @param amount - * @param mode - * @return Amount extracted. - */ - private long extractEssentiaFromCell( final Aspect aspect, final long amount, final Actionable mode ) - { - // Do we have this essentia stored? - int slotIndex = this.getSlotFor( aspect ); - if( ( slotIndex == -1 ) || ( this.storedEssentia[slotIndex] == null ) ) - { - // Not stored. - return 0; - } - - // Get the slot - IAspectStack slotToExtractFrom = this.storedEssentia[slotIndex]; - - // Calculate the amount to extract - long amountToExtract = Math.min( slotToExtractFrom.getStackSize(), amount ); - - // Are we modulating? - if( mode == Actionable.MODULATE ) - { - // Extract from the slot - slotToExtractFrom.adjustStackSize( -amountToExtract ); - - // Is the slot now empty? - if( slotToExtractFrom.isEmpty() ) - { - // Null it - slotToExtractFrom = null; - - // Update the storage - this.storedEssentia[slotIndex] = null; - } - - // Adjust the used amount - this.usedEssentiaStorage -= amountToExtract; - - // Sync the data tag - this.writeStorageChanges( slotIndex, slotToExtractFrom ); - - } - - return amountToExtract; - } - - /** - * Finds the first matching, or empty slot and return its index. - * - * @param aspect - * @return -1 if no match or empty slot found - */ - private int getSlotFor( final Aspect aspect ) - { - int slot = -1; - - // Look for a match - for( int index = 0; index < this.totalTypes; index++ ) - { - // Get the stack - IAspectStack internalStack = this.storedEssentia[index]; - - // Is the slot empty? - if( internalStack == null ) - { - // Is this the first empty slot we have encountered? - if( slot == -1 ) - { - // Set this as the empty slot to add to if no match is found. - slot = index; - } - continue; - } - - // Do the aspects match? - if( internalStack.getAspect() == aspect ) - { - // Found a match - slot = index; - - // Stop searching - break; - } - } - - return slot; - } - - /** - * Reads the data from the cell item. - */ - private void readCellData() - { - // Load stored essentia from data - for( int index = 0; index < this.totalTypes; index++ ) - { - // Is there a essentia tag? - if( this.cellData.hasKey( HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + index ) ) - { - // Set the storage - this.storedEssentia[index] = AspectStack.loadAspectStackFromNBT( this.cellData - .getCompoundTag( HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + index ) ); - - if( this.storedEssentia[index] != null ) - { - // Update the stored amount - this.usedEssentiaStorage += this.storedEssentia[index].getStackSize(); - } - } - } - - // Load the sort mode - if( this.cellData.hasKey( HandlerItemEssentiaCell.NBT_SORT_KEY ) ) - { - this.sortMode = AspectStackComparatorMode.VALUES[this.cellData.getInteger( NBT_SORT_KEY )]; - } - - // Load view mode - if( this.cellData.hasKey( NBT_KEY_VIEW_MODE ) ) - { - this.viewMode = EnumCache.AE_VIEW_ITEMS[this.cellData.getInteger( NBT_KEY_VIEW_MODE )]; - } - - // Load partition list - if( this.cellData.hasKey( HandlerItemEssentiaCell.NBT_PARTITION_KEY ) ) - { - // Get the partition tag - NBTTagCompound partitionData = this.cellData.getCompoundTag( HandlerItemEssentiaCell.NBT_PARTITION_KEY ); - - // Get the partition count - int partitionCount = partitionData.getInteger( HandlerItemEssentiaCell.NBT_PARTITION_COUNT_KEY ); - - // Read the partition list - String tag; - Aspect partitionAspect; - for( int i = 0; i < partitionCount; i++ ) - { - // Read the aspect tag - tag = partitionData.getString( HandlerItemEssentiaCell.NBT_PARTITION_NUMBER_KEY + i ); - - // Skip if empty tag - if( tag.equals( "" ) ) - { - continue; - } - - // Get the aspect - partitionAspect = Aspect.aspects.get( tag ); - - if( partitionAspect != null ) - { - // Add the aspect - this.partitionAspects.add( partitionAspect ); - } - } - } - } - - /** - * Synchronizes the data tag to the partition list. - */ - private void writePartitionList() - { - // Is the cell partitioned? - if( !this.isPartitioned() ) - { - // Remove the partition tag - this.cellData.removeTag( HandlerItemEssentiaCell.NBT_PARTITION_KEY ); - } - else - { - // Create the partition data - NBTTagCompound partitionData = new NBTTagCompound(); - - // Write the partition list - int count = 0; - for( Aspect pAspect : this.partitionAspects ) - { - // Write the aspect tag - partitionData.setString( HandlerItemEssentiaCell.NBT_PARTITION_NUMBER_KEY + count, pAspect.getTag() ); - - // Increment the count - count++ ; - } - - // Write the count - partitionData.setInteger( HandlerItemEssentiaCell.NBT_PARTITION_COUNT_KEY, count ); - - // Write the partition data - this.cellData.setTag( HandlerItemEssentiaCell.NBT_PARTITION_KEY, partitionData ); - } - - // Inform the save provider - if( this.saveProvider != null ) - { - this.saveProvider.saveChanges( this ); - } - } - - /** - * Synchronizes the data tag to the changed slot. - * - * @param slotIndex - * @param fluidStack - */ - private void writeStorageChanges( final int slotIndex, final IAspectStack aspectStack ) - { - // Create a new NBT - NBTTagCompound essentiaTag = new NBTTagCompound(); - - // Is there data to write? - if( ( aspectStack != null ) && aspectStack.hasAspect() && !aspectStack.isEmpty() ) - { - // Write the essentia to the tag - aspectStack.writeToNBT( essentiaTag ); - - // Update the data tag - this.cellData.setTag( HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + slotIndex, essentiaTag ); - } - else - { - // Remove the tag, as it is now empty - this.cellData.removeTag( HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + slotIndex ); - } - - // Inform the save provider - if( this.saveProvider != null ) - { - this.saveProvider.saveChanges( this ); - } - } - - /** - * Adds an aspect to the cells partitioning. - * - * @param aspect - */ - public boolean addAspectToPartitionList( final Aspect aspect ) - { - // Ensure the list does not already contain the aspect - if( !this.partitionAspects.contains( aspect ) ) - { - // Add to the list - this.partitionAspects.add( aspect ); - - // Update the cell data - this.writePartitionList(); - - return true; - } - - return false; - } - - /** - * Checks if the cell can accept/store the fluid. - */ - @Override - public boolean canAccept( final IAEFluidStack input ) - { - // Ensure there is an input - if( input == null ) - { - // Null input - return false; - } - - // Get the fluid - Fluid inputFluid = input.getFluid(); - - // Is the fluid an essentia gas? - if( !( inputFluid instanceof GaseousEssentia ) ) - { - // Not essentia gas - return false; - } - - // Is the cell partitioned? - if( this.isPartitioned() ) - { - // Get the input aspect - Aspect inputAspect = ( (GaseousEssentia)inputFluid ).getAspect(); - - // Is the cell partitioned for this aspect? - if( !this.partitionAspects.contains( inputAspect ) ) - { - // Cell partition will not allow this aspect. - return false; - } - } - - // Return if there is a match or empty slot for the essentia - return( -1 != this.getSlotFor( ( (GaseousEssentia)inputFluid ).getAspect() ) ); - } - - /** - * Removes all partitioning from the cell. - */ - public void clearPartitioning() - { - // Clear the list - this.partitionAspects.clear(); - - // Update the cell data - this.writePartitionList(); - } - - /** - * Attempts to extract essentia gas from the cell. - * returns the number of items extracted, null - */ - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource src ) - { - // Ensure there is a request, and that it is an essentia gas - if( ( request == null ) || ( request.getFluid() == null ) || ( !( request.getFluid() instanceof GaseousEssentia ) ) ) - { - // Invalid request. - return null; - } - - // Get the aspect of the essentia - Aspect requestAspect = ( (GaseousEssentia)request.getFluid() ).getAspect(); - - // Calculate the amount of essentia to extract - long essentiaAmountRequested = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( request.getStackSize() ); - - // Is the requested amount a whole essentia? - if( essentiaAmountRequested == 0 ) - { - // Can not extract partial amounts - return null; - } - - // Extract - long extractedEssentiaAmount = this.extractEssentiaFromCell( requestAspect, essentiaAmountRequested, mode ); - - // Did we extract any? - if( extractedEssentiaAmount == 0 ) - { - // Nothing was extracted - return null; - } - - // Copy the request - IAEFluidStack extractedFluid = request.copy(); - - // Set the amount extracted - extractedFluid.setStackSize( EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount( extractedEssentiaAmount ) ); - return extractedFluid; - - } - - /** - * Mode required to access the cell. - */ - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - /** - * Gets the list of essentia gasses stored on the cell. - */ - @Override - public IItemList getAvailableItems( final IItemList availableList ) - { - for( IAspectStack essentiaStack : this.storedEssentia ) - { - // Skip if null - if( essentiaStack == null ) - { - continue; - } - - // Get the gas - GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect( essentiaStack.getAspect() ); - - // Create the AE fluid stack - availableList.add( EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( essentiaGas, essentiaStack.getStackSize() ) ); - - } - - return availableList; - } - - /** - * Which storage channel this cell is on. - */ - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } - - /** - * Convenience function for determining how many bytes are free. - * - * @return - */ - public long getFreeBytes() - { - return this.totalBytes - this.getUsedBytes(); - } - - /** - * Gets the list of aspects this cell has been partitioned for. - * - * @return - */ - public ArrayList getPartitionAspects() - { - return this.partitionAspects; - } - - @Override - public int getPriority() - { - return 0; - } - - /** - * No idea. - */ - @Override - public int getSlot() - { - return 0; - } - - /** - * Gets the stored sorting mode. - * - * @return - */ - public AspectStackComparatorMode getSortingMode() - { - return this.sortMode; - } - - /** - * Gets a list of the stored essentia on this cell. - * - * @return - */ - public List getStoredEssentia() - { - // Make the list - List storedList = new ArrayList( this.totalTypes ); - - // Add each non-null stack - for( IAspectStack stack : this.storedEssentia ) - { - if( stack != null ) - { - storedList.add( stack ); - } - } - - return storedList; - } - - /** - * Total number of bytes the cell can hold. - * - * @return - */ - public long getTotalBytes() - { - return this.totalBytes; - } - - /** - * Total number of types the cell can hold. - * - * @return - */ - public int getTotalTypes() - { - return this.totalTypes; - } - - /** - * Returns how many bytes are used. - * - * @return - */ - public long getUsedBytes() - { - return (long)Math.ceil( this.usedEssentiaStorage / (double)HandlerItemEssentiaCell.ESSENTIA_PER_BYTE ); - } - - /** - * Returns how many types are used. - * - * @return - */ - public int getUsedTypes() - { - // Assume we are empty - int typeCount = 0; - - // Count the number of valid types - for( IAspectStack stack : this.storedEssentia ) - { - if( stack != null ) - { - typeCount++ ; - } - } - - // Return the count - return typeCount; - } - - /** - * Gets the view mode. - * - * @return - */ - public ViewItems getViewMode() - { - return this.viewMode; - } - - /** - * Attempts to add essentia gas to the cell. - * returns the number of items not added. - */ - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource src ) - { - // Ensure we have an input. - if( ( input == null ) ) - { - // No input - return null; - } - - // Ensure the input is a gas - if( ( input.getFluid() == null ) || !( input.getFluid() instanceof GaseousEssentia ) ) - { - // Invalid fluid - return input.copy(); - } - - // Ensure the essentia can be accepted - if( !this.canAccept( input ) ) - { - // Can not accept this essentia - return input.copy(); - } - - // Get the aspect of the gas - Aspect essentiaAspect = ( (GaseousEssentia)input.getFluid() ).getAspect(); - - // Calculate the amount to store - long amountToStore = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( input.getStackSize() ); - - // Is the amount a whole essentia? - if( amountToStore == 0 ) - { - // Can not store partial amounts. - return input.copy(); - } - - // Get the amount not stored - long amountNotStored = this.addEssentiaToCell( essentiaAspect, amountToStore, mode ); - - // Was all stored? - if( amountNotStored == 0 ) - { - // All was stored - return null; - } - - // Copy the input - IAEFluidStack result = input.copy(); - - // Set the size to how much was left over - result.setStackSize( EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount( amountNotStored ) ); - - return result; - } - - /** - * Is the cell being handled a creative cell? - * - * @return - */ - public boolean isCreative() - { - return false; - } - - /** - * Returns true if the cell is partitioned. - * - * @return - */ - public boolean isPartitioned() - { - return( this.partitionAspects.size() != 0 ); - } - - /** - * Is the cell partitioned to accept the fluid? - */ - @Override - public boolean isPrioritized( final IAEFluidStack input ) - { - // Is the cell partitioned? - if( this.isPartitioned() ) - { - // Ensure there is an input - if( input == null ) - { - // Null input - return false; - } - - // Get the fluid - Fluid inputFluid = input.getFluid(); - - // Is the fluid an essentia gas? - if( !( inputFluid instanceof GaseousEssentia ) ) - { - // Not essentia gas - return false; - } - - // Get the aspect - Aspect inputAspect = ( (GaseousEssentia)inputFluid ).getAspect(); - - // Is the cell partitioned for this aspect? - return this.partitionAspects.contains( inputAspect ); - } - - return false; - } - - /** - * Sets the partition list to the contents of the cell. - */ - public void partitionToCellContents() - { - // Clear any existing partition data - this.partitionAspects.clear(); - - // Loop over the cell contents - for( int slotIndex = 0; slotIndex < this.totalTypes; slotIndex++ ) - { - // Is there anything stored in this slot? - if( this.storedEssentia[slotIndex] != null ) - { - // Add to the partition list - this.partitionAspects.add( this.storedEssentia[slotIndex].getAspect() ); - } - } - - // Write changes - this.writePartitionList(); - } - - /** - * Removes an aspect from the cells partitioning. - * - * @param aspect - */ - public boolean removeAspectFromPartitionList( final Aspect aspect ) - { - // Was the aspect removed? - if( this.partitionAspects.remove( aspect ) ) - { - // Update the cell data - this.writePartitionList(); - - return true; - } - - return false; - } - - /** - * Replaces one aspect with another in the partition list. - * - * @param originalAspect - * @param newAspect - */ - public boolean replaceAspectInPartitionList( final Aspect originalAspect, final Aspect newAspect ) - { - // Get the index of the original aspect. - int index = this.partitionAspects.indexOf( originalAspect ); - - // Is the original aspect in the list? - if( index >= 0 ) - { - // Replace the aspect. - this.partitionAspects.set( index, newAspect ); - - // Update the cell data - this.writePartitionList(); - - return true; - } - - return false; - } - - /** - * Sets the stored sorting mode. - * - * @param sortMode - */ - public void setSortingMode( final AspectStackComparatorMode sortMode ) - { - // Set the mode - this.sortMode = sortMode; - - // Store the mode - if( this.sortMode != DEFAULT_SORT_MODE ) - { - this.cellData.setInteger( NBT_SORT_KEY, sortMode.ordinal() ); - } - } - - /** - * Sets the view mode. - * - * @param viewMode - */ - public void setViewMode( final ViewItems viewMode ) - { - // Set the mode - this.viewMode = viewMode; - - // Store the mode - if( this.viewMode != DEFAULT_VIEW_MODE ) - { - this.cellData.setInteger( NBT_KEY_VIEW_MODE, this.viewMode.ordinal() ); - } - } - - /** - * Valid for pass 1 if partitioned or has stored essentia. - * essentia. - * Valid for pass 2 if not partitioned and empty. - * - * @return - */ - @Override - public boolean validForPass( final int pass ) - { - boolean isPartitioned = this.isPartitioned(); - boolean hasStoredEssentia = ( this.usedEssentiaStorage > 0 ); - - // Is this the priority pass? - if( pass == 1 ) - { - // Valid if is partitioned or cell has something in it. - return( isPartitioned || hasStoredEssentia ); - } - - // Valid if not partitioned and cell is empty. - return( ( !isPartitioned ) && ( !hasStoredEssentia ) ); - } +public class HandlerItemEssentiaCell implements IMEInventoryHandler { + + /** + * NBT Keys + */ + private static final String NBT_ESSENTIA_NUMBER_KEY = "Essentia#", + NBT_SORT_KEY = "SortMode", + NBT_PARTITION_KEY = "Partitions", + NBT_PARTITION_COUNT_KEY = "PartitionCount", + NBT_PARTITION_NUMBER_KEY = "Partition#", + NBT_KEY_VIEW_MODE = "ViewMode"; + + /** + * Controls how many essentia can fit in a single byte. + */ + private static final long ESSENTIA_PER_BYTE = 2; + + /** + * Default sort mode. + */ + private static final AspectStackComparatorMode DEFAULT_SORT_MODE = AspectStackComparatorMode.MODE_ALPHABETIC; + + /** + * Default view mode. + */ + private static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; + + /** + * Stores cell data + */ + private NBTTagCompound cellData; + + /** + * Essentia stored on the cell. + */ + private IAspectStack[] storedEssentia; + + /** + * Total number of essentia types the cell can store. + */ + private int totalTypes; + + /** + * Total number of bytes the cell can store. + */ + protected long totalBytes; + + /** + * Total number of essentia the cell can hold. + */ + protected long totalEssentiaStorage; + + /** + * Number of essentia stored on the cell. + */ + private long usedEssentiaStorage = 0; + + /** + * Sorting mode when used in ME chest. + */ + private AspectStackComparatorMode sortMode = DEFAULT_SORT_MODE; + + /** + * View mode. + */ + private ViewItems viewMode = DEFAULT_VIEW_MODE; + + /** + * Who do we tell we have changed? + * Can be null. + */ + private final ISaveProvider saveProvider; + + /** + * List of aspects this cell can only accept. + */ + protected final ArrayList partitionAspects = new ArrayList(); + + public HandlerItemEssentiaCell(final ItemStack storageStack, final ISaveProvider saveProvider) { + // Ensure we have a NBT tag + if (!storageStack.hasTagCompound()) { + storageStack.setTagCompound(new NBTTagCompound()); + } + + // Get the NBT tag + this.cellData = storageStack.getTagCompound(); + + // Get the total types we can store + this.totalTypes = ((ItemEssentiaCell) ItemEnum.ESSENTIA_CELL.getItem()).maxTypes(storageStack); + + // Get the total bytes we can hold + this.totalBytes = ((ItemEssentiaCell) ItemEnum.ESSENTIA_CELL.getItem()).maxStorage(storageStack); + + // Calculate how many essentia we can hold + this.totalEssentiaStorage = this.totalBytes * HandlerItemEssentiaCell.ESSENTIA_PER_BYTE; + + // Setup the storage + this.storedEssentia = new IAspectStack[this.totalTypes]; + + // Set the save provider + this.saveProvider = saveProvider; + + // Read the cell data + this.readCellData(); + } + + /** + * Attempts to add the essentia to the cell + * + * @param aspect + * @param Amount + * @return Amount not stored + */ + private long addEssentiaToCell(final Aspect aspect, final long amount, final Actionable mode) { + // Calculate amount to store + long amountToStore = Math.min(amount, this.totalEssentiaStorage - this.usedEssentiaStorage); + + // Ensure we can store any + if (amountToStore == 0) { + // Cell is full + return amount; + } + + // Get the slot for this aspect + int slotIndex = this.getSlotFor(aspect); + + // Ensure there is somewhere to put the essentia + if (slotIndex == -1) { + return amount; + } + + // Are we modulating? + if (mode == Actionable.MODULATE) { + // Get the slot + IAspectStack stackToAddTo = this.storedEssentia[slotIndex]; + + // Is the slot null? + if (stackToAddTo == null) { + // Create the stack + stackToAddTo = new AspectStack(aspect, 0); + + // Store it + this.storedEssentia[slotIndex] = stackToAddTo; + } + + // Add to the stack + stackToAddTo.adjustStackSize(amountToStore); + + // Adjust the used amount + this.usedEssentiaStorage += amountToStore; + + // Write the changes to the data tag + this.writeStorageChanges(slotIndex, stackToAddTo); + } + + // Return the amount we could not store + return (amount - amountToStore); + } + + /** + * Attempts to extract essentia from the cell. + * + * @param aspect + * @param amount + * @param mode + * @return Amount extracted. + */ + private long extractEssentiaFromCell(final Aspect aspect, final long amount, final Actionable mode) { + // Do we have this essentia stored? + int slotIndex = this.getSlotFor(aspect); + if ((slotIndex == -1) || (this.storedEssentia[slotIndex] == null)) { + // Not stored. + return 0; + } + + // Get the slot + IAspectStack slotToExtractFrom = this.storedEssentia[slotIndex]; + + // Calculate the amount to extract + long amountToExtract = Math.min(slotToExtractFrom.getStackSize(), amount); + + // Are we modulating? + if (mode == Actionable.MODULATE) { + // Extract from the slot + slotToExtractFrom.adjustStackSize(-amountToExtract); + + // Is the slot now empty? + if (slotToExtractFrom.isEmpty()) { + // Null it + slotToExtractFrom = null; + + // Update the storage + this.storedEssentia[slotIndex] = null; + } + + // Adjust the used amount + this.usedEssentiaStorage -= amountToExtract; + + // Sync the data tag + this.writeStorageChanges(slotIndex, slotToExtractFrom); + } + + return amountToExtract; + } + + /** + * Finds the first matching, or empty slot and return its index. + * + * @param aspect + * @return -1 if no match or empty slot found + */ + private int getSlotFor(final Aspect aspect) { + int slot = -1; + + // Look for a match + for (int index = 0; index < this.totalTypes; index++) { + // Get the stack + IAspectStack internalStack = this.storedEssentia[index]; + + // Is the slot empty? + if (internalStack == null) { + // Is this the first empty slot we have encountered? + if (slot == -1) { + // Set this as the empty slot to add to if no match is found. + slot = index; + } + continue; + } + + // Do the aspects match? + if (internalStack.getAspect() == aspect) { + // Found a match + slot = index; + + // Stop searching + break; + } + } + + return slot; + } + + /** + * Reads the data from the cell item. + */ + private void readCellData() { + // Load stored essentia from data + for (int index = 0; index < this.totalTypes; index++) { + // Is there a essentia tag? + if (this.cellData.hasKey(HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + index)) { + // Set the storage + this.storedEssentia[index] = AspectStack.loadAspectStackFromNBT( + this.cellData.getCompoundTag(HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + index)); + + if (this.storedEssentia[index] != null) { + // Update the stored amount + this.usedEssentiaStorage += this.storedEssentia[index].getStackSize(); + } + } + } + + // Load the sort mode + if (this.cellData.hasKey(HandlerItemEssentiaCell.NBT_SORT_KEY)) { + this.sortMode = AspectStackComparatorMode.VALUES[this.cellData.getInteger(NBT_SORT_KEY)]; + } + + // Load view mode + if (this.cellData.hasKey(NBT_KEY_VIEW_MODE)) { + this.viewMode = EnumCache.AE_VIEW_ITEMS[this.cellData.getInteger(NBT_KEY_VIEW_MODE)]; + } + + // Load partition list + if (this.cellData.hasKey(HandlerItemEssentiaCell.NBT_PARTITION_KEY)) { + // Get the partition tag + NBTTagCompound partitionData = this.cellData.getCompoundTag(HandlerItemEssentiaCell.NBT_PARTITION_KEY); + + // Get the partition count + int partitionCount = partitionData.getInteger(HandlerItemEssentiaCell.NBT_PARTITION_COUNT_KEY); + + // Read the partition list + String tag; + Aspect partitionAspect; + for (int i = 0; i < partitionCount; i++) { + // Read the aspect tag + tag = partitionData.getString(HandlerItemEssentiaCell.NBT_PARTITION_NUMBER_KEY + i); + + // Skip if empty tag + if (tag.equals("")) { + continue; + } + + // Get the aspect + partitionAspect = Aspect.aspects.get(tag); + + if (partitionAspect != null) { + // Add the aspect + this.partitionAspects.add(partitionAspect); + } + } + } + } + + /** + * Synchronizes the data tag to the partition list. + */ + private void writePartitionList() { + // Is the cell partitioned? + if (!this.isPartitioned()) { + // Remove the partition tag + this.cellData.removeTag(HandlerItemEssentiaCell.NBT_PARTITION_KEY); + } else { + // Create the partition data + NBTTagCompound partitionData = new NBTTagCompound(); + + // Write the partition list + int count = 0; + for (Aspect pAspect : this.partitionAspects) { + // Write the aspect tag + partitionData.setString(HandlerItemEssentiaCell.NBT_PARTITION_NUMBER_KEY + count, pAspect.getTag()); + + // Increment the count + count++; + } + + // Write the count + partitionData.setInteger(HandlerItemEssentiaCell.NBT_PARTITION_COUNT_KEY, count); + + // Write the partition data + this.cellData.setTag(HandlerItemEssentiaCell.NBT_PARTITION_KEY, partitionData); + } + + // Inform the save provider + if (this.saveProvider != null) { + this.saveProvider.saveChanges(this); + } + } + + /** + * Synchronizes the data tag to the changed slot. + * + * @param slotIndex + * @param fluidStack + */ + private void writeStorageChanges(final int slotIndex, final IAspectStack aspectStack) { + // Create a new NBT + NBTTagCompound essentiaTag = new NBTTagCompound(); + + // Is there data to write? + if ((aspectStack != null) && aspectStack.hasAspect() && !aspectStack.isEmpty()) { + // Write the essentia to the tag + aspectStack.writeToNBT(essentiaTag); + + // Update the data tag + this.cellData.setTag(HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + slotIndex, essentiaTag); + } else { + // Remove the tag, as it is now empty + this.cellData.removeTag(HandlerItemEssentiaCell.NBT_ESSENTIA_NUMBER_KEY + slotIndex); + } + + // Inform the save provider + if (this.saveProvider != null) { + this.saveProvider.saveChanges(this); + } + } + + /** + * Adds an aspect to the cells partitioning. + * + * @param aspect + */ + public boolean addAspectToPartitionList(final Aspect aspect) { + // Ensure the list does not already contain the aspect + if (!this.partitionAspects.contains(aspect)) { + // Add to the list + this.partitionAspects.add(aspect); + + // Update the cell data + this.writePartitionList(); + + return true; + } + + return false; + } + + /** + * Checks if the cell can accept/store the fluid. + */ + @Override + public boolean canAccept(final IAEFluidStack input) { + // Ensure there is an input + if (input == null) { + // Null input + return false; + } + + // Get the fluid + Fluid inputFluid = input.getFluid(); + + // Is the fluid an essentia gas? + if (!(inputFluid instanceof GaseousEssentia)) { + // Not essentia gas + return false; + } + + // Is the cell partitioned? + if (this.isPartitioned()) { + // Get the input aspect + Aspect inputAspect = ((GaseousEssentia) inputFluid).getAspect(); + + // Is the cell partitioned for this aspect? + if (!this.partitionAspects.contains(inputAspect)) { + // Cell partition will not allow this aspect. + return false; + } + } + + // Return if there is a match or empty slot for the essentia + return (-1 != this.getSlotFor(((GaseousEssentia) inputFluid).getAspect())); + } + + /** + * Removes all partitioning from the cell. + */ + public void clearPartitioning() { + // Clear the list + this.partitionAspects.clear(); + + // Update the cell data + this.writePartitionList(); + } + + /** + * Attempts to extract essentia gas from the cell. + * returns the number of items extracted, null + */ + @Override + public IAEFluidStack extractItems(final IAEFluidStack request, final Actionable mode, final BaseActionSource src) { + // Ensure there is a request, and that it is an essentia gas + if ((request == null) || (request.getFluid() == null) || (!(request.getFluid() instanceof GaseousEssentia))) { + // Invalid request. + return null; + } + + // Get the aspect of the essentia + Aspect requestAspect = ((GaseousEssentia) request.getFluid()).getAspect(); + + // Calculate the amount of essentia to extract + long essentiaAmountRequested = + EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(request.getStackSize()); + + // Is the requested amount a whole essentia? + if (essentiaAmountRequested == 0) { + // Can not extract partial amounts + return null; + } + + // Extract + long extractedEssentiaAmount = this.extractEssentiaFromCell(requestAspect, essentiaAmountRequested, mode); + + // Did we extract any? + if (extractedEssentiaAmount == 0) { + // Nothing was extracted + return null; + } + + // Copy the request + IAEFluidStack extractedFluid = request.copy(); + + // Set the amount extracted + extractedFluid.setStackSize( + EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(extractedEssentiaAmount)); + return extractedFluid; + } + + /** + * Mode required to access the cell. + */ + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + /** + * Gets the list of essentia gasses stored on the cell. + */ + @Override + public IItemList getAvailableItems(final IItemList availableList) { + for (IAspectStack essentiaStack : this.storedEssentia) { + // Skip if null + if (essentiaStack == null) { + continue; + } + + // Get the gas + GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect(essentiaStack.getAspect()); + + // Create the AE fluid stack + availableList.add(EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( + essentiaGas, essentiaStack.getStackSize())); + } + + return availableList; + } + + /** + * Which storage channel this cell is on. + */ + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + /** + * Convenience function for determining how many bytes are free. + * + * @return + */ + public long getFreeBytes() { + return this.totalBytes - this.getUsedBytes(); + } + + /** + * Gets the list of aspects this cell has been partitioned for. + * + * @return + */ + public ArrayList getPartitionAspects() { + return this.partitionAspects; + } + + @Override + public int getPriority() { + return 0; + } + + /** + * No idea. + */ + @Override + public int getSlot() { + return 0; + } + + /** + * Gets the stored sorting mode. + * + * @return + */ + public AspectStackComparatorMode getSortingMode() { + return this.sortMode; + } + + /** + * Gets a list of the stored essentia on this cell. + * + * @return + */ + public List getStoredEssentia() { + // Make the list + List storedList = new ArrayList(this.totalTypes); + + // Add each non-null stack + for (IAspectStack stack : this.storedEssentia) { + if (stack != null) { + storedList.add(stack); + } + } + + return storedList; + } + + /** + * Total number of bytes the cell can hold. + * + * @return + */ + public long getTotalBytes() { + return this.totalBytes; + } + + /** + * Total number of types the cell can hold. + * + * @return + */ + public int getTotalTypes() { + return this.totalTypes; + } + + /** + * Returns how many bytes are used. + * + * @return + */ + public long getUsedBytes() { + return (long) Math.ceil(this.usedEssentiaStorage / (double) HandlerItemEssentiaCell.ESSENTIA_PER_BYTE); + } + + /** + * Returns how many types are used. + * + * @return + */ + public int getUsedTypes() { + // Assume we are empty + int typeCount = 0; + + // Count the number of valid types + for (IAspectStack stack : this.storedEssentia) { + if (stack != null) { + typeCount++; + } + } + + // Return the count + return typeCount; + } + + /** + * Gets the view mode. + * + * @return + */ + public ViewItems getViewMode() { + return this.viewMode; + } + + /** + * Attempts to add essentia gas to the cell. + * returns the number of items not added. + */ + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource src) { + // Ensure we have an input. + if ((input == null)) { + // No input + return null; + } + + // Ensure the input is a gas + if ((input.getFluid() == null) || !(input.getFluid() instanceof GaseousEssentia)) { + // Invalid fluid + return input.copy(); + } + + // Ensure the essentia can be accepted + if (!this.canAccept(input)) { + // Can not accept this essentia + return input.copy(); + } + + // Get the aspect of the gas + Aspect essentiaAspect = ((GaseousEssentia) input.getFluid()).getAspect(); + + // Calculate the amount to store + long amountToStore = EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(input.getStackSize()); + + // Is the amount a whole essentia? + if (amountToStore == 0) { + // Can not store partial amounts. + return input.copy(); + } + + // Get the amount not stored + long amountNotStored = this.addEssentiaToCell(essentiaAspect, amountToStore, mode); + + // Was all stored? + if (amountNotStored == 0) { + // All was stored + return null; + } + + // Copy the input + IAEFluidStack result = input.copy(); + + // Set the size to how much was left over + result.setStackSize(EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(amountNotStored)); + + return result; + } + + /** + * Is the cell being handled a creative cell? + * + * @return + */ + public boolean isCreative() { + return false; + } + + /** + * Returns true if the cell is partitioned. + * + * @return + */ + public boolean isPartitioned() { + return (this.partitionAspects.size() != 0); + } + + /** + * Is the cell partitioned to accept the fluid? + */ + @Override + public boolean isPrioritized(final IAEFluidStack input) { + // Is the cell partitioned? + if (this.isPartitioned()) { + // Ensure there is an input + if (input == null) { + // Null input + return false; + } + + // Get the fluid + Fluid inputFluid = input.getFluid(); + + // Is the fluid an essentia gas? + if (!(inputFluid instanceof GaseousEssentia)) { + // Not essentia gas + return false; + } + + // Get the aspect + Aspect inputAspect = ((GaseousEssentia) inputFluid).getAspect(); + + // Is the cell partitioned for this aspect? + return this.partitionAspects.contains(inputAspect); + } + + return false; + } + + /** + * Sets the partition list to the contents of the cell. + */ + public void partitionToCellContents() { + // Clear any existing partition data + this.partitionAspects.clear(); + + // Loop over the cell contents + for (int slotIndex = 0; slotIndex < this.totalTypes; slotIndex++) { + // Is there anything stored in this slot? + if (this.storedEssentia[slotIndex] != null) { + // Add to the partition list + this.partitionAspects.add(this.storedEssentia[slotIndex].getAspect()); + } + } + + // Write changes + this.writePartitionList(); + } + + /** + * Removes an aspect from the cells partitioning. + * + * @param aspect + */ + public boolean removeAspectFromPartitionList(final Aspect aspect) { + // Was the aspect removed? + if (this.partitionAspects.remove(aspect)) { + // Update the cell data + this.writePartitionList(); + + return true; + } + + return false; + } + + /** + * Replaces one aspect with another in the partition list. + * + * @param originalAspect + * @param newAspect + */ + public boolean replaceAspectInPartitionList(final Aspect originalAspect, final Aspect newAspect) { + // Get the index of the original aspect. + int index = this.partitionAspects.indexOf(originalAspect); + + // Is the original aspect in the list? + if (index >= 0) { + // Replace the aspect. + this.partitionAspects.set(index, newAspect); + + // Update the cell data + this.writePartitionList(); + + return true; + } + + return false; + } + + /** + * Sets the stored sorting mode. + * + * @param sortMode + */ + public void setSortingMode(final AspectStackComparatorMode sortMode) { + // Set the mode + this.sortMode = sortMode; + + // Store the mode + if (this.sortMode != DEFAULT_SORT_MODE) { + this.cellData.setInteger(NBT_SORT_KEY, sortMode.ordinal()); + } + } + + /** + * Sets the view mode. + * + * @param viewMode + */ + public void setViewMode(final ViewItems viewMode) { + // Set the mode + this.viewMode = viewMode; + + // Store the mode + if (this.viewMode != DEFAULT_VIEW_MODE) { + this.cellData.setInteger(NBT_KEY_VIEW_MODE, this.viewMode.ordinal()); + } + } + + /** + * Valid for pass 1 if partitioned or has stored essentia. + * essentia. + * Valid for pass 2 if not partitioned and empty. + * + * @return + */ + @Override + public boolean validForPass(final int pass) { + boolean isPartitioned = this.isPartitioned(); + boolean hasStoredEssentia = (this.usedEssentiaStorage > 0); + + // Is this the priority pass? + if (pass == 1) { + // Valid if is partitioned or cell has something in it. + return (isPartitioned || hasStoredEssentia); + } + + // Valid if not partitioned and cell is empty. + return ((!isPartitioned) && (!hasStoredEssentia)); + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCellCreative.java b/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCellCreative.java index d7dd291c..c502bd1a 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCellCreative.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerItemEssentiaCellCreative.java @@ -1,12 +1,12 @@ package thaumicenergistics.common.inventory; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.ISaveProvider; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import java.util.ArrayList; +import java.util.List; import net.minecraft.item.ItemStack; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.storage.IAspectStack; @@ -21,172 +21,150 @@ import thaumicenergistics.common.storage.AspectStack; * @author Nividica * */ -public class HandlerItemEssentiaCellCreative - extends HandlerItemEssentiaCell -{ +public class HandlerItemEssentiaCellCreative extends HandlerItemEssentiaCell { - public HandlerItemEssentiaCellCreative( final ItemStack storageStack, final ISaveProvider saveProvider ) - { - super( storageStack, saveProvider ); + public HandlerItemEssentiaCellCreative(final ItemStack storageStack, final ISaveProvider saveProvider) { + super(storageStack, saveProvider); - this.totalBytes = 0; - this.totalEssentiaStorage = 0; - } + this.totalBytes = 0; + this.totalEssentiaStorage = 0; + } - /** - * The creative cell can not store new essentia. - */ - @Override - public boolean canAccept( final IAEFluidStack input ) - { - return false; - } + /** + * The creative cell can not store new essentia. + */ + @Override + public boolean canAccept(final IAEFluidStack input) { + return false; + } - /** - * The creative cell can only provide essentia based on its parition table. - */ - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource src ) - { - // Ensure there is a request, and that it is an essentia gas - if( ( request != null ) && ( request.getFluid() != null ) && ( request.getFluid() instanceof GaseousEssentia ) ) - { - // Get the aspect of the essentia - Aspect requestAspect = ( (GaseousEssentia)request.getFluid() ).getAspect(); + /** + * The creative cell can only provide essentia based on its parition table. + */ + @Override + public IAEFluidStack extractItems(final IAEFluidStack request, final Actionable mode, final BaseActionSource src) { + // Ensure there is a request, and that it is an essentia gas + if ((request != null) && (request.getFluid() != null) && (request.getFluid() instanceof GaseousEssentia)) { + // Get the aspect of the essentia + Aspect requestAspect = ((GaseousEssentia) request.getFluid()).getAspect(); - // Is the cell partitioned for this aspect? - if( ( requestAspect != null ) && ( this.partitionAspects.contains( requestAspect ) ) ) - { - return request.copy(); - } - } + // Is the cell partitioned for this aspect? + if ((requestAspect != null) && (this.partitionAspects.contains(requestAspect))) { + return request.copy(); + } + } - return null; - } + return null; + } - /** - * Available items based on partition table. - */ - @Override - public IItemList getAvailableItems( final IItemList availableList ) - { - for( Aspect aspect : this.partitionAspects ) - { - // Get the gas - GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect( aspect ); + /** + * Available items based on partition table. + */ + @Override + public IItemList getAvailableItems(final IItemList availableList) { + for (Aspect aspect : this.partitionAspects) { + // Get the gas + GaseousEssentia essentiaGas = GaseousEssentia.getGasFromAspect(aspect); - // Create the AE fluid stack - availableList.add( EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits( essentiaGas, 2000000000 ) ); + // Create the AE fluid stack + availableList.add( + EssentiaConversionHelper.INSTANCE.createAEFluidStackInEssentiaUnits(essentiaGas, 2000000000)); + } - } + return availableList; + } - return availableList; - } + /** + * No storage + */ + @Override + public long getFreeBytes() { + return 0; + } - /** - * No storage - */ - @Override - public long getFreeBytes() - { - return 0; - } + /** + * 'Stored' essentia based on partition table. + */ + @Override + public List getStoredEssentia() { + // Make the list + List storedList = new ArrayList(this.partitionAspects.size()); - /** - * 'Stored' essentia based on partition table. - */ - @Override - public List getStoredEssentia() - { - // Make the list - List storedList = new ArrayList( this.partitionAspects.size() ); + for (Aspect aspect : this.partitionAspects) { + storedList.add(new AspectStack(aspect, 1)); + } - for( Aspect aspect : this.partitionAspects ) - { - storedList.add( new AspectStack( aspect, 1 ) ); - } + return storedList; + } - return storedList; - } + /** + * No storage + */ + @Override + public long getUsedBytes() { + return 0; + } - /** - * No storage - */ - @Override - public long getUsedBytes() - { - return 0; - } + /** + * Used types based on partition table. + */ + @Override + public int getUsedTypes() { + return this.partitionAspects.size(); + } - /** - * Used types based on partition table. - */ - @Override - public int getUsedTypes() - { - return this.partitionAspects.size(); - } + /** + * Creative cell can not inject. + */ + @Override + public IAEFluidStack injectItems(final IAEFluidStack input, final Actionable mode, final BaseActionSource src) { + // Ensure there is an input. + if ((input == null)) { + // No input + return null; + } - /** - * Creative cell can not inject. - */ - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource src ) - { - // Ensure there is an input. - if( ( input == null ) ) - { - // No input - return null; - } + // Can not inject items. + return input.copy(); + } - // Can not inject items. - return input.copy(); - } + /** + * This is a creative cell. + */ + @Override + public boolean isCreative() { + return true; + } - /** - * This is a creative cell. - */ - @Override - public boolean isCreative() - { - return true; - } + /** + * Creative cell is always partitioned. + */ + @Override + public boolean isPartitioned() { + return true; + } - /** - * Creative cell is always partitioned. - */ - @Override - public boolean isPartitioned() - { - return true; - } + /** + * Creative cell can not inject. + */ + @Override + public boolean isPrioritized(final IAEFluidStack input) { + return false; + } - /** - * Creative cell can not inject. - */ - @Override - public boolean isPrioritized( final IAEFluidStack input ) - { - return false; - } - - /** - * Meaniningless on creative cell. - */ - @Override - public void partitionToCellContents() - { - // Ignored - } - - /** - * Creative cell can not inject. - */ - @Override - public boolean validForPass( final int pass ) - { - return false; - } + /** + * Meaniningless on creative cell. + */ + @Override + public void partitionToCellContents() { + // Ignored + } + /** + * Creative cell can not inject. + */ + @Override + public boolean validForPass(final int pass) { + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerKnowledgeCore.java b/src/main/java/thaumicenergistics/common/inventory/HandlerKnowledgeCore.java index 7a2acb8e..8b068667 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerKnowledgeCore.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerKnowledgeCore.java @@ -1,6 +1,7 @@ package thaumicenergistics.common.inventory; import appeng.api.storage.data.IAEItemStack; +import java.util.ArrayList; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -8,368 +9,324 @@ import net.minecraftforge.common.util.Constants; import thaumicenergistics.common.integration.tc.ArcaneCraftingPattern; import thaumicenergistics.common.items.ItemKnowledgeCore; -import java.util.ArrayList; - /** * Handles an {@link ItemKnowledgeCore} * * @author Nividica * */ -public class HandlerKnowledgeCore -{ - /** - * NBT Keys. - */ - private static final String NBTKEY_PATTERNS = "Patterns"; +public class HandlerKnowledgeCore { + /** + * NBT Keys. + */ + private static final String NBTKEY_PATTERNS = "Patterns"; - /** - * Maximum number of stored patterns. - */ - public static final int MAXIMUM_STORED_PATTERNS = 21; + /** + * Maximum number of stored patterns. + */ + public static final int MAXIMUM_STORED_PATTERNS = 21; - /** - * Array of stored patterns. - */ - private final ArrayList patterns = new ArrayList( MAXIMUM_STORED_PATTERNS ); + /** + * Array of stored patterns. + */ + private final ArrayList patterns = + new ArrayList(MAXIMUM_STORED_PATTERNS); - /** - * Knowledge core being handled. - */ - private ItemStack kCore; + /** + * Knowledge core being handled. + */ + private ItemStack kCore; - /** - * Creates a handler without a core. - * Use open() to set the core in the future. - */ - public HandlerKnowledgeCore() - { - } + /** + * Creates a handler without a core. + * Use open() to set the core in the future. + */ + public HandlerKnowledgeCore() {} - /** - * Creates the handler with the specified core. - * - * @param kCore - */ - public HandlerKnowledgeCore( final ItemStack kCore ) - { - this.open( kCore ); - } + /** + * Creates the handler with the specified core. + * + * @param kCore + */ + public HandlerKnowledgeCore(final ItemStack kCore) { + this.open(kCore); + } - /** - * Gets or creates the NBT tag for the knowledge core. - * - * @return - */ - private NBTTagCompound getOrCreateNBT() - { - if( !this.kCore.hasTagCompound() ) - { - this.kCore.stackTagCompound = new NBTTagCompound(); - } + /** + * Gets or creates the NBT tag for the knowledge core. + * + * @return + */ + private NBTTagCompound getOrCreateNBT() { + if (!this.kCore.hasTagCompound()) { + this.kCore.stackTagCompound = new NBTTagCompound(); + } - return this.kCore.stackTagCompound; - } + return this.kCore.stackTagCompound; + } - /** - * Loads the data from the knowledge core's nbt. - */ - private void loadKCoreData() - { - // Clear any existing data - this.patterns.clear(); + /** + * Loads the data from the knowledge core's nbt. + */ + private void loadKCoreData() { + // Clear any existing data + this.patterns.clear(); - // Get the data tag - NBTTagCompound data = this.getOrCreateNBT(); + // Get the data tag + NBTTagCompound data = this.getOrCreateNBT(); - // Are there saved patterns? - if( data.hasKey( NBTKEY_PATTERNS ) ) - { - // Get the list - NBTTagList plist = data.getTagList( NBTKEY_PATTERNS, Constants.NBT.TAG_COMPOUND ); + // Are there saved patterns? + if (data.hasKey(NBTKEY_PATTERNS)) { + // Get the list + NBTTagList plist = data.getTagList(NBTKEY_PATTERNS, Constants.NBT.TAG_COMPOUND); - // Read in each pattern - for( int index = 0; index < plist.tagCount(); index++ ) - { - try - { - // Load the pattern - ArcaneCraftingPattern pattern = new ArcaneCraftingPattern( this.kCore, plist.getCompoundTagAt( index ) ); + // Read in each pattern + for (int index = 0; index < plist.tagCount(); index++) { + try { + // Load the pattern + ArcaneCraftingPattern pattern = + new ArcaneCraftingPattern(this.kCore, plist.getCompoundTagAt(index)); - // Is the pattern valid? - if( pattern.isPatternValid() ) - { - // Add the pattern - this.patterns.add( pattern ); - } - } - catch( Exception e ) - { - // Ignore invalid patterns - } - } - } + // Is the pattern valid? + if (pattern.isPatternValid()) { + // Add the pattern + this.patterns.add(pattern); + } + } catch (Exception e) { + // Ignore invalid patterns + } + } + } + } - } + /** + * Saves the data to the knowldge core's nbt. + */ + private void saveKCoreData() { + // Get the data tag + NBTTagCompound data = this.getOrCreateNBT(); - /** - * Saves the data to the knowldge core's nbt. - */ - private void saveKCoreData() - { - // Get the data tag - NBTTagCompound data = this.getOrCreateNBT(); + // Create the pattern list + NBTTagList plist = new NBTTagList(); - // Create the pattern list - NBTTagList plist = new NBTTagList(); + // Save each pattern + for (ArcaneCraftingPattern pattern : this.patterns) { + // Ensure the pattern is valid + if ((pattern == null) || (!pattern.isPatternValid())) { + continue; + } - // Save each pattern - for( ArcaneCraftingPattern pattern : this.patterns ) - { - // Ensure the pattern is valid - if( ( pattern == null ) || ( !pattern.isPatternValid() ) ) - { - continue; - } + // Write the pattern + plist.appendTag(pattern.writeToNBT(new NBTTagCompound())); + } - // Write the pattern - plist.appendTag( pattern.writeToNBT( new NBTTagCompound() ) ); - } + // Write the list to the data + if (plist.tagCount() > 0) { + data.setTag(NBTKEY_PATTERNS, plist); + } else { + data.removeTag(NBTKEY_PATTERNS); + } + } - // Write the list to the data - if( plist.tagCount() > 0 ) - { - data.setTag( NBTKEY_PATTERNS, plist ); - } - else - { - data.removeTag( NBTKEY_PATTERNS ); - } - } + /** + * Adds a pattern to the core. + */ + public void addPattern(final ArcaneCraftingPattern pattern) { + // Validate the pattern + if ((pattern == null) || (!pattern.isPatternValid())) { + return; + } - /** - * Adds a pattern to the core. - */ - public void addPattern( final ArcaneCraftingPattern pattern ) - { - // Validate the pattern - if( ( pattern == null ) || ( !pattern.isPatternValid() ) ) - { - return; - } + // Ensure there is room to store the pattern + if (!this.hasRoomToStorePattern()) { + return; + } - // Ensure there is room to store the pattern - if( !this.hasRoomToStorePattern() ) - { - return; - } + // Check for duplicate patterns + ArcaneCraftingPattern existingPattern = + this.getPatternForItem(pattern.getResult().getItemStack()); - // Check for duplicate patterns - ArcaneCraftingPattern existingPattern = this.getPatternForItem( pattern.getResult().getItemStack() ); + if (existingPattern == null) { + // remove the existing pattern, e.g. if the result changed + removePatternSameInputs(pattern); + // Add the pattern + this.patterns.add(pattern); - if( existingPattern == null ) - { - // remove the existing pattern, e.g. if the result changed - removePatternSameInputs(pattern); - // Add the pattern - this.patterns.add( pattern ); + // Save + this.saveKCoreData(); + } + } - // Save - this.saveKCoreData(); - } + private void removePatternSameInputs(final ArcaneCraftingPattern pattern) { + IAEItemStack[] newInputs = pattern.getInputs(); + // Loop over all stored patterns + for (ArcaneCraftingPattern p : this.patterns) { + IAEItemStack[] oldInputs = p.getInputs(); + if (newInputs.length != oldInputs.length) continue; + boolean match = true; + for (int i = 0; i < newInputs.length; ++i) { + if (oldInputs[i] == null && newInputs[i] == null) continue; + if (oldInputs[i] == null || newInputs[i] == null) { + match = false; + break; + } + if (!ItemStack.areItemStacksEqual(oldInputs[i].getItemStack(), newInputs[i].getItemStack())) { + match = false; + break; + } + } + if (match) { + // can't be more than one duplicate + this.patterns.remove(p); + return; + } + } + } - } - private void removePatternSameInputs(final ArcaneCraftingPattern pattern) { - IAEItemStack[] newInputs = pattern.getInputs(); - // Loop over all stored patterns - for (ArcaneCraftingPattern p : this.patterns) { - IAEItemStack[] oldInputs = p.getInputs(); - if (newInputs.length != oldInputs.length) - continue; - boolean match = true; - for (int i = 0; i < newInputs.length; ++i) { - if (oldInputs[i] == null && newInputs[i] == null) - continue; - if (oldInputs[i] == null || newInputs[i] == null) { - match = false; - break; - } - if (!ItemStack.areItemStacksEqual(oldInputs[i].getItemStack(), newInputs[i].getItemStack())) { - match = false; - break; - } - } - if (match) { - // can't be more than one duplicate - this.patterns.remove(p); - return; - } - } - } + /** + * Instructs the handler to close. + */ + public void close() { + this.kCore = null; + this.patterns.clear(); + } - /** - * Instructs the handler to close. - */ - public void close() - { - this.kCore = null; - this.patterns.clear(); - } + /** + * Gets the pattern that produces the result. + * + * @param resultStack + * @return + */ + public ArcaneCraftingPattern getPatternForItem(final ItemStack resultStack) { + // Loop over all stored patterns + for (ArcaneCraftingPattern p : this.patterns) { + // Does the pattern have a valid output? + if ((p != null) && (p.getResult() != null)) { + // Is the output equal to the specified result? + if (ItemStack.areItemStacksEqual(p.getResult().getItemStack(), resultStack)) { + // Found the pattern + return p; + } + } + } - /** - * Gets the pattern that produces the result. - * - * @param resultStack - * @return - */ - public ArcaneCraftingPattern getPatternForItem( final ItemStack resultStack ) - { - // Loop over all stored patterns - for( ArcaneCraftingPattern p : this.patterns ) - { - // Does the pattern have a valid output? - if( ( p != null ) && ( p.getResult() != null ) ) - { - // Is the output equal to the specified result? - if( ItemStack.areItemStacksEqual( p.getResult().getItemStack(), resultStack ) ) - { - // Found the pattern - return p; - } - } - } + // No matching patterns + return null; + } - // No matching patterns - return null; - } + /** + * Gets the list of stored patterns. + * + * @return + */ + public ArrayList getPatterns() { + return this.patterns; + } - /** - * Gets the list of stored patterns. - * - * @return - */ - public ArrayList getPatterns() - { - return this.patterns; - } + /** + * Gets the results of all stored patterns. + * + * @return + */ + public ArrayList getStoredOutputs() { + // Create the array + ArrayList results = new ArrayList(); - /** - * Gets the results of all stored patterns. - * - * @return - */ - public ArrayList getStoredOutputs() - { - // Create the array - ArrayList results = new ArrayList(); + // Add each stored patterns output + for (ArcaneCraftingPattern p : this.patterns) { + if ((p != null) && (p.getResult() != null)) { + results.add(p.getResult().getItemStack()); + } + } - // Add each stored patterns output - for( ArcaneCraftingPattern p : this.patterns ) - { - if( ( p != null ) && ( p.getResult() != null ) ) - { - results.add( p.getResult().getItemStack() ); - } - } + // Return the array + return results; + } - // Return the array - return results; - } + /** + * Returns true if the handler has a core. + * + * @return + */ + public boolean hasCore() { + return this.kCore != null; + } - /** - * Returns true if the handler has a core. - * - * @return - */ - public boolean hasCore() - { - return this.kCore != null; - } + /** + * Returns true if there is a pattern stored that produces the specified + * result. + * + * @param resultStack + * @return + */ + public boolean hasPatternFor(final ItemStack resultStack) { + return (this.getPatternForItem(resultStack) != null); + } - /** - * Returns true if there is a pattern stored that produces the specified - * result. - * - * @param resultStack - * @return - */ - public boolean hasPatternFor( final ItemStack resultStack ) - { - return( this.getPatternForItem( resultStack ) != null ); - } + /** + * Returns true if there is room to store a new pattern. + * + * @return + */ + public boolean hasRoomToStorePattern() { + return (this.patterns.size() < HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS); + } - /** - * Returns true if there is room to store a new pattern. - * - * @return - */ - public boolean hasRoomToStorePattern() - { - return( this.patterns.size() < HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS ); - } + /** + * Return's true if this handler is handling the specified knowledge core. + * + * @param kCore + * @return + */ + public boolean isHandlingCore(final ItemStack kCore) { + // Is the handler handling a core? + if (this.kCore == null) { + // Handler has been closed. + return false; + } - /** - * Return's true if this handler is handling the specified knowledge core. - * - * @param kCore - * @return - */ - public boolean isHandlingCore( final ItemStack kCore ) - { - // Is the handler handling a core? - if( this.kCore == null ) - { - // Handler has been closed. - return false; - } + // Is the specified itemstack valid? + if ((kCore == null) || (kCore.getItem() == null)) { + // Invalid itemstack + return false; + } - // Is the specified itemstack valid? - if( ( kCore == null ) || ( kCore.getItem() == null ) ) - { - // Invalid itemstack - return false; - } + // Is the specified item a knowledge core? + if (!(kCore.getItem() instanceof ItemKnowledgeCore)) { + // Invalid core + return false; + } - // Is the specified item a knowledge core? - if( !( kCore.getItem() instanceof ItemKnowledgeCore ) ) - { - // Invalid core - return false; - } + return (ItemStack.areItemStacksEqual(kCore, this.kCore) + && (ItemStack.areItemStackTagsEqual(kCore, this.kCore))); + } - return( ItemStack.areItemStacksEqual( kCore, this.kCore ) && ( ItemStack.areItemStackTagsEqual( kCore, this.kCore ) ) ); - } + /** + * Closes the previous core, and opens the new core. + * + * @param kCore + */ + public void open(final ItemStack kCore) { + // Close any existing core + this.close(); - /** - * Closes the previous core, and opens the new core. - * - * @param kCore - */ - public void open( final ItemStack kCore ) - { - // Close any existing core - this.close(); + // Set the kCore + this.kCore = kCore; - // Set the kCore - this.kCore = kCore; - - // Load - this.loadKCoreData(); - } - - /** - * Removes the specified pattern from the core. - * - * @param pattern - */ - public void removePattern( final ArcaneCraftingPattern pattern ) - { - // Attempt to remove the pattern - if( this.patterns.remove( pattern ) ) - { - // Save - this.saveKCoreData(); - } - } + // Load + this.loadKCoreData(); + } + /** + * Removes the specified pattern from the core. + * + * @param pattern + */ + public void removePattern(final ArcaneCraftingPattern pattern) { + // Attempt to remove the pattern + if (this.patterns.remove(pattern)) { + // Save + this.saveKCoreData(); + } + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/HandlerWirelessEssentiaTerminal.java b/src/main/java/thaumicenergistics/common/inventory/HandlerWirelessEssentiaTerminal.java index 39d4813d..67cc004c 100644 --- a/src/main/java/thaumicenergistics/common/inventory/HandlerWirelessEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/common/inventory/HandlerWirelessEssentiaTerminal.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.inventory; -import java.util.Set; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.ViewItems; @@ -14,6 +13,7 @@ import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; import appeng.api.util.IConfigManager; import appeng.core.AEConfig; +import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -38,441 +38,380 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class HandlerWirelessEssentiaTerminal - extends WirelessAELink - implements IActionHost, ICraftingIssuerHost, IGuiItemObject -{ - /** - * Redirects power requests to the wireless terminal. - * - * @author Nividica - * - */ - private class PowerRedirector - implements IEnergyGrid - { - - public PowerRedirector() - { - } - - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - // Ignored - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - return HandlerWirelessEssentiaTerminal.this.extractPower( amt, mode ); - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final Set seen ) - { - return HandlerWirelessEssentiaTerminal.this.extractPower( amt, mode ); - } - - @Override - public double getAvgPowerInjection() - { - // Ignored - return 0; - } - - @Override - public double getAvgPowerUsage() - { - // Ignored - return 0; - } - - @Override - public double getEnergyDemand( final double maxRequired ) - { - // Ignored - return 0; - } - - @Override - public double getEnergyDemand( final double d, final Set seen ) - { - // Ignored - return 0; - } - - @Override - public double getIdlePowerUsage() - { - // Ignored - return 0; - } - - @Override - public double getMaxStoredPower() - { - // Ignored - return 0; - } - - @Override - public double getStoredPower() - { - // Ignored - return 0; - } - - @Override - public double injectAEPower( final double amt, final Actionable mode, final Set seen ) - { - // Ignored - return amt; - } - - @Override - public double injectPower( final double amt, final Actionable mode ) - { - // Ignored - return amt; - } - - @Override - public boolean isNetworkPowered() - { - // Ignored - return true; - } - - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - // Ignored - } - - @Override - public void onSplit( final IGridStorage destinationStorage ) - { - // Ignored - } - - @Override - public void onUpdateTick() - { - // Ignored - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - // Ignored - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - // Ignored - } - - } - - /** - * NBT Keys - */ - private static final String NBT_KEY_SORTING_MODE = "SortingMode2", NBT_KEY_VIEW_MODE = "ViewMode"; - - /** - * Wireless terminal. - */ - private final IThEWirelessEssentiaTerminal wirelessTerminal; - - /** - * The itemstack that represents this terminal. - */ - final private ItemStack wirelessItemstack; - - /** - * How much to multiply the required power by. - */ - private double wirelessPowerMultiplier = 1.0D; - - public HandlerWirelessEssentiaTerminal( final EntityPlayer player, final String encryptionKey, - final IThEWirelessEssentiaTerminal wirelessTerminalInterface, - final ItemStack wirelessTerminalItemstack ) - { - // Call super - super( player, encryptionKey ); - - // Set the terminal interface - this.wirelessTerminal = wirelessTerminalInterface; - - // Set the itemstack - this.wirelessItemstack = wirelessTerminalItemstack; - } - - /** - * Returns true if the wireless terminal is linked to a network. - * - * @param wirelessTerminal - * @return - */ - public static boolean isTerminalLinked( final IThEWirelessEssentiaTerminal wirelessTerminal, final ItemStack wirelessTerminalItemstack ) - { - return( !wirelessTerminal.getEncryptionKey( wirelessTerminalItemstack ).isEmpty() ); - } - - @Override - protected int getUserPositionX() - { - return (int)this.player.posX; - } - - @Override - protected int getUserPositionY() - { - return (int)this.player.posY; - } - - @Override - protected int getUserPositionZ() - { - return (int)this.player.posZ; - } - - @Override - protected World getUserWorld() - { - return this.player.worldObj; - } - - /** - * Uses some of the terminals stored power. This does take into account the extra power required for wireless operations. - * - * @param amount - * @return Returns the amount extracted. - */ - public double extractPower( final double amount, final Actionable mode ) - { - // Has power usage been disabled? - if( ItemWirelessEssentiaTerminal.GLOBAL_POWER_MULTIPLIER == 0 ) - { - // Lie and say it was taken. - return amount; - } - - // Adjust by the power multiplier - double adjustedAmount = amount * this.wirelessPowerMultiplier; - - double extractedAmount = 0; - // Simulation? - if( mode == Actionable.SIMULATE ) - { - // Return the amount stored, capped at amount - extractedAmount = Math.min( this.wirelessTerminal.getAECurrentPower( this.wirelessItemstack ), adjustedAmount ); - } - else - { - // Return the amount extracted. - extractedAmount = this.wirelessTerminal.extractAEPower( this.wirelessItemstack, adjustedAmount ); - } - - // Adjust by the power multiplier - extractedAmount /= this.wirelessPowerMultiplier; - - return extractedAmount; - } - - @Override - public IGridNode getActionableNode() - { - if( this.accessPoint != null ) - { - return this.accessPoint.getActionableNode(); - } - return null; - } - - /** - * Gets the the player source used when interacting with the network. - * - * @return - */ - public BaseActionSource getActionHost() - { - return this.actionSource; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.NONE; - } - - @Override - public IConfigManager getConfigManager() - { - // Ignored. - return null; - } - - /** - * Gets the essentia monitor. - * - * @return - */ - @Override - public IMEEssentiaMonitor getEssentiaInventory() - { - - // Get the network essentia monitor - IMEEssentiaMonitor essMonitor = super.getEssentiaInventory(); - if( essMonitor == null ) - { - return null; - } - - // Create the power redirector - PowerRedirector pr = new PowerRedirector(); - - // Create and return the passthrough essentia monitor - IMEEssentiaMonitor monitor = new EssentiaPassThroughMonitor( essMonitor, pr ); - return monitor; - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getActionableNode(); - } - - @Override - public ItemStack getIcon() - { - return ItemEnum.WIRELESS_TERMINAL.getStack(); - } - - @Override - public ItemStack getItemStack() - { - return this.wirelessItemstack; - } - - /** - * Gets the terminals sorting mode. - * - * @return - */ - public AspectStackComparatorMode getSortingMode() - { - // Get the data tag - NBTTagCompound dataTagCompound = this.wirelessTerminal.getWETerminalTag( this.wirelessItemstack ); - - // Does the tag have the mode stored? - if( dataTagCompound.hasKey( NBT_KEY_SORTING_MODE ) ) - { - return AspectStackComparatorMode.VALUES[dataTagCompound.getInteger( NBT_KEY_SORTING_MODE )]; - } - - return AspectStackComparatorMode.MODE_ALPHABETIC; - } - - /** - * Gets the wireless terminal itemstack. - * - * @return - */ - public ItemStack getTerminalItem() - { - return this.wirelessItemstack; - } - - public ViewItems getViewMode() - { - // Get the data tag - NBTTagCompound dataTagCompound = this.wirelessTerminal.getWETerminalTag( this.wirelessItemstack ); - - // Does the tag have the mode stored? - if( dataTagCompound.hasKey( NBT_KEY_VIEW_MODE ) ) - { - return EnumCache.AE_VIEW_ITEMS[dataTagCompound.getInteger( NBT_KEY_VIEW_MODE )]; - } - - return ViewItems.ALL; - - } - - /** - * Returns true if the terminal has power. - * - * @return - */ - @Override - public boolean hasPowerToCommunicate() - { - return( this.wirelessTerminal.getAECurrentPower( this.wirelessItemstack ) > 0 ); - } - - @Override - public void launchGUI( final EntityPlayer player ) - { - if( EffectiveSide.isClientSide() ) - { - // Ask server to change GUI's - Packet_S_ChangeGui.sendGuiChangeToWirelessTerminal( player ); - } - else - { - // Open the gui - ThEApi.instance().interact().openWirelessTerminalGui( player ); - } - } - - @Override - public void securityBreak() - { - } - - /** - * Sets the terminals sorting mode. - * - * @param mode - */ - public void setSortingMode( final AspectStackComparatorMode mode ) - { - // Get the data tag - NBTTagCompound dataTag = this.wirelessTerminal.getWETerminalTag( this.wirelessItemstack ); - - // Set the sorting mode - dataTag.setInteger( NBT_KEY_SORTING_MODE, mode.ordinal() ); - } - - public void setViewMode( final ViewItems viewMode ) - { - // Get the data tag - NBTTagCompound dataTag = this.wirelessTerminal.getWETerminalTag( this.wirelessItemstack ); - - // Set the viewing mode - dataTag.setInteger( NBT_KEY_VIEW_MODE, viewMode.ordinal() ); - } - - /** - * Updates the power multiplier for wireless operations. - * - * @return - */ - public void updatePowerMultiplier() - { - // Get the squared distance - double distance = WirelessAELink.getSquaredDistanceFromAP( this.apLocation, - this.getUserPositionX(), - this.getUserPositionY(), - this.getUserPositionZ() ); - - // Calculate the distance - distance = Math.sqrt( distance ); - - // Calculate the power multiplier - this.wirelessPowerMultiplier = AEConfig.instance.wireless_getDrainRate( distance ); - } - +public class HandlerWirelessEssentiaTerminal extends WirelessAELink + implements IActionHost, ICraftingIssuerHost, IGuiItemObject { + /** + * Redirects power requests to the wireless terminal. + * + * @author Nividica + * + */ + private class PowerRedirector implements IEnergyGrid { + + public PowerRedirector() {} + + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + // Ignored + } + + @Override + public double extractAEPower( + final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) { + return HandlerWirelessEssentiaTerminal.this.extractPower(amt, mode); + } + + @Override + public double extractAEPower(final double amt, final Actionable mode, final Set seen) { + return HandlerWirelessEssentiaTerminal.this.extractPower(amt, mode); + } + + @Override + public double getAvgPowerInjection() { + // Ignored + return 0; + } + + @Override + public double getAvgPowerUsage() { + // Ignored + return 0; + } + + @Override + public double getEnergyDemand(final double maxRequired) { + // Ignored + return 0; + } + + @Override + public double getEnergyDemand(final double d, final Set seen) { + // Ignored + return 0; + } + + @Override + public double getIdlePowerUsage() { + // Ignored + return 0; + } + + @Override + public double getMaxStoredPower() { + // Ignored + return 0; + } + + @Override + public double getStoredPower() { + // Ignored + return 0; + } + + @Override + public double injectAEPower(final double amt, final Actionable mode, final Set seen) { + // Ignored + return amt; + } + + @Override + public double injectPower(final double amt, final Actionable mode) { + // Ignored + return amt; + } + + @Override + public boolean isNetworkPowered() { + // Ignored + return true; + } + + @Override + public void onJoin(final IGridStorage sourceStorage) { + // Ignored + } + + @Override + public void onSplit(final IGridStorage destinationStorage) { + // Ignored + } + + @Override + public void onUpdateTick() { + // Ignored + } + + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { + // Ignored + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + // Ignored + } + } + + /** + * NBT Keys + */ + private static final String NBT_KEY_SORTING_MODE = "SortingMode2", NBT_KEY_VIEW_MODE = "ViewMode"; + + /** + * Wireless terminal. + */ + private final IThEWirelessEssentiaTerminal wirelessTerminal; + + /** + * The itemstack that represents this terminal. + */ + private final ItemStack wirelessItemstack; + + /** + * How much to multiply the required power by. + */ + private double wirelessPowerMultiplier = 1.0D; + + public HandlerWirelessEssentiaTerminal( + final EntityPlayer player, + final String encryptionKey, + final IThEWirelessEssentiaTerminal wirelessTerminalInterface, + final ItemStack wirelessTerminalItemstack) { + // Call super + super(player, encryptionKey); + + // Set the terminal interface + this.wirelessTerminal = wirelessTerminalInterface; + + // Set the itemstack + this.wirelessItemstack = wirelessTerminalItemstack; + } + + /** + * Returns true if the wireless terminal is linked to a network. + * + * @param wirelessTerminal + * @return + */ + public static boolean isTerminalLinked( + final IThEWirelessEssentiaTerminal wirelessTerminal, final ItemStack wirelessTerminalItemstack) { + return (!wirelessTerminal.getEncryptionKey(wirelessTerminalItemstack).isEmpty()); + } + + @Override + protected int getUserPositionX() { + return (int) this.player.posX; + } + + @Override + protected int getUserPositionY() { + return (int) this.player.posY; + } + + @Override + protected int getUserPositionZ() { + return (int) this.player.posZ; + } + + @Override + protected World getUserWorld() { + return this.player.worldObj; + } + + /** + * Uses some of the terminals stored power. This does take into account the extra power required for wireless operations. + * + * @param amount + * @return Returns the amount extracted. + */ + public double extractPower(final double amount, final Actionable mode) { + // Has power usage been disabled? + if (ItemWirelessEssentiaTerminal.GLOBAL_POWER_MULTIPLIER == 0) { + // Lie and say it was taken. + return amount; + } + + // Adjust by the power multiplier + double adjustedAmount = amount * this.wirelessPowerMultiplier; + + double extractedAmount = 0; + // Simulation? + if (mode == Actionable.SIMULATE) { + // Return the amount stored, capped at amount + extractedAmount = Math.min(this.wirelessTerminal.getAECurrentPower(this.wirelessItemstack), adjustedAmount); + } else { + // Return the amount extracted. + extractedAmount = this.wirelessTerminal.extractAEPower(this.wirelessItemstack, adjustedAmount); + } + + // Adjust by the power multiplier + extractedAmount /= this.wirelessPowerMultiplier; + + return extractedAmount; + } + + @Override + public IGridNode getActionableNode() { + if (this.accessPoint != null) { + return this.accessPoint.getActionableNode(); + } + return null; + } + + /** + * Gets the the player source used when interacting with the network. + * + * @return + */ + public BaseActionSource getActionHost() { + return this.actionSource; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.NONE; + } + + @Override + public IConfigManager getConfigManager() { + // Ignored. + return null; + } + + /** + * Gets the essentia monitor. + * + * @return + */ + @Override + public IMEEssentiaMonitor getEssentiaInventory() { + + // Get the network essentia monitor + IMEEssentiaMonitor essMonitor = super.getEssentiaInventory(); + if (essMonitor == null) { + return null; + } + + // Create the power redirector + PowerRedirector pr = new PowerRedirector(); + + // Create and return the passthrough essentia monitor + IMEEssentiaMonitor monitor = new EssentiaPassThroughMonitor(essMonitor, pr); + return monitor; + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getActionableNode(); + } + + @Override + public ItemStack getIcon() { + return ItemEnum.WIRELESS_TERMINAL.getStack(); + } + + @Override + public ItemStack getItemStack() { + return this.wirelessItemstack; + } + + /** + * Gets the terminals sorting mode. + * + * @return + */ + public AspectStackComparatorMode getSortingMode() { + // Get the data tag + NBTTagCompound dataTagCompound = this.wirelessTerminal.getWETerminalTag(this.wirelessItemstack); + + // Does the tag have the mode stored? + if (dataTagCompound.hasKey(NBT_KEY_SORTING_MODE)) { + return AspectStackComparatorMode.VALUES[dataTagCompound.getInteger(NBT_KEY_SORTING_MODE)]; + } + + return AspectStackComparatorMode.MODE_ALPHABETIC; + } + + /** + * Gets the wireless terminal itemstack. + * + * @return + */ + public ItemStack getTerminalItem() { + return this.wirelessItemstack; + } + + public ViewItems getViewMode() { + // Get the data tag + NBTTagCompound dataTagCompound = this.wirelessTerminal.getWETerminalTag(this.wirelessItemstack); + + // Does the tag have the mode stored? + if (dataTagCompound.hasKey(NBT_KEY_VIEW_MODE)) { + return EnumCache.AE_VIEW_ITEMS[dataTagCompound.getInteger(NBT_KEY_VIEW_MODE)]; + } + + return ViewItems.ALL; + } + + /** + * Returns true if the terminal has power. + * + * @return + */ + @Override + public boolean hasPowerToCommunicate() { + return (this.wirelessTerminal.getAECurrentPower(this.wirelessItemstack) > 0); + } + + @Override + public void launchGUI(final EntityPlayer player) { + if (EffectiveSide.isClientSide()) { + // Ask server to change GUI's + Packet_S_ChangeGui.sendGuiChangeToWirelessTerminal(player); + } else { + // Open the gui + ThEApi.instance().interact().openWirelessTerminalGui(player); + } + } + + @Override + public void securityBreak() {} + + /** + * Sets the terminals sorting mode. + * + * @param mode + */ + public void setSortingMode(final AspectStackComparatorMode mode) { + // Get the data tag + NBTTagCompound dataTag = this.wirelessTerminal.getWETerminalTag(this.wirelessItemstack); + + // Set the sorting mode + dataTag.setInteger(NBT_KEY_SORTING_MODE, mode.ordinal()); + } + + public void setViewMode(final ViewItems viewMode) { + // Get the data tag + NBTTagCompound dataTag = this.wirelessTerminal.getWETerminalTag(this.wirelessItemstack); + + // Set the viewing mode + dataTag.setInteger(NBT_KEY_VIEW_MODE, viewMode.ordinal()); + } + + /** + * Updates the power multiplier for wireless operations. + * + * @return + */ + public void updatePowerMultiplier() { + // Get the squared distance + double distance = WirelessAELink.getSquaredDistanceFromAP( + this.apLocation, this.getUserPositionX(), this.getUserPositionY(), this.getUserPositionZ()); + + // Calculate the distance + distance = Math.sqrt(distance); + + // Calculate the power multiplier + this.wirelessPowerMultiplier = AEConfig.instance.wireless_getDrainRate(distance); + } } diff --git a/src/main/java/thaumicenergistics/common/inventory/TheInternalInventory.java b/src/main/java/thaumicenergistics/common/inventory/TheInternalInventory.java index a793f273..54ad6867 100644 --- a/src/main/java/thaumicenergistics/common/inventory/TheInternalInventory.java +++ b/src/main/java/thaumicenergistics/common/inventory/TheInternalInventory.java @@ -15,314 +15,270 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class TheInternalInventory - implements IInventory -{ - /** - * NBT keys - */ - private static final String NBT_KEY_SLOT = "Slot"; +public class TheInternalInventory implements IInventory { + /** + * NBT keys + */ + private static final String NBT_KEY_SLOT = "Slot"; - /** - * Stack size limit. - */ - private final int stackLimit; + /** + * Stack size limit. + */ + private final int stackLimit; - /** - * The inventory slots. - */ - private final ItemStack[] slots; + /** + * The inventory slots. + */ + private final ItemStack[] slots; - /** - * Name of the inventory. - */ - private final String customName; + /** + * Name of the inventory. + */ + private final String customName; - /** - * Creates the inventory. - * - * @param customName - * @param size - * @param stackLimit - */ - public TheInternalInventory( final String customName, final int size, final int stackLimit ) - { - this.slots = new ItemStack[size]; - this.customName = customName; - this.stackLimit = stackLimit; - } + /** + * Creates the inventory. + * + * @param customName + * @param size + * @param stackLimit + */ + public TheInternalInventory(final String customName, final int size, final int stackLimit) { + this.slots = new ItemStack[size]; + this.customName = customName; + this.stackLimit = stackLimit; + } - @Override - public void closeInventory() - { - } + @Override + public void closeInventory() {} - @Override - public ItemStack decrStackSize( final int slotIndex, final int amount ) - { - // Get the stack - ItemStack slotStack = this.slots[slotIndex]; - ItemStack resultStack = null; + @Override + public ItemStack decrStackSize(final int slotIndex, final int amount) { + // Get the stack + ItemStack slotStack = this.slots[slotIndex]; + ItemStack resultStack = null; - // Is the slot empty? - if( slotStack == null ) - { - // Slot is empty - return null; - } + // Is the slot empty? + if (slotStack == null) { + // Slot is empty + return null; + } - // Calculate the amount to get - int decAmount = Math.min( amount, slotStack.stackSize ); + // Calculate the amount to get + int decAmount = Math.min(amount, slotStack.stackSize); - // Was any amount gotten? - if( decAmount > 0 ) - { - resultStack = slotStack.copy(); - resultStack.stackSize = decAmount; - } + // Was any amount gotten? + if (decAmount > 0) { + resultStack = slotStack.copy(); + resultStack.stackSize = decAmount; + } - // Calculate the remaining amount - slotStack.stackSize = slotStack.stackSize - decAmount; + // Calculate the remaining amount + slotStack.stackSize = slotStack.stackSize - decAmount; - // Is there anything remaining in the slot? - if( slotStack.stackSize > 0 ) - { - // Re-set - this.setInventorySlotContents( slotIndex, slotStack ); - } - else - { - // Clear - this.setInventorySlotContents( slotIndex, null ); - } + // Is there anything remaining in the slot? + if (slotStack.stackSize > 0) { + // Re-set + this.setInventorySlotContents(slotIndex, slotStack); + } else { + // Clear + this.setInventorySlotContents(slotIndex, null); + } - return resultStack; - } + return resultStack; + } - /** - * Returns true if there is a stack in the specified slot. - * - * @param slotIndex - * @return - */ - public boolean getHasStack( final int slotIndex ) - { - return this.slots[slotIndex] != null; - } + /** + * Returns true if there is a stack in the specified slot. + * + * @param slotIndex + * @return + */ + public boolean getHasStack(final int slotIndex) { + return this.slots[slotIndex] != null; + } - @Override - public String getInventoryName() - { - return this.customName; - } + @Override + public String getInventoryName() { + return this.customName; + } - @Override - public int getInventoryStackLimit() - { - return this.stackLimit; - } + @Override + public int getInventoryStackLimit() { + return this.stackLimit; + } - @Override - public int getSizeInventory() - { - return this.slots.length; - } + @Override + public int getSizeInventory() { + return this.slots.length; + } - @Override - public ItemStack getStackInSlot( final int slotIndex ) - { - return this.slots[slotIndex]; - } + @Override + public ItemStack getStackInSlot(final int slotIndex) { + return this.slots[slotIndex]; + } - @Override - public ItemStack getStackInSlotOnClosing( final int slotIndex ) - { - return this.slots[slotIndex]; - } + @Override + public ItemStack getStackInSlotOnClosing(final int slotIndex) { + return this.slots[slotIndex]; + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - /** - * Increases the stack size of the specified slot, and marks the inventory - * as dirty. - * - * @param slotIndex - * @param amount - * @return The amount that was added. - */ - public int incrStackSize( final int slotIndex, final int amount ) - { - // Get the stack - ItemStack slotStack = this.slots[slotIndex]; + /** + * Increases the stack size of the specified slot, and marks the inventory + * as dirty. + * + * @param slotIndex + * @param amount + * @return The amount that was added. + */ + public int incrStackSize(final int slotIndex, final int amount) { + // Get the stack + ItemStack slotStack = this.slots[slotIndex]; - // Assume none was added - int added = 0; + // Assume none was added + int added = 0; - if( slotStack != null ) - { - // Calculate the stack limit - int stackLimit = Math.min( this.getInventoryStackLimit(), slotStack.getMaxStackSize() ); + if (slotStack != null) { + // Calculate the stack limit + int stackLimit = Math.min(this.getInventoryStackLimit(), slotStack.getMaxStackSize()); - // Calculate how much can be added - added = Math.min( amount, stackLimit - slotStack.stackSize ); + // Calculate how much can be added + added = Math.min(amount, stackLimit - slotStack.stackSize); - // Can any be added? - if( added > 0 ) - { - this.slots[slotIndex].stackSize += added; - this.markDirty(); - } - } + // Can any be added? + if (added > 0) { + this.slots[slotIndex].stackSize += added; + this.markDirty(); + } + } - return added; - } + return added; + } - /** - * True if the inventory is empty. - * - * @return - */ - public boolean isEmpty() - { - // Loop over the slots - for( int index = 0; index < this.slots.length; ++index ) - { - // Is this slot occupied? - if( this.slots[index] != null ) - { - // Inventory is not empty - return false; - } - } + /** + * True if the inventory is empty. + * + * @return + */ + public boolean isEmpty() { + // Loop over the slots + for (int index = 0; index < this.slots.length; ++index) { + // Is this slot occupied? + if (this.slots[index] != null) { + // Inventory is not empty + return false; + } + } - // Checked all slots, inventory is empty. - return true; - } + // Checked all slots, inventory is empty. + return true; + } - /** - * Must override, always return false. - */ - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack itemStack ) - { - // Assume it is not valid - return false; - } + /** + * Must override, always return false. + */ + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack itemStack) { + // Assume it is not valid + return false; + } - /** - * Always returns true. - */ - @Override - @Deprecated - public boolean isUseableByPlayer( final EntityPlayer player ) - { - return true; - } + /** + * Always returns true. + */ + @Override + @Deprecated + public boolean isUseableByPlayer(final EntityPlayer player) { + return true; + } - public boolean isUseableByPlayer( @Nonnull final EntityPlayer player, @Nonnull final TileEntity tile ) - { - return ThEUtils.canPlayerInteractWith( player, tile ); - } + public boolean isUseableByPlayer(@Nonnull final EntityPlayer player, @Nonnull final TileEntity tile) { + return ThEUtils.canPlayerInteractWith(player, tile); + } - @Override - public void markDirty() - { - } + @Override + public void markDirty() {} - @Override - public void openInventory() - { - } + @Override + public void openInventory() {} - public final void readFromNBT( final NBTTagCompound data, final String tagName ) - { - // Ensure there is a data tag - if( data == null ) - { - return; - } + public final void readFromNBT(final NBTTagCompound data, final String tagName) { + // Ensure there is a data tag + if (data == null) { + return; + } - // Ensure the data has our inventory - if( !data.hasKey( tagName ) ) - { - return; - } + // Ensure the data has our inventory + if (!data.hasKey(tagName)) { + return; + } - // Load the list - NBTTagList invList = data.getTagList( tagName, (byte)10 ); + // Load the list + NBTTagList invList = data.getTagList(tagName, (byte) 10); - // Load the inventory from the list - for( int index = 0; index < invList.tagCount(); index++ ) - { - // Get the compound - NBTTagCompound nbtCompound = invList.getCompoundTagAt( index ); + // Load the inventory from the list + for (int index = 0; index < invList.tagCount(); index++) { + // Get the compound + NBTTagCompound nbtCompound = invList.getCompoundTagAt(index); - // Get the slot number - int slotIndex = nbtCompound.getByte( TheInternalInventory.NBT_KEY_SLOT ) & 0xFF; + // Get the slot number + int slotIndex = nbtCompound.getByte(TheInternalInventory.NBT_KEY_SLOT) & 0xFF; - // Validate the slot number - if( ( slotIndex >= 0 ) && ( slotIndex < this.slots.length ) ) - { - // Load the itemstack - this.slots[slotIndex] = ItemStack.loadItemStackFromNBT( nbtCompound ); - } - } - } + // Validate the slot number + if ((slotIndex >= 0) && (slotIndex < this.slots.length)) { + // Load the itemstack + this.slots[slotIndex] = ItemStack.loadItemStackFromNBT(nbtCompound); + } + } + } - @Override - public void setInventorySlotContents( final int slotIndex, final ItemStack itemStack ) - { - // Is the stack size too large? - if( ( itemStack != null ) && ( itemStack.stackSize > this.getInventoryStackLimit() ) ) - { - itemStack.stackSize = this.getInventoryStackLimit(); - } + @Override + public void setInventorySlotContents(final int slotIndex, final ItemStack itemStack) { + // Is the stack size too large? + if ((itemStack != null) && (itemStack.stackSize > this.getInventoryStackLimit())) { + itemStack.stackSize = this.getInventoryStackLimit(); + } - this.slots[slotIndex] = itemStack; + this.slots[slotIndex] = itemStack; - this.markDirty(); - } + this.markDirty(); + } - public final void writeToNBT( final NBTTagCompound data, final String tagName ) - { - // Ensure there is a data tag - if( data == null ) - { - return; - } + public final void writeToNBT(final NBTTagCompound data, final String tagName) { + // Ensure there is a data tag + if (data == null) { + return; + } - // Create the list - NBTTagList invList = new NBTTagList(); + // Create the list + NBTTagList invList = new NBTTagList(); - // Write each slot into the list - for( int slotIndex = 0; slotIndex < this.slots.length; slotIndex++ ) - { - // Ensure the slot has something to write - if( this.slots[slotIndex] != null ) - { - // Create the compound - NBTTagCompound nbtCompound = new NBTTagCompound(); + // Write each slot into the list + for (int slotIndex = 0; slotIndex < this.slots.length; slotIndex++) { + // Ensure the slot has something to write + if (this.slots[slotIndex] != null) { + // Create the compound + NBTTagCompound nbtCompound = new NBTTagCompound(); - // Set the slot number - nbtCompound.setByte( TheInternalInventory.NBT_KEY_SLOT, (byte)slotIndex ); + // Set the slot number + nbtCompound.setByte(TheInternalInventory.NBT_KEY_SLOT, (byte) slotIndex); - // Save the inventory - this.slots[slotIndex].writeToNBT( nbtCompound ); + // Save the inventory + this.slots[slotIndex].writeToNBT(nbtCompound); - // Add to the list - invList.appendTag( nbtCompound ); - } - } - - // Write the list into the data - if( invList.tagCount() > 0 ) - { - data.setTag( tagName, invList ); - } - } + // Add to the list + invList.appendTag(nbtCompound); + } + } + // Write the list into the data + if (invList.tagCount() > 0) { + data.setTag(tagName, invList); + } + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemAEPart.java b/src/main/java/thaumicenergistics/common/items/ItemAEPart.java index 739ed498..d46a4fb1 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemAEPart.java +++ b/src/main/java/thaumicenergistics/common/items/ItemAEPart.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.items; -import java.util.List; -import java.util.Map; -import java.util.Set; import appeng.api.AEApi; import appeng.api.config.Upgrades; import appeng.api.implementations.items.IItemGroup; @@ -10,6 +7,9 @@ import appeng.api.parts.IPart; import appeng.api.parts.IPartItem; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import java.util.Map; +import java.util.Set; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -27,118 +27,106 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public class ItemAEPart - extends Item - implements IPartItem, IItemGroup -{ - /** - * Constructor - */ - public ItemAEPart() - { - // Undamageable - this.setMaxDamage( 0 ); +public class ItemAEPart extends Item implements IPartItem, IItemGroup { + /** + * Constructor + */ + public ItemAEPart() { + // Undamageable + this.setMaxDamage(0); - // Has sub types - this.setHasSubtypes( true ); + // Has sub types + this.setHasSubtypes(true); - // Can be rendered on a cable. - AEApi.instance().partHelper().setItemBusRenderer( this ); + // Can be rendered on a cable. + AEApi.instance().partHelper().setItemBusRenderer(this); - // Register parts who can take an upgrade card. - Map possibleUpgradesList; - for( AEPartsEnum part : AEPartsEnum.VALUES ) - { - possibleUpgradesList = part.getUpgrades(); + // Register parts who can take an upgrade card. + Map possibleUpgradesList; + for (AEPartsEnum part : AEPartsEnum.VALUES) { + possibleUpgradesList = part.getUpgrades(); - for( Upgrades upgrade : possibleUpgradesList.keySet() ) - { - upgrade.registerItem( new ItemStack( this, 1, part.ordinal() ), possibleUpgradesList.get( upgrade ).intValue() ); - } - } + for (Upgrades upgrade : possibleUpgradesList.keySet()) { + upgrade.registerItem( + new ItemStack(this, 1, part.ordinal()), + possibleUpgradesList.get(upgrade).intValue()); + } + } + } - } + @Override + public IPart createPartFromItemStack(final ItemStack itemStack) { + IPart newPart = null; - @Override - public IPart createPartFromItemStack( final ItemStack itemStack ) - { - IPart newPart = null; + // Get the part + AEPartsEnum part = AEPartsEnum.getPartFromDamageValue(itemStack); - // Get the part - AEPartsEnum part = AEPartsEnum.getPartFromDamageValue( itemStack ); + // Attempt to create a new instance of the part + try { + newPart = part.createPartInstance(itemStack); + } catch (Throwable e) { + // Bad stuff, log the error. + ThELog.error(e, "Unable to create cable-part from item: %s", itemStack.getDisplayName()); + } - // Attempt to create a new instance of the part - try - { - newPart = part.createPartInstance( itemStack ); - } - catch( Throwable e ) - { - // Bad stuff, log the error. - ThELog.error( e, "Unable to create cable-part from item: %s", itemStack.getDisplayName() ); - } + // Return the part + return newPart; + } - // Return the part - return newPart; + @Override + public EnumRarity getRarity(final ItemStack itemStack) { + return EnumRarity.rare; + } - } + @SideOnly(Side.CLIENT) + @Override + public int getSpriteNumber() { + return 0; + } - @Override - public EnumRarity getRarity( final ItemStack itemStack ) - { - return EnumRarity.rare; - } + @Override + public void getSubItems(final Item item, final CreativeTabs tab, final List itemList) { + // Get the number of parts + int count = AEPartsEnum.VALUES.length; - @SideOnly(Side.CLIENT) - @Override - public int getSpriteNumber() - { - return 0; - } + // Add each one to the list + for (int i = 0; i < count; i++) { + itemList.add(new ItemStack(item, 1, i)); + } + } - @Override - public void getSubItems( final Item item, final CreativeTabs tab, final List itemList ) - { - // Get the number of parts - int count = AEPartsEnum.VALUES.length; + @Override + public String getUnlocalizedGroupName(final Set arg0, final ItemStack itemStack) { + return AEPartsEnum.getPartFromDamageValue(itemStack).getGroupName(); + } - // Add each one to the list - for( int i = 0; i < count; i++ ) - { - itemList.add( new ItemStack( item, 1, i ) ); - } + @Override + public String getUnlocalizedName() { + return ThaumicEnergistics.MOD_ID + ".item.aeparts"; + } - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return AEPartsEnum.getPartFromDamageValue(itemStack).getUnlocalizedName(); + } - @Override - public String getUnlocalizedGroupName( final Set arg0, final ItemStack itemStack ) - { - return AEPartsEnum.getPartFromDamageValue( itemStack ).getGroupName(); - } + @Override + public boolean onItemUse( + final ItemStack itemStack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ) { + // Can we place the item on the bus? + return AEApi.instance().partHelper().placeBus(itemStack, x, y, z, side, player, world); + } - @Override - public String getUnlocalizedName() - { - return ThaumicEnergistics.MOD_ID + ".item.aeparts"; - } - - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return AEPartsEnum.getPartFromDamageValue( itemStack ).getUnlocalizedName(); - } - - @Override - public boolean onItemUse( final ItemStack itemStack, final EntityPlayer player, final World world, final int x, final int y, final int z, - final int side, final float hitX, final float hitY, final float hitZ ) - { - // Can we place the item on the bus? - return AEApi.instance().partHelper().placeBus( itemStack, x, y, z, side, player, world ); - } - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(final IIconRegister par1IconRegister) {} } diff --git a/src/main/java/thaumicenergistics/common/items/ItemBlockArcaneAssembler.java b/src/main/java/thaumicenergistics/common/items/ItemBlockArcaneAssembler.java index 8fa08a97..9543b24f 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemBlockArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/common/items/ItemBlockArcaneAssembler.java @@ -15,31 +15,29 @@ import thaumicenergistics.common.tiles.TileArcaneAssembler; * @author Nividica * */ -public class ItemBlockArcaneAssembler - extends ItemBlock -{ +public class ItemBlockArcaneAssembler extends ItemBlock { - public ItemBlockArcaneAssembler( final Block block ) - { - super( block ); - } + public ItemBlockArcaneAssembler(final Block block) { + super(block); + } - @Override - public void addInformation( final ItemStack stack, final EntityPlayer player, final List displayList, final boolean advancedItemTooltips ) - { - // Ensure the stack has a tag - if( !stack.hasTagCompound() ) - { - return; - } - - // Ensure it has stored vis - if( stack.getTagCompound().hasKey( TileArcaneAssembler.NBTKEY_STORED_VIS ) ) - { - // Add the info - displayList.add( EnumChatFormatting.WHITE.toString() + EnumChatFormatting.ITALIC.toString() + - ThEStrings.Tooltip_ArcaneAssemblerHasVis.getLocalized() ); - } - } + @Override + public void addInformation( + final ItemStack stack, + final EntityPlayer player, + final List displayList, + final boolean advancedItemTooltips) { + // Ensure the stack has a tag + if (!stack.hasTagCompound()) { + return; + } + // Ensure it has stored vis + if (stack.getTagCompound().hasKey(TileArcaneAssembler.NBTKEY_STORED_VIS)) { + // Add the info + displayList.add(EnumChatFormatting.WHITE.toString() + + EnumChatFormatting.ITALIC.toString() + + ThEStrings.Tooltip_ArcaneAssemblerHasVis.getLocalized()); + } + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemBlockEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/items/ItemBlockEssentiaVibrationChamber.java index 227d1a32..7935bf38 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemBlockEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/items/ItemBlockEssentiaVibrationChamber.java @@ -1,13 +1,13 @@ package thaumicenergistics.common.items; import java.util.List; -import org.lwjgl.input.Keyboard; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; +import org.lwjgl.input.Keyboard; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import thaumicenergistics.api.items.IRestrictedEssentiaContainerItem; @@ -23,145 +23,125 @@ import thaumicenergistics.common.tiles.abstraction.TileEVCBase; * @author Nividica * */ -public class ItemBlockEssentiaVibrationChamber - extends ItemBlock - implements IRestrictedEssentiaContainerItem -{ - public ItemBlockEssentiaVibrationChamber( final Block block ) - { - super( block ); - } +public class ItemBlockEssentiaVibrationChamber extends ItemBlock implements IRestrictedEssentiaContainerItem { + public ItemBlockEssentiaVibrationChamber(final Block block) { + super(block); + } - /** - * Gets the aspect stack from the EVC item. - * - * @param evcStack - * @return AspectStack or null - */ - private IAspectStack getStoredAspectStack( final ItemStack evcStack ) - { - // Get the tag - NBTTagCompound data = evcStack.getTagCompound(); + /** + * Gets the aspect stack from the EVC item. + * + * @param evcStack + * @return AspectStack or null + */ + private IAspectStack getStoredAspectStack(final ItemStack evcStack) { + // Get the tag + NBTTagCompound data = evcStack.getTagCompound(); - // Is there essentia stored? - if( ( data == null ) || ( !data.hasKey( TileEVCBase.NBTKEY_STORED ) ) ) - { - return null; - } + // Is there essentia stored? + if ((data == null) || (!data.hasKey(TileEVCBase.NBTKEY_STORED))) { + return null; + } - return AspectStack.loadAspectStackFromNBT( data.getCompoundTag( TileEVCBase.NBTKEY_STORED ) ); - } + return AspectStack.loadAspectStackFromNBT(data.getCompoundTag(TileEVCBase.NBTKEY_STORED)); + } - private void setStoredAspectStack( final ItemStack evcStack, final IAspectStack aspectStack ) - { - // Get the tag - NBTTagCompound data = evcStack.getTagCompound(); - if( data == null ) - { - data = new NBTTagCompound(); - } + private void setStoredAspectStack(final ItemStack evcStack, final IAspectStack aspectStack) { + // Get the tag + NBTTagCompound data = evcStack.getTagCompound(); + if (data == null) { + data = new NBTTagCompound(); + } - // Is the stack empty? - if( aspectStack == null ) - { - // Remove the stored data - data.removeTag( TileEVCBase.NBTKEY_STORED ); - } - else - { - // Create the subtag - NBTTagCompound storedTag = new NBTTagCompound(); + // Is the stack empty? + if (aspectStack == null) { + // Remove the stored data + data.removeTag(TileEVCBase.NBTKEY_STORED); + } else { + // Create the subtag + NBTTagCompound storedTag = new NBTTagCompound(); - // Write the aspect stack into it - aspectStack.writeToNBT( storedTag ); + // Write the aspect stack into it + aspectStack.writeToNBT(storedTag); - // Write the stored tag - data.setTag( TileEVCBase.NBTKEY_STORED, storedTag ); - } + // Write the stored tag + data.setTag(TileEVCBase.NBTKEY_STORED, storedTag); + } - // Is the data tag empty? - if( data.hasNoTags() ) - { - // Set to null - data = null; - } + // Is the data tag empty? + if (data.hasNoTags()) { + // Set to null + data = null; + } - // Set tag - evcStack.setTagCompound( data ); - } + // Set tag + evcStack.setTagCompound(data); + } - @Override - public boolean acceptsAspect( final Aspect aspect ) - { - return TileEVCBase.acceptsAspect( aspect ); - } + @Override + public boolean acceptsAspect(final Aspect aspect) { + return TileEVCBase.acceptsAspect(aspect); + } - @Override - public void addInformation( final ItemStack evcStack, final EntityPlayer player, final List displayList, final boolean advancedItemTooltips ) - { - // Ignore stacks without a tag - if( !evcStack.hasTagCompound() ) - { - return; - } + @Override + public void addInformation( + final ItemStack evcStack, + final EntityPlayer player, + final List displayList, + final boolean advancedItemTooltips) { + // Ignore stacks without a tag + if (!evcStack.hasTagCompound()) { + return; + } - // Is shift being held? - if( Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || ( Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ) ) ) - { + // Is shift being held? + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || (Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))) { - // Load the stack - IAspectStack storedEssentia = this.getStoredAspectStack( evcStack ); + // Load the stack + IAspectStack storedEssentia = this.getStoredAspectStack(evcStack); - // Add stored info - if( storedEssentia != null ) - { - displayList.add( String.format( "%s x %d", storedEssentia.getAspectName(), storedEssentia.getStackSize() ) ); - } - } - else - { - // Let the user know they can hold shift - displayList.add( EnumChatFormatting.WHITE.toString() + EnumChatFormatting.ITALIC.toString() + - ThEStrings.Tooltip_ItemStackDetails.getLocalized() ); - } + // Add stored info + if (storedEssentia != null) { + displayList.add( + String.format("%s x %d", storedEssentia.getAspectName(), storedEssentia.getStackSize())); + } + } else { + // Let the user know they can hold shift + displayList.add(EnumChatFormatting.WHITE.toString() + + EnumChatFormatting.ITALIC.toString() + + ThEStrings.Tooltip_ItemStackDetails.getLocalized()); + } + } - } + @Override + public AspectList getAspects(final ItemStack evcStack) { + AspectList list = new AspectList(); - @Override - public AspectList getAspects( final ItemStack evcStack ) - { - AspectList list = new AspectList(); + // Ignore stacks without a tag + if (evcStack.hasTagCompound()) { + // Get the stored aspect + IAspectStack stored = this.getStoredAspectStack(evcStack); + if ((stored != null) && !stored.isEmpty()) { + // Add it + list.add(stored.getAspect(), (int) stored.getStackSize()); + } + } - // Ignore stacks without a tag - if( evcStack.hasTagCompound() ) - { - // Get the stored aspect - IAspectStack stored = this.getStoredAspectStack( evcStack ); - if( ( stored != null ) && !stored.isEmpty() ) - { - // Add it - list.add( stored.getAspect(), (int)stored.getStackSize() ); - } + return list; + } - } + @Override + public void setAspects(final ItemStack evcStack, final AspectList list) { + IAspectStack aspectStack = null; - return list; - } + if (list.size() > 0) { + Aspect aspect = list.getAspects()[0]; - @Override - public void setAspects( final ItemStack evcStack, final AspectList list ) - { - IAspectStack aspectStack = null; + // Create the aspect stack + aspectStack = new AspectStack(aspect, list.getAmount(aspect)); + } - if( list.size() > 0 ) - { - Aspect aspect = list.getAspects()[0]; - - // Create the aspect stack - aspectStack = new AspectStack( aspect, list.getAmount( aspect ) ); - } - - // Set the tag - this.setStoredAspectStack( evcStack, aspectStack ); - } + // Set the tag + this.setStoredAspectStack(evcStack, aspectStack); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemCraftingAspect.java b/src/main/java/thaumicenergistics/common/items/ItemCraftingAspect.java index 0886b4f6..a0368e78 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemCraftingAspect.java +++ b/src/main/java/thaumicenergistics/common/items/ItemCraftingAspect.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.items; -import java.util.List; -import javax.annotation.Nonnull; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; +import javax.annotation.Nonnull; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; @@ -25,213 +25,187 @@ import thaumicenergistics.common.integration.tc.AspectHooks; * @author Nividica * */ -public class ItemCraftingAspect - extends Item -{ - private static final String NBTKEY_ASPECT = "Aspect"; +public class ItemCraftingAspect extends Item { + private static final String NBTKEY_ASPECT = "Aspect"; - public ItemCraftingAspect() - { - this.setMaxStackSize( 64 ); - this.setHasSubtypes( true ); - this.setMaxDamage( 0 ); - this.setCreativeTab( ThaumicEnergistics.ThETab ); - this.setUnlocalizedName( "itemCraftingAspect" ); - } + public ItemCraftingAspect() { + this.setMaxStackSize(64); + this.setHasSubtypes(true); + this.setMaxDamage(0); + this.setCreativeTab(ThaumicEnergistics.ThETab); + this.setUnlocalizedName("itemCraftingAspect"); + } - /** - * Returns true if the player has discovered the aspect. - * - * @param player - * @param aspect - * @return - */ - public static boolean canPlayerSeeAspect( @Nonnull final EntityPlayer player, @Nonnull final Aspect aspect ) - { - return Thaumcraft.proxy.playerKnowledge.hasDiscoveredAspect( player.getCommandSenderName(), aspect ); - } + /** + * Returns true if the player has discovered the aspect. + * + * @param player + * @param aspect + * @return + */ + public static boolean canPlayerSeeAspect(@Nonnull final EntityPlayer player, @Nonnull final Aspect aspect) { + return Thaumcraft.proxy.playerKnowledge.hasDiscoveredAspect(player.getCommandSenderName(), aspect); + } - /** - * Creates a new crafting aspect stack with the specified amount. - * - * @param aspect - * @param amount - * @return - */ - public static ItemStack createStackForAspect( final Aspect aspect, final int amount ) - { - // Create the stack - ItemStack stack = ItemEnum.CRAFTING_ASPECT.getStack( amount ); + /** + * Creates a new crafting aspect stack with the specified amount. + * + * @param aspect + * @param amount + * @return + */ + public static ItemStack createStackForAspect(final Aspect aspect, final int amount) { + // Create the stack + ItemStack stack = ItemEnum.CRAFTING_ASPECT.getStack(amount); - // Set the aspect - setAspect( stack, aspect ); + // Set the aspect + setAspect(stack, aspect); - return stack; - } + return stack; + } - /** - * Gets the aspect associated with the item. - * - * @param itemStack - * @return - */ - public static Aspect getAspect( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return null; - } - return getAspect( itemStack.getTagCompound() ); - } + /** + * Gets the aspect associated with the item. + * + * @param itemStack + * @return + */ + public static Aspect getAspect(final ItemStack itemStack) { + if (itemStack == null) { + return null; + } + return getAspect(itemStack.getTagCompound()); + } - /** - * Gets the aspect stored in the crafting items tag. - * - * @param tag - * @return - */ - public static Aspect getAspect( final NBTTagCompound tag ) - { - if( ( tag != null ) && tag.hasKey( NBTKEY_ASPECT ) ) - { - // Get the aspect - return Aspect.getAspect( tag.getString( NBTKEY_ASPECT ) ); - } - return null; - } + /** + * Gets the aspect stored in the crafting items tag. + * + * @param tag + * @return + */ + public static Aspect getAspect(final NBTTagCompound tag) { + if ((tag != null) && tag.hasKey(NBTKEY_ASPECT)) { + // Get the aspect + return Aspect.getAspect(tag.getString(NBTKEY_ASPECT)); + } + return null; + } - /** - * Sets the aspect of the item stack. - * - * @param stack - * @param aspect - */ - public static void setAspect( final ItemStack stack, final Aspect aspect ) - { - // Null check - if( aspect == null ) - { - // Clear the aspect - stack.setTagCompound( null ); - return; - } + /** + * Sets the aspect of the item stack. + * + * @param stack + * @param aspect + */ + public static void setAspect(final ItemStack stack, final Aspect aspect) { + // Null check + if (aspect == null) { + // Clear the aspect + stack.setTagCompound(null); + return; + } - NBTTagCompound tag = null; + NBTTagCompound tag = null; - // Is there a tag? - if( !stack.hasTagCompound() ) - { - // Create the tag - tag = new NBTTagCompound(); + // Is there a tag? + if (!stack.hasTagCompound()) { + // Create the tag + tag = new NBTTagCompound(); - // Set the tag - stack.setTagCompound( tag ); - } - else - { - tag = stack.getTagCompound(); - } + // Set the tag + stack.setTagCompound(tag); + } else { + tag = stack.getTagCompound(); + } - // Set the aspect - tag.setString( NBTKEY_ASPECT, aspect.getTag() ); - } + // Set the aspect + tag.setString(NBTKEY_ASPECT, aspect.getTag()); + } - @Override - public void addInformation( final ItemStack stack, final EntityPlayer player, final List list, final boolean advancedInfo ) - { - // Call super - super.addInformation( stack, player, list, advancedInfo ); + @Override + public void addInformation( + final ItemStack stack, final EntityPlayer player, final List list, final boolean advancedInfo) { + // Call super + super.addInformation(stack, player, list, advancedInfo); - // Is there an aspect associated? - Aspect aspect = ItemCraftingAspect.getAspect( stack ); - if( aspect != null ) - { - // Has the player discovered this aspect? - if( ItemCraftingAspect.canPlayerSeeAspect( player, aspect ) ) - { - // Add the aspect info - list.add( aspect.getLocalizedDescription() ); + // Is there an aspect associated? + Aspect aspect = ItemCraftingAspect.getAspect(stack); + if (aspect != null) { + // Has the player discovered this aspect? + if (ItemCraftingAspect.canPlayerSeeAspect(player, aspect)) { + // Add the aspect info + list.add(aspect.getLocalizedDescription()); - ModContainer mod = AspectHooks.aspectToMod.getOrDefault( aspect, null ); - if( mod != null ) - { - list.add( EnumChatFormatting.DARK_PURPLE.toString() + EnumChatFormatting.ITALIC.toString() + mod.getName() ); - } - } - else - { - // Show unknown - list.add( StatCollector.translateToLocal( "tc.aspect.unknown" ) ); - } - } - } + ModContainer mod = AspectHooks.aspectToMod.getOrDefault(aspect, null); + if (mod != null) { + list.add(EnumChatFormatting.DARK_PURPLE.toString() + + EnumChatFormatting.ITALIC.toString() + + mod.getName()); + } + } else { + // Show unknown + list.add(StatCollector.translateToLocal("tc.aspect.unknown")); + } + } + } - @Override - @SideOnly(Side.CLIENT) - public int getColorFromItemStack( final ItemStack stack, final int renderPass ) - { - // Is there an aspect associated? - Aspect aspect = ItemCraftingAspect.getAspect( stack ); - if( aspect != null ) - { - // Return it's color - return aspect.getColor(); - } + @Override + @SideOnly(Side.CLIENT) + public int getColorFromItemStack(final ItemStack stack, final int renderPass) { + // Is there an aspect associated? + Aspect aspect = ItemCraftingAspect.getAspect(stack); + if (aspect != null) { + // Return it's color + return aspect.getColor(); + } - // Pass to super - return super.getColorFromItemStack( stack, renderPass ); - } + // Pass to super + return super.getColorFromItemStack(stack, renderPass); + } - @Override - public String getItemStackDisplayName( final ItemStack stack ) - { - return this.getUnlocalizedNameInefficiently( stack ); - } + @Override + public String getItemStackDisplayName(final ItemStack stack) { + return this.getUnlocalizedNameInefficiently(stack); + } - @Override - @SideOnly(Side.CLIENT) - public void getSubItems( final Item item, final CreativeTabs par2CreativeTabs, final List itemList ) - { - // Don't show these - /* - for( Aspect aspect : Aspect.aspects.values() ) - { - ItemStack stack = new ItemStack( this, 1, 0 ); - ItemCraftingAspect.setAspect( stack, aspect ); - itemList.add( stack ); - } - */ - } + @Override + @SideOnly(Side.CLIENT) + public void getSubItems(final Item item, final CreativeTabs par2CreativeTabs, final List itemList) { + // Don't show these + /* + for( Aspect aspect : Aspect.aspects.values() ) + { + ItemStack stack = new ItemStack( this, 1, 0 ); + ItemCraftingAspect.setAspect( stack, aspect ); + itemList.add( stack ); + } + */ + } - @Override - @SideOnly(Side.CLIENT) - public String getUnlocalizedName( final ItemStack stack ) - { - Aspect aspect = ItemCraftingAspect.getAspect( stack ); + @Override + @SideOnly(Side.CLIENT) + public String getUnlocalizedName(final ItemStack stack) { + Aspect aspect = ItemCraftingAspect.getAspect(stack); - // Null check - if( aspect != null ) - { - // Get the player - EntityPlayer player = Minecraft.getMinecraft().thePlayer; + // Null check + if (aspect != null) { + // Get the player + EntityPlayer player = Minecraft.getMinecraft().thePlayer; - // Has the player discovered the aspect? - if( ItemCraftingAspect.canPlayerSeeAspect( player, aspect ) ) - { - // Show name - return aspect.getName(); - } - } + // Has the player discovered the aspect? + if (ItemCraftingAspect.canPlayerSeeAspect(player, aspect)) { + // Show name + return aspect.getName(); + } + } - // Show unknown - return "tc.aspect.unknown"; + // Show unknown + return "tc.aspect.unknown"; + } - } - - @SideOnly(Side.CLIENT) - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - // Handled by special renderer - } + @SideOnly(Side.CLIENT) + @Override + public void registerIcons(final IIconRegister par1IconRegister) { + // Handled by special renderer + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemEnum.java b/src/main/java/thaumicenergistics/common/items/ItemEnum.java index 26124eee..b8fd8d57 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemEnum.java +++ b/src/main/java/thaumicenergistics/common/items/ItemEnum.java @@ -10,95 +10,86 @@ import thaumicenergistics.common.ThaumicEnergistics; * @author Nividica * */ -public enum ItemEnum -{ - ITEM_AEPART ("part.base", new ItemAEPart()), - ESSENTIA_CELL ("storage.essentia", new ItemEssentiaCell()), - STORAGE_COMPONENT ("storage.component", new ItemStorageComponent()), - STORAGE_CASING ("storage.casing", new ItemStorageCasing()), - MATERIAL ("material", new ItemMaterial()), - WIRELESS_TERMINAL ("wireless.essentia.terminal", new ItemWirelessEssentiaTerminal()), - KNOWLEDGE_CORE ("knowledge.core", new ItemKnowledgeCore()), - FOCUS_AEWRENCH ("focus.aewrench", new ItemFocusAEWrench()), - CRAFTING_ASPECT ("crafting.aspect", new ItemCraftingAspect()), - GOLEM_WIFI_BACKPACK ("golem.wifi.backpack", new ItemGolemWirelessBackpack()); +public enum ItemEnum { + ITEM_AEPART("part.base", new ItemAEPart()), + ESSENTIA_CELL("storage.essentia", new ItemEssentiaCell()), + STORAGE_COMPONENT("storage.component", new ItemStorageComponent()), + STORAGE_CASING("storage.casing", new ItemStorageCasing()), + MATERIAL("material", new ItemMaterial()), + WIRELESS_TERMINAL("wireless.essentia.terminal", new ItemWirelessEssentiaTerminal()), + KNOWLEDGE_CORE("knowledge.core", new ItemKnowledgeCore()), + FOCUS_AEWRENCH("focus.aewrench", new ItemFocusAEWrench()), + CRAFTING_ASPECT("crafting.aspect", new ItemCraftingAspect()), + GOLEM_WIFI_BACKPACK("golem.wifi.backpack", new ItemGolemWirelessBackpack()); - /** - * Cache of the enum values - */ - public static final ItemEnum[] VALUES = ItemEnum.values(); + /** + * Cache of the enum values + */ + public static final ItemEnum[] VALUES = ItemEnum.values(); - /** - * Internal name of the item. - */ - private final String internalName; + /** + * Internal name of the item. + */ + private final String internalName; - /** - * The actual item. - */ - private Item item; + /** + * The actual item. + */ + private Item item; - private ItemEnum( final String internalName, final Item item ) - { - this.internalName = internalName; + private ItemEnum(final String internalName, final Item item) { + this.internalName = internalName; - this.item = item; + this.item = item; - this.item.setCreativeTab( ThaumicEnergistics.ThETab ); - } + this.item.setCreativeTab(ThaumicEnergistics.ThETab); + } - /** - * Gets an item stack of size 1 with the specified damage value. - * - * @param damageValue - * @return - */ - public ItemStack getDMGStack( final int damageValue ) - { - return this.getDMGStack( damageValue, 1 ); - } + /** + * Gets an item stack of size 1 with the specified damage value. + * + * @param damageValue + * @return + */ + public ItemStack getDMGStack(final int damageValue) { + return this.getDMGStack(damageValue, 1); + } - /** - * Gets an item stack of the specified size and damage value. - * - * @param damageValue - * @param size - * @return - */ - public ItemStack getDMGStack( final int damageValue, final int size ) - { - return new ItemStack( this.item, size, damageValue ); - } + /** + * Gets an item stack of the specified size and damage value. + * + * @param damageValue + * @param size + * @return + */ + public ItemStack getDMGStack(final int damageValue, final int size) { + return new ItemStack(this.item, size, damageValue); + } - public String getInternalName() - { - return this.internalName; - } + public String getInternalName() { + return this.internalName; + } - public Item getItem() - { - return this.item; - } + public Item getItem() { + return this.item; + } - /** - * Gets an item stack of size 1. - * - * @return - */ - public ItemStack getStack() - { - return this.getStack( 1 ); - } - - /** - * Gets an item stack of the specified size. - * - * @param size - * @return - */ - public ItemStack getStack( final int size ) - { - return new ItemStack( this.item, size ); - } + /** + * Gets an item stack of size 1. + * + * @return + */ + public ItemStack getStack() { + return this.getStack(1); + } + /** + * Gets an item stack of the specified size. + * + * @param size + * @return + */ + public ItemStack getStack(final int size) { + return new ItemStack(this.item, size); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemEssentiaCell.java b/src/main/java/thaumicenergistics/common/items/ItemEssentiaCell.java index 205f9964..62a3145b 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemEssentiaCell.java +++ b/src/main/java/thaumicenergistics/common/items/ItemEssentiaCell.java @@ -1,11 +1,5 @@ package thaumicenergistics.common.items; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.lwjgl.input.Keyboard; import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.implementations.tiles.IMEChest; @@ -15,6 +9,10 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.core.localization.GuiText; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -27,6 +25,7 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import org.lwjgl.input.Keyboard; import thaumicenergistics.api.storage.IAspectStack; import thaumicenergistics.client.textures.BlockTextureManager; import thaumicenergistics.common.ThEGuiHandler; @@ -44,415 +43,393 @@ import thaumicenergistics.common.storage.EnumEssentiaStorageTypes; * @author Nividica * */ -public class ItemEssentiaCell - extends Item - implements ICellHandler -{ - /** - * Status of the cell. - */ - private static final int CELL_STATUS_MISSING = 0, CELL_STATUS_HAS_ROOM = 1, CELL_STATUS_TYPES_FULL = 2, CELL_STATUS_FULL = 3; +public class ItemEssentiaCell extends Item implements ICellHandler { + /** + * Status of the cell. + */ + private static final int CELL_STATUS_MISSING = 0, + CELL_STATUS_HAS_ROOM = 1, + CELL_STATUS_TYPES_FULL = 2, + CELL_STATUS_FULL = 3; - /** - * Icons for each type. - */ - private IIcon[] icons; + /** + * Icons for each type. + */ + private IIcon[] icons; - public ItemEssentiaCell() - { - // Add the handler to AE2 - AEApi.instance().registries().cell().addCellHandler( this ); + public ItemEssentiaCell() { + // Add the handler to AE2 + AEApi.instance().registries().cell().addCellHandler(this); - // Set max stack size to 1 - this.setMaxStackSize( 1 ); + // Set max stack size to 1 + this.setMaxStackSize(1); - // No damage - this.setMaxDamage( 0 ); + // No damage + this.setMaxDamage(0); - // Has sub-types - this.setHasSubtypes( true ); - } - - /** - * Adds the contents of the cell to the description tooltip. - * - * @param cellHandler - * @param displayList - * @param player - */ - private void addContentsToCellDescription( final HandlerItemEssentiaCell cellHandler, final List displayList, final EntityPlayer player ) - { - // Get the list of stored aspects - List cellAspects = cellHandler.getStoredEssentia(); - - // Sort the list - Collections.sort( cellAspects, new AspectStackComparator() ); - - for( IAspectStack currentStack : cellAspects ) - { - if( currentStack != null ) - { - // Get the chat color - String aspectChatColor = currentStack.getChatColor(); - - // Build the display string - String aspectInfo = String.format( " %s%s%s x %d", aspectChatColor, currentStack.getAspectName( player ), - EnumChatFormatting.WHITE, currentStack.getStackSize() ); - - // Add to the list - displayList.add( aspectInfo ); - } - } - - } - - /** - * Adds the partitions of the cell to the description tooltip. - * - * @param cellHandler - * @param player - */ - private List addPartitionsToCellDescription(final HandlerItemEssentiaCell cellHandler, final EntityPlayer player) { - return cellHandler.getPartitionAspects().stream() - .filter(Objects::nonNull) - .map(aspect -> new AspectStack(aspect, 1)) - .sorted(new AspectStackComparator()) - .map(aspect -> String.format(" %s%s", aspect.getChatColor(), aspect.getAspectName(player))) - .collect(Collectors.toList()); + // Has sub-types + this.setHasSubtypes(true); } - /** - * Creates the cell tooltip. - */ - @Override - public void addInformation( final ItemStack essentiaCell, final EntityPlayer player, final List displayList, final boolean advancedItemTooltips ) - { - // Get the contents of the cell - IMEInventoryHandler handler = AEApi.instance().registries().cell() - .getCellInventory( essentiaCell, null, StorageChannel.FLUIDS ); + /** + * Adds the contents of the cell to the description tooltip. + * + * @param cellHandler + * @param displayList + * @param player + */ + private void addContentsToCellDescription( + final HandlerItemEssentiaCell cellHandler, final List displayList, final EntityPlayer player) { + // Get the list of stored aspects + List cellAspects = cellHandler.getStoredEssentia(); - // Ensure we have a cell inventory handler - if( !( handler instanceof HandlerItemEssentiaCell ) ) - { - return; - } + // Sort the list + Collections.sort(cellAspects, new AspectStackComparator()); - // Cast to cell inventory handler - HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell)handler; + for (IAspectStack currentStack : cellAspects) { + if (currentStack != null) { + // Get the chat color + String aspectChatColor = currentStack.getChatColor(); - // Create the bytes tooltip - String bytesTip = String.format( ThEStrings.Tooltip_CellBytes.getLocalized(), cellHandler.getUsedBytes(), cellHandler.getTotalBytes() ); + // Build the display string + String aspectInfo = String.format( + " %s%s%s x %d", + aspectChatColor, + currentStack.getAspectName(player), + EnumChatFormatting.WHITE, + currentStack.getStackSize()); - // Create the types tooltip - String typesTip = String.format( ThEStrings.Tooltip_CellTypes.getLocalized(), cellHandler.getUsedTypes(), cellHandler.getTotalTypes() ); + // Add to the list + displayList.add(aspectInfo); + } + } + } - // Add the tooltips - displayList.add( bytesTip ); - displayList.add( typesTip ); + /** + * Adds the partitions of the cell to the description tooltip. + * + * @param cellHandler + * @param player + */ + private List addPartitionsToCellDescription( + final HandlerItemEssentiaCell cellHandler, final EntityPlayer player) { + return cellHandler.getPartitionAspects().stream() + .filter(Objects::nonNull) + .map(aspect -> new AspectStack(aspect, 1)) + .sorted(new AspectStackComparator()) + .map(aspect -> String.format(" %s%s", aspect.getChatColor(), aspect.getAspectName(player))) + .collect(Collectors.toList()); + } - // Is the cell pre-formated? - if( cellHandler.isPartitioned() ) - { - displayList.add( GuiText.Partitioned.getLocal() ); + /** + * Creates the cell tooltip. + */ + @Override + public void addInformation( + final ItemStack essentiaCell, + final EntityPlayer player, + final List displayList, + final boolean advancedItemTooltips) { + // Get the contents of the cell + IMEInventoryHandler handler = + AEApi.instance().registries().cell().getCellInventory(essentiaCell, null, StorageChannel.FLUIDS); - if( Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || ( Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ) ) ) - { - // Add information about the partitioned essentia types in the cell - displayList.add(GuiText.Filter.getLocal() + ": "); + // Ensure we have a cell inventory handler + if (!(handler instanceof HandlerItemEssentiaCell)) { + return; + } + + // Cast to cell inventory handler + HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell) handler; + + // Create the bytes tooltip + String bytesTip = String.format( + ThEStrings.Tooltip_CellBytes.getLocalized(), cellHandler.getUsedBytes(), cellHandler.getTotalBytes()); + + // Create the types tooltip + String typesTip = String.format( + ThEStrings.Tooltip_CellTypes.getLocalized(), cellHandler.getUsedTypes(), cellHandler.getTotalTypes()); + + // Add the tooltips + displayList.add(bytesTip); + displayList.add(typesTip); + + // Is the cell pre-formated? + if (cellHandler.isPartitioned()) { + displayList.add(GuiText.Partitioned.getLocal()); + + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || (Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))) { + // Add information about the partitioned essentia types in the cell + displayList.add(GuiText.Filter.getLocal() + ": "); displayList.addAll(addPartitionsToCellDescription(cellHandler, player)); - } - } + } + } - // Does the cell have anything stored? - if( cellHandler.getUsedTypes() > 0 ) - { - // Is control being held? - if( Keyboard.isKeyDown( Keyboard.KEY_LCONTROL ) || ( Keyboard.isKeyDown( Keyboard.KEY_RCONTROL ) ) ) - { - displayList.add(ThEStrings.Tooltip_CellContains.getLocalized() + ":"); - // Add information about the essentia types in the cell - this.addContentsToCellDescription( cellHandler, displayList, player ); - } - else - { - // Let the user know they can hold shift - displayList.add( EnumChatFormatting.WHITE + EnumChatFormatting.ITALIC.toString() + - ThEStrings.Tooltip_ItemStackDetails.getLocalized() ); - } - } + // Does the cell have anything stored? + if (cellHandler.getUsedTypes() > 0) { + // Is control being held? + if (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || (Keyboard.isKeyDown(Keyboard.KEY_RCONTROL))) { + displayList.add(ThEStrings.Tooltip_CellContains.getLocalized() + ":"); + // Add information about the essentia types in the cell + this.addContentsToCellDescription(cellHandler, displayList, player); + } else { + // Let the user know they can hold shift + displayList.add(EnumChatFormatting.WHITE + + EnumChatFormatting.ITALIC.toString() + + ThEStrings.Tooltip_ItemStackDetails.getLocalized()); + } + } + } - } + /** + * How much power is required by the cell each tick. + */ + @Override + public double cellIdleDrain(final ItemStack itemStack, final IMEInventory handler) { + return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].idleAEPowerDrain; + } - /** - * How much power is required by the cell each tick. - */ - @Override - public double cellIdleDrain( final ItemStack itemStack, final IMEInventory handler ) - { - return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].idleAEPowerDrain; - } + /** + * Gets a handler for the cell. + */ + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack essentiaCell, final ISaveProvider saveProvider, final StorageChannel channel) { + // Ensure the channel is fluid and there is an appropriate item. + if ((channel != StorageChannel.FLUIDS) || !(essentiaCell.getItem() instanceof ItemEssentiaCell)) { + return null; + } - /** - * Gets a handler for the cell. - */ - @Override - public IMEInventoryHandler getCellInventory( final ItemStack essentiaCell, final ISaveProvider saveProvider, final StorageChannel channel ) - { - // Ensure the channel is fluid and there is an appropriate item. - if( ( channel != StorageChannel.FLUIDS ) || !( essentiaCell.getItem() instanceof ItemEssentiaCell ) ) - { - return null; - } + // Is the type creative? + if (essentiaCell.getItemDamage() == EnumEssentiaStorageTypes.Type_Creative.index) { + // Return a creative handler. + return new HandlerItemEssentiaCellCreative(essentiaCell, saveProvider); + } - // Is the type creative? - if( essentiaCell.getItemDamage() == EnumEssentiaStorageTypes.Type_Creative.index ) - { - // Return a creative handler. - return new HandlerItemEssentiaCellCreative( essentiaCell, saveProvider ); - } + // Return a standard handler. + return new HandlerItemEssentiaCell(essentiaCell, saveProvider); + } - // Return a standard handler. - return new HandlerItemEssentiaCell( essentiaCell, saveProvider ); - } + /** + * Gets the cell's icon. + */ + @Override + public IIcon getIconFromDamage(final int dmg) { + // Clamp the index + int index = MathHelper.clamp_int(dmg, 0, EnumEssentiaStorageTypes.fromIndex.length - 1); - /** - * Gets the cell's icon. - */ - @Override - public IIcon getIconFromDamage( final int dmg ) - { - // Clamp the index - int index = MathHelper.clamp_int( dmg, 0, EnumEssentiaStorageTypes.fromIndex.length - 1 ); + // Return the icon + return this.icons[index]; + } - // Return the icon - return this.icons[index]; - } + /** + * Gets the rarity of the cell. + */ + @Override + public EnumRarity getRarity(final ItemStack itemStack) { + // Get the index based off of the meta data + int index = MathHelper.clamp_int(itemStack.getItemDamage(), 0, EnumEssentiaStorageTypes.fromIndex.length - 1); - /** - * Gets the rarity of the cell. - */ - @Override - public EnumRarity getRarity( final ItemStack itemStack ) - { - // Get the index based off of the meta data - int index = MathHelper.clamp_int( itemStack.getItemDamage(), 0, EnumEssentiaStorageTypes.fromIndex.length - 1 ); + // Return the rarity + return EnumEssentiaStorageTypes.fromIndex[index].rarity; + } - // Return the rarity - return EnumEssentiaStorageTypes.fromIndex[index].rarity; - } + /** + * Gets the status of the cell. + * Full | Type Full | Has Room + */ + @Override + public int getStatusForCell(final ItemStack essentiaCell, final IMEInventory handler) { + // Do we have a handler? + if (handler == null) { + return ItemEssentiaCell.CELL_STATUS_MISSING; + } - /** - * Gets the status of the cell. - * Full | Type Full | Has Room - */ - @Override - public int getStatusForCell( final ItemStack essentiaCell, final IMEInventory handler ) - { - // Do we have a handler? - if( handler == null ) - { - return ItemEssentiaCell.CELL_STATUS_MISSING; - } + // Get the inventory handler + HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell) handler; - // Get the inventory handler - HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell)handler; + // Creative? + if (cellHandler.isCreative()) { + return ItemEssentiaCell.CELL_STATUS_TYPES_FULL; + } - // Creative? - if( cellHandler.isCreative() ) - { - return ItemEssentiaCell.CELL_STATUS_TYPES_FULL; - } + // Full bytes? + if (cellHandler.getUsedBytes() == cellHandler.getTotalBytes()) { + return ItemEssentiaCell.CELL_STATUS_FULL; + } - // Full bytes? - if( cellHandler.getUsedBytes() == cellHandler.getTotalBytes() ) - { - return ItemEssentiaCell.CELL_STATUS_FULL; - } + // Full types? + if (cellHandler.getUsedTypes() == cellHandler.getTotalTypes()) { + return ItemEssentiaCell.CELL_STATUS_TYPES_FULL; + } - // Full types? - if( cellHandler.getUsedTypes() == cellHandler.getTotalTypes() ) - { - return ItemEssentiaCell.CELL_STATUS_TYPES_FULL; - } + return ItemEssentiaCell.CELL_STATUS_HAS_ROOM; + } - return ItemEssentiaCell.CELL_STATUS_HAS_ROOM; + /** + * Gets the different cell sizes and places them on the creative tab. + */ + @Override + public void getSubItems(final Item item, final CreativeTabs creativeTab, final List listSubItems) { + for (EnumEssentiaStorageTypes type : EnumEssentiaStorageTypes.fromIndex) { + listSubItems.add(type.getCell()); + } + } - } + /** + * ME Chest icon + */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getTopTexture_Dark() { + return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0]; + } - /** - * Gets the different cell sizes and places them on the creative tab. - */ - @Override - public void getSubItems( final Item item, final CreativeTabs creativeTab, final List listSubItems ) - { - for( EnumEssentiaStorageTypes type : EnumEssentiaStorageTypes.fromIndex ) - { - listSubItems.add( type.getCell() ); - } - } + /** + * ME Chest icon + */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getTopTexture_Light() { + return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2]; + } - /** - * ME Chest icon - */ - @Override - @SideOnly(Side.CLIENT) - public IIcon getTopTexture_Dark() - { - return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0]; - } + /** + * ME Chest icon + */ + @Override + @SideOnly(Side.CLIENT) + public IIcon getTopTexture_Medium() { + return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1]; + } - /** - * ME Chest icon - */ - @Override - @SideOnly(Side.CLIENT) - public IIcon getTopTexture_Light() - { - return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2]; - } + @Override + public String getUnlocalizedName() { + return ThaumicEnergistics.MOD_ID + ".item.essentia.cell"; + } - /** - * ME Chest icon - */ - @Override - @SideOnly(Side.CLIENT) - public IIcon getTopTexture_Medium() - { - return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1]; - } + /** + * Name of the cell. + */ + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].cellName.getUnlocalized(); + } - @Override - public String getUnlocalizedName() - { - return ThaumicEnergistics.MOD_ID + ".item.essentia.cell"; - } + /** + * True if the specified item is an Essentia cell. + */ + @Override + public boolean isCell(final ItemStack itemStack) { + return itemStack.getItem() == this; + } - /** - * Name of the cell. - */ - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].cellName.getUnlocalized(); - } + /** + * Maximum storage, in bytes, the cell can hold. + * + * @param essentiaCell + * @return + */ + public int maxStorage(final ItemStack essentiaCell) { + return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].capacity; + } - /** - * True if the specified item is an Essentia cell. - */ - @Override - public boolean isCell( final ItemStack itemStack ) - { - return itemStack.getItem() == this; - } + /** + * The maximum number of types each cell can hold. + * + * @param essentiaCell + * @return + */ + public int maxTypes(final ItemStack essentiaCell) { + return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].maxStoredTypes; + } - /** - * Maximum storage, in bytes, the cell can hold. - * - * @param essentiaCell - * @return - */ - public int maxStorage( final ItemStack essentiaCell ) - { - return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].capacity; - } + /** + * Attempts to remove the storage component. + */ + @Override + public ItemStack onItemRightClick(final ItemStack essentiaCell, final World world, final EntityPlayer player) { + // Ensure the player is sneaking(holding shift) + if (!player.isSneaking()) { + return essentiaCell; + } - /** - * The maximum number of types each cell can hold. - * - * @param essentiaCell - * @return - */ - public int maxTypes( final ItemStack essentiaCell ) - { - return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].maxStoredTypes; - } + // Ensure this is not a creative cell + if (essentiaCell.getItemDamage() == EnumEssentiaStorageTypes.Type_Creative.index) { + return essentiaCell; + } - /** - * Attempts to remove the storage component. - */ - @Override - public ItemStack onItemRightClick( final ItemStack essentiaCell, final World world, final EntityPlayer player ) - { - // Ensure the player is sneaking(holding shift) - if( !player.isSneaking() ) - { - return essentiaCell; - } + // Get the handler + IMEInventoryHandler handler = + AEApi.instance().registries().cell().getCellInventory(essentiaCell, null, StorageChannel.FLUIDS); - // Ensure this is not a creative cell - if( essentiaCell.getItemDamage() == EnumEssentiaStorageTypes.Type_Creative.index ) - { - return essentiaCell; - } + // Is it the correct handler type? + if (!(handler instanceof HandlerItemEssentiaCell)) { + return essentiaCell; + } - // Get the handler - IMEInventoryHandler handler = AEApi.instance().registries().cell() - .getCellInventory( essentiaCell, null, StorageChannel.FLUIDS ); + // Cast + HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell) handler; - // Is it the correct handler type? - if( !( handler instanceof HandlerItemEssentiaCell ) ) - { - return essentiaCell; - } + // If the cell is empty, and the player can hold the casing + if ((cellHandler.getUsedBytes() == 0) + && (player.inventory.addItemStackToInventory(ItemEnum.STORAGE_CASING.getStack()))) { + // Return the storage component + return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].getComponent(1); + } - // Cast - HandlerItemEssentiaCell cellHandler = (HandlerItemEssentiaCell)handler; + // Can not remove storage component, return the current cell as is. + return essentiaCell; + } - // If the cell is empty, and the player can hold the casing - if( ( cellHandler.getUsedBytes() == 0 ) && ( player.inventory.addItemStackToInventory( ItemEnum.STORAGE_CASING.getStack() ) ) ) - { - // Return the storage component - return EnumEssentiaStorageTypes.fromIndex[essentiaCell.getItemDamage()].getComponent( 1 ); - } + /** + * Shows the cell GUI. + */ + @Override + public void openChestGui( + final EntityPlayer player, + final IChestOrDrive chest, + final ICellHandler cellHandler, + final IMEInventoryHandler inv, + final ItemStack itemStack, + final StorageChannel channel) { + // Ensure this is the fluid channel + if (channel != StorageChannel.FLUIDS) { + return; + } - // Can not remove storage component, return the current cell as is. - return essentiaCell; - } + // Ensure we have a chest + if (chest != null) { + // Get a reference to the chest's inventories + IStorageMonitorable monitorable = + ((IMEChest) chest).getMonitorable(ForgeDirection.UNKNOWN, new PlayerSource(player, chest)); - /** - * Shows the cell GUI. - */ - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, - final ItemStack itemStack, final StorageChannel channel ) - { - // Ensure this is the fluid channel - if( channel != StorageChannel.FLUIDS ) - { - return; - } + // Ensure we got the inventories + if (monitorable != null) { + // Get the chest tile entity + TileEntity chestEntity = (TileEntity) chest; - // Ensure we have a chest - if( chest != null ) - { - // Get a reference to the chest's inventories - IStorageMonitorable monitorable = ( (IMEChest)chest ).getMonitorable( ForgeDirection.UNKNOWN, new PlayerSource( player, chest ) ); + // Show the terminal gui + ThEGuiHandler.launchGui( + ThEGuiHandler.ESSENTIA_CELL_ID, + player, + chestEntity.getWorldObj(), + chestEntity.xCoord, + chestEntity.yCoord, + chestEntity.zCoord); + } + } + } - // Ensure we got the inventories - if( monitorable != null ) - { - // Get the chest tile entity - TileEntity chestEntity = (TileEntity)chest; - - // Show the terminal gui - ThEGuiHandler.launchGui( ThEGuiHandler.ESSENTIA_CELL_ID, player, chestEntity.getWorldObj(), chestEntity.xCoord, chestEntity.yCoord, - chestEntity.zCoord ); - } - } - - } - - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - // Create the icon array - this.icons = new IIcon[EnumEssentiaStorageTypes.fromIndex.length]; - - // Add each type - for( int i = 0; i < this.icons.length; i++ ) - { - this.icons[i] = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":essentia.cell." + EnumEssentiaStorageTypes.fromIndex[i].suffix ); - } - } + @Override + public void registerIcons(final IIconRegister iconRegister) { + // Create the icon array + this.icons = new IIcon[EnumEssentiaStorageTypes.fromIndex.length]; + // Add each type + for (int i = 0; i < this.icons.length; i++) { + this.icons[i] = iconRegister.registerIcon( + ThaumicEnergistics.MOD_ID + ":essentia.cell." + EnumEssentiaStorageTypes.fromIndex[i].suffix); + } + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemFocusAEWrench.java b/src/main/java/thaumicenergistics/common/items/ItemFocusAEWrench.java index a55ce452..c2ca5db8 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemFocusAEWrench.java +++ b/src/main/java/thaumicenergistics/common/items/ItemFocusAEWrench.java @@ -37,393 +37,391 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class ItemFocusAEWrench - extends ItemFocusBasic -{ - - /** - * Wrench used for dismantling. - */ - private static ItemStack psuedoWrench = null; - - /** - * How much vis is cost to use the focus. - */ - private final static AspectList castCost = new AspectList(); - - public ItemFocusAEWrench() - { - if( ItemFocusAEWrench.castCost.size() == 0 ) - { - // Set the casting cost - ItemFocusAEWrench.castCost.add( Aspect.FIRE, 10 ); - ItemFocusAEWrench.castCost.add( Aspect.AIR, 10 ); - } - } - - /** - * Consumes the casting cost of the focus from he wand and spawns the - * activation beam. - * - * @param wand - * @param wandStack - * @param player - * @param beamX - * @param beamY - * @param beamZ - */ - private static void consumeVisAndSpawnBeam( final ItemWandCasting wand, final ItemStack wandStack, final EntityPlayer player, final double beamX, - final double beamY, final double beamZ ) - { - // Use vis - wand.consumeAllVis( wandStack, player, ItemFocusAEWrench.castCost, true, false ); - - // Spawn beam - Packet_R_ParticleFX.createWrenchFX( - player.worldObj, player.posX, player.posY, player.posZ, - beamX, beamY, beamZ, Aspect.ENERGY, 20.0f ); - } - - private static ItemStack getWrench() - { - // Has the wrench already be initialized, and can it be? - if( ( ItemFocusAEWrench.psuedoWrench == null ) && FeatureRegistry.instance().featureWrenchFocus.isAvailable() ) - { - ItemFocusAEWrench.psuedoWrench = AEApi.instance().definitions().items().certusQuartzWrench().maybeStack( 1 ).orNull(); - } - - return ItemFocusAEWrench.psuedoWrench; - } - - /** - * Returns the wand if it is valid and contains enough charge to perform a - * cast. - * - * @param stack - * @param player - * @return - */ - private static ItemWandCasting wandIfValid( final ItemStack stack, final EntityPlayer player ) - { - // Ensure it is a wand or staff - if( !ThEUtils.isItemValidWand( stack, true ) ) - { - return null; - } - - // Get the wand - ItemWandCasting wand = (ItemWandCasting)stack.getItem(); - - // Ensure there is enough vis for the cast - if( !wand.consumeAllVis( stack, player, ItemFocusAEWrench.castCost, false, false ) ) - { - // Not enough vis - return null; - } - - // Wand is good and is charged - return wand; - } - - /** - * Called after the client has sent the request to the server. - * Because where your eyes are matters a great deal. - * - * @param player - * @param eyeHeight - * @param x - * @param y - * @param z - * @param side - */ - public static void performDismantleOnPartHost( final EntityPlayer player, final float eyeHeight, final MovingObjectPosition position ) - { - // Get the wrench - ItemStack wrench; - - // Ensure there is a wrench - if( ( wrench = ItemFocusAEWrench.getWrench() ) == null ) - { - return; - } - - // Get the item the player is holding - ItemStack heldItem = player.getCurrentEquippedItem(); - - // Ensure it is a charged wand - ItemWandCasting wand; - if( ( wand = ItemFocusAEWrench.wandIfValid( heldItem, player ) ) == null ) - { - return; - } - - // Update the AE render mode, in-case they are hiding facades - CommonHelper.proxy.updateRenderMode( player ); - - // Set the eye height - PartPlacement.setEyeHeight( eyeHeight ); - - // Wrench the target - PartPlacement.place( wrench, position.blockX, position.blockY, position.blockZ, position.sideHit, player, player.worldObj, - PlaceType.INTERACT_FIRST_PASS, 0 ); - - // Reset the AE render mode - CommonHelper.proxy.updateRenderMode( null ); - - // Take vis and show beam - ItemFocusAEWrench.consumeVisAndSpawnBeam( wand, heldItem, player, position.blockX, position.blockY, position.blockZ ); - } - - /** - * Attempts to use the focus. - * Position must contain a block hit. - * - * @param world - * @param player - * @param position - * @param wandStack - * @param action - * @return - */ - private boolean onUse( final World world, final EntityPlayer player, final MovingObjectPosition position, final ItemStack wandStack, - final Action action ) - { - // For all current actions the player must be sneaking - if( !player.isSneaking() ) - { - return false; - } - - // Get the wand - ItemWandCasting wand; - if( ( wand = ItemFocusAEWrench.wandIfValid( wandStack, player ) ) == null ) - { - // Wand does not have enough charge. - return false; - } - - // Ensure the player is allowed to modify the block - if( !world.canMineBlock( player, position.blockX, position.blockY, position.blockZ ) ) - { - // Player can not modify block - return false; - } - - // Get the tile - TileEntity te = world.getTileEntity( position.blockX, position.blockY, position.blockZ ); - - // Is there a valid tile entity? - if( te == null ) - { - // Nothing to do here. - return false; - } - - // Is the entity a pedestal? - if( ( te instanceof TilePedestal ) || - ( te.getClass().getName().equals( "cofh.thermalexpansion.block.cache.TileCache" ) && ( action != Action.LEFT_CLICK_BLOCK ) ) ) - { - return false; - } - - // Is the block an part host? - boolean isPartHost = ( te instanceof IPartHost ); - - // Was a part host right clicked? - if( isPartHost && ( action == Action.RIGHT_CLICK_BLOCK ) ) - { - // Send packet if client side - if( world.isRemote ) - { - Packet_S_WrenchFocus.sendWrenchFocusRequest( player, position ); - } - - return true; - } - - // All further actions ignored on client side. - if( ( world.isRemote ) || !( player instanceof EntityPlayerMP ) ) - { - return true; - } - - // Was a non-part host left clicked? - if( !isPartHost && ( action == Action.LEFT_CLICK_BLOCK ) ) - { - // Get the block - Block block = world.getBlock( position.blockX, position.blockY, position.blockZ ); - - // Attempt to rotate the block - if( block.rotateBlock( world, position.blockX, position.blockY, position.blockZ, ForgeDirection.getOrientation( position.sideHit ) ) ) - { - // Take vis and show beam - ItemFocusAEWrench.consumeVisAndSpawnBeam( wand, wandStack, player, position.blockX, position.blockY, position.blockZ ); - - // Fire an update - block.onNeighborBlockChange( world, position.blockX, position.blockY, position.blockZ, Blocks.air ); - } - - return true; - } - - // Save what the player is holding - ItemStack prevHolding = player.getCurrentEquippedItem(); - - // Set to true if the focus did something. - boolean handled = false; - - try - { - ItemStack pWrench = ItemFocusAEWrench.getWrench().copy(); - - // Set the wrench as what the player is holding - player.setCurrentItemOrArmor( 0, pWrench ); - - // The sneak state of the player depends on what was clicked - - // Was a part host left clicked? - if( isPartHost && ( action == Action.LEFT_CLICK_BLOCK ) ) - { - // Set the player as not sneaking - player.setSneaking( false ); - } - - // Was a non-part host right clicked? - //if( !isPartHost && ( action == Action.RIGHT_CLICK_BLOCK ) ) - //{ - // Ensure the player is sneaking - //player.setSneaking( true ); - //} - - // Calculate the offsets - float xOffset = (float)position.hitVec.xCoord - position.blockX; - float yOffset = (float)position.hitVec.yCoord - position.blockY; - float zOffset = (float)position.hitVec.zCoord - position.blockZ; - - // Activate - handled = ( (EntityPlayerMP)player ).theItemInWorldManager.activateBlockOrUseItem( player, world, ItemFocusAEWrench.getWrench(), - position.blockX, position.blockY, position.blockZ, position.sideHit, xOffset, yOffset, zOffset ); - - // Was it handled or is the block gone? - if( handled || ( world.getBlock( position.blockX, position.blockY, position.blockZ ) == Blocks.air ) ) - { - - // Take vis and show beam - ItemFocusAEWrench.consumeVisAndSpawnBeam( wand, wandStack, player, position.blockX, position.blockY, position.blockZ ); - } - } - - finally - { - // Restore what the player was holding and sneak state - player.setCurrentItemOrArmor( 0, prevHolding ); - player.setSneaking( true ); - } - - return handled; - } - - @Override - public int getActivationCooldown( final ItemStack focusstack ) - { - // 250ms between uses - return 250; - } - - @Override - public int getFocusColor( final ItemStack itemStack ) - { - return Aspect.ENERGY.getColor(); - } - - @Override - public FocusUpgradeType[] getPossibleUpgradesByRank( final ItemStack itemStack, final int rank ) - { - return new FocusUpgradeType[0]; - } - - @Override - public String getUnlocalizedName() - { - try - { - // Is the focus enabled? - if( FeatureRegistry.instance().featureWrenchFocus.isAvailable() ) - { - // Wrench enabled - return ThEStrings.Item_FocusAEWrench.getUnlocalized(); - } - } - catch( Exception e ) - { - - } - - // Wrench disabled - return ThEStrings.Item_FocusAEWrench_Disabled.getUnlocalized(); - } - - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return this.getUnlocalizedName(); - } - - @Override - public AspectList getVisCost( final ItemStack itemStack ) - { - - return ItemFocusAEWrench.castCost; - } - - /** - * Called when the player left-clicks - */ - @Override - public boolean onEntitySwing( final EntityLivingBase entity, final ItemStack wandStack ) - { - // Is the entity a player? - if( entity instanceof EntityPlayer ) - { - // Cast to player - EntityPlayer player = (EntityPlayer)entity; - - // Ray trace - MovingObjectPosition position = this.getMovingObjectPositionFromPlayer( player.worldObj, player, true ); - - // Was a block hit? - if( ( position != null ) && ( position.typeOfHit == MovingObjectType.BLOCK ) ) - { - // Use the focus - return this.onUse( player.worldObj, player, position, wandStack, Action.LEFT_CLICK_BLOCK ); - } - } - - return false; - - } - - /** - * Called when the player right-clicks - */ - @Override - public ItemStack onFocusRightClick( final ItemStack wandStack, final World world, final EntityPlayer player, final MovingObjectPosition position ) - { - - // Was a block hit? - if( ( position != null ) && ( position.typeOfHit == MovingObjectType.BLOCK ) ) - { - // Use the focus - this.onUse( world, player, position, wandStack, Action.RIGHT_CLICK_BLOCK ); - } - - return wandStack; - } - - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - this.icon = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":foci.aewrench" ); - } - +public class ItemFocusAEWrench extends ItemFocusBasic { + + /** + * Wrench used for dismantling. + */ + private static ItemStack psuedoWrench = null; + + /** + * How much vis is cost to use the focus. + */ + private static final AspectList castCost = new AspectList(); + + public ItemFocusAEWrench() { + if (ItemFocusAEWrench.castCost.size() == 0) { + // Set the casting cost + ItemFocusAEWrench.castCost.add(Aspect.FIRE, 10); + ItemFocusAEWrench.castCost.add(Aspect.AIR, 10); + } + } + + /** + * Consumes the casting cost of the focus from he wand and spawns the + * activation beam. + * + * @param wand + * @param wandStack + * @param player + * @param beamX + * @param beamY + * @param beamZ + */ + private static void consumeVisAndSpawnBeam( + final ItemWandCasting wand, + final ItemStack wandStack, + final EntityPlayer player, + final double beamX, + final double beamY, + final double beamZ) { + // Use vis + wand.consumeAllVis(wandStack, player, ItemFocusAEWrench.castCost, true, false); + + // Spawn beam + Packet_R_ParticleFX.createWrenchFX( + player.worldObj, player.posX, player.posY, player.posZ, beamX, beamY, beamZ, Aspect.ENERGY, 20.0f); + } + + private static ItemStack getWrench() { + // Has the wrench already be initialized, and can it be? + if ((ItemFocusAEWrench.psuedoWrench == null) + && FeatureRegistry.instance().featureWrenchFocus.isAvailable()) { + ItemFocusAEWrench.psuedoWrench = AEApi.instance() + .definitions() + .items() + .certusQuartzWrench() + .maybeStack(1) + .orNull(); + } + + return ItemFocusAEWrench.psuedoWrench; + } + + /** + * Returns the wand if it is valid and contains enough charge to perform a + * cast. + * + * @param stack + * @param player + * @return + */ + private static ItemWandCasting wandIfValid(final ItemStack stack, final EntityPlayer player) { + // Ensure it is a wand or staff + if (!ThEUtils.isItemValidWand(stack, true)) { + return null; + } + + // Get the wand + ItemWandCasting wand = (ItemWandCasting) stack.getItem(); + + // Ensure there is enough vis for the cast + if (!wand.consumeAllVis(stack, player, ItemFocusAEWrench.castCost, false, false)) { + // Not enough vis + return null; + } + + // Wand is good and is charged + return wand; + } + + /** + * Called after the client has sent the request to the server. + * Because where your eyes are matters a great deal. + * + * @param player + * @param eyeHeight + * @param x + * @param y + * @param z + * @param side + */ + public static void performDismantleOnPartHost( + final EntityPlayer player, final float eyeHeight, final MovingObjectPosition position) { + // Get the wrench + ItemStack wrench; + + // Ensure there is a wrench + if ((wrench = ItemFocusAEWrench.getWrench()) == null) { + return; + } + + // Get the item the player is holding + ItemStack heldItem = player.getCurrentEquippedItem(); + + // Ensure it is a charged wand + ItemWandCasting wand; + if ((wand = ItemFocusAEWrench.wandIfValid(heldItem, player)) == null) { + return; + } + + // Update the AE render mode, in-case they are hiding facades + CommonHelper.proxy.updateRenderMode(player); + + // Set the eye height + PartPlacement.setEyeHeight(eyeHeight); + + // Wrench the target + PartPlacement.place( + wrench, + position.blockX, + position.blockY, + position.blockZ, + position.sideHit, + player, + player.worldObj, + PlaceType.INTERACT_FIRST_PASS, + 0); + + // Reset the AE render mode + CommonHelper.proxy.updateRenderMode(null); + + // Take vis and show beam + ItemFocusAEWrench.consumeVisAndSpawnBeam( + wand, heldItem, player, position.blockX, position.blockY, position.blockZ); + } + + /** + * Attempts to use the focus. + * Position must contain a block hit. + * + * @param world + * @param player + * @param position + * @param wandStack + * @param action + * @return + */ + private boolean onUse( + final World world, + final EntityPlayer player, + final MovingObjectPosition position, + final ItemStack wandStack, + final Action action) { + // For all current actions the player must be sneaking + if (!player.isSneaking()) { + return false; + } + + // Get the wand + ItemWandCasting wand; + if ((wand = ItemFocusAEWrench.wandIfValid(wandStack, player)) == null) { + // Wand does not have enough charge. + return false; + } + + // Ensure the player is allowed to modify the block + if (!world.canMineBlock(player, position.blockX, position.blockY, position.blockZ)) { + // Player can not modify block + return false; + } + + // Get the tile + TileEntity te = world.getTileEntity(position.blockX, position.blockY, position.blockZ); + + // Is there a valid tile entity? + if (te == null) { + // Nothing to do here. + return false; + } + + // Is the entity a pedestal? + if ((te instanceof TilePedestal) + || (te.getClass().getName().equals("cofh.thermalexpansion.block.cache.TileCache") + && (action != Action.LEFT_CLICK_BLOCK))) { + return false; + } + + // Is the block an part host? + boolean isPartHost = (te instanceof IPartHost); + + // Was a part host right clicked? + if (isPartHost && (action == Action.RIGHT_CLICK_BLOCK)) { + // Send packet if client side + if (world.isRemote) { + Packet_S_WrenchFocus.sendWrenchFocusRequest(player, position); + } + + return true; + } + + // All further actions ignored on client side. + if ((world.isRemote) || !(player instanceof EntityPlayerMP)) { + return true; + } + + // Was a non-part host left clicked? + if (!isPartHost && (action == Action.LEFT_CLICK_BLOCK)) { + // Get the block + Block block = world.getBlock(position.blockX, position.blockY, position.blockZ); + + // Attempt to rotate the block + if (block.rotateBlock( + world, + position.blockX, + position.blockY, + position.blockZ, + ForgeDirection.getOrientation(position.sideHit))) { + // Take vis and show beam + ItemFocusAEWrench.consumeVisAndSpawnBeam( + wand, wandStack, player, position.blockX, position.blockY, position.blockZ); + + // Fire an update + block.onNeighborBlockChange(world, position.blockX, position.blockY, position.blockZ, Blocks.air); + } + + return true; + } + + // Save what the player is holding + ItemStack prevHolding = player.getCurrentEquippedItem(); + + // Set to true if the focus did something. + boolean handled = false; + + try { + ItemStack pWrench = ItemFocusAEWrench.getWrench().copy(); + + // Set the wrench as what the player is holding + player.setCurrentItemOrArmor(0, pWrench); + + // The sneak state of the player depends on what was clicked + + // Was a part host left clicked? + if (isPartHost && (action == Action.LEFT_CLICK_BLOCK)) { + // Set the player as not sneaking + player.setSneaking(false); + } + + // Was a non-part host right clicked? + // if( !isPartHost && ( action == Action.RIGHT_CLICK_BLOCK ) ) + // { + // Ensure the player is sneaking + // player.setSneaking( true ); + // } + + // Calculate the offsets + float xOffset = (float) position.hitVec.xCoord - position.blockX; + float yOffset = (float) position.hitVec.yCoord - position.blockY; + float zOffset = (float) position.hitVec.zCoord - position.blockZ; + + // Activate + handled = ((EntityPlayerMP) player) + .theItemInWorldManager.activateBlockOrUseItem( + player, + world, + ItemFocusAEWrench.getWrench(), + position.blockX, + position.blockY, + position.blockZ, + position.sideHit, + xOffset, + yOffset, + zOffset); + + // Was it handled or is the block gone? + if (handled || (world.getBlock(position.blockX, position.blockY, position.blockZ) == Blocks.air)) { + + // Take vis and show beam + ItemFocusAEWrench.consumeVisAndSpawnBeam( + wand, wandStack, player, position.blockX, position.blockY, position.blockZ); + } + } finally { + // Restore what the player was holding and sneak state + player.setCurrentItemOrArmor(0, prevHolding); + player.setSneaking(true); + } + + return handled; + } + + @Override + public int getActivationCooldown(final ItemStack focusstack) { + // 250ms between uses + return 250; + } + + @Override + public int getFocusColor(final ItemStack itemStack) { + return Aspect.ENERGY.getColor(); + } + + @Override + public FocusUpgradeType[] getPossibleUpgradesByRank(final ItemStack itemStack, final int rank) { + return new FocusUpgradeType[0]; + } + + @Override + public String getUnlocalizedName() { + try { + // Is the focus enabled? + if (FeatureRegistry.instance().featureWrenchFocus.isAvailable()) { + // Wrench enabled + return ThEStrings.Item_FocusAEWrench.getUnlocalized(); + } + } catch (Exception e) { + + } + + // Wrench disabled + return ThEStrings.Item_FocusAEWrench_Disabled.getUnlocalized(); + } + + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return this.getUnlocalizedName(); + } + + @Override + public AspectList getVisCost(final ItemStack itemStack) { + + return ItemFocusAEWrench.castCost; + } + + /** + * Called when the player left-clicks + */ + @Override + public boolean onEntitySwing(final EntityLivingBase entity, final ItemStack wandStack) { + // Is the entity a player? + if (entity instanceof EntityPlayer) { + // Cast to player + EntityPlayer player = (EntityPlayer) entity; + + // Ray trace + MovingObjectPosition position = this.getMovingObjectPositionFromPlayer(player.worldObj, player, true); + + // Was a block hit? + if ((position != null) && (position.typeOfHit == MovingObjectType.BLOCK)) { + // Use the focus + return this.onUse(player.worldObj, player, position, wandStack, Action.LEFT_CLICK_BLOCK); + } + } + + return false; + } + + /** + * Called when the player right-clicks + */ + @Override + public ItemStack onFocusRightClick( + final ItemStack wandStack, + final World world, + final EntityPlayer player, + final MovingObjectPosition position) { + + // Was a block hit? + if ((position != null) && (position.typeOfHit == MovingObjectType.BLOCK)) { + // Use the focus + this.onUse(world, player, position, wandStack, Action.RIGHT_CLICK_BLOCK); + } + + return wandStack; + } + + @Override + public void registerIcons(final IIconRegister iconRegister) { + this.icon = iconRegister.registerIcon(ThaumicEnergistics.MOD_ID + ":foci.aewrench"); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemGolemWirelessBackpack.java b/src/main/java/thaumicenergistics/common/items/ItemGolemWirelessBackpack.java index 95a70ff9..da4828af 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemGolemWirelessBackpack.java +++ b/src/main/java/thaumicenergistics/common/items/ItemGolemWirelessBackpack.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.items; -import java.util.List; import appeng.api.features.INetworkEncodable; import appeng.core.localization.GuiText; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -19,127 +19,108 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public class ItemGolemWirelessBackpack - extends Item - implements INetworkEncodable -{ - public static enum BackpackSkins - { - Thaumium ("Thaum"), - Stone ("Stone"), - Straw ("Straw"), - GreatWood ("Wood"), - Flesh ("Flesh"), - Clay ("Clay"), - Iron ("Iron"), - Tallow ("Tallow"), - Gold ("Gold"), - Diamond ("Diamond"); +public class ItemGolemWirelessBackpack extends Item implements INetworkEncodable { + public static enum BackpackSkins { + Thaumium("Thaum"), + Stone("Stone"), + Straw("Straw"), + GreatWood("Wood"), + Flesh("Flesh"), + Clay("Clay"), + Iron("Iron"), + Tallow("Tallow"), + Gold("Gold"), + Diamond("Diamond"); - /** - * Array of skins. - */ - public static final BackpackSkins VALUES[] = BackpackSkins.values(); + /** + * Array of skins. + */ + public static final BackpackSkins VALUES[] = BackpackSkins.values(); - /** - * Skin texture. - */ - private ResourceLocation texture = null; + /** + * Skin texture. + */ + private ResourceLocation texture = null; - /** - * Texture ID of the skin - */ - private final String texID; + /** + * Texture ID of the skin + */ + private final String texID; - /** - * Private constructor - * - * @param ID - */ - private BackpackSkins( final String ID ) - { - this.texID = ID; - } + /** + * Private constructor + * + * @param ID + */ + private BackpackSkins(final String ID) { + this.texID = ID; + } - /** - * Gets the texture for this skin. - * - * @return - */ - public ResourceLocation getTextureLocation() - { - if( this.texture == null ) - { - this.texture = new ResourceLocation( ThaumicEnergistics.MOD_ID, "textures/models/golemBackpack/" + this.texID + ".png" ); - } - return this.texture; - } - } + /** + * Gets the texture for this skin. + * + * @return + */ + public ResourceLocation getTextureLocation() { + if (this.texture == null) { + this.texture = new ResourceLocation( + ThaumicEnergistics.MOD_ID, "textures/models/golemBackpack/" + this.texID + ".png"); + } + return this.texture; + } + } - private static final String NBT_ENCRYPTION_KEY = "wifiKey"; + private static final String NBT_ENCRYPTION_KEY = "wifiKey"; - public ItemGolemWirelessBackpack() - { - // Set the texture - this.setTextureName( ThaumicEnergistics.MOD_ID + ":golem.wifi.backpack" ); + public ItemGolemWirelessBackpack() { + // Set the texture + this.setTextureName(ThaumicEnergistics.MOD_ID + ":golem.wifi.backpack"); - // Set non stacking - this.setMaxStackSize( 1 ); + // Set non stacking + this.setMaxStackSize(1); - // Set non-damageable - this.setMaxDamage( 0 ); - } + // Set non-damageable + this.setMaxDamage(0); + } - @Override - @SideOnly(Side.CLIENT) - public void addInformation( final ItemStack stack, final EntityPlayer player, final List list, final boolean advancedInfo ) - { - if( stack.hasTagCompound() ) - { - list.add( GuiText.Linked.getLocal() ); - } - else - { - list.add( GuiText.Unlinked.getLocal() ); - } - } + @Override + @SideOnly(Side.CLIENT) + public void addInformation( + final ItemStack stack, final EntityPlayer player, final List list, final boolean advancedInfo) { + if (stack.hasTagCompound()) { + list.add(GuiText.Linked.getLocal()); + } else { + list.add(GuiText.Unlinked.getLocal()); + } + } - @Override - public String getEncryptionKey( final ItemStack stack ) - { - if( stack.hasTagCompound() && stack.stackTagCompound.hasKey( NBT_ENCRYPTION_KEY ) ) - { - return stack.stackTagCompound.getString( NBT_ENCRYPTION_KEY ); - } - return null; - } + @Override + public String getEncryptionKey(final ItemStack stack) { + if (stack.hasTagCompound() && stack.stackTagCompound.hasKey(NBT_ENCRYPTION_KEY)) { + return stack.stackTagCompound.getString(NBT_ENCRYPTION_KEY); + } + return null; + } - @Override - public String getUnlocalizedName() - { - return ThEStrings.Item_Golem_Wifi_Backpack.getUnlocalized(); - } + @Override + public String getUnlocalizedName() { + return ThEStrings.Item_Golem_Wifi_Backpack.getUnlocalized(); + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return this.getUnlocalizedName(); - } - - @Override - public void setEncryptionKey( final ItemStack stack, final String encKey, final String name ) - { - NBTTagCompound tag; - if( !stack.hasTagCompound() ) - { - tag = new NBTTagCompound(); - stack.stackTagCompound = tag; - } - else - { - tag = stack.stackTagCompound; - } - tag.setString( NBT_ENCRYPTION_KEY, encKey ); - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return this.getUnlocalizedName(); + } + @Override + public void setEncryptionKey(final ItemStack stack, final String encKey, final String name) { + NBTTagCompound tag; + if (!stack.hasTagCompound()) { + tag = new NBTTagCompound(); + stack.stackTagCompound = tag; + } else { + tag = stack.stackTagCompound; + } + tag.setString(NBT_ENCRYPTION_KEY, encKey); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemKnowledgeCore.java b/src/main/java/thaumicenergistics/common/items/ItemKnowledgeCore.java index 4db2dce9..2578f4ea 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemKnowledgeCore.java +++ b/src/main/java/thaumicenergistics/common/items/ItemKnowledgeCore.java @@ -14,46 +14,38 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public class ItemKnowledgeCore - extends Item -{ +public class ItemKnowledgeCore extends Item { - public ItemKnowledgeCore() - { - // Can not be damaged - this.setMaxDamage( 0 ); + public ItemKnowledgeCore() { + // Can not be damaged + this.setMaxDamage(0); - // Has no subtypes - this.setHasSubtypes( false ); + // Has no subtypes + this.setHasSubtypes(false); - // Can not stack - this.setMaxStackSize( 1 ); - } + // Can not stack + this.setMaxStackSize(1); + } - @Override - public void addInformation( final ItemStack kCore, final EntityPlayer player, final List tooltip, final boolean advancedItemTooltips ) - { + @Override + public void addInformation( + final ItemStack kCore, final EntityPlayer player, final List tooltip, final boolean advancedItemTooltips) {} - } + @Override + public String getUnlocalizedName() { + return ThEStrings.Item_KnowledgeCore.getUnlocalized(); + } - @Override - public String getUnlocalizedName() - { - return ThEStrings.Item_KnowledgeCore.getUnlocalized(); - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return ThEStrings.Item_KnowledgeCore.getUnlocalized(); + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return ThEStrings.Item_KnowledgeCore.getUnlocalized(); - } - - /** - * Registers and sets the core icon - */ - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - this.itemIcon = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":knowledge.core" ); - } + /** + * Registers and sets the core icon + */ + @Override + public void registerIcons(final IIconRegister iconRegister) { + this.itemIcon = iconRegister.registerIcon(ThaumicEnergistics.MOD_ID + ":knowledge.core"); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemMaterial.java b/src/main/java/thaumicenergistics/common/items/ItemMaterial.java index 91b1c532..e2dfbc8d 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemMaterial.java +++ b/src/main/java/thaumicenergistics/common/items/ItemMaterial.java @@ -16,149 +16,132 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public class ItemMaterial - extends Item -{ +public class ItemMaterial extends Item { - /** - * Enum of all materials - * - * @author Nividica - * - */ - public static enum MaterialTypes - { - DIFFUSION_CORE (0, "diffusion.core", ThEStrings.Item_DiffusionCore), - COALESCENCE_CORE (1, "coalescence.core", ThEStrings.Item_CoalescenceCore), - IRON_GEAR (2, "iron.gear", ThEStrings.Item_IronGear); + /** + * Enum of all materials + * + * @author Nividica + * + */ + public static enum MaterialTypes { + DIFFUSION_CORE(0, "diffusion.core", ThEStrings.Item_DiffusionCore), + COALESCENCE_CORE(1, "coalescence.core", ThEStrings.Item_CoalescenceCore), + IRON_GEAR(2, "iron.gear", ThEStrings.Item_IronGear); - /** - * Cache of the enum values - */ - public static final MaterialTypes[] VALUES = MaterialTypes.values(); + /** + * Cache of the enum values + */ + public static final MaterialTypes[] VALUES = MaterialTypes.values(); - /** - * Numeric ID of the material. - */ - private int ID; + /** + * Numeric ID of the material. + */ + private int ID; - /** - * Location of the material texture. - */ - private String textureLocation; + /** + * Location of the material texture. + */ + private String textureLocation; - /** - * Localization string. - */ - private ThEStrings unlocalizedName; + /** + * Localization string. + */ + private ThEStrings unlocalizedName; - private MaterialTypes( final int ID, final String textureName, final ThEStrings unlocalizedName ) - { - this.ID = ID; + private MaterialTypes(final int ID, final String textureName, final ThEStrings unlocalizedName) { + this.ID = ID; - this.textureLocation = ThaumicEnergistics.MOD_ID + ":material." + textureName; + this.textureLocation = ThaumicEnergistics.MOD_ID + ":material." + textureName; - this.unlocalizedName = unlocalizedName; - } + this.unlocalizedName = unlocalizedName; + } - public int getID() - { - return this.ID; - } + public int getID() { + return this.ID; + } - /** - * Gets an item stack of size 1 of the material item. - * - * @return - */ - public ItemStack getStack() - { - return this.getStack( 1 ); - } + /** + * Gets an item stack of size 1 of the material item. + * + * @return + */ + public ItemStack getStack() { + return this.getStack(1); + } - /** - * Gets an item stack of the specified size of the material item. - * - * @param size - * @return - */ - public ItemStack getStack( final int size ) - { - return ItemEnum.MATERIAL.getDMGStack( this.ordinal(), size ); - } + /** + * Gets an item stack of the specified size of the material item. + * + * @param size + * @return + */ + public ItemStack getStack(final int size) { + return ItemEnum.MATERIAL.getDMGStack(this.ordinal(), size); + } - public String getTextureLocation() - { - return this.textureLocation; - } + public String getTextureLocation() { + return this.textureLocation; + } - public String getUnlocalizedName() - { - return this.unlocalizedName.getUnlocalized(); - } - } + public String getUnlocalizedName() { + return this.unlocalizedName.getUnlocalized(); + } + } - /** - * List of icons based on damage/meta value - */ - private IIcon[] icons; + /** + * List of icons based on damage/meta value + */ + private IIcon[] icons; - public ItemMaterial() - { - this.setMaxDamage( 0 ); - this.setHasSubtypes( true ); - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + public ItemMaterial() { + this.setMaxDamage(0); + this.setHasSubtypes(true); + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - /** - * Gets the icon for the specified material. - */ - @Override - public IIcon getIconFromDamage( final int damage ) - { - int index = MathHelper.clamp_int( damage, 0, MaterialTypes.VALUES.length - 1 ); + /** + * Gets the icon for the specified material. + */ + @Override + public IIcon getIconFromDamage(final int damage) { + int index = MathHelper.clamp_int(damage, 0, MaterialTypes.VALUES.length - 1); - return this.icons[index]; - } + return this.icons[index]; + } - @Override - public void getSubItems( final Item item, final CreativeTabs creativeTab, final List itemList ) - { - // Add each material item - for( MaterialTypes material : MaterialTypes.VALUES ) - { - itemList.add( new ItemStack( item, 1, material.getID() ) ); - } - } + @Override + public void getSubItems(final Item item, final CreativeTabs creativeTab, final List itemList) { + // Add each material item + for (MaterialTypes material : MaterialTypes.VALUES) { + itemList.add(new ItemStack(item, 1, material.getID())); + } + } - @Override - public String getUnlocalizedName() - { - return ThaumicEnergistics.MOD_ID + ".item.material"; - } + @Override + public String getUnlocalizedName() { + return ThaumicEnergistics.MOD_ID + ".item.material"; + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - int index = MathHelper.clamp_int( itemStack.getItemDamage(), 0, MaterialTypes.VALUES.length - 1 ); + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + int index = MathHelper.clamp_int(itemStack.getItemDamage(), 0, MaterialTypes.VALUES.length - 1); - return MaterialTypes.VALUES[index].getUnlocalizedName(); - } + return MaterialTypes.VALUES[index].getUnlocalizedName(); + } - /** - * Registers each materials icon. - */ - @Override - public void registerIcons( final IIconRegister iconRegister ) - { + /** + * Registers each materials icon. + */ + @Override + public void registerIcons(final IIconRegister iconRegister) { - // Create the icon array - this.icons = new IIcon[MaterialTypes.VALUES.length]; + // Create the icon array + this.icons = new IIcon[MaterialTypes.VALUES.length]; - // Register each icon - for( MaterialTypes material : MaterialTypes.VALUES ) - { - this.icons[material.getID()] = iconRegister.registerIcon( material.getTextureLocation() ); - } - } + // Register each icon + for (MaterialTypes material : MaterialTypes.VALUES) { + this.icons[material.getID()] = iconRegister.registerIcon(material.getTextureLocation()); + } + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemStorageCasing.java b/src/main/java/thaumicenergistics/common/items/ItemStorageCasing.java index b08f5e41..3f59fb38 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemStorageCasing.java +++ b/src/main/java/thaumicenergistics/common/items/ItemStorageCasing.java @@ -12,32 +12,25 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public class ItemStorageCasing - extends Item -{ - public ItemStorageCasing() - { - this.setMaxDamage( 0 ); +public class ItemStorageCasing extends Item { + public ItemStorageCasing() { + this.setMaxDamage(0); - this.setHasSubtypes( false ); - } + this.setHasSubtypes(false); + } - @Override - public String getUnlocalizedName() - { - return ThEStrings.Item_EssentiaCellHousing.getUnlocalized(); - } + @Override + public String getUnlocalizedName() { + return ThEStrings.Item_EssentiaCellHousing.getUnlocalized(); + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return ThEStrings.Item_EssentiaCellHousing.getUnlocalized(); - } - - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - this.itemIcon = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":essentia.cell.casing" ); - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return ThEStrings.Item_EssentiaCellHousing.getUnlocalized(); + } + @Override + public void registerIcons(final IIconRegister iconRegister) { + this.itemIcon = iconRegister.registerIcon(ThaumicEnergistics.MOD_ID + ":essentia.cell.casing"); + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemStorageComponent.java b/src/main/java/thaumicenergistics/common/items/ItemStorageComponent.java index 302fb767..5407fe74 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemStorageComponent.java +++ b/src/main/java/thaumicenergistics/common/items/ItemStorageComponent.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.items; -import java.util.List; import appeng.api.implementations.items.IStorageComponent; +import java.util.List; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumRarity; @@ -17,101 +17,81 @@ import thaumicenergistics.common.storage.EnumEssentiaStorageTypes; * @author Nividica * */ -public class ItemStorageComponent - extends Item - implements IStorageComponent -{ +public class ItemStorageComponent extends Item implements IStorageComponent { - /** - * Component icons. - */ - private IIcon[] icons; + /** + * Component icons. + */ + private IIcon[] icons; - public ItemStorageComponent() - { - // No damage - this.setMaxDamage( 0 ); + public ItemStorageComponent() { + // No damage + this.setMaxDamage(0); - // Has subtypes - this.setHasSubtypes( true ); + // Has subtypes + this.setHasSubtypes(true); - // Goes in ThE's creative tab. - this.setCreativeTab( ThaumicEnergistics.ThETab ); - } + // Goes in ThE's creative tab. + this.setCreativeTab(ThaumicEnergistics.ThETab); + } - @Override - public int getBytes( final ItemStack itemStack ) - { - return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].capacity; - } + @Override + public int getBytes(final ItemStack itemStack) { + return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].capacity; + } - @Override - public IIcon getIconFromDamage( final int damage ) - { - // Return icon - return this.icons[damage]; - } + @Override + public IIcon getIconFromDamage(final int damage) { + // Return icon + return this.icons[damage]; + } - @Override - public EnumRarity getRarity( final ItemStack itemStack ) - { - // Return the rarity - return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].rarity; - } + @Override + public EnumRarity getRarity(final ItemStack itemStack) { + // Return the rarity + return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].rarity; + } - @Override - public void getSubItems( final Item item, final CreativeTabs creativeTab, final List itemList ) - { - for( EnumEssentiaStorageTypes type : EnumEssentiaStorageTypes.fromIndex ) - { - // Skip the creative cell, it has no component - if( type == EnumEssentiaStorageTypes.Type_Creative ) - { - continue; - } - itemList.add( type.getComponent( 1 ) ); + @Override + public void getSubItems(final Item item, final CreativeTabs creativeTab, final List itemList) { + for (EnumEssentiaStorageTypes type : EnumEssentiaStorageTypes.fromIndex) { + // Skip the creative cell, it has no component + if (type == EnumEssentiaStorageTypes.Type_Creative) { + continue; + } + itemList.add(type.getComponent(1)); + } + } - } - } + @Override + public String getUnlocalizedName() { + return ThaumicEnergistics.MOD_ID + ".item.storage.component"; + } - @Override - public String getUnlocalizedName() - { - return ThaumicEnergistics.MOD_ID + ".item.storage.component"; - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].componentName.getUnlocalized(); + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return EnumEssentiaStorageTypes.fromIndex[itemStack.getItemDamage()].componentName.getUnlocalized(); - } + @Override + public boolean isStorageComponent(final ItemStack itemStack) { + return (itemStack.getItem() == this); + } - @Override - public boolean isStorageComponent( final ItemStack itemStack ) - { - return( itemStack.getItem() == this ); - } - - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - // Create the icon array - this.icons = new IIcon[EnumEssentiaStorageTypes.fromIndex.length]; - - // Add each type - for( int i = 0; i < this.icons.length; i++ ) - { - // Skip creative - if( i == EnumEssentiaStorageTypes.Type_Creative.index ) - { - this.icons[i] = null; - } - else - { - this.icons[i] = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":storage.component." + - EnumEssentiaStorageTypes.fromIndex[i].suffix ); - } - } - } + @Override + public void registerIcons(final IIconRegister iconRegister) { + // Create the icon array + this.icons = new IIcon[EnumEssentiaStorageTypes.fromIndex.length]; + // Add each type + for (int i = 0; i < this.icons.length; i++) { + // Skip creative + if (i == EnumEssentiaStorageTypes.Type_Creative.index) { + this.icons[i] = null; + } else { + this.icons[i] = iconRegister.registerIcon(ThaumicEnergistics.MOD_ID + ":storage.component." + + EnumEssentiaStorageTypes.fromIndex[i].suffix); + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/items/ItemWirelessEssentiaTerminal.java b/src/main/java/thaumicenergistics/common/items/ItemWirelessEssentiaTerminal.java index a638d73f..eff095ff 100644 --- a/src/main/java/thaumicenergistics/common/items/ItemWirelessEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/common/items/ItemWirelessEssentiaTerminal.java @@ -1,8 +1,8 @@ package thaumicenergistics.common.items; -import com.google.common.base.Optional; import appeng.api.config.PowerMultiplier; import appeng.items.tools.powered.powersink.AEBasePoweredItem; +import com.google.common.base.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; @@ -23,164 +23,146 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public class ItemWirelessEssentiaTerminal - extends AEBasePoweredItem - implements IThEWirelessEssentiaTerminal -{ - /** - * NBT keys - */ - private static final String NBT_AE_SOURCE_KEY = "SourceKey"; +public class ItemWirelessEssentiaTerminal extends AEBasePoweredItem implements IThEWirelessEssentiaTerminal { + /** + * NBT keys + */ + private static final String NBT_AE_SOURCE_KEY = "SourceKey"; - /** - * Amount of power the wireless terminal can store. - */ - private static final int POWER_STORAGE = 1600000; + /** + * Amount of power the wireless terminal can store. + */ + private static final int POWER_STORAGE = 1600000; - /** - * Used during power calculations. - */ - public static double GLOBAL_POWER_MULTIPLIER = PowerMultiplier.CONFIG.multiplier; + /** + * Used during power calculations. + */ + public static double GLOBAL_POWER_MULTIPLIER = PowerMultiplier.CONFIG.multiplier; - /** - * Creates the wireless terminal item. - */ - public ItemWirelessEssentiaTerminal() - { - super( POWER_STORAGE, Optional. absent() ); - } + /** + * Creates the wireless terminal item. + */ + public ItemWirelessEssentiaTerminal() { + super(POWER_STORAGE, Optional.absent()); + } - /** - * Gets or creates the NBT compound tag for the terminal. - * - * @param wirelessTerminal - * @return - */ - private NBTTagCompound getOrCreateCompoundTag( final ItemStack wirelessTerminal ) - { - NBTTagCompound dataTag; + /** + * Gets or creates the NBT compound tag for the terminal. + * + * @param wirelessTerminal + * @return + */ + private NBTTagCompound getOrCreateCompoundTag(final ItemStack wirelessTerminal) { + NBTTagCompound dataTag; - // Ensure the terminal has a tag - if( !wirelessTerminal.hasTagCompound() ) - { - // Create a new tag. - wirelessTerminal.setTagCompound( ( dataTag = new NBTTagCompound() ) ); - } - else - { - // Get the tag - dataTag = wirelessTerminal.getTagCompound(); - } + // Ensure the terminal has a tag + if (!wirelessTerminal.hasTagCompound()) { + // Create a new tag. + wirelessTerminal.setTagCompound((dataTag = new NBTTagCompound())); + } else { + // Get the tag + dataTag = wirelessTerminal.getTagCompound(); + } - return dataTag; - } + return dataTag; + } - /** - * Gets the encryption, or source, key for the specified terminal. - * - * @param wirelessTerminal - * @return - */ - @Override - public String getEncryptionKey( final ItemStack wirelessTerminal ) - { - // Ensure the terminal has a tag - if( wirelessTerminal.hasTagCompound() ) - { - // Get the security terminal source key - String sourceKey = wirelessTerminal.getTagCompound().getString( ItemWirelessEssentiaTerminal.NBT_AE_SOURCE_KEY ); + /** + * Gets the encryption, or source, key for the specified terminal. + * + * @param wirelessTerminal + * @return + */ + @Override + public String getEncryptionKey(final ItemStack wirelessTerminal) { + // Ensure the terminal has a tag + if (wirelessTerminal.hasTagCompound()) { + // Get the security terminal source key + String sourceKey = + wirelessTerminal.getTagCompound().getString(ItemWirelessEssentiaTerminal.NBT_AE_SOURCE_KEY); - // Ensure the source is not empty nor null - if( ( sourceKey != null ) && ( !sourceKey.isEmpty() ) ) - { - // The terminal is linked. - return sourceKey; - } - } + // Ensure the source is not empty nor null + if ((sourceKey != null) && (!sourceKey.isEmpty())) { + // The terminal is linked. + return sourceKey; + } + } - // Terminal is unlinked. - return ""; - } + // Terminal is unlinked. + return ""; + } - @Override - public String getUnlocalizedName() - { - return ThEStrings.Item_WirelessEssentiaTerminal.getUnlocalized(); - } + @Override + public String getUnlocalizedName() { + return ThEStrings.Item_WirelessEssentiaTerminal.getUnlocalized(); + } - @Override - public String getUnlocalizedName( final ItemStack itemStack ) - { - return ThEStrings.Item_WirelessEssentiaTerminal.getUnlocalized(); - } + @Override + public String getUnlocalizedName(final ItemStack itemStack) { + return ThEStrings.Item_WirelessEssentiaTerminal.getUnlocalized(); + } - /** - * Gets the data tag used to save the terminal settings a power level. - */ - @Override - public NBTTagCompound getWETerminalTag( final ItemStack wirelessTerminal ) - { - return this.getOrCreateCompoundTag( wirelessTerminal ); - } + /** + * Gets the data tag used to save the terminal settings a power level. + */ + @Override + public NBTTagCompound getWETerminalTag(final ItemStack wirelessTerminal) { + return this.getOrCreateCompoundTag(wirelessTerminal); + } - @SideOnly(Side.CLIENT) - @Override - public boolean isFull3D() - { - return false; - } + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } - /** - * Opens the wireless terminal. - * - * @param itemStack - * @param world - * @param entityPlayer - * @return - */ - @Override - public ItemStack onItemRightClick( final ItemStack itemStack, final World world, final EntityPlayer player ) - { - // Open the gui - ThEApi.instance().interact().openWirelessTerminalGui( player ); + /** + * Opens the wireless terminal. + * + * @param itemStack + * @param world + * @param entityPlayer + * @return + */ + @Override + public ItemStack onItemRightClick(final ItemStack itemStack, final World world, final EntityPlayer player) { + // Open the gui + ThEApi.instance().interact().openWirelessTerminalGui(player); - return itemStack; + return itemStack; + } - } + /** + * Registers and sets the wireless terminal icon. + */ + @Override + public void registerIcons(final IIconRegister iconRegister) { + this.itemIcon = iconRegister.registerIcon(ThaumicEnergistics.MOD_ID + ":wireless.essentia.terminal"); + } - /** - * Registers and sets the wireless terminal icon. - */ - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - this.itemIcon = iconRegister.registerIcon( ThaumicEnergistics.MOD_ID + ":wireless.essentia.terminal" ); - } + /** + * Sets the encryption, or source, key for the specified terminal. + * + * @param wirelessTerminal + * @param sourceKey + * @param name + * Ignored. + */ + @Override + public void setEncryptionKey(final ItemStack wirelessTerminal, final String sourceKey, final String name) { + // Set the key + this.getOrCreateCompoundTag(wirelessTerminal) + .setString(ItemWirelessEssentiaTerminal.NBT_AE_SOURCE_KEY, sourceKey); + } - /** - * Sets the encryption, or source, key for the specified terminal. - * - * @param wirelessTerminal - * @param sourceKey - * @param name - * Ignored. - */ - @Override - public void setEncryptionKey( final ItemStack wirelessTerminal, final String sourceKey, final String name ) - { - // Set the key - this.getOrCreateCompoundTag( wirelessTerminal ).setString( ItemWirelessEssentiaTerminal.NBT_AE_SOURCE_KEY, sourceKey ); - } - - /** - * Always show the durability bar. - * - * @param wirelessTerminal - * @return - */ - @Override - public boolean showDurabilityBar( final ItemStack wirelessTerminal ) - { - return true; - } + /** + * Always show the durability bar. + * + * @param wirelessTerminal + * @return + */ + @Override + public boolean showDurabilityBar(final ItemStack wirelessTerminal) { + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/network/HandlerClient.java b/src/main/java/thaumicenergistics/common/network/HandlerClient.java index e2a4fd74..7ec0065b 100644 --- a/src/main/java/thaumicenergistics/common/network/HandlerClient.java +++ b/src/main/java/thaumicenergistics/common/network/HandlerClient.java @@ -11,15 +11,11 @@ import thaumicenergistics.common.network.packet.client.WrapperPacket_C; * @author Nividica * */ -public class HandlerClient - implements IMessageHandler -{ - - @Override - public IMessage onMessage( final WrapperPacket_C message, final MessageContext ctx ) - { - message.execute(); - return null; - } +public class HandlerClient implements IMessageHandler { + @Override + public IMessage onMessage(final WrapperPacket_C message, final MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/network/HandlerServer.java b/src/main/java/thaumicenergistics/common/network/HandlerServer.java index 8040bb93..ebed48a7 100644 --- a/src/main/java/thaumicenergistics/common/network/HandlerServer.java +++ b/src/main/java/thaumicenergistics/common/network/HandlerServer.java @@ -11,14 +11,11 @@ import thaumicenergistics.common.network.packet.server.WrapperPacket_S; * @author Nividica * */ -public class HandlerServer - implements IMessageHandler -{ +public class HandlerServer implements IMessageHandler { - @Override - public IMessage onMessage( final WrapperPacket_S message, final MessageContext ctx ) - { - message.execute(); - return null; - } + @Override + public IMessage onMessage(final WrapperPacket_S message, final MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/java/thaumicenergistics/common/network/IAspectSlotPart.java b/src/main/java/thaumicenergistics/common/network/IAspectSlotPart.java index 19129a98..977ddbe9 100644 --- a/src/main/java/thaumicenergistics/common/network/IAspectSlotPart.java +++ b/src/main/java/thaumicenergistics/common/network/IAspectSlotPart.java @@ -9,7 +9,6 @@ import thaumcraft.api.aspects.Aspect; * @author Nividica * */ -public interface IAspectSlotPart -{ - void setAspect( int index, Aspect aspect, EntityPlayer player ); +public interface IAspectSlotPart { + void setAspect(int index, Aspect aspect, EntityPlayer player); } diff --git a/src/main/java/thaumicenergistics/common/network/NetworkHandler.java b/src/main/java/thaumicenergistics/common/network/NetworkHandler.java index 2a6881c8..fa82e905 100644 --- a/src/main/java/thaumicenergistics/common/network/NetworkHandler.java +++ b/src/main/java/thaumicenergistics/common/network/NetworkHandler.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.network; -import java.util.HashMap; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; +import java.util.HashMap; import net.minecraft.entity.player.EntityPlayerMP; import thaumicenergistics.common.ThaumicEnergistics; import thaumicenergistics.common.network.packet.client.*; @@ -16,160 +16,152 @@ import thaumicenergistics.common.network.packet.server.*; * @author Nividica * */ -public class NetworkHandler -{ - /** - * Channel used to send packets. - */ - private static SimpleNetworkWrapper channel = NetworkRegistry.INSTANCE.newSimpleChannel( ThaumicEnergistics.MOD_ID ); +public class NetworkHandler { + /** + * Channel used to send packets. + */ + private static SimpleNetworkWrapper channel = NetworkRegistry.INSTANCE.newSimpleChannel(ThaumicEnergistics.MOD_ID); - /** - * Next packet ID. - */ - private static short nextID = 0; + /** + * Next packet ID. + */ + private static short nextID = 0; - /** - * Maps a class to a unique id. - */ - private static HashMap ClassToID = new HashMap(); + /** + * Maps a class to a unique id. + */ + private static HashMap ClassToID = new HashMap(); - /** - * Maps a unique id to a class. - */ - private static HashMap IDToClass = new HashMap(); + /** + * Maps a unique id to a class. + */ + private static HashMap IDToClass = new HashMap(); - /** - * Registers a packet. - * - * @param packetClass - */ - private static void registerPacket( final Class packetClass ) - { - NetworkHandler.ClassToID.put( packetClass, NetworkHandler.nextID ); - NetworkHandler.IDToClass.put( NetworkHandler.nextID, packetClass ); - ++NetworkHandler.nextID; - } + /** + * Registers a packet. + * + * @param packetClass + */ + private static void registerPacket(final Class packetClass) { + NetworkHandler.ClassToID.put(packetClass, NetworkHandler.nextID); + NetworkHandler.IDToClass.put(NetworkHandler.nextID, packetClass); + ++NetworkHandler.nextID; + } - /** - * Get's the class for the packet with the specified ID. - * - * @param id - * @return - */ - public static Class getPacketClassFromID( final Short id ) - { - return NetworkHandler.IDToClass.getOrDefault( id, null ); - } + /** + * Get's the class for the packet with the specified ID. + * + * @param id + * @return + */ + public static Class getPacketClassFromID(final Short id) { + return NetworkHandler.IDToClass.getOrDefault(id, null); + } - /** - * Gets the ID for the specified packet. - * - * @param packet - * @return - */ - public static short getPacketID( final ThEBasePacket packet ) - { - return NetworkHandler.ClassToID.getOrDefault( packet.getClass(), (short) -1 ); - } + /** + * Gets the ID for the specified packet. + * + * @param packet + * @return + */ + public static short getPacketID(final ThEBasePacket packet) { + return NetworkHandler.ClassToID.getOrDefault(packet.getClass(), (short) -1); + } - /** - * Registers all packets - */ - public static void registerPackets() - { - // Register channel client side handler - NetworkHandler.channel.registerMessage( HandlerClient.class, WrapperPacket_C.class, 1, Side.CLIENT ); + /** + * Registers all packets + */ + public static void registerPackets() { + // Register channel client side handler + NetworkHandler.channel.registerMessage(HandlerClient.class, WrapperPacket_C.class, 1, Side.CLIENT); - // Register channel server side handler - NetworkHandler.channel.registerMessage( HandlerServer.class, WrapperPacket_S.class, 2, Side.SERVER ); + // Register channel server side handler + NetworkHandler.channel.registerMessage(HandlerServer.class, WrapperPacket_S.class, 2, Side.SERVER); - // Aspect slot - registerPacket( Packet_C_AspectSlot.class ); - registerPacket( Packet_S_AspectSlot.class ); + // Aspect slot + registerPacket(Packet_C_AspectSlot.class); + registerPacket(Packet_S_AspectSlot.class); - // Essentia import/export bus - registerPacket( Packet_C_EssentiaIOBus.class ); - registerPacket( Packet_S_EssentiaIOBus.class ); + // Essentia import/export bus + registerPacket(Packet_C_EssentiaIOBus.class); + registerPacket(Packet_S_EssentiaIOBus.class); - // Essentia storage bus - registerPacket( Packet_C_EssentiaStorageBus.class ); - registerPacket( Packet_S_EssentiaStorageBus.class ); + // Essentia storage bus + registerPacket(Packet_C_EssentiaStorageBus.class); + registerPacket(Packet_S_EssentiaStorageBus.class); - // Essentia level emitter - registerPacket( Packet_C_EssentiaEmitter.class ); - registerPacket( Packet_S_EssentiaEmitter.class ); + // Essentia level emitter + registerPacket(Packet_C_EssentiaEmitter.class); + registerPacket(Packet_S_EssentiaEmitter.class); - // Essentia terminal - registerPacket( Packet_C_EssentiaCellTerminal.class ); - registerPacket( Packet_S_EssentiaCellTerminal.class ); + // Essentia terminal + registerPacket(Packet_C_EssentiaCellTerminal.class); + registerPacket(Packet_S_EssentiaCellTerminal.class); - // Arcane crafting terminal - registerPacket( Packet_C_ArcaneCraftingTerminal.class ); - registerPacket( Packet_S_ArcaneCraftingTerminal.class ); + // Arcane crafting terminal + registerPacket(Packet_C_ArcaneCraftingTerminal.class); + registerPacket(Packet_S_ArcaneCraftingTerminal.class); - // Change GUI - registerPacket( Packet_S_ChangeGui.class ); + // Change GUI + registerPacket(Packet_S_ChangeGui.class); - // Priority GUI - registerPacket( Packet_C_Priority.class ); - registerPacket( Packet_S_Priority.class ); + // Priority GUI + registerPacket(Packet_C_Priority.class); + registerPacket(Packet_S_Priority.class); - // Essentia cell workbench - registerPacket( Packet_S_EssentiaCellWorkbench.class ); + // Essentia cell workbench + registerPacket(Packet_S_EssentiaCellWorkbench.class); - // Knowledge inscriber - registerPacket( Packet_C_KnowledgeInscriber.class ); - registerPacket( Packet_S_KnowledgeInscriber.class ); + // Knowledge inscriber + registerPacket(Packet_C_KnowledgeInscriber.class); + registerPacket(Packet_S_KnowledgeInscriber.class); - // Particle FX - registerPacket( Packet_R_ParticleFX.class ); + // Particle FX + registerPacket(Packet_R_ParticleFX.class); - // Wrench Focus - registerPacket( Packet_S_WrenchFocus.class ); + // Wrench Focus + registerPacket(Packet_S_WrenchFocus.class); - // Essentia Vibration Chamber - registerPacket( Packet_C_EssentiaVibrationChamber.class ); + // Essentia Vibration Chamber + registerPacket(Packet_C_EssentiaVibrationChamber.class); - // Confirm crafting - registerPacket( Packet_S_ConfirmCraftingJob.class ); + // Confirm crafting + registerPacket(Packet_S_ConfirmCraftingJob.class); - // Distillation encoder - registerPacket( Packet_S_DistillationEncoder.class ); + // Distillation encoder + registerPacket(Packet_S_DistillationEncoder.class); - // Sync packet - registerPacket( Packet_C_Sync.class ); + // Sync packet + registerPacket(Packet_C_Sync.class); - registerPacket( Packet_S_NEIRecipe.class ); - } + registerPacket(Packet_S_NEIRecipe.class); + } - public static void sendAreaPacketToClients( final ThEAreaPacket areaPacket, final float range ) - { - // Create the wrapper packet - WrapperPacket wrapper = new WrapperPacket_C( areaPacket ); + public static void sendAreaPacketToClients(final ThEAreaPacket areaPacket, final float range) { + // Create the wrapper packet + WrapperPacket wrapper = new WrapperPacket_C(areaPacket); - // Create the target point - TargetPoint targetPoint = new TargetPoint( areaPacket.getDimension(), areaPacket.getX(), areaPacket.getY(), areaPacket.getZ(), range ); + // Create the target point + TargetPoint targetPoint = new TargetPoint( + areaPacket.getDimension(), areaPacket.getX(), areaPacket.getY(), areaPacket.getZ(), range); - // Send the packet - NetworkHandler.channel.sendToAllAround( wrapper, targetPoint ); + // Send the packet + NetworkHandler.channel.sendToAllAround(wrapper, targetPoint); + } - } + public static void sendPacketToClient(final ThEClientPacket clientPacket) { + // Create the wrapper packet + WrapperPacket wrapper = new WrapperPacket_C(clientPacket); - public static void sendPacketToClient( final ThEClientPacket clientPacket ) - { - // Create the wrapper packet - WrapperPacket wrapper = new WrapperPacket_C( clientPacket ); + // Send the packet + NetworkHandler.channel.sendTo(wrapper, (EntityPlayerMP) clientPacket.player); + } - // Send the packet - NetworkHandler.channel.sendTo( wrapper, (EntityPlayerMP)clientPacket.player ); - } + public static void sendPacketToServer(final ThEServerPacket serverPacket) { + // Create the wrapper packet + WrapperPacket wrapper = new WrapperPacket_S(serverPacket); - public static void sendPacketToServer( final ThEServerPacket serverPacket ) - { - // Create the wrapper packet - WrapperPacket wrapper = new WrapperPacket_S( serverPacket ); - - // Send the packet - NetworkHandler.channel.sendToServer( wrapper ); - } + // Send the packet + NetworkHandler.channel.sendToServer(wrapper); + } } diff --git a/src/main/java/thaumicenergistics/common/network/ThEBasePacket.java b/src/main/java/thaumicenergistics/common/network/ThEBasePacket.java index a34dcd9d..0c8ca2e8 100644 --- a/src/main/java/thaumicenergistics/common/network/ThEBasePacket.java +++ b/src/main/java/thaumicenergistics/common/network/ThEBasePacket.java @@ -1,15 +1,9 @@ package thaumicenergistics.common.network; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.Deflater; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; -import com.google.common.base.Charsets; import appeng.api.parts.IPartHost; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; +import com.google.common.base.Charsets; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; @@ -17,6 +11,12 @@ import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.Deflater; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -34,516 +34,449 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public abstract class ThEBasePacket - implements IMessage -{ - class ConfigurableGZIPOutputStream - extends GZIPOutputStream - { - public ConfigurableGZIPOutputStream( final OutputStream out ) throws IOException - { - super( out ); - } - - public void setLevel( final int level ) - { - this.def.setLevel( level ); - } - } - - /** - * Starting size of buffers compressed buffers, 1 Megabyte - */ - private static final int COMPRESSED_BUFFER_SIZE = ( 1024 * 1024 ) * 1; - - /** - * Player entity - */ - public EntityPlayer player; - - /** - * Used by subclasses to distinguish what's in the stream. - */ - protected byte mode; - - /** - * If true will compress subclass data streams. - */ - protected boolean useCompression; - - /** - * Creates an empty packet (called from the netty core) - */ - public ThEBasePacket() - { - this.player = null; - this.mode = -1; - this.useCompression = false; - } - - /** - * Gets the loaded world on the client side. - * - * @return - */ - @SideOnly(Side.CLIENT) - private static World getClientWorld() - { - return Minecraft.getMinecraft().theWorld; - } - - /** - * Reads an AE itemstack from the stream. - * - * @param stream - * @return - */ - protected static IAEItemStack readAEItemStack( final ByteBuf stream ) - { - IAEItemStack itemStack; - try - { - itemStack = AEItemStack.loadItemStackFromPacket( stream ); - - return itemStack; - } - catch( IOException e ) - { - } - - return null; - - } - - /** - * Reads an itemstack from the stream. - * - * @param stream - * @return - */ - protected static ItemStack readItemstack( final ByteBuf stream ) - { - return ByteBufUtils.readItemStack( stream ); - } - - /** - * Reads an AE part from the stream. - * - * @param stream - * @return - */ - protected static ThEPartBase readPart( final ByteBuf stream ) - { - ForgeDirection side = ForgeDirection.getOrientation( stream.readInt() ); - - IPartHost host = (IPartHost)ThEBasePacket.readTileEntity( stream ); - - return (ThEPartBase)host.getPart( side ); - } - - /** - * Reads a player entity from the stream. - * - * @param stream - * @return - */ - protected static EntityPlayer readPlayer( final ByteBuf stream ) - { - EntityPlayer player = null; - - if( stream.readBoolean() ) - { - World playerWorld = ThEBasePacket.readWorld( stream ); - player = playerWorld.getPlayerEntityByName( ThEBasePacket.readString( stream ) ); - } - - return player; - } - - /** - * Reads a string from the stream. - * - * @param stream - * @return - */ - protected static String readString( final ByteBuf stream ) - { - byte[] stringBytes = new byte[stream.readInt()]; - - stream.readBytes( stringBytes ); - - return new String( stringBytes, Charsets.UTF_8 ); - } - - /** - * Reads a tile entity from the stream. - * - * @param stream - * @return - */ - protected static TileEntity readTileEntity( final ByteBuf stream ) - { - World world = ThEBasePacket.readWorld( stream ); - - return world.getTileEntity( stream.readInt(), stream.readInt(), stream.readInt() ); - } - - /** - * Reads a world from the stream. - * - * @param stream - * @return - */ - protected static World readWorld( final ByteBuf stream ) - { - World world = DimensionManager.getWorld( stream.readInt() ); - - if( FMLCommonHandler.instance().getSide() == Side.CLIENT ) - { - if( world == null ) - { - world = ThEBasePacket.getClientWorld(); - } - } - - return world; - } - - /** - * Writes an AE itemstack to the stream. - * - * @param itemStack - * @param stream - */ - protected static void writeAEItemStack( final IAEItemStack itemStack, final ByteBuf stream ) - { - // Do we have a valid stack? - if( itemStack != null ) - { - // Write into the stream - try - { - itemStack.writeToPacket( stream ); - } - catch( IOException e ) - { - } - } - } - - /** - * Writes an itemstack into the stream. - * - * @param stack - * @param stream - */ - protected static void writeItemstack( final ItemStack stack, final ByteBuf stream ) - { - ByteBufUtils.writeItemStack( stream, stack ); - } - - /** - * Writes an AE part to the stream. - * - * @param part - * @param stream - */ - protected static void writePart( final ThEPartBase part, final ByteBuf stream ) - { - stream.writeInt( part.getSide().ordinal() ); - - ThEBasePacket.writeTileEntity( part.getHost().getTile(), stream ); - } - - /** - * Writes a player to the stream. - * - * @param player - * @param stream - */ - @SuppressWarnings("null") - protected static void writePlayer( final EntityPlayer player, final ByteBuf stream ) - { - boolean validPlayer = ( player != null ); - - stream.writeBoolean( validPlayer ); - - if( validPlayer ) - { - ThEBasePacket.writeWorld( player.worldObj, stream ); - ThEBasePacket.writeString( player.getCommandSenderName(), stream ); - } - } - - /** - * Writes a string to the stream. - * - * @param string - * @param stream - */ - protected static void writeString( final String string, final ByteBuf stream ) - { - byte[] stringBytes = string.getBytes( Charsets.UTF_8 ); - - stream.writeInt( stringBytes.length ); - - stream.writeBytes( stringBytes ); - } - - /** - * Writes a tile entity to the stream. - * - * @param entity - * @param stream - */ - protected static void writeTileEntity( final TileEntity entity, final ByteBuf stream ) - { - ThEBasePacket.writeWorld( entity.getWorldObj(), stream ); - stream.writeInt( entity.xCoord ); - stream.writeInt( entity.yCoord ); - stream.writeInt( entity.zCoord ); - } - - /** - * Writes a world to the stream. - * - * @param world - * @param stream - */ - protected static void writeWorld( final World world, final ByteBuf stream ) - { - stream.writeInt( world.provider.dimensionId ); - } - - /** - * Reads a Thaumcraft aspect from the stream. - * - * @param stream - * @return - */ - public static Aspect readAspect( final ByteBuf stream ) - { - // Read the name - String name = ThEBasePacket.readString( stream ); - if( name != "" ) - { - // Return the aspect - return Aspect.aspects.get( name ); - } - - return null; - } - - /** - * Writes a Thaumcraft aspect to the stream. - * - * @param aspect - * @param stream - */ - public static void writeAspect( final Aspect aspect, final ByteBuf stream ) - { - String aspectName = ""; - - if( aspect != null ) - { - aspectName = aspect.getTag(); - } - - ThEBasePacket.writeString( aspectName, stream ); - } - - private void fromCompressedBytes( final ByteBuf packetStream ) - { - // Create a new data stream - ByteBuf decompressedStream = Unpooled.buffer( ThEBasePacket.COMPRESSED_BUFFER_SIZE ); - - try( - InputStream inStream = new InputStream() - { - - @Override - public int read() throws IOException - { - // Is there anymore data to read from the packet stream? - if( packetStream.readableBytes() <= 0 ) - { - // Return end marker - return -1; - } - - // Return the byte - return packetStream.readByte() & 0xFF; - } - }; - - // Create the decompressor - GZIPInputStream decompressor = new GZIPInputStream( inStream ) ) - { - - // Create a temporary holding array - byte[] holding = new byte[512]; - - // Decompress - while( decompressor.available() != 0 ) - { - // Read into the holding array - int bytesRead = decompressor.read( holding ); - - // Did we read any data? - if( bytesRead > 0 ) - { - // Write the holding array into the decompressed stream - decompressedStream.writeBytes( holding, 0, bytesRead ); - } - } - - // Close the decompressor - decompressor.close(); - - // Reset stream position - decompressedStream.readerIndex( 0 ); - - // Pass to subclass - this.readData( decompressedStream ); - - } - catch( IOException e ) - { - // Failed - ThELog.error( e, "Packet decompression failed." ); - } - } - - /** - * Creates a new stream, calls to the subclass to write - * into it, then compresses it into the packet stream. - * - * @param packetStream - */ - private void toCompressedBytes( final ByteBuf packetStream ) - { - // Create a new data stream - ByteBuf streamToCompress = Unpooled.buffer( ThEBasePacket.COMPRESSED_BUFFER_SIZE ); - - // Pass to subclass - this.writeData( streamToCompress ); - - // Create the compressor - try( - OutputStream outStream = new OutputStream() - { - - @Override - public void write( final int byteToWrite ) throws IOException - { - // Write the byte to the packet stream - packetStream.writeByte( byteToWrite & 0xFF ); - } - }; - - ConfigurableGZIPOutputStream compressor = new ConfigurableGZIPOutputStream( outStream ) ) - - { - // Set compression level to best - compressor.setLevel( Deflater.BEST_COMPRESSION ); - - // Compress - compressor.write( streamToCompress.array(), 0, streamToCompress.writerIndex() ); - - // Close the compressor - compressor.close(); - } - catch( IOException e ) - { - // Failed - ThELog.error( e, "Packet compression failed, packet will be incomplete or dropped." ); - } - } - - /** - * Return true if the player should be included in the data stream. - * - * @return - */ - protected abstract boolean includePlayerInStream(); - - /** - * Allows subclasses to read data from the specified stream. - * - * @param stream - */ - protected abstract void readData( ByteBuf stream ); - - /** - * Allows subclasses to write data into the specified stream. - * - * @param stream - */ - protected abstract void writeData( ByteBuf stream ); - - /** - * Packet has been read and action can now take place. - */ - public abstract void execute(); - - /** - * Reads data from the packet stream. - */ - @Override - public void fromBytes( final ByteBuf stream ) - { - // Read mode - this.mode = stream.readByte(); - - // Read player - if( this.includePlayerInStream() ) - { - this.player = ThEBasePacket.readPlayer( stream ); - } - - // Read compression - this.useCompression = stream.readBoolean(); - - // Is there a compressed substream? - if( this.useCompression ) - { - this.fromCompressedBytes( stream ); - } - else - { - // Pass stream directly to subclass - this.readData( stream ); - } - } - - /** - * Writes data into the packet stream. - */ - @Override - public void toBytes( final ByteBuf stream ) - { - // Write the mode - stream.writeByte( this.mode ); - - // Write the player - if( this.includePlayerInStream() ) - { - ThEBasePacket.writePlayer( this.player, stream ); - } - - // Write if there is a compressed sub-stream. - stream.writeBoolean( this.useCompression ); - - // Is compression enabled? - if( this.useCompression ) - { - this.toCompressedBytes( stream ); - } - else - { - // No compression, subclass writes directly into stream. - this.writeData( stream ); - } - } - +public abstract class ThEBasePacket implements IMessage { + class ConfigurableGZIPOutputStream extends GZIPOutputStream { + public ConfigurableGZIPOutputStream(final OutputStream out) throws IOException { + super(out); + } + + public void setLevel(final int level) { + this.def.setLevel(level); + } + } + + /** + * Starting size of buffers compressed buffers, 1 Megabyte + */ + private static final int COMPRESSED_BUFFER_SIZE = (1024 * 1024) * 1; + + /** + * Player entity + */ + public EntityPlayer player; + + /** + * Used by subclasses to distinguish what's in the stream. + */ + protected byte mode; + + /** + * If true will compress subclass data streams. + */ + protected boolean useCompression; + + /** + * Creates an empty packet (called from the netty core) + */ + public ThEBasePacket() { + this.player = null; + this.mode = -1; + this.useCompression = false; + } + + /** + * Gets the loaded world on the client side. + * + * @return + */ + @SideOnly(Side.CLIENT) + private static World getClientWorld() { + return Minecraft.getMinecraft().theWorld; + } + + /** + * Reads an AE itemstack from the stream. + * + * @param stream + * @return + */ + protected static IAEItemStack readAEItemStack(final ByteBuf stream) { + IAEItemStack itemStack; + try { + itemStack = AEItemStack.loadItemStackFromPacket(stream); + + return itemStack; + } catch (IOException e) { + } + + return null; + } + + /** + * Reads an itemstack from the stream. + * + * @param stream + * @return + */ + protected static ItemStack readItemstack(final ByteBuf stream) { + return ByteBufUtils.readItemStack(stream); + } + + /** + * Reads an AE part from the stream. + * + * @param stream + * @return + */ + protected static ThEPartBase readPart(final ByteBuf stream) { + ForgeDirection side = ForgeDirection.getOrientation(stream.readInt()); + + IPartHost host = (IPartHost) ThEBasePacket.readTileEntity(stream); + + return (ThEPartBase) host.getPart(side); + } + + /** + * Reads a player entity from the stream. + * + * @param stream + * @return + */ + protected static EntityPlayer readPlayer(final ByteBuf stream) { + EntityPlayer player = null; + + if (stream.readBoolean()) { + World playerWorld = ThEBasePacket.readWorld(stream); + player = playerWorld.getPlayerEntityByName(ThEBasePacket.readString(stream)); + } + + return player; + } + + /** + * Reads a string from the stream. + * + * @param stream + * @return + */ + protected static String readString(final ByteBuf stream) { + byte[] stringBytes = new byte[stream.readInt()]; + + stream.readBytes(stringBytes); + + return new String(stringBytes, Charsets.UTF_8); + } + + /** + * Reads a tile entity from the stream. + * + * @param stream + * @return + */ + protected static TileEntity readTileEntity(final ByteBuf stream) { + World world = ThEBasePacket.readWorld(stream); + + return world.getTileEntity(stream.readInt(), stream.readInt(), stream.readInt()); + } + + /** + * Reads a world from the stream. + * + * @param stream + * @return + */ + protected static World readWorld(final ByteBuf stream) { + World world = DimensionManager.getWorld(stream.readInt()); + + if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { + if (world == null) { + world = ThEBasePacket.getClientWorld(); + } + } + + return world; + } + + /** + * Writes an AE itemstack to the stream. + * + * @param itemStack + * @param stream + */ + protected static void writeAEItemStack(final IAEItemStack itemStack, final ByteBuf stream) { + // Do we have a valid stack? + if (itemStack != null) { + // Write into the stream + try { + itemStack.writeToPacket(stream); + } catch (IOException e) { + } + } + } + + /** + * Writes an itemstack into the stream. + * + * @param stack + * @param stream + */ + protected static void writeItemstack(final ItemStack stack, final ByteBuf stream) { + ByteBufUtils.writeItemStack(stream, stack); + } + + /** + * Writes an AE part to the stream. + * + * @param part + * @param stream + */ + protected static void writePart(final ThEPartBase part, final ByteBuf stream) { + stream.writeInt(part.getSide().ordinal()); + + ThEBasePacket.writeTileEntity(part.getHost().getTile(), stream); + } + + /** + * Writes a player to the stream. + * + * @param player + * @param stream + */ + @SuppressWarnings("null") + protected static void writePlayer(final EntityPlayer player, final ByteBuf stream) { + boolean validPlayer = (player != null); + + stream.writeBoolean(validPlayer); + + if (validPlayer) { + ThEBasePacket.writeWorld(player.worldObj, stream); + ThEBasePacket.writeString(player.getCommandSenderName(), stream); + } + } + + /** + * Writes a string to the stream. + * + * @param string + * @param stream + */ + protected static void writeString(final String string, final ByteBuf stream) { + byte[] stringBytes = string.getBytes(Charsets.UTF_8); + + stream.writeInt(stringBytes.length); + + stream.writeBytes(stringBytes); + } + + /** + * Writes a tile entity to the stream. + * + * @param entity + * @param stream + */ + protected static void writeTileEntity(final TileEntity entity, final ByteBuf stream) { + ThEBasePacket.writeWorld(entity.getWorldObj(), stream); + stream.writeInt(entity.xCoord); + stream.writeInt(entity.yCoord); + stream.writeInt(entity.zCoord); + } + + /** + * Writes a world to the stream. + * + * @param world + * @param stream + */ + protected static void writeWorld(final World world, final ByteBuf stream) { + stream.writeInt(world.provider.dimensionId); + } + + /** + * Reads a Thaumcraft aspect from the stream. + * + * @param stream + * @return + */ + public static Aspect readAspect(final ByteBuf stream) { + // Read the name + String name = ThEBasePacket.readString(stream); + if (name != "") { + // Return the aspect + return Aspect.aspects.get(name); + } + + return null; + } + + /** + * Writes a Thaumcraft aspect to the stream. + * + * @param aspect + * @param stream + */ + public static void writeAspect(final Aspect aspect, final ByteBuf stream) { + String aspectName = ""; + + if (aspect != null) { + aspectName = aspect.getTag(); + } + + ThEBasePacket.writeString(aspectName, stream); + } + + private void fromCompressedBytes(final ByteBuf packetStream) { + // Create a new data stream + ByteBuf decompressedStream = Unpooled.buffer(ThEBasePacket.COMPRESSED_BUFFER_SIZE); + + try (InputStream inStream = new InputStream() { + + @Override + public int read() throws IOException { + // Is there anymore data to read from the packet stream? + if (packetStream.readableBytes() <= 0) { + // Return end marker + return -1; + } + + // Return the byte + return packetStream.readByte() & 0xFF; + } + }; + + // Create the decompressor + GZIPInputStream decompressor = new GZIPInputStream(inStream)) { + + // Create a temporary holding array + byte[] holding = new byte[512]; + + // Decompress + while (decompressor.available() != 0) { + // Read into the holding array + int bytesRead = decompressor.read(holding); + + // Did we read any data? + if (bytesRead > 0) { + // Write the holding array into the decompressed stream + decompressedStream.writeBytes(holding, 0, bytesRead); + } + } + + // Close the decompressor + decompressor.close(); + + // Reset stream position + decompressedStream.readerIndex(0); + + // Pass to subclass + this.readData(decompressedStream); + + } catch (IOException e) { + // Failed + ThELog.error(e, "Packet decompression failed."); + } + } + + /** + * Creates a new stream, calls to the subclass to write + * into it, then compresses it into the packet stream. + * + * @param packetStream + */ + private void toCompressedBytes(final ByteBuf packetStream) { + // Create a new data stream + ByteBuf streamToCompress = Unpooled.buffer(ThEBasePacket.COMPRESSED_BUFFER_SIZE); + + // Pass to subclass + this.writeData(streamToCompress); + + // Create the compressor + try (OutputStream outStream = new OutputStream() { + + @Override + public void write(final int byteToWrite) throws IOException { + // Write the byte to the packet stream + packetStream.writeByte(byteToWrite & 0xFF); + } + }; + ConfigurableGZIPOutputStream compressor = new ConfigurableGZIPOutputStream(outStream)) { + + // Set compression level to best + compressor.setLevel(Deflater.BEST_COMPRESSION); + + // Compress + compressor.write(streamToCompress.array(), 0, streamToCompress.writerIndex()); + + // Close the compressor + compressor.close(); + } catch (IOException e) { + // Failed + ThELog.error(e, "Packet compression failed, packet will be incomplete or dropped."); + } + } + + /** + * Return true if the player should be included in the data stream. + * + * @return + */ + protected abstract boolean includePlayerInStream(); + + /** + * Allows subclasses to read data from the specified stream. + * + * @param stream + */ + protected abstract void readData(ByteBuf stream); + + /** + * Allows subclasses to write data into the specified stream. + * + * @param stream + */ + protected abstract void writeData(ByteBuf stream); + + /** + * Packet has been read and action can now take place. + */ + public abstract void execute(); + + /** + * Reads data from the packet stream. + */ + @Override + public void fromBytes(final ByteBuf stream) { + // Read mode + this.mode = stream.readByte(); + + // Read player + if (this.includePlayerInStream()) { + this.player = ThEBasePacket.readPlayer(stream); + } + + // Read compression + this.useCompression = stream.readBoolean(); + + // Is there a compressed substream? + if (this.useCompression) { + this.fromCompressedBytes(stream); + } else { + // Pass stream directly to subclass + this.readData(stream); + } + } + + /** + * Writes data into the packet stream. + */ + @Override + public void toBytes(final ByteBuf stream) { + // Write the mode + stream.writeByte(this.mode); + + // Write the player + if (this.includePlayerInStream()) { + ThEBasePacket.writePlayer(this.player, stream); + } + + // Write if there is a compressed sub-stream. + stream.writeBoolean(this.useCompression); + + // Is compression enabled? + if (this.useCompression) { + this.toCompressedBytes(stream); + } else { + // No compression, subclass writes directly into stream. + this.writeData(stream); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/WrapperPacket.java b/src/main/java/thaumicenergistics/common/network/WrapperPacket.java index 149bb321..47d5ec66 100644 --- a/src/main/java/thaumicenergistics/common/network/WrapperPacket.java +++ b/src/main/java/thaumicenergistics/common/network/WrapperPacket.java @@ -10,90 +10,72 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public abstract class WrapperPacket - implements IMessage -{ - private ThEBasePacket embeddedPacket; +public abstract class WrapperPacket implements IMessage { + private ThEBasePacket embeddedPacket; - /** - * Required. - */ - public WrapperPacket() - { - } + /** + * Required. + */ + public WrapperPacket() {} - /** - * Constructs the wrapper, wrapping the specified packet. - * - * @param packet - */ - public WrapperPacket( final ThEBasePacket packet ) - { - this.embeddedPacket = packet; - } + /** + * Constructs the wrapper, wrapping the specified packet. + * + * @param packet + */ + public WrapperPacket(final ThEBasePacket packet) { + this.embeddedPacket = packet; + } - /** - * Executes the packet. - */ - public void execute() - { - if( this.embeddedPacket != null ) - { - this.embeddedPacket.execute(); - } - } + /** + * Executes the packet. + */ + public void execute() { + if (this.embeddedPacket != null) { + this.embeddedPacket.execute(); + } + } - @Override - public void fromBytes( final ByteBuf stream ) - { - // Read the id - short id = stream.readShort(); - if( id == -1 ) - { - // Invalid packet - ThELog.warning( "Unknown packet detected" ); - return; - } + @Override + public void fromBytes(final ByteBuf stream) { + // Read the id + short id = stream.readShort(); + if (id == -1) { + // Invalid packet + ThELog.warning("Unknown packet detected"); + return; + } - // Get the class for that id - Class epClass = NetworkHandler.getPacketClassFromID( id ); - if( epClass == null ) - { - return; - } + // Get the class for that id + Class epClass = NetworkHandler.getPacketClassFromID(id); + if (epClass == null) { + return; + } - // Construct the class - try - { - this.embeddedPacket = (ThEBasePacket)epClass.newInstance(); + // Construct the class + try { + this.embeddedPacket = (ThEBasePacket) epClass.newInstance(); - // Pass to packet - this.embeddedPacket.fromBytes( stream ); - } - catch( Exception e ) - { - // Packet did not have default constructor - ThELog.warning( "Unable to construct packet %s", epClass.getCanonicalName() ); - } - } + // Pass to packet + this.embeddedPacket.fromBytes(stream); + } catch (Exception e) { + // Packet did not have default constructor + ThELog.warning("Unable to construct packet %s", epClass.getCanonicalName()); + } + } - @Override - public void toBytes( final ByteBuf stream ) - { - if( this.embeddedPacket != null ) - { - // Write the id - short id = NetworkHandler.getPacketID( this.embeddedPacket ); - stream.writeShort( id ); - - // Call embedded - this.embeddedPacket.toBytes( stream ); - } - else - { - // Write -1 - stream.writeShort( -1 ); - } - } + @Override + public void toBytes(final ByteBuf stream) { + if (this.embeddedPacket != null) { + // Write the id + short id = NetworkHandler.getPacketID(this.embeddedPacket); + stream.writeShort(id); + // Call embedded + this.embeddedPacket.toBytes(stream); + } else { + // Write -1 + stream.writeShort(-1); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_ArcaneCraftingTerminal.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_ArcaneCraftingTerminal.java index 6d1e55ca..ba3f61e4 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_ArcaneCraftingTerminal.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_ArcaneCraftingTerminal.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.network.packet.client; -import java.util.Iterator; import appeng.api.AEApi; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -10,6 +9,7 @@ import appeng.api.storage.data.IItemList; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.util.Iterator; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; @@ -25,249 +25,230 @@ import thaumicenergistics.common.registries.EnumCache; * @author Nividica * */ -public class Packet_C_ArcaneCraftingTerminal - extends ThEClientPacket -{ - /** - * Packet modes - */ - private static final byte MODE_RECEIVE_CHANGE = 0, - MODE_RECEIVE_FULL_LIST = 1, - MODE_RECEIVE_SORTS = 3, - MODE_UPDATE_COSTS = 4; +public class Packet_C_ArcaneCraftingTerminal extends ThEClientPacket { + /** + * Packet modes + */ + private static final byte MODE_RECEIVE_CHANGE = 0, + MODE_RECEIVE_FULL_LIST = 1, + MODE_RECEIVE_SORTS = 3, + MODE_UPDATE_COSTS = 4; - private IAEItemStack changedStack; - private IItemList fullList; - private SortOrder sortingOrder; - private SortDir sortingDirection; - private ViewItems viewMode; + private IAEItemStack changedStack; + private IItemList fullList; + private SortOrder sortingOrder; + private SortDir sortingDirection; + private ViewItems viewMode; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_C_ArcaneCraftingTerminal newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_C_ArcaneCraftingTerminal packet = new Packet_C_ArcaneCraftingTerminal(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_C_ArcaneCraftingTerminal newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_C_ArcaneCraftingTerminal packet = new Packet_C_ArcaneCraftingTerminal(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - /** - * Creates a packet with the full list of items in the AE network. - * Only send in response to a request. - * - * @param player - * @param fullList - */ - public static void sendAllNetworkItems( final EntityPlayer player, final IItemList fullList ) - { - // Create the packet - Packet_C_ArcaneCraftingTerminal packet = newPacket( player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST ); + /** + * Creates a packet with the full list of items in the AE network. + * Only send in response to a request. + * + * @param player + * @param fullList + */ + public static void sendAllNetworkItems(final EntityPlayer player, final IItemList fullList) { + // Create the packet + Packet_C_ArcaneCraftingTerminal packet = + newPacket(player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST); - // Enable compression - packet.useCompression = true; + // Enable compression + packet.useCompression = true; - // Set the full list - packet.fullList = fullList; + // Set the full list + packet.fullList = fullList; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Creates a packet with an update to the sorting order and direction. - * - * @param player - * @param order - * @param direction - * @return - */ - public static void sendModeChange( final EntityPlayer player, final SortOrder order, final SortDir direction, - final ViewItems viewMode ) - { - // Create the packet - Packet_C_ArcaneCraftingTerminal packet = newPacket( player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS ); + /** + * Creates a packet with an update to the sorting order and direction. + * + * @param player + * @param order + * @param direction + * @return + */ + public static void sendModeChange( + final EntityPlayer player, final SortOrder order, final SortDir direction, final ViewItems viewMode) { + // Create the packet + Packet_C_ArcaneCraftingTerminal packet = newPacket(player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS); - // Set the sorts - packet.sortingDirection = direction; - packet.sortingOrder = order; - packet.viewMode = viewMode; + // Set the sorts + packet.sortingDirection = direction; + packet.sortingOrder = order; + packet.viewMode = viewMode; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Creates a packet with a changed network stack amount - * - * @param player - * @param change - */ - public static void stackAmountChanged( final EntityPlayer player, final IAEItemStack change ) - { - // Create the packet - Packet_C_ArcaneCraftingTerminal packet = newPacket( player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE ); + /** + * Creates a packet with a changed network stack amount + * + * @param player + * @param change + */ + public static void stackAmountChanged(final EntityPlayer player, final IAEItemStack change) { + // Create the packet + Packet_C_ArcaneCraftingTerminal packet = newPacket(player, Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE); - // Set the change - packet.changedStack = change; + // Set the change + packet.changedStack = change; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Forces the client to re-calculate the displayed aspect costs - * - * @return - */ - public static void updateAspectCost( final EntityPlayer player ) - { - // Create the packet - Packet_C_ArcaneCraftingTerminal packet = newPacket( player, Packet_C_ArcaneCraftingTerminal.MODE_UPDATE_COSTS ); + /** + * Forces the client to re-calculate the displayed aspect costs + * + * @return + */ + public static void updateAspectCost(final EntityPlayer player) { + // Create the packet + Packet_C_ArcaneCraftingTerminal packet = newPacket(player, Packet_C_ArcaneCraftingTerminal.MODE_UPDATE_COSTS); - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the current screen being displayed to the user - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the current screen being displayed to the user + Gui gui = Minecraft.getMinecraft().currentScreen; - // Is that screen the gui for the ACT? - if( gui instanceof GuiArcaneCraftingTerminal ) - { - switch ( this.mode ) - { - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: - // Set the item list - ( (GuiArcaneCraftingTerminal)gui ).onReceiveFullList( this.fullList ); - break; + // Is that screen the gui for the ACT? + if (gui instanceof GuiArcaneCraftingTerminal) { + switch (this.mode) { + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: + // Set the item list + ((GuiArcaneCraftingTerminal) gui).onReceiveFullList(this.fullList); + break; - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: - // Update the item list - ( (GuiArcaneCraftingTerminal)gui ).onReceiveChange( this.changedStack ); - break; + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: + // Update the item list + ((GuiArcaneCraftingTerminal) gui).onReceiveChange(this.changedStack); + break; - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: - ( (GuiArcaneCraftingTerminal)gui ).onReceiveSorting( this.sortingOrder, this.sortingDirection, this.viewMode ); - break; + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: + ((GuiArcaneCraftingTerminal) gui) + .onReceiveSorting(this.sortingOrder, this.sortingDirection, this.viewMode); + break; - case Packet_C_ArcaneCraftingTerminal.MODE_UPDATE_COSTS: - ( (GuiArcaneCraftingTerminal)gui ).onServerSendForceUpdateCost(); - break; - } - } - } + case Packet_C_ArcaneCraftingTerminal.MODE_UPDATE_COSTS: + ((GuiArcaneCraftingTerminal) gui).onServerSendForceUpdateCost(); + break; + } + } + } - @Override - public void readData( final ByteBuf stream ) - { + @Override + public void readData(final ByteBuf stream) { - switch ( this.mode ) - { - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: - // Create a new list - this.fullList = AEApi.instance().storage().createItemList(); + switch (this.mode) { + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: + // Create a new list + this.fullList = AEApi.instance().storage().createItemList(); - // Read how many items there are - int count = stream.readInt(); + // Read how many items there are + int count = stream.readInt(); - for( int i = 0; i < count; i++ ) - { - // Also ensure there are bytes to read - if( stream.readableBytes() <= 0 ) - { - break; - } + for (int i = 0; i < count; i++) { + // Also ensure there are bytes to read + if (stream.readableBytes() <= 0) { + break; + } - // Read the itemstack - IAEItemStack itemStack = ThEBasePacket.readAEItemStack( stream ); + // Read the itemstack + IAEItemStack itemStack = ThEBasePacket.readAEItemStack(stream); - // Ensure it is not null - if( itemStack != null ) - { - // Add to the list - this.fullList.add( itemStack ); - } - } - break; + // Ensure it is not null + if (itemStack != null) { + // Add to the list + this.fullList.add(itemStack); + } + } + break; - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: - // Read the change amount - int changeAmount = stream.readInt(); + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: + // Read the change amount + int changeAmount = stream.readInt(); - // Read the item - this.changedStack = ThEBasePacket.readAEItemStack( stream ); + // Read the item + this.changedStack = ThEBasePacket.readAEItemStack(stream); - // Adjust it's size - this.changedStack.setStackSize( changeAmount ); + // Adjust it's size + this.changedStack.setStackSize(changeAmount); - break; + break; - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: - // Read sorts - this.sortingDirection = EnumCache.AE_SORT_DIRECTIONS[stream.readInt()]; - this.sortingOrder = EnumCache.AE_SORT_ORDERS[stream.readInt()]; - this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; - break; - } - } + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: + // Read sorts + this.sortingDirection = EnumCache.AE_SORT_DIRECTIONS[stream.readInt()]; + this.sortingOrder = EnumCache.AE_SORT_ORDERS[stream.readInt()]; + this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; + break; + } + } - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: - // Is the list null? - if( this.fullList == null ) - { - // No items - stream.writeInt( 0 ); - return; - } + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_FULL_LIST: + // Is the list null? + if (this.fullList == null) { + // No items + stream.writeInt(0); + return; + } - // Write how many items there are - stream.writeInt( this.fullList.size() ); + // Write how many items there are + stream.writeInt(this.fullList.size()); - // Get the iterator - Iterator listIterator = this.fullList.iterator(); + // Get the iterator + Iterator listIterator = this.fullList.iterator(); - // Write each item - while( listIterator.hasNext() ) - { - ThEBasePacket.writeAEItemStack( listIterator.next(), stream ); - } - break; + // Write each item + while (listIterator.hasNext()) { + ThEBasePacket.writeAEItemStack(listIterator.next(), stream); + } + break; - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: - // Write the change amount - stream.writeInt( (int)this.changedStack.getStackSize() ); + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_CHANGE: + // Write the change amount + stream.writeInt((int) this.changedStack.getStackSize()); - // Write the change - ThEBasePacket.writeAEItemStack( this.changedStack, stream ); - break; - - case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: - // Write the sorts - stream.writeInt( this.sortingDirection.ordinal() ); - stream.writeInt( this.sortingOrder.ordinal() ); - stream.writeInt( this.viewMode.ordinal() ); - break; - } - - } + // Write the change + ThEBasePacket.writeAEItemStack(this.changedStack, stream); + break; + case Packet_C_ArcaneCraftingTerminal.MODE_RECEIVE_SORTS: + // Write the sorts + stream.writeInt(this.sortingDirection.ordinal()); + stream.writeInt(this.sortingOrder.ordinal()); + stream.writeInt(this.viewMode.ordinal()); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_AspectSlot.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_AspectSlot.java index 1ed3236c..b081d4cc 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_AspectSlot.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_AspectSlot.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.network.packet.client; -import java.util.ArrayList; -import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; @@ -19,92 +19,78 @@ import thaumicenergistics.common.network.ThEBasePacket; * @author Nividica * */ -public class Packet_C_AspectSlot - extends ThEClientPacket -{ - private static final byte MODE_LIST_UPDATE = 0; +public class Packet_C_AspectSlot extends ThEClientPacket { + private static final byte MODE_LIST_UPDATE = 0; - private List filterAspects; + private List filterAspects; - public static void setFilterList( final List filterAspects, final EntityPlayer player ) - { - Packet_C_AspectSlot packet = new Packet_C_AspectSlot(); + public static void setFilterList(final List filterAspects, final EntityPlayer player) { + Packet_C_AspectSlot packet = new Packet_C_AspectSlot(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_C_AspectSlot.MODE_LIST_UPDATE; + // Set the mode + packet.mode = Packet_C_AspectSlot.MODE_LIST_UPDATE; - // Mark to use compression - packet.useCompression = true; + // Mark to use compression + packet.useCompression = true; - // Set the list - packet.filterAspects = filterAspects; + // Set the list + packet.filterAspects = filterAspects; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - // Ensure it is an IAspectSlotGui - if( !( gui instanceof IAspectSlotGui ) ) - { - return; - } + // Ensure it is an IAspectSlotGui + if (!(gui instanceof IAspectSlotGui)) { + return; + } - switch ( this.mode ) - { - case Packet_C_AspectSlot.MODE_LIST_UPDATE: - ( (IAspectSlotGui)gui ).updateAspects( this.filterAspects ); - break; - } + switch (this.mode) { + case Packet_C_AspectSlot.MODE_LIST_UPDATE: + ((IAspectSlotGui) gui).updateAspects(this.filterAspects); + break; + } + } - } + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_AspectSlot.MODE_LIST_UPDATE: + // Read the size + int size = stream.readInt(); - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_AspectSlot.MODE_LIST_UPDATE: - // Read the size - int size = stream.readInt(); + // Create the list + this.filterAspects = new ArrayList(size); - // Create the list - this.filterAspects = new ArrayList( size ); + // Read each aspect + for (int i = 0; i < size; i++) { + this.filterAspects.add(ThEBasePacket.readAspect(stream)); + } + break; + } + } - // Read each aspect - for( int i = 0; i < size; i++ ) - { - this.filterAspects.add( ThEBasePacket.readAspect( stream ) ); - } - break; - } - } - - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_AspectSlot.MODE_LIST_UPDATE: - // Write the size of the list - stream.writeInt( this.filterAspects.size() ); - - // Write each aspect - for( int index = 0; index < this.filterAspects.size(); index++ ) - { - ThEBasePacket.writeAspect( this.filterAspects.get( index ), stream ); - } - break; - } - } + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_AspectSlot.MODE_LIST_UPDATE: + // Write the size of the list + stream.writeInt(this.filterAspects.size()); + // Write each aspect + for (int index = 0; index < this.filterAspects.size(); index++) { + ThEBasePacket.writeAspect(this.filterAspects.get(index), stream); + } + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaCellTerminal.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaCellTerminal.java index 823e51df..3a660986 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaCellTerminal.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaCellTerminal.java @@ -1,11 +1,11 @@ package thaumicenergistics.common.network.packet.client; -import java.util.ArrayList; -import java.util.Collection; import appeng.api.config.ViewItems; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.Collection; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; @@ -27,208 +27,193 @@ import thaumicenergistics.common.storage.AspectStackComparator.AspectStackCompar * @author Nividica * */ -public class Packet_C_EssentiaCellTerminal - extends ThEClientPacket -{ - /** - * Modes - */ - private static final byte MODE_FULL_LIST = 0, - MODE_SELECTED_ASPECT = 1, - MODE_VIEWING_CHANGED = 2, - MODE_LIST_CHANGED = 3; +public class Packet_C_EssentiaCellTerminal extends ThEClientPacket { + /** + * Modes + */ + private static final byte MODE_FULL_LIST = 0, + MODE_SELECTED_ASPECT = 1, + MODE_VIEWING_CHANGED = 2, + MODE_LIST_CHANGED = 3; - private Collection aspectStackList; - private Aspect selectedAspect; - private AspectStackComparatorMode sortMode; - private IAspectStack change; - private ViewItems viewMode; + private Collection aspectStackList; + private Aspect selectedAspect; + private AspectStackComparatorMode sortMode; + private IAspectStack change; + private ViewItems viewMode; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_C_EssentiaCellTerminal newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_C_EssentiaCellTerminal packet = new Packet_C_EssentiaCellTerminal(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_C_EssentiaCellTerminal newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_C_EssentiaCellTerminal packet = new Packet_C_EssentiaCellTerminal(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - /** - * Called to send the full list of aspects. - * - * @param player - * @param list - */ - public static void sendFullList( final EntityPlayer player, final Collection list ) - { - Packet_C_EssentiaCellTerminal packet = newPacket( player, MODE_FULL_LIST ); + /** + * Called to send the full list of aspects. + * + * @param player + * @param list + */ + public static void sendFullList(final EntityPlayer player, final Collection list) { + Packet_C_EssentiaCellTerminal packet = newPacket(player, MODE_FULL_LIST); - // Mark to use compression - packet.useCompression = true; + // Mark to use compression + packet.useCompression = true; - // Set the list - packet.aspectStackList = list; + // Set the list + packet.aspectStackList = list; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Sends the viewing modes. - * - * @param player - * @param sortMode - */ - public static void sendViewingModes( final EntityPlayer player, final AspectStackComparatorMode sortMode, final ViewItems viewMode ) - { - Packet_C_EssentiaCellTerminal packet = newPacket( player, MODE_VIEWING_CHANGED ); + /** + * Sends the viewing modes. + * + * @param player + * @param sortMode + */ + public static void sendViewingModes( + final EntityPlayer player, final AspectStackComparatorMode sortMode, final ViewItems viewMode) { + Packet_C_EssentiaCellTerminal packet = newPacket(player, MODE_VIEWING_CHANGED); - // Set the sort mode - packet.sortMode = sortMode; + // Set the sort mode + packet.sortMode = sortMode; - // Set the view mode - packet.viewMode = viewMode; + // Set the view mode + packet.viewMode = viewMode; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Called when an aspect amount changes. - * - * @param player - * @param change - */ - public static void setAspectAmount( final EntityPlayer player, final IAspectStack change ) - { - Packet_C_EssentiaCellTerminal packet = newPacket( player, MODE_LIST_CHANGED ); + /** + * Called when an aspect amount changes. + * + * @param player + * @param change + */ + public static void setAspectAmount(final EntityPlayer player, final IAspectStack change) { + Packet_C_EssentiaCellTerminal packet = newPacket(player, MODE_LIST_CHANGED); - // Set the change - packet.change = change; + // Set the change + packet.change = change; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Called when the selected aspect changes. - * - * @param player - * @param selectedAspect - */ - public static void setSelectedAspect( final EntityPlayer player, final Aspect selectedAspect ) - { - Packet_C_EssentiaCellTerminal packet = newPacket( player, MODE_SELECTED_ASPECT ); + /** + * Called when the selected aspect changes. + * + * @param player + * @param selectedAspect + */ + public static void setSelectedAspect(final EntityPlayer player, final Aspect selectedAspect) { + Packet_C_EssentiaCellTerminal packet = newPacket(player, MODE_SELECTED_ASPECT); - // Set the selected aspect - packet.selectedAspect = selectedAspect; + // Set the selected aspect + packet.selectedAspect = selectedAspect; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + Gui gui = Minecraft.getMinecraft().currentScreen; - if( gui instanceof GuiEssentiaCellTerminal ) - { - switch ( this.mode ) - { - case MODE_FULL_LIST: - ( (GuiEssentiaCellTerminal)gui ).onReceiveAspectList( this.aspectStackList ); - break; + if (gui instanceof GuiEssentiaCellTerminal) { + switch (this.mode) { + case MODE_FULL_LIST: + ((GuiEssentiaCellTerminal) gui).onReceiveAspectList(this.aspectStackList); + break; - case MODE_SELECTED_ASPECT: - ( (GuiEssentiaCellTerminal)gui ).onReceiveSelectedAspect( this.selectedAspect ); - break; + case MODE_SELECTED_ASPECT: + ((GuiEssentiaCellTerminal) gui).onReceiveSelectedAspect(this.selectedAspect); + break; - case MODE_VIEWING_CHANGED: - // Update the modes - ( (GuiEssentiaCellTerminal)gui ).onViewingModesChanged( this.sortMode, this.viewMode ); - break; + case MODE_VIEWING_CHANGED: + // Update the modes + ((GuiEssentiaCellTerminal) gui).onViewingModesChanged(this.sortMode, this.viewMode); + break; - case MODE_LIST_CHANGED: - // Update the list - ( (GuiEssentiaCellTerminal)gui ).onReceiveAspectListChange( this.change ); - break; - } - } - } + case MODE_LIST_CHANGED: + // Update the list + ((GuiEssentiaCellTerminal) gui).onReceiveAspectListChange(this.change); + break; + } + } + } - @Override - public void readData( final ByteBuf stream ) - { + @Override + public void readData(final ByteBuf stream) { - switch ( this.mode ) - { - case Packet_C_EssentiaCellTerminal.MODE_FULL_LIST: - this.aspectStackList = new ArrayList(); + switch (this.mode) { + case Packet_C_EssentiaCellTerminal.MODE_FULL_LIST: + this.aspectStackList = new ArrayList(); - // Read each stack - while( stream.readableBytes() > 0 ) - { - this.aspectStackList.add( AspectStack.loadAspectStackFromStream( stream ) ); - } - break; + // Read each stack + while (stream.readableBytes() > 0) { + this.aspectStackList.add(AspectStack.loadAspectStackFromStream(stream)); + } + break; - case Packet_C_EssentiaCellTerminal.MODE_SELECTED_ASPECT: - // Read aspect - this.selectedAspect = ThEBasePacket.readAspect( stream ); - break; + case Packet_C_EssentiaCellTerminal.MODE_SELECTED_ASPECT: + // Read aspect + this.selectedAspect = ThEBasePacket.readAspect(stream); + break; - case Packet_C_EssentiaCellTerminal.MODE_VIEWING_CHANGED: - // Read the mode ordinals - this.sortMode = AspectStackComparatorMode.VALUES[stream.readInt()]; - this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; - break; + case Packet_C_EssentiaCellTerminal.MODE_VIEWING_CHANGED: + // Read the mode ordinals + this.sortMode = AspectStackComparatorMode.VALUES[stream.readInt()]; + this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; + break; - case Packet_C_EssentiaCellTerminal.MODE_LIST_CHANGED: - // Read the stack - this.change = AspectStack.loadAspectStackFromStream( stream ); - } - } + case Packet_C_EssentiaCellTerminal.MODE_LIST_CHANGED: + // Read the stack + this.change = AspectStack.loadAspectStackFromStream(stream); + } + } - @Override - public void writeData( final ByteBuf stream ) - { + @Override + public void writeData(final ByteBuf stream) { - switch ( this.mode ) - { - case Packet_C_EssentiaCellTerminal.MODE_FULL_LIST: - // Write each stack - for( IAspectStack stack : this.aspectStackList ) - { - stack.writeToStream( stream ); - } - break; + switch (this.mode) { + case Packet_C_EssentiaCellTerminal.MODE_FULL_LIST: + // Write each stack + for (IAspectStack stack : this.aspectStackList) { + stack.writeToStream(stream); + } + break; - case Packet_C_EssentiaCellTerminal.MODE_SELECTED_ASPECT: - // Write aspect - ThEBasePacket.writeAspect( this.selectedAspect, stream ); - break; + case Packet_C_EssentiaCellTerminal.MODE_SELECTED_ASPECT: + // Write aspect + ThEBasePacket.writeAspect(this.selectedAspect, stream); + break; - case Packet_C_EssentiaCellTerminal.MODE_VIEWING_CHANGED: - // Write the mode ordinals - stream.writeInt( this.sortMode.ordinal() ); - stream.writeInt( this.viewMode.ordinal() ); - break; + case Packet_C_EssentiaCellTerminal.MODE_VIEWING_CHANGED: + // Write the mode ordinals + stream.writeInt(this.sortMode.ordinal()); + stream.writeInt(this.viewMode.ordinal()); + break; - case Packet_C_EssentiaCellTerminal.MODE_LIST_CHANGED: - // Write the stack - this.change.writeToStream( stream ); - } - } + case Packet_C_EssentiaCellTerminal.MODE_LIST_CHANGED: + // Write the stack + this.change.writeToStream(stream); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaEmitter.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaEmitter.java index f8dff1f4..3a28c0e9 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaEmitter.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaEmitter.java @@ -18,124 +18,111 @@ import thaumicenergistics.common.registries.EnumCache; * @author Nividica * */ -public class Packet_C_EssentiaEmitter - extends ThEClientPacket -{ - /** - * Packet modes. - */ - private static final byte MODE_UPDATE_WANTED = 1, - MODE_UPDATE_REDSTONE = 2; +public class Packet_C_EssentiaEmitter extends ThEClientPacket { + /** + * Packet modes. + */ + private static final byte MODE_UPDATE_WANTED = 1, MODE_UPDATE_REDSTONE = 2; - private RedstoneMode redstoneMode; - private long threshold; + private RedstoneMode redstoneMode; + private long threshold; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_C_EssentiaEmitter newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_C_EssentiaEmitter packet = new Packet_C_EssentiaEmitter(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_C_EssentiaEmitter newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_C_EssentiaEmitter packet = new Packet_C_EssentiaEmitter(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendRedstoneMode( final RedstoneMode redstoneMode, final EntityPlayer player ) - { - Packet_C_EssentiaEmitter packet = newPacket( player, MODE_UPDATE_REDSTONE ); + public static void sendRedstoneMode(final RedstoneMode redstoneMode, final EntityPlayer player) { + Packet_C_EssentiaEmitter packet = newPacket(player, MODE_UPDATE_REDSTONE); - // Set the redstone mode - packet.redstoneMode = redstoneMode; + // Set the redstone mode + packet.redstoneMode = redstoneMode; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Create a packet to update a client with a new wanted amount. - * - * @param threshold - * @param player - * @return - */ - public static void sendThresholdValue( final long threshold, final EntityPlayer player ) - { - Packet_C_EssentiaEmitter packet = newPacket( player, MODE_UPDATE_WANTED ); + /** + * Create a packet to update a client with a new wanted amount. + * + * @param threshold + * @param player + * @return + */ + public static void sendThresholdValue(final long threshold, final EntityPlayer player) { + Packet_C_EssentiaEmitter packet = newPacket(player, MODE_UPDATE_WANTED); - // Set the wanted amount - packet.threshold = threshold; + // Set the wanted amount + packet.threshold = threshold; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the current screen being displayed to the user - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the current screen being displayed to the user + Gui gui = Minecraft.getMinecraft().currentScreen; - // Ensure it is a GuiEssentiaLevelEmitter - if( gui instanceof GuiEssentiaLevelEmitter ) - { + // Ensure it is a GuiEssentiaLevelEmitter + if (gui instanceof GuiEssentiaLevelEmitter) { - switch ( this.mode ) - { - case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: - // Update wanted amount - ( (GuiEssentiaLevelEmitter)gui ).onReceiveThresholdValue( this.threshold ); - break; + switch (this.mode) { + case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: + // Update wanted amount + ((GuiEssentiaLevelEmitter) gui).onReceiveThresholdValue(this.threshold); + break; - case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: - // Update redstone mode - ( (GuiEssentiaLevelEmitter)gui ).onReceiveRedstoneMode( this.redstoneMode ); - break; - } - } - } + case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: + // Update redstone mode + ((GuiEssentiaLevelEmitter) gui).onReceiveRedstoneMode(this.redstoneMode); + break; + } + } + } - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: - // Read the wanted amount - this.threshold = stream.readLong(); - break; + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: + // Read the wanted amount + this.threshold = stream.readLong(); + break; - case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: - // Read the redstone mode ordinal - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readInt()]; - break; - } - } + case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: + // Read the redstone mode ordinal + this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readInt()]; + break; + } + } - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: - // Write the wanted amount - stream.writeLong( this.threshold ); - break; + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaEmitter.MODE_UPDATE_WANTED: + // Write the wanted amount + stream.writeLong(this.threshold); + break; - case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: - // Write the redstone mode ordinal - stream.writeInt( this.redstoneMode.ordinal() ); + case Packet_C_EssentiaEmitter.MODE_UPDATE_REDSTONE: + // Write the redstone mode ordinal + stream.writeInt(this.redstoneMode.ordinal()); - break; - } - } + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaIOBus.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaIOBus.java index b0b7c6e4..425d8a93 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaIOBus.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaIOBus.java @@ -19,316 +19,301 @@ import thaumicenergistics.common.registries.EnumCache; * @author Nividica * */ -public class Packet_C_EssentiaIOBus - extends ThEClientPacket -{ - /** - * Packet modes. - */ - private static final byte MODE_SET_REDSTONE_CONTROLLED = 0, - MODE_SET_REDSTONE_MODE = 1, - MODE_SET_FILTER_SIZE = 2, - MODE_SEND_FULL_UPDATE = 3, - MODE_SEND_VOID_MODE = 4, - MODE_SEND_HAS_CRAFTINFG = 5, - MODE_SET_CRAFTING_MODE = 6; +public class Packet_C_EssentiaIOBus extends ThEClientPacket { + /** + * Packet modes. + */ + private static final byte MODE_SET_REDSTONE_CONTROLLED = 0, + MODE_SET_REDSTONE_MODE = 1, + MODE_SET_FILTER_SIZE = 2, + MODE_SEND_FULL_UPDATE = 3, + MODE_SEND_VOID_MODE = 4, + MODE_SEND_HAS_CRAFTINFG = 5, + MODE_SET_CRAFTING_MODE = 6; - private RedstoneMode redstoneMode; + private RedstoneMode redstoneMode; - private byte filterSize; + private byte filterSize; - private boolean redstoneControlled, isVoidAllowed, hasCraftingCard, craftingOnly; + private boolean redstoneControlled, isVoidAllowed, hasCraftingCard, craftingOnly; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_C_EssentiaIOBus newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_C_EssentiaIOBus packet = new Packet_C_EssentiaIOBus(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_C_EssentiaIOBus newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_C_EssentiaIOBus packet = new Packet_C_EssentiaIOBus(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendBusState( final EntityPlayer player, final RedstoneMode redstoneMode, final byte filterSize, - final boolean redstoneControlled, final boolean hasCraftingCard, final boolean isCraftingOnly ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SEND_FULL_UPDATE ); + public static void sendBusState( + final EntityPlayer player, + final RedstoneMode redstoneMode, + final byte filterSize, + final boolean redstoneControlled, + final boolean hasCraftingCard, + final boolean isCraftingOnly) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SEND_FULL_UPDATE); - // Set the redstone mode - packet.redstoneMode = redstoneMode; + // Set the redstone mode + packet.redstoneMode = redstoneMode; - // Set the filter size - packet.filterSize = filterSize; + // Set the filter size + packet.filterSize = filterSize; - // Set controlled - packet.redstoneControlled = redstoneControlled; - packet.hasCraftingCard = hasCraftingCard; - packet.craftingOnly = isCraftingOnly; + // Set controlled + packet.redstoneControlled = redstoneControlled; + packet.hasCraftingCard = hasCraftingCard; + packet.craftingOnly = isCraftingOnly; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Create a packet to update the clients filter size. - * - * @param player - * @param filterSize - * @return - */ - public static void sendFilterSize( final EntityPlayer player, final byte filterSize ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SET_FILTER_SIZE ); + /** + * Create a packet to update the clients filter size. + * + * @param player + * @param filterSize + * @return + */ + public static void sendFilterSize(final EntityPlayer player, final byte filterSize) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SET_FILTER_SIZE); - // Set the filter size - packet.filterSize = filterSize; + // Set the filter size + packet.filterSize = filterSize; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Create a packet to update the client whether the bus is controlled - * by redstone or not. - * - * @param player - * @param redstoneControlled - * @return - */ - public static void sendRedstoneControlled( final EntityPlayer player, final boolean redstoneControlled ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SET_REDSTONE_CONTROLLED ); + /** + * Create a packet to update the client whether the bus is controlled + * by redstone or not. + * + * @param player + * @param redstoneControlled + * @return + */ + public static void sendRedstoneControlled(final EntityPlayer player, final boolean redstoneControlled) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SET_REDSTONE_CONTROLLED); - // Set controlled - packet.redstoneControlled = redstoneControlled; + // Set controlled + packet.redstoneControlled = redstoneControlled; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - public static void sendHasCraftingCard( final EntityPlayer player, final boolean hasCraftingCard ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SEND_HAS_CRAFTINFG ); + public static void sendHasCraftingCard(final EntityPlayer player, final boolean hasCraftingCard) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SEND_HAS_CRAFTINFG); - // Set controlled - packet.hasCraftingCard = hasCraftingCard; + // Set controlled + packet.hasCraftingCard = hasCraftingCard; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Create a packet to update the clients redstone mode. - * - * @param player - * @param redstoneMode - * @return - */ - public static void sendRedstoneMode( final EntityPlayer player, final RedstoneMode redstoneMode ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SET_REDSTONE_MODE ); + /** + * Create a packet to update the clients redstone mode. + * + * @param player + * @param redstoneMode + * @return + */ + public static void sendRedstoneMode(final EntityPlayer player, final RedstoneMode redstoneMode) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SET_REDSTONE_MODE); - // Set the redstone mode - packet.redstoneMode = redstoneMode; + // Set the redstone mode + packet.redstoneMode = redstoneMode; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Sends an update the client informing it of the void mode. - * - * @param player - * @param isVoidAllowed - * @return - */ - public static void sendVoidMode( final EntityPlayer player, final boolean isVoidAllowed ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SEND_VOID_MODE ); + /** + * Sends an update the client informing it of the void mode. + * + * @param player + * @param isVoidAllowed + * @return + */ + public static void sendVoidMode(final EntityPlayer player, final boolean isVoidAllowed) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SEND_VOID_MODE); - // Set the void mode - packet.isVoidAllowed = isVoidAllowed; + // Set the void mode + packet.isVoidAllowed = isVoidAllowed; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - public static void sendCraftingMode( final EntityPlayer player, final boolean isCraftingOnly ) - { - Packet_C_EssentiaIOBus packet = newPacket( player, MODE_SET_CRAFTING_MODE ); + public static void sendCraftingMode(final EntityPlayer player, final boolean isCraftingOnly) { + Packet_C_EssentiaIOBus packet = newPacket(player, MODE_SET_CRAFTING_MODE); - // Set the void mode - packet.craftingOnly = isCraftingOnly; + // Set the void mode + packet.craftingOnly = isCraftingOnly; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + // Ensure the gui is a GuiEssentiaIO + if (!(gui instanceof GuiEssentiaIO)) { + return; + } - // Ensure the gui is a GuiEssentiaIO - if( !( gui instanceof GuiEssentiaIO ) ) - { - return; - } + switch (this.mode) { + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: + // Set redstone controlled + ((GuiEssentiaIO) gui).onReceiveRedstoneControlled(this.redstoneControlled); + break; - switch ( this.mode ) - { - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: - // Set redstone controlled - ( (GuiEssentiaIO)gui ).onReceiveRedstoneControlled( this.redstoneControlled ); - break; + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: + // Set redstone mode + ((GuiEssentiaIO) gui).onReceiveRedstoneMode(this.redstoneMode); + break; - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: - // Set redstone mode - ( (GuiEssentiaIO)gui ).onReceiveRedstoneMode( this.redstoneMode ); - break; + case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: + // Set filter size + ((GuiEssentiaIO) gui).onReceiveFilterSize(this.filterSize); + break; - case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: - // Set filter size - ( (GuiEssentiaIO)gui ).onReceiveFilterSize( this.filterSize ); - break; + case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: + // Set redstone mode + ((GuiEssentiaIO) gui).onReceiveRedstoneMode(this.redstoneMode); - case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: - // Set redstone mode - ( (GuiEssentiaIO)gui ).onReceiveRedstoneMode( this.redstoneMode ); + // Set redstone controlled + ((GuiEssentiaIO) gui).onReceiveRedstoneControlled(this.redstoneControlled); - // Set redstone controlled - ( (GuiEssentiaIO)gui ).onReceiveRedstoneControlled( this.redstoneControlled ); + // Set filter size + ((GuiEssentiaIO) gui).onReceiveFilterSize(this.filterSize); + ((GuiEssentiaIO) gui).onReceiveHasCrafting(this.hasCraftingCard); + ((GuiEssentiaIO) gui).onReceiveCraftingOnly(this.craftingOnly); + break; - // Set filter size - ( (GuiEssentiaIO)gui ).onReceiveFilterSize( this.filterSize ); - ( (GuiEssentiaIO)gui ).onReceiveHasCrafting(this.hasCraftingCard); - ( (GuiEssentiaIO)gui ).onReceiveCraftingOnly(this.craftingOnly); - break; + case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: + // Set void mode + ((GuiEssentiaIO) gui).onServerSendVoidMode(this.isVoidAllowed); + break; - case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: - // Set void mode - ( (GuiEssentiaIO)gui ).onServerSendVoidMode( this.isVoidAllowed ); - break; + case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: + ((GuiEssentiaIO) gui).onReceiveCraftingOnly(this.craftingOnly); + break; - case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: - ( (GuiEssentiaIO)gui ).onReceiveCraftingOnly(this.craftingOnly); - break; + case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: + ((GuiEssentiaIO) gui).onReceiveHasCrafting(this.hasCraftingCard); + break; + } + } - case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: - ( (GuiEssentiaIO)gui ).onReceiveHasCrafting(this.hasCraftingCard); - break; + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: + // Read redstone controlled + this.redstoneControlled = stream.readBoolean(); + break; - } - } + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: + // Read the redstone mode ordinal + this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readByte()]; + break; - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: - // Read redstone controlled - this.redstoneControlled = stream.readBoolean(); - break; + case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: + // Read the filter size + this.filterSize = stream.readByte(); + break; - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: - // Read the redstone mode ordinal - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readByte()]; - break; + case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: + // Read redstone controlled + this.redstoneControlled = stream.readBoolean(); - case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: - // Read the filter size - this.filterSize = stream.readByte(); - break; + // Read the redstone mode ordinal + this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readByte()]; - case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: - // Read redstone controlled - this.redstoneControlled = stream.readBoolean(); + // Read the filter size + this.filterSize = stream.readByte(); - // Read the redstone mode ordinal - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[stream.readByte()]; + this.hasCraftingCard = stream.readBoolean(); + this.craftingOnly = stream.readBoolean(); + break; - // Read the filter size - this.filterSize = stream.readByte(); + case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: + // Read void mode + this.isVoidAllowed = stream.readBoolean(); + break; - this.hasCraftingCard = stream.readBoolean(); - this.craftingOnly = stream.readBoolean(); - break; + case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: + this.craftingOnly = stream.readBoolean(); + break; - case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: - // Read void mode - this.isVoidAllowed = stream.readBoolean(); - break; + case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: + this.hasCraftingCard = stream.readBoolean(); + break; + } + } - case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: - this.craftingOnly = stream.readBoolean(); - break; + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: + // Write redstone controlled + stream.writeBoolean(this.redstoneControlled); + break; - case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: - this.hasCraftingCard = stream.readBoolean(); - break; - } - } + case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: + // Write the redstone mode ordinal + stream.writeByte((byte) this.redstoneMode.ordinal()); + break; - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_CONTROLLED: - // Write redstone controlled - stream.writeBoolean( this.redstoneControlled ); - break; + case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: + // Write the filter size + stream.writeByte(this.filterSize); + break; - case Packet_C_EssentiaIOBus.MODE_SET_REDSTONE_MODE: - // Write the redstone mode ordinal - stream.writeByte( (byte)this.redstoneMode.ordinal() ); - break; + case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: + // Write redstone controlled + stream.writeBoolean(this.redstoneControlled); - case Packet_C_EssentiaIOBus.MODE_SET_FILTER_SIZE: - // Write the filter size - stream.writeByte( this.filterSize ); - break; + // Write the redstone mode ordinal + stream.writeByte((byte) this.redstoneMode.ordinal()); - case Packet_C_EssentiaIOBus.MODE_SEND_FULL_UPDATE: - // Write redstone controlled - stream.writeBoolean( this.redstoneControlled ); + // Write the filter size + stream.writeByte(this.filterSize); - // Write the redstone mode ordinal - stream.writeByte( (byte)this.redstoneMode.ordinal() ); + stream.writeBoolean(this.hasCraftingCard); + stream.writeBoolean(this.craftingOnly); + break; - // Write the filter size - stream.writeByte( this.filterSize ); + case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: + // Write void mode + stream.writeBoolean(this.isVoidAllowed); + break; - stream.writeBoolean(this.hasCraftingCard); - stream.writeBoolean(this.craftingOnly); - break; - - case Packet_C_EssentiaIOBus.MODE_SEND_VOID_MODE: - // Write void mode - stream.writeBoolean( this.isVoidAllowed ); - break; - - case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: - stream.writeBoolean(this.craftingOnly); - break; - - case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: - stream.writeBoolean(this.hasCraftingCard); - break; - } - } + case Packet_C_EssentiaIOBus.MODE_SET_CRAFTING_MODE: + stream.writeBoolean(this.craftingOnly); + break; + case Packet_C_EssentiaIOBus.MODE_SEND_HAS_CRAFTINFG: + stream.writeBoolean(this.hasCraftingCard); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaStorageBus.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaStorageBus.java index 4d77f2e2..e934e98d 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaStorageBus.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaStorageBus.java @@ -16,78 +16,66 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -public class Packet_C_EssentiaStorageBus - extends ThEClientPacket -{ - /** - * Packet modes. - */ - private static final byte MODE_SET_VOID = 1; +public class Packet_C_EssentiaStorageBus extends ThEClientPacket { + /** + * Packet modes. + */ + private static final byte MODE_SET_VOID = 1; - private boolean isVoidAllowed; + private boolean isVoidAllowed; - public static void sendIsVoidAllowed( final EntityPlayer player, final boolean isVoidAllowed ) - { - Packet_C_EssentiaStorageBus packet = new Packet_C_EssentiaStorageBus(); + public static void sendIsVoidAllowed(final EntityPlayer player, final boolean isVoidAllowed) { + Packet_C_EssentiaStorageBus packet = new Packet_C_EssentiaStorageBus(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_C_EssentiaStorageBus.MODE_SET_VOID; + // Set the mode + packet.mode = Packet_C_EssentiaStorageBus.MODE_SET_VOID; - // Set void - packet.isVoidAllowed = isVoidAllowed; + // Set void + packet.isVoidAllowed = isVoidAllowed; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaStorageBus.MODE_SET_VOID: - // Read void mode - this.isVoidAllowed = stream.readBoolean(); - break; - } - } + @Override + protected void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaStorageBus.MODE_SET_VOID: + // Read void mode + this.isVoidAllowed = stream.readBoolean(); + break; + } + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - // Ensure the gui is a GuiEssentiaStorageBus - if( !( gui instanceof GuiEssentiaStorageBus ) ) - { - return; - } + // Ensure the gui is a GuiEssentiaStorageBus + if (!(gui instanceof GuiEssentiaStorageBus)) { + return; + } - switch ( this.mode ) - { - case Packet_C_EssentiaStorageBus.MODE_SET_VOID: - // Set void mode - ( (GuiEssentiaStorageBus)gui ).onServerSentVoidMode( this.isVoidAllowed ); - break; - } - - } - - @Override - protected void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_C_EssentiaStorageBus.MODE_SET_VOID: - // Write void mode - stream.writeBoolean( this.isVoidAllowed ); - break; - } - } + switch (this.mode) { + case Packet_C_EssentiaStorageBus.MODE_SET_VOID: + // Set void mode + ((GuiEssentiaStorageBus) gui).onServerSentVoidMode(this.isVoidAllowed); + break; + } + } + @Override + protected void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_C_EssentiaStorageBus.MODE_SET_VOID: + // Write void mode + stream.writeBoolean(this.isVoidAllowed); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaVibrationChamber.java index 184ac10d..e1c475f4 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_EssentiaVibrationChamber.java @@ -18,105 +18,97 @@ import thaumicenergistics.common.tiles.TileEssentiaVibrationChamber; * @author Nividica * */ -public class Packet_C_EssentiaVibrationChamber - extends ThEClientPacket -{ - private static final byte MODE_UPDATE = 1; +public class Packet_C_EssentiaVibrationChamber extends ThEClientPacket { + private static final byte MODE_UPDATE = 1; - private float powerPerTick, maxPowerPerTick; - private int ticksRemaining, totalTicks; + private float powerPerTick, maxPowerPerTick; + private int ticksRemaining, totalTicks; - /** - * Creates an update packet. - * - * @param player - * @param powerPerTick - * @param ticksRemaining - * @param totalTicks - * @return - */ - public static void sendUpdate( final EntityPlayer player, final float powerPerTick, final float maxPowerPerTick, - final int ticksRemaining, final int totalTicks ) - { - Packet_C_EssentiaVibrationChamber packet = new Packet_C_EssentiaVibrationChamber(); + /** + * Creates an update packet. + * + * @param player + * @param powerPerTick + * @param ticksRemaining + * @param totalTicks + * @return + */ + public static void sendUpdate( + final EntityPlayer player, + final float powerPerTick, + final float maxPowerPerTick, + final int ticksRemaining, + final int totalTicks) { + Packet_C_EssentiaVibrationChamber packet = new Packet_C_EssentiaVibrationChamber(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_C_EssentiaVibrationChamber.MODE_UPDATE; + // Set the mode + packet.mode = Packet_C_EssentiaVibrationChamber.MODE_UPDATE; - // Set values - packet.powerPerTick = powerPerTick; - packet.maxPowerPerTick = maxPowerPerTick; - packet.ticksRemaining = ticksRemaining; - packet.totalTicks = totalTicks; + // Set values + packet.powerPerTick = powerPerTick; + packet.maxPowerPerTick = maxPowerPerTick; + packet.ticksRemaining = ticksRemaining; + packet.totalTicks = totalTicks; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - if( this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE ) - { - // Read PPT - this.powerPerTick = stream.readFloat(); + @Override + protected void readData(final ByteBuf stream) { + if (this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE) { + // Read PPT + this.powerPerTick = stream.readFloat(); - // Read MPPT - this.maxPowerPerTick = stream.readFloat(); + // Read MPPT + this.maxPowerPerTick = stream.readFloat(); - // Read TR - this.ticksRemaining = stream.readInt(); + // Read TR + this.ticksRemaining = stream.readInt(); - // Read TT - this.totalTicks = stream.readInt(); - } + // Read TT + this.totalTicks = stream.readInt(); + } + } - } + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + // Ensure the gui is the EVC + if (!(gui instanceof GuiEssentiaVibrationChamber)) { + return; + } - // Ensure the gui is the EVC - if( !( gui instanceof GuiEssentiaVibrationChamber ) ) - { - return; - } + // Get the container + Container container = ((GuiEssentiaVibrationChamber) gui).inventorySlots; - // Get the container - Container container = ( (GuiEssentiaVibrationChamber)gui ).inventorySlots; + if (this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE) { + // Call update + ((ContainerEssentiaVibrationChamber) container) + .onChamberUpdate(this.powerPerTick, this.maxPowerPerTick, this.ticksRemaining, this.totalTicks); + } + } - if( this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE ) - { - // Call update - ( (ContainerEssentiaVibrationChamber)container ).onChamberUpdate( this.powerPerTick, this.maxPowerPerTick, this.ticksRemaining, - this.totalTicks ); - } - } + @Override + protected void writeData(final ByteBuf stream) { + if (this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE) { + // Write PPT + stream.writeFloat(this.powerPerTick); - @Override - protected void writeData( final ByteBuf stream ) - { - if( this.mode == Packet_C_EssentiaVibrationChamber.MODE_UPDATE ) - { - // Write PPT - stream.writeFloat( this.powerPerTick ); + // Write MPPT + stream.writeFloat(this.maxPowerPerTick); - // Write MPPT - stream.writeFloat( this.maxPowerPerTick ); - - // Write TR - stream.writeInt( this.ticksRemaining ); - - // Write TT - stream.writeInt( this.totalTicks ); - } - } + // Write TR + stream.writeInt(this.ticksRemaining); + // Write TT + stream.writeInt(this.totalTicks); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_KnowledgeInscriber.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_KnowledgeInscriber.java index 2dcbf6d2..71be3ac8 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_KnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_KnowledgeInscriber.java @@ -17,63 +17,55 @@ import thaumicenergistics.common.tiles.TileKnowledgeInscriber; * @author Nividica * */ -public class Packet_C_KnowledgeInscriber - extends ThEClientPacket -{ +public class Packet_C_KnowledgeInscriber extends ThEClientPacket { - private static final byte MODE_SENDSAVE = 0; + private static final byte MODE_SENDSAVE = 0; - private static final CoreSaveState[] SAVE_STATES = CoreSaveState.values(); + private static final CoreSaveState[] SAVE_STATES = CoreSaveState.values(); - private CoreSaveState saveState; + private CoreSaveState saveState; - private boolean justSaved; + private boolean justSaved; - public static void sendSaveState( final EntityPlayer player, final CoreSaveState saveState, final boolean justSaved ) - { - Packet_C_KnowledgeInscriber packet = new Packet_C_KnowledgeInscriber(); + public static void sendSaveState( + final EntityPlayer player, final CoreSaveState saveState, final boolean justSaved) { + Packet_C_KnowledgeInscriber packet = new Packet_C_KnowledgeInscriber(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_C_KnowledgeInscriber.MODE_SENDSAVE; + // Set the mode + packet.mode = Packet_C_KnowledgeInscriber.MODE_SENDSAVE; - // Set the state - packet.saveState = saveState; - packet.justSaved = justSaved; + // Set the state + packet.saveState = saveState; + packet.justSaved = justSaved; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - this.saveState = Packet_C_KnowledgeInscriber.SAVE_STATES[stream.readInt()]; - this.justSaved = stream.readBoolean(); - } + @Override + protected void readData(final ByteBuf stream) { + this.saveState = Packet_C_KnowledgeInscriber.SAVE_STATES[stream.readInt()]; + this.justSaved = stream.readBoolean(); + } - @SideOnly(Side.CLIENT) - @Override - protected void wrappedExecute() - { - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + @SideOnly(Side.CLIENT) + @Override + protected void wrappedExecute() { + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - // Ensure it is the knowledge inscriber - if( gui instanceof GuiKnowledgeInscriber ) - { - ( (GuiKnowledgeInscriber)gui ).onReceiveSaveState( this.saveState, this.justSaved ); - } - - } - - @Override - protected void writeData( final ByteBuf stream ) - { - stream.writeInt( this.saveState.ordinal() ); - stream.writeBoolean( this.justSaved ); - } + // Ensure it is the knowledge inscriber + if (gui instanceof GuiKnowledgeInscriber) { + ((GuiKnowledgeInscriber) gui).onReceiveSaveState(this.saveState, this.justSaved); + } + } + @Override + protected void writeData(final ByteBuf stream) { + stream.writeInt(this.saveState.ordinal()); + stream.writeBoolean(this.justSaved); + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Priority.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Priority.java index 64fad2ed..b4ff5087 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Priority.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Priority.java @@ -15,74 +15,62 @@ import thaumicenergistics.common.network.NetworkHandler; * @author Nividica * */ -public class Packet_C_Priority - extends ThEClientPacket -{ - private static final byte MODE_SEND = 0; +public class Packet_C_Priority extends ThEClientPacket { + private static final byte MODE_SEND = 0; - private int priority; + private int priority; - public static void sendPriority( final int priority, final EntityPlayer player ) - { - Packet_C_Priority packet = new Packet_C_Priority(); + public static void sendPriority(final int priority, final EntityPlayer player) { + Packet_C_Priority packet = new Packet_C_Priority(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_C_Priority.MODE_SEND; + // Set the mode + packet.mode = Packet_C_Priority.MODE_SEND; - // Set the priority - packet.priority = priority; + // Set the priority + packet.priority = priority; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - if( this.mode == Packet_C_Priority.MODE_SEND ) - { - // Read the priority - this.priority = stream.readInt(); - } - } + @Override + protected void readData(final ByteBuf stream) { + if (this.mode == Packet_C_Priority.MODE_SEND) { + // Read the priority + this.priority = stream.readInt(); + } + } - @Override - @SideOnly(Side.CLIENT) - protected void wrappedExecute() - { - // Ensure we have a player - if( this.player == null ) - { - return; - } + @Override + @SideOnly(Side.CLIENT) + protected void wrappedExecute() { + // Ensure we have a player + if (this.player == null) { + return; + } - // Get the gui - Gui gui = Minecraft.getMinecraft().currentScreen; + // Get the gui + Gui gui = Minecraft.getMinecraft().currentScreen; - // Ensure they are looking at the priority gui - if( !( gui instanceof GuiPriority ) ) - { - return; - } + // Ensure they are looking at the priority gui + if (!(gui instanceof GuiPriority)) { + return; + } - if( this.mode == Packet_C_Priority.MODE_SEND ) - { - // Set the priority - ( (GuiPriority)gui ).onServerSendPriority( this.priority ); - } - } - - @Override - protected void writeData( final ByteBuf stream ) - { - if( this.mode == Packet_C_Priority.MODE_SEND ) - { - // Write the priority - stream.writeInt( this.priority ); - } - } + if (this.mode == Packet_C_Priority.MODE_SEND) { + // Set the priority + ((GuiPriority) gui).onServerSendPriority(this.priority); + } + } + @Override + protected void writeData(final ByteBuf stream) { + if (this.mode == Packet_C_Priority.MODE_SEND) { + // Write the priority + stream.writeInt(this.priority); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Sync.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Sync.java index 445263ab..e51c43b0 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Sync.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_C_Sync.java @@ -13,140 +13,123 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class Packet_C_Sync - extends ThEClientPacket -{ - /** - * Packet modes. - */ - private static final byte MODE_PLAYER_HELD = 1, - MODE_SOUND = 2; +public class Packet_C_Sync extends ThEClientPacket { + /** + * Packet modes. + */ + private static final byte MODE_PLAYER_HELD = 1, MODE_SOUND = 2; - private ItemStack syncStack; + private ItemStack syncStack; - private boolean syncFlag; + private boolean syncFlag; - private String syncString; + private String syncString; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_C_Sync newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_C_Sync packet = new Packet_C_Sync(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_C_Sync newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_C_Sync packet = new Packet_C_Sync(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - /** - * Creates a packet with an update to what itemstack the player is holding. - * - * @param player - * @param heldItem - * @return - */ - public static void sendPlayerHeldItem( final EntityPlayer player, final ItemStack heldItem ) - { - // Create the packet - Packet_C_Sync packet = Packet_C_Sync.newPacket( player, Packet_C_Sync.MODE_PLAYER_HELD ); + /** + * Creates a packet with an update to what itemstack the player is holding. + * + * @param player + * @param heldItem + * @return + */ + public static void sendPlayerHeldItem(final EntityPlayer player, final ItemStack heldItem) { + // Create the packet + Packet_C_Sync packet = Packet_C_Sync.newPacket(player, Packet_C_Sync.MODE_PLAYER_HELD); - // Set the held item - packet.syncStack = heldItem; + // Set the held item + packet.syncStack = heldItem; - // Is the player holding anything? - packet.syncFlag = ( heldItem != null ); + // Is the player holding anything? + packet.syncFlag = (heldItem != null); - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - /** - * Sends a sound to the player to play. - * - * @param player - * @param soundLocation - */ - public static void sendPlaySound( final EntityPlayer player, final String soundLocation ) - { - // Create the packet - Packet_C_Sync packet = Packet_C_Sync.newPacket( player, Packet_C_Sync.MODE_SOUND ); + /** + * Sends a sound to the player to play. + * + * @param player + * @param soundLocation + */ + public static void sendPlaySound(final EntityPlayer player, final String soundLocation) { + // Create the packet + Packet_C_Sync packet = Packet_C_Sync.newPacket(player, Packet_C_Sync.MODE_SOUND); - // Set the sound location - packet.syncString = soundLocation; + // Set the sound location + packet.syncString = soundLocation; - // Send it - NetworkHandler.sendPacketToClient( packet ); - } + // Send it + NetworkHandler.sendPacketToClient(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_PLAYER_HELD: - // Read if the item is null - this.syncFlag = stream.readBoolean(); - if( this.syncFlag ) - { - // Read stack - this.syncStack = ThEBasePacket.readItemstack( stream ); - } - else - { - this.syncStack = null; - } - break; + @Override + protected void readData(final ByteBuf stream) { + switch (this.mode) { + case MODE_PLAYER_HELD: + // Read if the item is null + this.syncFlag = stream.readBoolean(); + if (this.syncFlag) { + // Read stack + this.syncStack = ThEBasePacket.readItemstack(stream); + } else { + this.syncStack = null; + } + break; - case MODE_SOUND: - // Read the sound location - this.syncString = ThEBasePacket.readString( stream ); - break; - } - } + case MODE_SOUND: + // Read the sound location + this.syncString = ThEBasePacket.readString(stream); + break; + } + } - @Override - protected void wrappedExecute() - { - switch ( this.mode ) - { - case MODE_PLAYER_HELD: - // Set what the player is holding. - this.player.inventory.setItemStack( this.syncStack ); - break; - case MODE_SOUND: - // Play the sound - ThEUtils.playClientSound( null, this.syncString ); - } - } - - @Override - protected void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_PLAYER_HELD: - // Write if the held item is null - stream.writeBoolean( this.syncFlag ); - if( this.syncFlag ) - { - // Write the stack - ThEBasePacket.writeItemstack( this.syncStack, stream ); - } - break; - case MODE_SOUND: - // Write the sound location - ThEBasePacket.writeString( this.syncString, stream ); - break; - } - } + @Override + protected void wrappedExecute() { + switch (this.mode) { + case MODE_PLAYER_HELD: + // Set what the player is holding. + this.player.inventory.setItemStack(this.syncStack); + break; + case MODE_SOUND: + // Play the sound + ThEUtils.playClientSound(null, this.syncString); + } + } + @Override + protected void writeData(final ByteBuf stream) { + switch (this.mode) { + case MODE_PLAYER_HELD: + // Write if the held item is null + stream.writeBoolean(this.syncFlag); + if (this.syncFlag) { + // Write the stack + ThEBasePacket.writeItemstack(this.syncStack, stream); + } + break; + case MODE_SOUND: + // Write the sound location + ThEBasePacket.writeString(this.syncString, stream); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_R_ParticleFX.java b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_R_ParticleFX.java index b6095c03..0fd5f87e 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/Packet_R_ParticleFX.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/Packet_R_ParticleFX.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.network.packet.client; -import java.awt.Color; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.awt.Color; import net.minecraft.client.Minecraft; import net.minecraft.world.World; import thaumcraft.api.aspects.Aspect; @@ -17,144 +17,148 @@ import thaumicenergistics.common.network.NetworkHandler; * @author Nividica * */ -public class Packet_R_ParticleFX - extends ThEAreaPacket -{ +public class Packet_R_ParticleFX extends ThEAreaPacket { - private static final byte MODE_WRENCH_FX = 0; + private static final byte MODE_WRENCH_FX = 0; - /** - * Destination coords. - */ - private float dX, dY, dZ; + /** + * Destination coords. + */ + private float dX, dY, dZ; - /** - * Color of the FX. - */ - private int aspectColor; + /** + * Color of the FX. + */ + private int aspectColor; - /** - * Creates an FX packet. - * - * @param world - * @param sourceX - * @param sourceY - * @param sourceZ - * @param destinationX - * @param destinationY - * @param destinationZ - * @param aspectColor - * @param range - */ - public static void createWrenchFX( final World world, final double sourceX, final double sourceY, final double sourceZ, - final double destinationX, final double destinationY, final double destinationZ, - final Aspect aspectColor, final float range ) - { - Packet_R_ParticleFX packet = new Packet_R_ParticleFX(); + /** + * Creates an FX packet. + * + * @param world + * @param sourceX + * @param sourceY + * @param sourceZ + * @param destinationX + * @param destinationY + * @param destinationZ + * @param aspectColor + * @param range + */ + public static void createWrenchFX( + final World world, + final double sourceX, + final double sourceY, + final double sourceZ, + final double destinationX, + final double destinationY, + final double destinationZ, + final Aspect aspectColor, + final float range) { + Packet_R_ParticleFX packet = new Packet_R_ParticleFX(); - // Set the mode - packet.mode = Packet_R_ParticleFX.MODE_WRENCH_FX; + // Set the mode + packet.mode = Packet_R_ParticleFX.MODE_WRENCH_FX; - // Set the world - packet.targetWorld = world; + // Set the world + packet.targetWorld = world; - // Set the target coords - packet.targetX = (float)sourceX; - packet.targetY = (float)sourceY; - packet.targetZ = (float)sourceZ; + // Set the target coords + packet.targetX = (float) sourceX; + packet.targetY = (float) sourceY; + packet.targetZ = (float) sourceZ; - // Set the destination values - packet.dX = (float)destinationX; - packet.dY = (float)destinationY; - packet.dZ = (float)destinationZ; + // Set the destination values + packet.dX = (float) destinationX; + packet.dY = (float) destinationY; + packet.dZ = (float) destinationZ; - // Set the aspect color - packet.aspectColor = aspectColor.getColor(); + // Set the aspect color + packet.aspectColor = aspectColor.getColor(); - // Send it - NetworkHandler.sendAreaPacketToClients( packet, range ); - } + // Send it + NetworkHandler.sendAreaPacketToClients(packet, range); + } - @SideOnly(Side.CLIENT) - private void addWrenchFX() - { - // Get the color - Color color = new Color( this.aspectColor ); + @SideOnly(Side.CLIENT) + private void addWrenchFX() { + // Get the color + Color color = new Color(this.aspectColor); - // Create the particle - FXBeam beam = new FXBeam( this.targetWorld, this.targetX, this.targetY + 1.5D, this.targetZ, this.dX + 0.5D, this.dY + 0.5D, this.dZ + 0.5D, - color.getRed() / 255.0F, color.getGreen() / 255.0F, color.getBlue() / 255.0F, 6 ); + // Create the particle + FXBeam beam = new FXBeam( + this.targetWorld, + this.targetX, + this.targetY + 1.5D, + this.targetZ, + this.dX + 0.5D, + this.dY + 0.5D, + this.dZ + 0.5D, + color.getRed() / 255.0F, + color.getGreen() / 255.0F, + color.getBlue() / 255.0F, + 6); - // Set the width - beam.width = 0.2F; + // Set the width + beam.width = 0.2F; - // Add the particle to thaumcraft engine - ParticleEngine.instance.addEffect( this.targetWorld, beam ); - } + // Add the particle to thaumcraft engine + ParticleEngine.instance.addEffect(this.targetWorld, beam); + } - @Override - protected void readData( final ByteBuf stream ) - { - // Call super - super.readData( stream ); + @Override + protected void readData(final ByteBuf stream) { + // Call super + super.readData(stream); - switch ( this.mode ) - { - case Packet_R_ParticleFX.MODE_WRENCH_FX: + switch (this.mode) { + case Packet_R_ParticleFX.MODE_WRENCH_FX: - // Read the destination - this.dX = stream.readFloat(); - this.dY = stream.readFloat(); - this.dZ = stream.readFloat(); + // Read the destination + this.dX = stream.readFloat(); + this.dY = stream.readFloat(); + this.dZ = stream.readFloat(); - // Read the color - this.aspectColor = stream.readInt(); - break; - } + // Read the color + this.aspectColor = stream.readInt(); + break; + } + } - } + @Override + protected void writeData(final ByteBuf stream) { + // Call super + super.writeData(stream); - @Override - protected void writeData( final ByteBuf stream ) - { - // Call super - super.writeData( stream ); + switch (this.mode) { + case Packet_R_ParticleFX.MODE_WRENCH_FX: + // Write the destination + stream.writeFloat(this.dX); + stream.writeFloat(this.dY); + stream.writeFloat(this.dZ); - switch ( this.mode ) - { - case Packet_R_ParticleFX.MODE_WRENCH_FX: - // Write the destination - stream.writeFloat( this.dX ); - stream.writeFloat( this.dY ); - stream.writeFloat( this.dZ ); + // Write the color + stream.writeInt(this.aspectColor); + break; + } + } - // Write the color - stream.writeInt( this.aspectColor ); - break; - } - } + @SideOnly(Side.CLIENT) + @Override + public void areaExecute() { + // Ensure the world is valid + if (this.targetWorld == null) { + return; + } - @SideOnly(Side.CLIENT) - @Override - public void areaExecute() - { - // Ensure the world is valid - if( this.targetWorld == null ) - { - return; - } + // Has the player set particles to minimum? + if (Minecraft.getMinecraft().gameSettings.particleSetting == 2) { + return; + } - // Has the player set particles to minimum? - if( Minecraft.getMinecraft().gameSettings.particleSetting == 2 ) - { - return; - } - - switch ( this.mode ) - { - case Packet_R_ParticleFX.MODE_WRENCH_FX: - this.addWrenchFX(); - break; - } - } + switch (this.mode) { + case Packet_R_ParticleFX.MODE_WRENCH_FX: + this.addWrenchFX(); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/ThEAreaPacket.java b/src/main/java/thaumicenergistics/common/network/packet/client/ThEAreaPacket.java index 861bf2da..c9c21c1b 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/ThEAreaPacket.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/ThEAreaPacket.java @@ -12,72 +12,62 @@ import net.minecraft.world.World; * @author Nividica * */ -public abstract class ThEAreaPacket - extends ThEClientPacket -{ +public abstract class ThEAreaPacket extends ThEClientPacket { - /** - * Target coords. - */ - protected float targetX, targetY, targetZ; + /** + * Target coords. + */ + protected float targetX, targetY, targetZ; - /** - * Target world. - */ - protected World targetWorld; + /** + * Target world. + */ + protected World targetWorld; - @SideOnly(Side.CLIENT) - private void setClientWorld() - { - this.targetWorld = FMLClientHandler.instance().getClient().theWorld; - } + @SideOnly(Side.CLIENT) + private void setClientWorld() { + this.targetWorld = FMLClientHandler.instance().getClient().theWorld; + } - @Override - protected void readData( final ByteBuf stream ) - { - // Read target coords - this.targetX = stream.readFloat(); - this.targetY = stream.readFloat(); - this.targetZ = stream.readFloat(); - } + @Override + protected void readData(final ByteBuf stream) { + // Read target coords + this.targetX = stream.readFloat(); + this.targetY = stream.readFloat(); + this.targetZ = stream.readFloat(); + } - @Override - protected void writeData( final ByteBuf stream ) - { - // Write target coords - stream.writeFloat( this.targetX ); - stream.writeFloat( this.targetY ); - stream.writeFloat( this.targetZ ); - } + @Override + protected void writeData(final ByteBuf stream) { + // Write target coords + stream.writeFloat(this.targetX); + stream.writeFloat(this.targetY); + stream.writeFloat(this.targetZ); + } - @SideOnly(Side.CLIENT) - public abstract void areaExecute(); + @SideOnly(Side.CLIENT) + public abstract void areaExecute(); - public int getDimension() - { - return this.targetWorld.provider.dimensionId; - } + public int getDimension() { + return this.targetWorld.provider.dimensionId; + } - public float getX() - { - return this.targetX; - } + public float getX() { + return this.targetX; + } - public float getY() - { - return this.targetY; - } + public float getY() { + return this.targetY; + } - public float getZ() - { - return this.targetZ; - } + public float getZ() { + return this.targetZ; + } - @Override - @SideOnly(Side.CLIENT) - public final void wrappedExecute() - { - this.setClientWorld(); - this.areaExecute(); - } + @Override + @SideOnly(Side.CLIENT) + public final void wrappedExecute() { + this.setClientWorld(); + this.areaExecute(); + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/ThEClientPacket.java b/src/main/java/thaumicenergistics/common/network/packet/client/ThEClientPacket.java index c369ad71..b3de4332 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/ThEClientPacket.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/ThEClientPacket.java @@ -12,35 +12,29 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public abstract class ThEClientPacket - extends ThEBasePacket -{ - @SideOnly(Side.CLIENT) - private final void preWrap() - { - // Set the player - this.player = Minecraft.getMinecraft().thePlayer; +public abstract class ThEClientPacket extends ThEBasePacket { + @SideOnly(Side.CLIENT) + private final void preWrap() { + // Set the player + this.player = Minecraft.getMinecraft().thePlayer; - // Execute the packet - this.wrappedExecute(); - } + // Execute the packet + this.wrappedExecute(); + } - @Override - protected final boolean includePlayerInStream() - { - return false; - } + @Override + protected final boolean includePlayerInStream() { + return false; + } - @SideOnly(Side.CLIENT) - protected abstract void wrappedExecute(); + @SideOnly(Side.CLIENT) + protected abstract void wrappedExecute(); - @Override - public final void execute() - { - // Ensure this is client side - if( EffectiveSide.isClientSide() ) - { - this.preWrap(); - } - } + @Override + public final void execute() { + // Ensure this is client side + if (EffectiveSide.isClientSide()) { + this.preWrap(); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/client/WrapperPacket_C.java b/src/main/java/thaumicenergistics/common/network/packet/client/WrapperPacket_C.java index 434e0396..6a2f11f5 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/client/WrapperPacket_C.java +++ b/src/main/java/thaumicenergistics/common/network/packet/client/WrapperPacket_C.java @@ -8,16 +8,10 @@ import thaumicenergistics.common.network.WrapperPacket; * @author Nividica * */ -public class WrapperPacket_C - extends WrapperPacket -{ - public WrapperPacket_C() - { +public class WrapperPacket_C extends WrapperPacket { + public WrapperPacket_C() {} - } - - public WrapperPacket_C( final ThEClientPacket packet ) - { - super( packet ); - } + public WrapperPacket_C(final ThEClientPacket packet) { + super(packet); + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ArcaneCraftingTerminal.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ArcaneCraftingTerminal.java index 09e063d8..6324cfc1 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ArcaneCraftingTerminal.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ArcaneCraftingTerminal.java @@ -18,414 +18,395 @@ import thaumicenergistics.common.registries.EnumCache; * @author Nividica * */ -public class Packet_S_ArcaneCraftingTerminal - extends ThEServerPacket -{ - - private static final byte MODE_REQUEST_FULL_LIST = 1; - private static final byte MODE_REQUEST_EXTRACTION = 2; - private static final byte MODE_REQUEST_DEPOSIT = 3; - private static final byte MODE_REQUEST_CLEAR_GRID = 4; - private static final byte MODE_REQUEST_DEPOSIT_REGION = 5; - private static final byte MODE_REQUEST_SET_SORT = 6; - private static final byte MODE_REQUEST_SET_GRID = 7; - private static final byte MODE_REQUEST_AUTO_CRAFT = 8; - private static final byte MODE_REQUEST_SWAP_ARMOR = 9; - - private static final int ITEM_GRID_SIZE = 9; - - /** - * Extracted or deposited item. - */ - private IAEItemStack itemStack; - - /** - * Mouse button being held. - */ - private int mouseButton; - - /** - * True if shift is being held. - */ - private boolean isShiftHeld; - - /** - * Identifies a region by a slot inside of it. - */ - private int slotNumber; - - /** - * Order to sort the items. - */ - private SortOrder sortingOrder; - - /** - * Direction to sort the items. - */ - private SortDir sortingDirection; - - /** - * What mode is used to view the items. - */ - private ViewItems viewMode; - - /** - * Items to set the crafting grid to. - */ - private IAEItemStack[] gridItems; - - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_ArcaneCraftingTerminal newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_ArcaneCraftingTerminal packet = new Packet_S_ArcaneCraftingTerminal(); - - // Set the player & mode - packet.player = player; - packet.mode = mode; - - return packet; - } - - /** - * Create a packet to request to autocraft the specified item. - * - * @param player - * @param result - * @return - */ - public static void sendAutoCraft( final EntityPlayer player, final IAEItemStack result ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_AUTO_CRAFT ); - - // Set the result - packet.itemStack = result; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Create a packet to request that the crafting grid be cleared. - * the ME network. Use only when needed. - * - * @param player - */ - public static void sendClearGrid( final EntityPlayer player ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_CLEAR_GRID ); - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Creates a packet letting the server know the user would like to - * deposition whatever they are holding into the ME network. - * - * @param player - * @return - */ - public static void sendDeposit( final EntityPlayer player, final int mouseButton ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_DEPOSIT ); - - // Set the button - packet.mouseButton = mouseButton; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Create a packet requesting that a region(inventory) be deposited into the - * ME network. - * - * @param player - * @param slotNumber - * @return - */ - public static void sendDepositRegion( final EntityPlayer player, final int slotNumber ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_DEPOSIT_REGION ); - - // Set the slot number - packet.slotNumber = slotNumber; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Creates a packet letting the server know the user would like to - * extract the specified itemstack from the ME network. - * - * @param player - * @param itemStack - * @param mouseButton - * @return - */ - public static void sendExtract( final EntityPlayer player, final IAEItemStack itemStack, final int mouseButton, - final boolean isShiftHeld ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_EXTRACTION ); - - // Set stack - packet.itemStack = itemStack; - - // Set mouse button - packet.mouseButton = mouseButton; - - // Set shift - packet.isShiftHeld = isShiftHeld; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Create a packet in full list mode. - * This will request a full list of all items in - * the ME network. Use only when needed. - * - * @param player - */ - public static void sendFullListRequest( final EntityPlayer player ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_FULL_LIST ); - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Create a packet to request the sorting order and direction. - * - * @param player - * @param order - * @param direction - * @return - */ - public static void sendMode( final EntityPlayer player, final SortOrder order, final SortDir direction, - final ViewItems viewMode ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_SET_SORT ); - - // Set the sorts - packet.sortingDirection = direction; - packet.sortingOrder = order; - packet.viewMode = viewMode; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - /** - * Create a packet to request that the crafting grid be set to these items. - * - * @param player - * @param items - * Must be at least length of 9 - * @return - */ - public static void sendSetCrafting_NEI( final EntityPlayer player, final IAEItemStack[] items ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_SET_GRID ); - - // Set the items - packet.gridItems = items; - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - public static void sendSwapArmor( final EntityPlayer player ) - { - Packet_S_ArcaneCraftingTerminal packet = newPacket( player, MODE_REQUEST_SWAP_ARMOR ); - - // Send it - NetworkHandler.sendPacketToServer( packet ); - } - - @Override - public void execute() - { - // If the player is not null, and they have the ACT container open - if( ( this.player != null ) && ( this.player.openContainer instanceof ContainerPartArcaneCraftingTerminal ) ) - { - switch ( this.mode ) - { - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_FULL_LIST: - // Request the full list - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestFullUpdate( this.player ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: - // Request extraction - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestExtract( this.player, this.itemStack, - this.mouseButton, this.isShiftHeld ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: - // Request deposit - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestDeposit( this.player, this.mouseButton ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_CLEAR_GRID: - // Request clear grid - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestClearCraftingGrid( this.player ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: - // Request deposit region - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestDepositRegion( this.player, this.slotNumber ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: - // Request set sort - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestSetSort( this.sortingOrder, - this.sortingDirection, this.viewMode ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: - // Request set grid - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ) - .onClientNEIRequestSetCraftingGrid( this.player, this.gridItems ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: - // Request auto-crafting - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestAutoCraft( this.player, this.itemStack ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SWAP_ARMOR: - // Request armor swap - ( (ContainerPartArcaneCraftingTerminal)this.player.openContainer ).onClientRequestSwapArmor( this.player ); - break; - } - } - } - - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: - // Read the item - this.itemStack = ThEBasePacket.readAEItemStack( stream ); - - // Read the mouse button - this.mouseButton = stream.readInt(); - - // Read the shift status - this.isShiftHeld = stream.readBoolean(); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: - // Read the mouse button - this.mouseButton = stream.readInt(); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: - // Read the slot number - this.slotNumber = stream.readInt(); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: - // Read sorts - this.sortingDirection = EnumCache.AE_SORT_DIRECTIONS[stream.readInt()]; - this.sortingOrder = EnumCache.AE_SORT_ORDERS[stream.readInt()]; - this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: - // Init the items - this.gridItems = new IAEItemStack[Packet_S_ArcaneCraftingTerminal.ITEM_GRID_SIZE]; - - // Read the items - for( int slotIndex = 0; slotIndex < 9; slotIndex++ ) - { - // Do we have an item to read? - if( stream.readBoolean() ) - { - // Set the item - this.gridItems[slotIndex] = ThEBasePacket.readAEItemStack( stream ); - } - } - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: - // Read the requested item - this.itemStack = ThEBasePacket.readAEItemStack( stream ); - break; - } - - } - - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: - // Write the itemstack - ThEBasePacket.writeAEItemStack( this.itemStack, stream ); - - // Write the mouse button - stream.writeInt( this.mouseButton ); - - // Write the shift status - stream.writeBoolean( this.isShiftHeld ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: - // Write the mouse button - stream.writeInt( this.mouseButton ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: - // Write the slot number to the stream - stream.writeInt( this.slotNumber ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: - // Write the sorts - stream.writeInt( this.sortingDirection.ordinal() ); - stream.writeInt( this.sortingOrder.ordinal() ); - stream.writeInt( this.viewMode.ordinal() ); - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: - // Write each non-null item - for( int slotIndex = 0; slotIndex < Packet_S_ArcaneCraftingTerminal.ITEM_GRID_SIZE; slotIndex++ ) - { - // Get the item - IAEItemStack slotItem = this.gridItems[slotIndex]; - - // Write if the slot is not null - boolean hasItem = slotItem != null; - stream.writeBoolean( hasItem ); - - if( hasItem ) - { - // Write the item - ThEBasePacket.writeAEItemStack( slotItem, stream ); - } - } - break; - - case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: - // Write the requested item - ThEBasePacket.writeAEItemStack( this.itemStack, stream ); - break; - } - } - +public class Packet_S_ArcaneCraftingTerminal extends ThEServerPacket { + + private static final byte MODE_REQUEST_FULL_LIST = 1; + private static final byte MODE_REQUEST_EXTRACTION = 2; + private static final byte MODE_REQUEST_DEPOSIT = 3; + private static final byte MODE_REQUEST_CLEAR_GRID = 4; + private static final byte MODE_REQUEST_DEPOSIT_REGION = 5; + private static final byte MODE_REQUEST_SET_SORT = 6; + private static final byte MODE_REQUEST_SET_GRID = 7; + private static final byte MODE_REQUEST_AUTO_CRAFT = 8; + private static final byte MODE_REQUEST_SWAP_ARMOR = 9; + + private static final int ITEM_GRID_SIZE = 9; + + /** + * Extracted or deposited item. + */ + private IAEItemStack itemStack; + + /** + * Mouse button being held. + */ + private int mouseButton; + + /** + * True if shift is being held. + */ + private boolean isShiftHeld; + + /** + * Identifies a region by a slot inside of it. + */ + private int slotNumber; + + /** + * Order to sort the items. + */ + private SortOrder sortingOrder; + + /** + * Direction to sort the items. + */ + private SortDir sortingDirection; + + /** + * What mode is used to view the items. + */ + private ViewItems viewMode; + + /** + * Items to set the crafting grid to. + */ + private IAEItemStack[] gridItems; + + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_ArcaneCraftingTerminal newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_ArcaneCraftingTerminal packet = new Packet_S_ArcaneCraftingTerminal(); + + // Set the player & mode + packet.player = player; + packet.mode = mode; + + return packet; + } + + /** + * Create a packet to request to autocraft the specified item. + * + * @param player + * @param result + * @return + */ + public static void sendAutoCraft(final EntityPlayer player, final IAEItemStack result) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_AUTO_CRAFT); + + // Set the result + packet.itemStack = result; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Create a packet to request that the crafting grid be cleared. + * the ME network. Use only when needed. + * + * @param player + */ + public static void sendClearGrid(final EntityPlayer player) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_CLEAR_GRID); + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Creates a packet letting the server know the user would like to + * deposition whatever they are holding into the ME network. + * + * @param player + * @return + */ + public static void sendDeposit(final EntityPlayer player, final int mouseButton) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_DEPOSIT); + + // Set the button + packet.mouseButton = mouseButton; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Create a packet requesting that a region(inventory) be deposited into the + * ME network. + * + * @param player + * @param slotNumber + * @return + */ + public static void sendDepositRegion(final EntityPlayer player, final int slotNumber) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_DEPOSIT_REGION); + + // Set the slot number + packet.slotNumber = slotNumber; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Creates a packet letting the server know the user would like to + * extract the specified itemstack from the ME network. + * + * @param player + * @param itemStack + * @param mouseButton + * @return + */ + public static void sendExtract( + final EntityPlayer player, final IAEItemStack itemStack, final int mouseButton, final boolean isShiftHeld) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_EXTRACTION); + + // Set stack + packet.itemStack = itemStack; + + // Set mouse button + packet.mouseButton = mouseButton; + + // Set shift + packet.isShiftHeld = isShiftHeld; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Create a packet in full list mode. + * This will request a full list of all items in + * the ME network. Use only when needed. + * + * @param player + */ + public static void sendFullListRequest(final EntityPlayer player) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_FULL_LIST); + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Create a packet to request the sorting order and direction. + * + * @param player + * @param order + * @param direction + * @return + */ + public static void sendMode( + final EntityPlayer player, final SortOrder order, final SortDir direction, final ViewItems viewMode) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_SET_SORT); + + // Set the sorts + packet.sortingDirection = direction; + packet.sortingOrder = order; + packet.viewMode = viewMode; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + /** + * Create a packet to request that the crafting grid be set to these items. + * + * @param player + * @param items + * Must be at least length of 9 + * @return + */ + public static void sendSetCrafting_NEI(final EntityPlayer player, final IAEItemStack[] items) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_SET_GRID); + + // Set the items + packet.gridItems = items; + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + public static void sendSwapArmor(final EntityPlayer player) { + Packet_S_ArcaneCraftingTerminal packet = newPacket(player, MODE_REQUEST_SWAP_ARMOR); + + // Send it + NetworkHandler.sendPacketToServer(packet); + } + + @Override + public void execute() { + // If the player is not null, and they have the ACT container open + if ((this.player != null) && (this.player.openContainer instanceof ContainerPartArcaneCraftingTerminal)) { + switch (this.mode) { + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_FULL_LIST: + // Request the full list + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestFullUpdate(this.player); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: + // Request extraction + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestExtract(this.player, this.itemStack, this.mouseButton, this.isShiftHeld); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: + // Request deposit + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestDeposit(this.player, this.mouseButton); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_CLEAR_GRID: + // Request clear grid + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestClearCraftingGrid(this.player); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: + // Request deposit region + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestDepositRegion(this.player, this.slotNumber); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: + // Request set sort + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestSetSort(this.sortingOrder, this.sortingDirection, this.viewMode); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: + // Request set grid + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientNEIRequestSetCraftingGrid(this.player, this.gridItems); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: + // Request auto-crafting + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestAutoCraft(this.player, this.itemStack); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SWAP_ARMOR: + // Request armor swap + ((ContainerPartArcaneCraftingTerminal) this.player.openContainer) + .onClientRequestSwapArmor(this.player); + break; + } + } + } + + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: + // Read the item + this.itemStack = ThEBasePacket.readAEItemStack(stream); + + // Read the mouse button + this.mouseButton = stream.readInt(); + + // Read the shift status + this.isShiftHeld = stream.readBoolean(); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: + // Read the mouse button + this.mouseButton = stream.readInt(); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: + // Read the slot number + this.slotNumber = stream.readInt(); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: + // Read sorts + this.sortingDirection = EnumCache.AE_SORT_DIRECTIONS[stream.readInt()]; + this.sortingOrder = EnumCache.AE_SORT_ORDERS[stream.readInt()]; + this.viewMode = EnumCache.AE_VIEW_ITEMS[stream.readInt()]; + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: + // Init the items + this.gridItems = new IAEItemStack[Packet_S_ArcaneCraftingTerminal.ITEM_GRID_SIZE]; + + // Read the items + for (int slotIndex = 0; slotIndex < 9; slotIndex++) { + // Do we have an item to read? + if (stream.readBoolean()) { + // Set the item + this.gridItems[slotIndex] = ThEBasePacket.readAEItemStack(stream); + } + } + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: + // Read the requested item + this.itemStack = ThEBasePacket.readAEItemStack(stream); + break; + } + } + + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_EXTRACTION: + // Write the itemstack + ThEBasePacket.writeAEItemStack(this.itemStack, stream); + + // Write the mouse button + stream.writeInt(this.mouseButton); + + // Write the shift status + stream.writeBoolean(this.isShiftHeld); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT: + // Write the mouse button + stream.writeInt(this.mouseButton); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_DEPOSIT_REGION: + // Write the slot number to the stream + stream.writeInt(this.slotNumber); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_SORT: + // Write the sorts + stream.writeInt(this.sortingDirection.ordinal()); + stream.writeInt(this.sortingOrder.ordinal()); + stream.writeInt(this.viewMode.ordinal()); + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_SET_GRID: + // Write each non-null item + for (int slotIndex = 0; slotIndex < Packet_S_ArcaneCraftingTerminal.ITEM_GRID_SIZE; slotIndex++) { + // Get the item + IAEItemStack slotItem = this.gridItems[slotIndex]; + + // Write if the slot is not null + boolean hasItem = slotItem != null; + stream.writeBoolean(hasItem); + + if (hasItem) { + // Write the item + ThEBasePacket.writeAEItemStack(slotItem, stream); + } + } + break; + + case Packet_S_ArcaneCraftingTerminal.MODE_REQUEST_AUTO_CRAFT: + // Write the requested item + ThEBasePacket.writeAEItemStack(this.itemStack, stream); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_AspectSlot.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_AspectSlot.java index 82d4981b..5a69bfbd 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_AspectSlot.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_AspectSlot.java @@ -14,86 +14,77 @@ import thaumicenergistics.common.parts.ThEPartBase; * @author Nividica * */ -public class Packet_S_AspectSlot - extends ThEServerPacket -{ - private static final byte MODE_SET_ASPECT = 0; +public class Packet_S_AspectSlot extends ThEServerPacket { + private static final byte MODE_SET_ASPECT = 0; - private int index; + private int index; - private Aspect aspect; + private Aspect aspect; - private IAspectSlotPart part; + private IAspectSlotPart part; - public static void sendAspectChange( final IAspectSlotPart part, final int index, final Aspect aspect, final EntityPlayer player ) - { - Packet_S_AspectSlot packet = new Packet_S_AspectSlot(); + public static void sendAspectChange( + final IAspectSlotPart part, final int index, final Aspect aspect, final EntityPlayer player) { + Packet_S_AspectSlot packet = new Packet_S_AspectSlot(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_S_AspectSlot.MODE_SET_ASPECT; + // Set the mode + packet.mode = Packet_S_AspectSlot.MODE_SET_ASPECT; - // Set the index - packet.index = index; + // Set the index + packet.index = index; - // Set the part - packet.part = part; + // Set the part + packet.part = part; - // Set the aspect - packet.aspect = aspect; + // Set the aspect + packet.aspect = aspect; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - public void execute() - { - switch ( this.mode ) - { - case Packet_S_AspectSlot.MODE_SET_ASPECT: - // Inform the part of the aspect change - this.part.setAspect( this.index, this.aspect, this.player ); - break; - } - } + @Override + public void execute() { + switch (this.mode) { + case Packet_S_AspectSlot.MODE_SET_ASPECT: + // Inform the part of the aspect change + this.part.setAspect(this.index, this.aspect, this.player); + break; + } + } - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_AspectSlot.MODE_SET_ASPECT: - // Read the part - this.part = ( (IAspectSlotPart)ThEBasePacket.readPart( stream ) ); + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_AspectSlot.MODE_SET_ASPECT: + // Read the part + this.part = ((IAspectSlotPart) ThEBasePacket.readPart(stream)); - // Read the index - this.index = stream.readInt(); + // Read the index + this.index = stream.readInt(); - // Read the aspect - this.aspect = ThEBasePacket.readAspect( stream ); - break; - } - } + // Read the aspect + this.aspect = ThEBasePacket.readAspect(stream); + break; + } + } - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_AspectSlot.MODE_SET_ASPECT: - // Write the part - ThEBasePacket.writePart( (ThEPartBase)this.part, stream ); + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_AspectSlot.MODE_SET_ASPECT: + // Write the part + ThEBasePacket.writePart((ThEPartBase) this.part, stream); - // Write the index - stream.writeInt( this.index ); - - // Write the aspect - ThEBasePacket.writeAspect( this.aspect, stream ); - break; - } - } + // Write the index + stream.writeInt(this.index); + // Write the aspect + ThEBasePacket.writeAspect(this.aspect, stream); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ChangeGui.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ChangeGui.java index 78e4da86..d9f960b3 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ChangeGui.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ChangeGui.java @@ -15,162 +15,145 @@ import thaumicenergistics.common.parts.ThEPartBase; * @author Nividica * */ -public class Packet_S_ChangeGui - extends ThEServerPacket -{ - /** - * Packet modes - */ - private static final byte MODE_REGULAR = 0, - MODE_PART = 1, - MODE_WIRELESS = 2; +public class Packet_S_ChangeGui extends ThEServerPacket { + /** + * Packet modes + */ + private static final byte MODE_REGULAR = 0, MODE_PART = 1, MODE_WIRELESS = 2; - private int guiID; - private ThEPartBase part; - private World world; - private int x; - private int y; - private int z; + private int guiID; + private ThEPartBase part; + private World world; + private int x; + private int y; + private int z; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_ChangeGui newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_ChangeGui packet = new Packet_S_ChangeGui(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_ChangeGui newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_ChangeGui packet = new Packet_S_ChangeGui(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendGuiChange( final int guiID, final EntityPlayer player, final World world, final int x, final int y, - final int z ) - { - Packet_S_ChangeGui packet = newPacket( player, MODE_REGULAR ); + public static void sendGuiChange( + final int guiID, final EntityPlayer player, final World world, final int x, final int y, final int z) { + Packet_S_ChangeGui packet = newPacket(player, MODE_REGULAR); - // Set the guiID - packet.guiID = guiID; + // Set the guiID + packet.guiID = guiID; - // Set the world - packet.world = world; + // Set the world + packet.world = world; - // Set the coords - packet.x = x; - packet.y = y; - packet.z = z; + // Set the coords + packet.x = x; + packet.y = y; + packet.z = z; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendGuiChangeToPart( final ThEPartBase part, final EntityPlayer player, final World world, final int x, - final int y, final int z ) - { - Packet_S_ChangeGui packet = newPacket( player, MODE_PART ); + public static void sendGuiChangeToPart( + final ThEPartBase part, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z) { + Packet_S_ChangeGui packet = newPacket(player, MODE_PART); - // Set the part - packet.part = part; + // Set the part + packet.part = part; - // Set the world - packet.world = world; + // Set the world + packet.world = world; - // Set the coords - packet.x = x; - packet.y = y; - packet.z = z; + // Set the coords + packet.x = x; + packet.y = y; + packet.z = z; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendGuiChangeToWirelessTerminal( final EntityPlayer player ) - { - Packet_S_ChangeGui packet = newPacket( player, MODE_WIRELESS ); + public static void sendGuiChangeToWirelessTerminal(final EntityPlayer player) { + Packet_S_ChangeGui packet = newPacket(player, MODE_WIRELESS); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - public void execute() - { - switch ( this.mode ) - { - case MODE_REGULAR: - // Launch regular - ThEGuiHandler.launchGui( this.guiID, this.player, this.world, this.x, this.y, this.z ); - break; + @Override + public void execute() { + switch (this.mode) { + case MODE_REGULAR: + // Launch regular + ThEGuiHandler.launchGui(this.guiID, this.player, this.world, this.x, this.y, this.z); + break; - case MODE_PART: - // Launch part - ThEGuiHandler.launchGui( this.part, this.player, this.world, this.x, this.y, this.z ); - break; + case MODE_PART: + // Launch part + ThEGuiHandler.launchGui(this.part, this.player, this.world, this.x, this.y, this.z); + break; - case MODE_WIRELESS: - // Launch wireless - ThEApi.instance().interact().openWirelessTerminalGui( this.player ); - break; - } + case MODE_WIRELESS: + // Launch wireless + ThEApi.instance().interact().openWirelessTerminalGui(this.player); + break; + } + } - } + @Override + public void readData(final ByteBuf stream) { + if (this.mode != MODE_WIRELESS) { + if (this.mode == MODE_REGULAR) { + // Read the ID + this.guiID = stream.readInt(); + } else if (this.mode == MODE_PART) { + // Read the part + this.part = ThEBasePacket.readPart(stream); + } - @Override - public void readData( final ByteBuf stream ) - { - if( this.mode != MODE_WIRELESS ) - { - if( this.mode == MODE_REGULAR ) - { - // Read the ID - this.guiID = stream.readInt(); - } - else if( this.mode == MODE_PART ) - { - // Read the part - this.part = ThEBasePacket.readPart( stream ); - } + // Read the world + this.world = ThEBasePacket.readWorld(stream); - // Read the world - this.world = ThEBasePacket.readWorld( stream ); + // Read the coords + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + } + } - // Read the coords - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - } - } - - @Override - public void writeData( final ByteBuf stream ) - { - if( this.mode != MODE_WIRELESS ) - { - if( this.mode == MODE_REGULAR ) - { - // Write the ID - stream.writeInt( this.guiID ); - } - else if( this.mode == MODE_PART ) - { - // Write the part - ThEBasePacket.writePart( this.part, stream ); - } - // Write the world - ThEBasePacket.writeWorld( this.world, stream ); - - // Write the coords - stream.writeInt( this.x ); - stream.writeInt( this.y ); - stream.writeInt( this.z ); - } - } + @Override + public void writeData(final ByteBuf stream) { + if (this.mode != MODE_WIRELESS) { + if (this.mode == MODE_REGULAR) { + // Write the ID + stream.writeInt(this.guiID); + } else if (this.mode == MODE_PART) { + // Write the part + ThEBasePacket.writePart(this.part, stream); + } + // Write the world + ThEBasePacket.writeWorld(this.world, stream); + // Write the coords + stream.writeInt(this.x); + stream.writeInt(this.y); + stream.writeInt(this.z); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ConfirmCraftingJob.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ConfirmCraftingJob.java index 269d6558..d94e5512 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ConfirmCraftingJob.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_ConfirmCraftingJob.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.network.packet.server; -import java.util.concurrent.Future; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -11,6 +10,7 @@ import appeng.container.implementations.ContainerCraftAmount; import appeng.container.implementations.ContainerCraftConfirm; import appeng.core.AELog; import io.netty.buffer.ByteBuf; +import java.util.concurrent.Future; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.ForgeDirection; import thaumicenergistics.common.ThEGuiHandler; @@ -22,121 +22,105 @@ import thaumicenergistics.common.network.NetworkHandler; * @author Nividica * */ -public class Packet_S_ConfirmCraftingJob - extends ThEServerPacket -{ - private static final byte MODE_REQUEST_CONFIRM = 1; +public class Packet_S_ConfirmCraftingJob extends ThEServerPacket { + private static final byte MODE_REQUEST_CONFIRM = 1; - private long amount; - private boolean heldShift; + private long amount; + private boolean heldShift; - public static void sendConfirmAutoCraft( final EntityPlayer player, final long amount, final boolean isShiftHeld ) - { - Packet_S_ConfirmCraftingJob packet = new Packet_S_ConfirmCraftingJob(); + public static void sendConfirmAutoCraft(final EntityPlayer player, final long amount, final boolean isShiftHeld) { + Packet_S_ConfirmCraftingJob packet = new Packet_S_ConfirmCraftingJob(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = Packet_S_ConfirmCraftingJob.MODE_REQUEST_CONFIRM; + // Set the mode + packet.mode = Packet_S_ConfirmCraftingJob.MODE_REQUEST_CONFIRM; - // Set amount - packet.amount = amount; + // Set amount + packet.amount = amount; - // Set shift - packet.heldShift = isShiftHeld; + // Set shift + packet.heldShift = isShiftHeld; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - // Read amount - this.amount = stream.readLong(); + @Override + protected void readData(final ByteBuf stream) { + // Read amount + this.amount = stream.readLong(); - // Read shift - this.heldShift = stream.readBoolean(); - } + // Read shift + this.heldShift = stream.readBoolean(); + } - @Override - protected void writeData( final ByteBuf stream ) - { - // Write amount - stream.writeLong( this.amount ); + @Override + protected void writeData(final ByteBuf stream) { + // Write amount + stream.writeLong(this.amount); - // Write shift - stream.writeBoolean( this.heldShift ); - } + // Write shift + stream.writeBoolean(this.heldShift); + } - @Override - public void execute() - { - // Sanity check. - if( this.mode != Packet_S_ConfirmCraftingJob.MODE_REQUEST_CONFIRM ) - { - return; - } + @Override + public void execute() { + // Sanity check. + if (this.mode != Packet_S_ConfirmCraftingJob.MODE_REQUEST_CONFIRM) { + return; + } - // NOTE: The code from here down was copied from "PacketCraftRequest" from AE2 - // The only change is which GUI is launched. + // NOTE: The code from here down was copied from "PacketCraftRequest" from AE2 + // The only change is which GUI is launched. - if( this.player.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount)this.player.openContainer; - final Object target = cca.getTarget(); - if( target instanceof IGridHost ) - { - final IGridHost gh = (IGridHost)target; - final IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); - if( gn == null ) - { - return; - } + if (this.player.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) this.player.openContainer; + final Object target = cca.getTarget(); + if (target instanceof IGridHost) { + final IGridHost gh = (IGridHost) target; + final IGridNode gn = gh.getGridNode(ForgeDirection.UNKNOWN); + if (gn == null) { + return; + } - final IGrid g = gn.getGrid(); - if( ( g == null ) || ( cca.getItemToCraft() == null ) ) - { - return; - } + final IGrid g = gn.getGrid(); + if ((g == null) || (cca.getItemToCraft() == null)) { + return; + } - cca.getItemToCraft().setStackSize( this.amount ); + cca.getItemToCraft().setStackSize(this.amount); - Future futureJob = null; - try - { - final ICraftingGrid cg = g.getCache( ICraftingGrid.class ); - futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null ); + Future futureJob = null; + try { + final ICraftingGrid cg = g.getCache(ICraftingGrid.class); + futureJob = cg.beginCraftingJob( + cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null); - final ContainerOpenContext context = cca.getOpenContext(); - if( context != null ) - { - // Begin Thaumic Energistics Changes =============================== + final ContainerOpenContext context = cca.getOpenContext(); + if (context != null) { + // Begin Thaumic Energistics Changes =============================== - ThEGuiHandler.launchGui( ThEGuiHandler.AUTO_CRAFTING_CONFIRM, this.player, this.player.worldObj, 0, 0, 0 ); + ThEGuiHandler.launchGui( + ThEGuiHandler.AUTO_CRAFTING_CONFIRM, this.player, this.player.worldObj, 0, 0, 0); - // End Thaumic Energistics Changes =============================== - - if( this.player.openContainer instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm ccc = (ContainerCraftConfirm)this.player.openContainer; - ccc.setAutoStart( this.heldShift ); - ccc.setJob( futureJob ); - cca.detectAndSendChanges(); - } - } - } - catch( final Throwable e ) - { - if( futureJob != null ) - { - futureJob.cancel( true ); - } - AELog.error( e ); - } - } - } - } + // End Thaumic Energistics Changes =============================== + if (this.player.openContainer instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm ccc = (ContainerCraftConfirm) this.player.openContainer; + ccc.setAutoStart(this.heldShift); + ccc.setJob(futureJob); + cca.detectAndSendChanges(); + } + } + } catch (final Throwable e) { + if (futureJob != null) { + futureJob.cancel(true); + } + AELog.error(e); + } + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_DistillationEncoder.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_DistillationEncoder.java index dbc628a0..d80ee47e 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_DistillationEncoder.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_DistillationEncoder.java @@ -12,51 +12,40 @@ import thaumicenergistics.common.tiles.TileDistillationPatternEncoder; * @author Nividica * */ -public class Packet_S_DistillationEncoder - extends ThEServerPacket -{ - private static final byte MODE_ENCODE = 1; +public class Packet_S_DistillationEncoder extends ThEServerPacket { + private static final byte MODE_ENCODE = 1; - public static void sendEncodePattern( final EntityPlayer player ) - { - // Create a new packet - Packet_S_DistillationEncoder packet = new Packet_S_DistillationEncoder(); + public static void sendEncodePattern(final EntityPlayer player) { + // Create a new packet + Packet_S_DistillationEncoder packet = new Packet_S_DistillationEncoder(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = MODE_ENCODE; + // Set the mode + packet.mode = MODE_ENCODE; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - } + @Override + protected void readData(final ByteBuf stream) {} - @Override - protected void writeData( final ByteBuf stream ) - { - } + @Override + protected void writeData(final ByteBuf stream) {} - @Override - public void execute() - { - // Sanity check - if( this.mode != MODE_ENCODE ) - { - return; - } - - // Get the players open container - if( this.player.openContainer instanceof ContainerDistillationPatternEncoder ) - { - // Send the encode - ( (ContainerDistillationPatternEncoder)this.player.openContainer ).onEncodePattern(); - } - } + @Override + public void execute() { + // Sanity check + if (this.mode != MODE_ENCODE) { + return; + } + // Get the players open container + if (this.player.openContainer instanceof ContainerDistillationPatternEncoder) { + // Send the encode + ((ContainerDistillationPatternEncoder) this.player.openContainer).onEncodePattern(); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellTerminal.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellTerminal.java index 3aa31641..58d96a87 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellTerminal.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellTerminal.java @@ -16,226 +16,214 @@ import thaumicenergistics.common.parts.PartEssentiaTerminal; * @author Nividica * */ -public class Packet_S_EssentiaCellTerminal - extends ThEServerPacket -{ - /** - * Packet modes - */ - private static final byte MODE_SELECTED_ASPECT = 0, - MODE_FULL_UPDATE = 1, - MODE_SORT_CHANGE = 2, - MODE_AUTO_CRAFT = 3, - MODE_VIEW_CHANGE = 4, - MODE_HELD_ITEM = 5; +public class Packet_S_EssentiaCellTerminal extends ThEServerPacket { + /** + * Packet modes + */ + private static final byte MODE_SELECTED_ASPECT = 0, + MODE_FULL_UPDATE = 1, + MODE_SORT_CHANGE = 2, + MODE_AUTO_CRAFT = 3, + MODE_VIEW_CHANGE = 4, + MODE_HELD_ITEM = 5; - /** - * The aspect. - */ - private Aspect selectedAspect; + /** + * The aspect. + */ + private Aspect selectedAspect; - /** - * Boolean flag. What more needs to be said :P - */ - private Boolean flag; + /** + * Boolean flag. What more needs to be said :P + */ + private Boolean flag; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_EssentiaCellTerminal newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = new Packet_S_EssentiaCellTerminal(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_EssentiaCellTerminal newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = new Packet_S_EssentiaCellTerminal(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - /** - * Asks the server to begin a crafting job for the specified aspect. - * - * @param player - * @param aspect - */ - public static void sendAutoCraft( final EntityPlayer player, final Aspect aspect ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_AUTO_CRAFT ); + /** + * Asks the server to begin a crafting job for the specified aspect. + * + * @param player + * @param aspect + */ + public static void sendAutoCraft(final EntityPlayer player, final Aspect aspect) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_AUTO_CRAFT); - // Set the aspect - packet.selectedAspect = aspect; + // Set the aspect + packet.selectedAspect = aspect; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Asks the server to change the sorting mode. - * - * @param player - */ - public static void sendChangeSorting( final EntityPlayer player, final boolean wasRightClick ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_SORT_CHANGE ); + /** + * Asks the server to change the sorting mode. + * + * @param player + */ + public static void sendChangeSorting(final EntityPlayer player, final boolean wasRightClick) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_SORT_CHANGE); - // Set the flag - packet.flag = wasRightClick; + // Set the flag + packet.flag = wasRightClick; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Asks the server to change the view mode. - * - * @param player - */ - public static void sendChangeView( final EntityPlayer player, final boolean wasRightClick ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_VIEW_CHANGE ); + /** + * Asks the server to change the view mode. + * + * @param player + */ + public static void sendChangeView(final EntityPlayer player, final boolean wasRightClick) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_VIEW_CHANGE); - // Set the flag - packet.flag = wasRightClick; + // Set the flag + packet.flag = wasRightClick; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Requests a full update from the server. - * - * @param player - */ - public static void sendFullUpdateRequest( final EntityPlayer player ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_FULL_UPDATE ); + /** + * Requests a full update from the server. + * + * @param player + */ + public static void sendFullUpdateRequest(final EntityPlayer player) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_FULL_UPDATE); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Informs the server when an aspect has been clicked on and the player - * is holding an item. - * - * @param player - * @param aspect - */ - public static void sendInteractWithHeldItem( final EntityPlayer player, final Aspect aspect ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_HELD_ITEM ); + /** + * Informs the server when an aspect has been clicked on and the player + * is holding an item. + * + * @param player + * @param aspect + */ + public static void sendInteractWithHeldItem(final EntityPlayer player, final Aspect aspect) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_HELD_ITEM); - // Set the aspect - packet.selectedAspect = aspect; + // Set the aspect + packet.selectedAspect = aspect; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Informs the server the player has (un)selected an aspect. - * - * @param player - * @param currentAspect - */ - public static void sendSelectedAspect( final EntityPlayer player, final Aspect currentAspect ) - { - // Create the packet - Packet_S_EssentiaCellTerminal packet = newPacket( player, MODE_SELECTED_ASPECT ); + /** + * Informs the server the player has (un)selected an aspect. + * + * @param player + * @param currentAspect + */ + public static void sendSelectedAspect(final EntityPlayer player, final Aspect currentAspect) { + // Create the packet + Packet_S_EssentiaCellTerminal packet = newPacket(player, MODE_SELECTED_ASPECT); - // Set the current aspect - packet.selectedAspect = currentAspect; + // Set the current aspect + packet.selectedAspect = currentAspect; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - public void execute() - { - // Sanity checks - if( ( this.player == null ) || !( this.player.openContainer instanceof ContainerEssentiaCellTerminalBase ) ) - { - return; - } + @Override + public void execute() { + // Sanity checks + if ((this.player == null) || !(this.player.openContainer instanceof ContainerEssentiaCellTerminalBase)) { + return; + } - switch ( this.mode ) - { - case MODE_SELECTED_ASPECT: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onReceivedSelectedAspect( this.selectedAspect ); - break; + switch (this.mode) { + case MODE_SELECTED_ASPECT: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer) + .onReceivedSelectedAspect(this.selectedAspect); + break; - case MODE_FULL_UPDATE: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onClientRequestFullUpdate(); - break; + case MODE_FULL_UPDATE: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer).onClientRequestFullUpdate(); + break; - case MODE_SORT_CHANGE: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onClientRequestSortModeChange( this.player, this.flag ); - break; + case MODE_SORT_CHANGE: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer) + .onClientRequestSortModeChange(this.player, this.flag); + break; - case MODE_AUTO_CRAFT: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onClientRequestAutoCraft( this.player, this.selectedAspect ); - break; + case MODE_AUTO_CRAFT: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer) + .onClientRequestAutoCraft(this.player, this.selectedAspect); + break; - case MODE_VIEW_CHANGE: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onClientRequestViewModeChange( this.player, this.flag ); - break; + case MODE_VIEW_CHANGE: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer) + .onClientRequestViewModeChange(this.player, this.flag); + break; - case MODE_HELD_ITEM: - ( (ContainerEssentiaCellTerminalBase)this.player.openContainer ).onInteractWithHeldItem( this.player, this.selectedAspect ); - break; - } + case MODE_HELD_ITEM: + ((ContainerEssentiaCellTerminalBase) this.player.openContainer) + .onInteractWithHeldItem(this.player, this.selectedAspect); + break; + } + } - } + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case MODE_SELECTED_ASPECT: + case MODE_AUTO_CRAFT: + case MODE_HELD_ITEM: + // Read the aspect + this.selectedAspect = ThEBasePacket.readAspect(stream); + break; - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_SELECTED_ASPECT: - case MODE_AUTO_CRAFT: - case MODE_HELD_ITEM: - // Read the aspect - this.selectedAspect = ThEBasePacket.readAspect( stream ); - break; + case MODE_SORT_CHANGE: + case MODE_VIEW_CHANGE: + // Read the flag + this.flag = stream.readBoolean(); + break; + } + } - case MODE_SORT_CHANGE: - case MODE_VIEW_CHANGE: - // Read the flag - this.flag = stream.readBoolean(); - break; - } - } + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case MODE_SELECTED_ASPECT: + case MODE_AUTO_CRAFT: + case MODE_HELD_ITEM: + // Write the aspect + ThEBasePacket.writeAspect(this.selectedAspect, stream); + break; - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_SELECTED_ASPECT: - case MODE_AUTO_CRAFT: - case MODE_HELD_ITEM: - // Write the aspect - ThEBasePacket.writeAspect( this.selectedAspect, stream ); - break; - - case MODE_SORT_CHANGE: - case MODE_VIEW_CHANGE: - // Write the flag - stream.writeBoolean( this.flag ); - break; - } - } + case MODE_SORT_CHANGE: + case MODE_VIEW_CHANGE: + // Write the flag + stream.writeBoolean(this.flag); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellWorkbench.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellWorkbench.java index f158301f..eede6c1a 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellWorkbench.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaCellWorkbench.java @@ -14,209 +14,197 @@ import thaumicenergistics.common.tiles.TileEssentiaCellWorkbench; * @author Nividica * */ -public class Packet_S_EssentiaCellWorkbench - extends ThEServerPacket -{ - /** - * Packet modes. - */ - private static final byte MODE_REQUEST_ADD_ASPECT = 0, MODE_REQUEST_REMOVE_ASPECT = 1, MODE_REQUEST_REPLACE_ASPECT = 2, - MODE_REQUEST_FULL_LIST = 4, MODE_REQUEST_CLEAR = 5, MODE_REQUEST_PARITION_CONTENTS = 6; +public class Packet_S_EssentiaCellWorkbench extends ThEServerPacket { + /** + * Packet modes. + */ + private static final byte MODE_REQUEST_ADD_ASPECT = 0, + MODE_REQUEST_REMOVE_ASPECT = 1, + MODE_REQUEST_REPLACE_ASPECT = 2, + MODE_REQUEST_FULL_LIST = 4, + MODE_REQUEST_CLEAR = 5, + MODE_REQUEST_PARITION_CONTENTS = 6; - private Aspect arAspect, replaceAspect; + private Aspect arAspect, replaceAspect; - private TileEssentiaCellWorkbench workbench; + private TileEssentiaCellWorkbench workbench; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_EssentiaCellWorkbench newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_EssentiaCellWorkbench packet = new Packet_S_EssentiaCellWorkbench(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_EssentiaCellWorkbench newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_EssentiaCellWorkbench packet = new Packet_S_EssentiaCellWorkbench(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendAddAspect( final EntityPlayer player, final TileEssentiaCellWorkbench workbench, - final Aspect aspect ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_ADD_ASPECT ); + public static void sendAddAspect( + final EntityPlayer player, final TileEssentiaCellWorkbench workbench, final Aspect aspect) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_ADD_ASPECT); - // Set the aspect - packet.arAspect = aspect; + // Set the aspect + packet.arAspect = aspect; - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendClearPartitioning( final EntityPlayer player, final TileEssentiaCellWorkbench workbench ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_CLEAR ); + public static void sendClearPartitioning(final EntityPlayer player, final TileEssentiaCellWorkbench workbench) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_CLEAR); - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendGetPartitionList( final EntityPlayer player, final TileEssentiaCellWorkbench workbench ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_FULL_LIST ); + public static void sendGetPartitionList(final EntityPlayer player, final TileEssentiaCellWorkbench workbench) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_FULL_LIST); - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendPartitionToContents( final EntityPlayer player, final TileEssentiaCellWorkbench workbench ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_PARITION_CONTENTS ); + public static void sendPartitionToContents(final EntityPlayer player, final TileEssentiaCellWorkbench workbench) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_PARITION_CONTENTS); - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendRemoveAspect( final EntityPlayer player, final TileEssentiaCellWorkbench workbench, - final Aspect aspect ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_REMOVE_ASPECT ); + public static void sendRemoveAspect( + final EntityPlayer player, final TileEssentiaCellWorkbench workbench, final Aspect aspect) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_REMOVE_ASPECT); - // Set the aspect - packet.arAspect = aspect; + // Set the aspect + packet.arAspect = aspect; - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendReplaceAspect( final EntityPlayer player, final TileEssentiaCellWorkbench workbench, - final Aspect originalAspect, final Aspect newAspect ) - { - Packet_S_EssentiaCellWorkbench packet = newPacket( player, MODE_REQUEST_REPLACE_ASPECT ); + public static void sendReplaceAspect( + final EntityPlayer player, + final TileEssentiaCellWorkbench workbench, + final Aspect originalAspect, + final Aspect newAspect) { + Packet_S_EssentiaCellWorkbench packet = newPacket(player, MODE_REQUEST_REPLACE_ASPECT); - // Set the aspects - packet.arAspect = originalAspect; - packet.replaceAspect = newAspect; + // Set the aspects + packet.arAspect = originalAspect; + packet.replaceAspect = newAspect; - // Set the workbench - packet.workbench = workbench; + // Set the workbench + packet.workbench = workbench; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - // Read the workbench - this.workbench = (TileEssentiaCellWorkbench)ThEBasePacket.readTileEntity( stream ); + @Override + protected void readData(final ByteBuf stream) { + // Read the workbench + this.workbench = (TileEssentiaCellWorkbench) ThEBasePacket.readTileEntity(stream); - switch ( this.mode ) - { - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: - // Read the aspect - this.arAspect = ThEBasePacket.readAspect( stream ); - break; + switch (this.mode) { + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: + // Read the aspect + this.arAspect = ThEBasePacket.readAspect(stream); + break; - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: - // Read the original aspect - this.arAspect = ThEBasePacket.readAspect( stream ); + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: + // Read the original aspect + this.arAspect = ThEBasePacket.readAspect(stream); - // Read the replacement aspect - this.replaceAspect = ThEBasePacket.readAspect( stream ); - break; - } - } + // Read the replacement aspect + this.replaceAspect = ThEBasePacket.readAspect(stream); + break; + } + } - @Override - protected void writeData( final ByteBuf stream ) - { - // Write the workbench - ThEBasePacket.writeTileEntity( this.workbench, stream ); + @Override + protected void writeData(final ByteBuf stream) { + // Write the workbench + ThEBasePacket.writeTileEntity(this.workbench, stream); - switch ( this.mode ) - { - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: - // Write the aspect - ThEBasePacket.writeAspect( this.arAspect, stream ); - break; + switch (this.mode) { + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: + // Write the aspect + ThEBasePacket.writeAspect(this.arAspect, stream); + break; - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: - // Write the original aspect - ThEBasePacket.writeAspect( this.arAspect, stream ); + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: + // Write the original aspect + ThEBasePacket.writeAspect(this.arAspect, stream); - // Write the replacement aspect - ThEBasePacket.writeAspect( this.replaceAspect, stream ); - break; - } + // Write the replacement aspect + ThEBasePacket.writeAspect(this.replaceAspect, stream); + break; + } + } - } + @Override + public void execute() { + // Sanity check + if (this.workbench == null) { + return; + } - @Override - public void execute() - { - // Sanity check - if( this.workbench == null ) - { - return; - } + switch (this.mode) { + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: + // Request the aspect be added + this.workbench.addAspectToPartition(this.arAspect); + break; - switch ( this.mode ) - { - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_ADD_ASPECT: - // Request the aspect be added - this.workbench.addAspectToPartition( this.arAspect ); - break; + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: + // Request the aspect be removed + this.workbench.removeAspectFromPartition(this.arAspect); + break; - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REMOVE_ASPECT: - // Request the aspect be removed - this.workbench.removeAspectFromPartition( this.arAspect ); - break; + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: + // Request the aspect be replaced + this.workbench.swapPartitionedAspect(this.arAspect, this.replaceAspect); + break; - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_REPLACE_ASPECT: - // Request the aspect be replaced - this.workbench.swapPartitionedAspect( this.arAspect, this.replaceAspect ); - break; + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_FULL_LIST: + // Request the full list + if (this.player.openContainer instanceof ContainerEssentiaCellWorkbench) { + ((ContainerEssentiaCellWorkbench) this.player.openContainer).onClientRequestPartitionList(); + } + break; - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_FULL_LIST: - // Request the full list - if( this.player.openContainer instanceof ContainerEssentiaCellWorkbench ) - { - ( (ContainerEssentiaCellWorkbench)this.player.openContainer ).onClientRequestPartitionList(); - } - break; - - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_CLEAR: - // Request the clear - this.workbench.clearAllPartitioning(); - break; - - case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_PARITION_CONTENTS: - this.workbench.partitionToCellContents(); - break; - } - } + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_CLEAR: + // Request the clear + this.workbench.clearAllPartitioning(); + break; + case Packet_S_EssentiaCellWorkbench.MODE_REQUEST_PARITION_CONTENTS: + this.workbench.partitionToCellContents(); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaEmitter.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaEmitter.java index a23e017f..53e07609 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaEmitter.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaEmitter.java @@ -12,175 +12,159 @@ import thaumicenergistics.common.parts.PartEssentiaLevelEmitter; * @author Nividica * */ -public class Packet_S_EssentiaEmitter - extends ThEServerPacket -{ - private static final byte MODE_SEND_WANTED = 1, - MODE_ADJUST_WANTED = 2, - MODE_TOGGLE_REDSTONE = 3; +public class Packet_S_EssentiaEmitter extends ThEServerPacket { + private static final byte MODE_SEND_WANTED = 1, MODE_ADJUST_WANTED = 2, MODE_TOGGLE_REDSTONE = 3; - private PartEssentiaLevelEmitter part; - private long wantedAmount; - private int adjustmentAmount; + private PartEssentiaLevelEmitter part; + private long wantedAmount; + private int adjustmentAmount; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_EssentiaEmitter newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_EssentiaEmitter packet = new Packet_S_EssentiaEmitter(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_EssentiaEmitter newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_EssentiaEmitter packet = new Packet_S_EssentiaEmitter(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendRedstoneModeToggle( final PartEssentiaLevelEmitter part, final EntityPlayer player ) - { - Packet_S_EssentiaEmitter packet = newPacket( player, MODE_TOGGLE_REDSTONE ); + public static void sendRedstoneModeToggle(final PartEssentiaLevelEmitter part, final EntityPlayer player) { + Packet_S_EssentiaEmitter packet = newPacket(player, MODE_TOGGLE_REDSTONE); - // Set the part - packet.part = part; + // Set the part + packet.part = part; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Creates a packet to update the wanted amount on the server - * - * @param wantedAmount - * @param part - * @param player - * @return - */ - public static void sendWantedAmount( final long wantedAmount, final PartEssentiaLevelEmitter part, - final EntityPlayer player ) - { - Packet_S_EssentiaEmitter packet = newPacket( player, MODE_SEND_WANTED ); + /** + * Creates a packet to update the wanted amount on the server + * + * @param wantedAmount + * @param part + * @param player + * @return + */ + public static void sendWantedAmount( + final long wantedAmount, final PartEssentiaLevelEmitter part, final EntityPlayer player) { + Packet_S_EssentiaEmitter packet = newPacket(player, MODE_SEND_WANTED); - // Set the part - packet.part = part; + // Set the part + packet.part = part; - // Set the wanted amount - packet.wantedAmount = wantedAmount; + // Set the wanted amount + packet.wantedAmount = wantedAmount; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Creates a packet to adjust the wanted amount on the server - * - * @param adjustmentAmount - * @param part - * @param player - * @return - */ - public static void sendWantedAmountDelta( final int adjustmentAmount, final PartEssentiaLevelEmitter part, - final EntityPlayer player ) - { - Packet_S_EssentiaEmitter packet = newPacket( player, MODE_ADJUST_WANTED ); + /** + * Creates a packet to adjust the wanted amount on the server + * + * @param adjustmentAmount + * @param part + * @param player + * @return + */ + public static void sendWantedAmountDelta( + final int adjustmentAmount, final PartEssentiaLevelEmitter part, final EntityPlayer player) { + Packet_S_EssentiaEmitter packet = newPacket(player, MODE_ADJUST_WANTED); - // Set the part - packet.part = part; + // Set the part + packet.part = part; - // Set the adjustment - packet.adjustmentAmount = adjustmentAmount; + // Set the adjustment + packet.adjustmentAmount = adjustmentAmount; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - public void execute() - { - // Null check - if( this.part == null ) - { - return; - } + @Override + public void execute() { + // Null check + if (this.part == null) { + return; + } - switch ( this.mode ) - { - case MODE_SEND_WANTED: - // Set the wanted amount - this.part.onSetThresholdLevel( this.wantedAmount, this.player ); - break; + switch (this.mode) { + case MODE_SEND_WANTED: + // Set the wanted amount + this.part.onSetThresholdLevel(this.wantedAmount, this.player); + break; - case MODE_ADJUST_WANTED: - // Set the adjustment amount - this.part.onAdjustThresholdLevel( this.adjustmentAmount, this.player ); - break; + case MODE_ADJUST_WANTED: + // Set the adjustment amount + this.part.onAdjustThresholdLevel(this.adjustmentAmount, this.player); + break; - case MODE_TOGGLE_REDSTONE: - // Toggle the redstone mode - this.part.onClientToggleRedstoneMode( this.player ); - break; - } - } + case MODE_TOGGLE_REDSTONE: + // Toggle the redstone mode + this.part.onClientToggleRedstoneMode(this.player); + break; + } + } - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_TOGGLE_REDSTONE: - // Read the part - this.part = (PartEssentiaLevelEmitter)ThEBasePacket.readPart( stream ); - break; + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case MODE_TOGGLE_REDSTONE: + // Read the part + this.part = (PartEssentiaLevelEmitter) ThEBasePacket.readPart(stream); + break; - case MODE_SEND_WANTED: - // Read the part - this.part = (PartEssentiaLevelEmitter)ThEBasePacket.readPart( stream ); + case MODE_SEND_WANTED: + // Read the part + this.part = (PartEssentiaLevelEmitter) ThEBasePacket.readPart(stream); - // Read the wanted amount - this.wantedAmount = stream.readLong(); - break; + // Read the wanted amount + this.wantedAmount = stream.readLong(); + break; - case MODE_ADJUST_WANTED: - // Read the part - this.part = (PartEssentiaLevelEmitter)ThEBasePacket.readPart( stream ); + case MODE_ADJUST_WANTED: + // Read the part + this.part = (PartEssentiaLevelEmitter) ThEBasePacket.readPart(stream); - // Read the adjustment amount - this.adjustmentAmount = stream.readInt(); - break; - } - } + // Read the adjustment amount + this.adjustmentAmount = stream.readInt(); + break; + } + } - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case MODE_TOGGLE_REDSTONE: - // Write the part - ThEBasePacket.writePart( this.part, stream ); - break; + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case MODE_TOGGLE_REDSTONE: + // Write the part + ThEBasePacket.writePart(this.part, stream); + break; - case MODE_SEND_WANTED: - // Write the part - ThEBasePacket.writePart( this.part, stream ); + case MODE_SEND_WANTED: + // Write the part + ThEBasePacket.writePart(this.part, stream); - // Write wanted amount - stream.writeLong( this.wantedAmount ); - break; + // Write wanted amount + stream.writeLong(this.wantedAmount); + break; - case MODE_ADJUST_WANTED: - // Write the part - ThEBasePacket.writePart( this.part, stream ); - - // Write the adjustment amount - stream.writeInt( this.adjustmentAmount ); - break; - } - } + case MODE_ADJUST_WANTED: + // Write the part + ThEBasePacket.writePart(this.part, stream); + // Write the adjustment amount + stream.writeInt(this.adjustmentAmount); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaIOBus.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaIOBus.java index 1d27a040..1d19f4c7 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaIOBus.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaIOBus.java @@ -14,144 +14,131 @@ import thaumicenergistics.common.parts.ThEPartEssentiaIOBus_Base; * @author Nividica * */ -public class Packet_S_EssentiaIOBus - extends ThEServerPacket -{ - private static final byte MODE_REQUEST_FULL_UPDATE = 0, MODE_REQUEST_CHANGE_REDSTONE_MODE = 1, MODE_REQUEST_CHANGE_VOID_MODE = 2, MODE_REQUEST_CHANGE_CRAFTING_MODE = 3; +public class Packet_S_EssentiaIOBus extends ThEServerPacket { + private static final byte MODE_REQUEST_FULL_UPDATE = 0, + MODE_REQUEST_CHANGE_REDSTONE_MODE = 1, + MODE_REQUEST_CHANGE_VOID_MODE = 2, + MODE_REQUEST_CHANGE_CRAFTING_MODE = 3; - private ThEPartEssentiaIOBus_Base part; + private ThEPartEssentiaIOBus_Base part; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_EssentiaIOBus newPacket( final EntityPlayer player, final byte mode, final ThEPartEssentiaIOBus_Base part ) - { - // Create the packet - Packet_S_EssentiaIOBus packet = new Packet_S_EssentiaIOBus(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_EssentiaIOBus newPacket( + final EntityPlayer player, final byte mode, final ThEPartEssentiaIOBus_Base part) { + // Create the packet + Packet_S_EssentiaIOBus packet = new Packet_S_EssentiaIOBus(); - // Set the player & mode & part - packet.player = player; - packet.mode = mode; - packet.part = part; + // Set the player & mode & part + packet.player = player; + packet.mode = mode; + packet.part = part; - return packet; - } + return packet; + } - /** - * Sends a request to the server to change the redstone mode. - * - * @param player - * @param part - * @return - */ - public static void sendRedstoneModeChange( final EntityPlayer player, final ThEPartEssentiaIOBus_Base part ) - { - Packet_S_EssentiaIOBus packet = newPacket( player, MODE_REQUEST_CHANGE_REDSTONE_MODE, part ); + /** + * Sends a request to the server to change the redstone mode. + * + * @param player + * @param part + * @return + */ + public static void sendRedstoneModeChange(final EntityPlayer player, final ThEPartEssentiaIOBus_Base part) { + Packet_S_EssentiaIOBus packet = newPacket(player, MODE_REQUEST_CHANGE_REDSTONE_MODE, part); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Sends a request to the server to change the crafting mode. - * - * @param player - * @param part - * @return - */ - public static void sendCraftingModeChange( final EntityPlayer player, final ThEPartEssentiaIOBus_Base part ) - { - NetworkHandler.sendPacketToServer( newPacket( player, MODE_REQUEST_CHANGE_CRAFTING_MODE, part ) ); - } + /** + * Sends a request to the server to change the crafting mode. + * + * @param player + * @param part + * @return + */ + public static void sendCraftingModeChange(final EntityPlayer player, final ThEPartEssentiaIOBus_Base part) { + NetworkHandler.sendPacketToServer(newPacket(player, MODE_REQUEST_CHANGE_CRAFTING_MODE, part)); + } + /** + * Sends a request to the server for a full update of the buses state. + * + * @param player + * @param part + * @return + */ + public static void sendRequestFilterList(final EntityPlayer player, final ThEPartEssentiaIOBus_Base part) { + NetworkHandler.sendPacketToServer(newPacket(player, MODE_REQUEST_FULL_UPDATE, part)); + } - /** - * Sends a request to the server for a full update of the buses state. - * - * @param player - * @param part - * @return - */ - public static void sendRequestFilterList( final EntityPlayer player, final ThEPartEssentiaIOBus_Base part ) - { - NetworkHandler.sendPacketToServer( newPacket( player, MODE_REQUEST_FULL_UPDATE, part ) ); - } + /** + * Sends a request to the server to update the void mode. + * + * @param player + * @param part + * @return + */ + public static void sendVoidModeChange(final EntityPlayer player, final PartEssentiaExportBus part) { + NetworkHandler.sendPacketToServer(newPacket(player, MODE_REQUEST_CHANGE_VOID_MODE, part)); + } - /** - * Sends a request to the server to update the void mode. - * - * @param player - * @param part - * @return - */ - public static void sendVoidModeChange( final EntityPlayer player, final PartEssentiaExportBus part ) - { - NetworkHandler.sendPacketToServer( newPacket( player, MODE_REQUEST_CHANGE_VOID_MODE, part ) ); - } + @Override + public void execute() { + switch (this.mode) { + case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: + // Request a full update + this.part.onClientRequestFilterList(this.player); + break; - @Override - public void execute() - { - switch ( this.mode ) - { - case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: - // Request a full update - this.part.onClientRequestFilterList( this.player ); - break; + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: + // Request a redstone mode change + this.part.onClientRequestChangeRedstoneMode(); + break; - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: - // Request a redstone mode change - this.part.onClientRequestChangeRedstoneMode(); - break; + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: + // Request a void mode change + if (this.part instanceof PartEssentiaExportBus) { + ((PartEssentiaExportBus) this.part).toggleVoidMode(); + } + break; + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: + if (this.part instanceof PartEssentiaExportBus) { + ((PartEssentiaExportBus) this.part).toggleCraftingMode(); + } + break; + } + } - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: - // Request a void mode change - if( this.part instanceof PartEssentiaExportBus ) - { - ( (PartEssentiaExportBus)this.part ).toggleVoidMode(); - } - break; - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: - if( this.part instanceof PartEssentiaExportBus ) - { - ( (PartEssentiaExportBus)this.part ).toggleCraftingMode(); - } - break; - } - } - - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: - // Read the part - this.part = ( (ThEPartEssentiaIOBus_Base)ThEBasePacket.readPart( stream ) ); - break; - } - } - - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: - case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: - // Write the part - ThEBasePacket.writePart( this.part, stream ); - break; - } - } + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: + // Read the part + this.part = ((ThEPartEssentiaIOBus_Base) ThEBasePacket.readPart(stream)); + break; + } + } + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_EssentiaIOBus.MODE_REQUEST_FULL_UPDATE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_REDSTONE_MODE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_VOID_MODE: + case Packet_S_EssentiaIOBus.MODE_REQUEST_CHANGE_CRAFTING_MODE: + // Write the part + ThEBasePacket.writePart(this.part, stream); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaStorageBus.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaStorageBus.java index 0baeb04b..1de59aac 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaStorageBus.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_EssentiaStorageBus.java @@ -12,87 +12,77 @@ import thaumicenergistics.common.parts.PartEssentiaStorageBus; * @author Nividica * */ -public class Packet_S_EssentiaStorageBus - extends ThEServerPacket -{ - /** - * Packet modes - */ - private static final byte MODE_REQUEST_SET_VOID = 1; +public class Packet_S_EssentiaStorageBus extends ThEServerPacket { + /** + * Packet modes + */ + private static final byte MODE_REQUEST_SET_VOID = 1; - private PartEssentiaStorageBus part; - private boolean isVoidAllowed; + private PartEssentiaStorageBus part; + private boolean isVoidAllowed; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_EssentiaStorageBus newPacket( final EntityPlayer player, final byte mode, final PartEssentiaStorageBus part ) - { - // Create the packet - Packet_S_EssentiaStorageBus packet = new Packet_S_EssentiaStorageBus(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_EssentiaStorageBus newPacket( + final EntityPlayer player, final byte mode, final PartEssentiaStorageBus part) { + // Create the packet + Packet_S_EssentiaStorageBus packet = new Packet_S_EssentiaStorageBus(); - // Set the player & mode & part - packet.player = player; - packet.mode = mode; - packet.part = part; + // Set the player & mode & part + packet.player = player; + packet.mode = mode; + packet.part = part; - return packet; - } + return packet; + } - public static void setVoidAllowed( final EntityPlayer player, final PartEssentiaStorageBus part, - final boolean isVoidAllowed ) - { - Packet_S_EssentiaStorageBus packet = newPacket( player, MODE_REQUEST_SET_VOID, part ); + public static void setVoidAllowed( + final EntityPlayer player, final PartEssentiaStorageBus part, final boolean isVoidAllowed) { + Packet_S_EssentiaStorageBus packet = newPacket(player, MODE_REQUEST_SET_VOID, part); - // Set if void is allowed - packet.isVoidAllowed = isVoidAllowed; + // Set if void is allowed + packet.isVoidAllowed = isVoidAllowed; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - public void execute() - { - switch ( this.mode ) - { - case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: - // Request set void - this.part.onClientRequestSetVoidMode( this.player, this.isVoidAllowed ); - break; - } - } + @Override + public void execute() { + switch (this.mode) { + case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: + // Request set void + this.part.onClientRequestSetVoidMode(this.player, this.isVoidAllowed); + break; + } + } - @Override - public void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: - // Read the part - this.part = ( (PartEssentiaStorageBus)ThEBasePacket.readPart( stream ) ); - // Read void - this.isVoidAllowed = stream.readBoolean(); - break; - } - } - - @Override - public void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: - // Write the part - ThEBasePacket.writePart( this.part, stream ); - // Write void - stream.writeBoolean( this.isVoidAllowed ); - break; - } - } + @Override + public void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: + // Read the part + this.part = ((PartEssentiaStorageBus) ThEBasePacket.readPart(stream)); + // Read void + this.isVoidAllowed = stream.readBoolean(); + break; + } + } + @Override + public void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_EssentiaStorageBus.MODE_REQUEST_SET_VOID: + // Write the part + ThEBasePacket.writePart(this.part, stream); + // Write void + stream.writeBoolean(this.isVoidAllowed); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_KnowledgeInscriber.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_KnowledgeInscriber.java index d43c127e..7fb4db6e 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_KnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_KnowledgeInscriber.java @@ -12,92 +12,79 @@ import thaumicenergistics.common.tiles.TileKnowledgeInscriber; * @author Nividica * */ -public class Packet_S_KnowledgeInscriber - extends ThEServerPacket -{ - /** - * Packet modes - */ - private static final byte MODE_FULL_UPDATE = 0, - MODE_SAVEDELETE = 1, - MODE_CLEAR = 2; +public class Packet_S_KnowledgeInscriber extends ThEServerPacket { + /** + * Packet modes + */ + private static final byte MODE_FULL_UPDATE = 0, MODE_SAVEDELETE = 1, MODE_CLEAR = 2; - private static Packet_S_KnowledgeInscriber newPacket( final EntityPlayer player, final byte mode ) - { - Packet_S_KnowledgeInscriber packet = new Packet_S_KnowledgeInscriber(); + private static Packet_S_KnowledgeInscriber newPacket(final EntityPlayer player, final byte mode) { + Packet_S_KnowledgeInscriber packet = new Packet_S_KnowledgeInscriber(); - // Set the player - packet.player = player; + // Set the player + packet.player = player; - // Set the mode - packet.mode = mode; + // Set the mode + packet.mode = mode; - return packet; - } + return packet; + } - public static void sendClearGrid( final EntityPlayer player ) - { - // Create the packet - Packet_S_KnowledgeInscriber packet = newPacket( player, MODE_CLEAR ); + public static void sendClearGrid(final EntityPlayer player) { + // Create the packet + Packet_S_KnowledgeInscriber packet = newPacket(player, MODE_CLEAR); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendFullUpdateRequest( final EntityPlayer player ) - { - // Create the packet - Packet_S_KnowledgeInscriber packet = newPacket( player, MODE_FULL_UPDATE ); + public static void sendFullUpdateRequest(final EntityPlayer player) { + // Create the packet + Packet_S_KnowledgeInscriber packet = newPacket(player, MODE_FULL_UPDATE); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendSaveDelete( final EntityPlayer player ) - { - // Create the packet - Packet_S_KnowledgeInscriber packet = newPacket( player, MODE_SAVEDELETE ); + public static void sendSaveDelete(final EntityPlayer player) { + // Create the packet + Packet_S_KnowledgeInscriber packet = newPacket(player, MODE_SAVEDELETE); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - // Intentionally empty + @Override + protected void readData(final ByteBuf stream) { + // Intentionally empty - } + } - @Override - protected void writeData( final ByteBuf stream ) - { - // Intentionally empty - } + @Override + protected void writeData(final ByteBuf stream) { + // Intentionally empty + } - @Override - public void execute() - { - // If the player is not null, and they have the KI container open - if( ( this.player != null ) && ( this.player.openContainer instanceof ContainerKnowledgeInscriber ) ) - { - switch ( this.mode ) - { - case MODE_FULL_UPDATE: - // Request full update - ( (ContainerKnowledgeInscriber)this.player.openContainer ).onClientRequestSaveState(); - break; + @Override + public void execute() { + // If the player is not null, and they have the KI container open + if ((this.player != null) && (this.player.openContainer instanceof ContainerKnowledgeInscriber)) { + switch (this.mode) { + case MODE_FULL_UPDATE: + // Request full update + ((ContainerKnowledgeInscriber) this.player.openContainer).onClientRequestSaveState(); + break; - case MODE_SAVEDELETE: - // Request save/delete - ( (ContainerKnowledgeInscriber)this.player.openContainer ).onClientRequestSaveOrDelete( this.player ); - break; + case MODE_SAVEDELETE: + // Request save/delete + ((ContainerKnowledgeInscriber) this.player.openContainer).onClientRequestSaveOrDelete(this.player); + break; - case MODE_CLEAR: - // Request clear - ( (ContainerKnowledgeInscriber)this.player.openContainer ).onClientRequestClearGrid(); - break; - } - } - } + case MODE_CLEAR: + // Request clear + ((ContainerKnowledgeInscriber) this.player.openContainer).onClientRequestClearGrid(); + break; + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_NEIRecipe.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_NEIRecipe.java index c4e58d26..1662feed 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_NEIRecipe.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_NEIRecipe.java @@ -43,24 +43,22 @@ import thaumicenergistics.common.parts.PartArcaneCraftingTerminal; public class Packet_S_NEIRecipe extends ThEServerPacket { private ItemStack[][] recipe = null; private NBTTagCompound nbt = null; + @Override protected void readData(ByteBuf stream) { setRecipe(ByteBufUtils.readTag(stream)); } + public void setRecipe(NBTTagCompound comp) { nbt = comp; - if( comp != null ) - { + if (comp != null) { this.recipe = new ItemStack[9][]; - for( int x = 0; x < this.recipe.length; x++ ) - { - final NBTTagList list = comp.getTagList( "#" + x, 10 ); - if( list.tagCount() > 0 ) - { + for (int x = 0; x < this.recipe.length; x++) { + final NBTTagList list = comp.getTagList("#" + x, 10); + if (list.tagCount() > 0) { this.recipe[x] = new ItemStack[list.tagCount()]; - for( int y = 0; y < list.tagCount(); y++ ) - { - this.recipe[x][y] = ItemStack.loadItemStackFromNBT( list.getCompoundTagAt( y ) ); + for (int y = 0; y < list.tagCount(); y++) { + this.recipe[x][y] = ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(y)); } } } @@ -74,8 +72,7 @@ public class Packet_S_NEIRecipe extends ThEServerPacket { */ @Override protected void writeData(ByteBuf stream) { - if (nbt != null) - ByteBufUtils.writeTag(stream, nbt); + if (nbt != null) ByteBufUtils.writeTag(stream, nbt); } /** @@ -88,137 +85,169 @@ public class Packet_S_NEIRecipe extends ThEServerPacket { if (con instanceof ContainerPartArcaneCraftingTerminal) { - ContainerPartArcaneCraftingTerminal act = (ContainerPartArcaneCraftingTerminal)con; - InventoryCrafting testInv = new InventoryCrafting( new ContainerInternalCrafting(),3, 3 ); - for( int x = 0; x < 9; x++ ) - { - if( this.recipe[x] != null && this.recipe[x].length > 0 ) - { - testInv.setInventorySlotContents( x, this.recipe[x][0] ); + ContainerPartArcaneCraftingTerminal act = (ContainerPartArcaneCraftingTerminal) con; + InventoryCrafting testInv = new InventoryCrafting(new ContainerInternalCrafting(), 3, 3); + for (int x = 0; x < 9; x++) { + if (this.recipe[x] != null && this.recipe[x].length > 0) { + testInv.setInventorySlotContents(x, this.recipe[x][0]); } } IRecipe r = Platform.findMatchingRecipe(testInv, player.worldObj); - IArcaneRecipe arcaneRecipe = r == null ? ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult( testInv, 0,9, this.player ) : null; + IArcaneRecipe arcaneRecipe = + r == null ? ArcaneRecipeHelper.INSTANCE.findMatchingArcaneResult(testInv, 0, 9, this.player) : null; IGrid grid = act.getHostGrid(); - if( grid == null ) - return; - final IStorageGrid inv = grid.getCache( IStorageGrid.class ); - final IEnergyGrid energy = grid.getCache( IEnergyGrid.class ); - final ISecurityGrid security = grid.getCache( ISecurityGrid.class ); - TileMagicWorkbench workbenchTile = ArcaneRecipeHelper.INSTANCE.createBridgeInventory( testInv, 0, 9 ); + if (grid == null) return; + final IStorageGrid inv = grid.getCache(IStorageGrid.class); + final IEnergyGrid energy = grid.getCache(IEnergyGrid.class); + final ISecurityGrid security = grid.getCache(ISecurityGrid.class); + TileMagicWorkbench workbenchTile = ArcaneRecipeHelper.INSTANCE.createBridgeInventory(testInv, 0, 9); workbenchTile.setWorldObj(player.worldObj); - if ((r != null || arcaneRecipe != null) && security != null && security.hasPermission( player, SecurityPermissions.EXTRACT)) - { - final ItemStack is = r != null ? r.getCraftingResult( testInv ) : arcaneRecipe.getCraftingResult(workbenchTile); - if (is == null) - return; + if ((r != null || arcaneRecipe != null) + && security != null + && security.hasPermission(player, SecurityPermissions.EXTRACT)) { + final ItemStack is = + r != null ? r.getCraftingResult(testInv) : arcaneRecipe.getCraftingResult(workbenchTile); + if (is == null) return; final IMEMonitor storage = inv.getItemInventory(); final IItemList all = storage.getStorageList(); - final IPartitionList filter = ItemViewCell.createFilter( act.getViewCells() ); - final IInventory craftMatrix = (PartArcaneCraftingTerminal)act.getCraftingHost(); + final IPartitionList filter = ItemViewCell.createFilter(act.getViewCells()); + final IInventory craftMatrix = (PartArcaneCraftingTerminal) act.getCraftingHost(); final IInventory playerInventory = player.inventory; BaseActionSource as = new PlayerSource(player, act.terminal); - for( int x = 0; x < 9; x++ ) - { - final ItemStack patternItem = testInv.getStackInSlot( x ); - ItemStack currentItem = craftMatrix.getStackInSlot( x ); - if( currentItem != null ) - { - testInv.setInventorySlotContents( x, currentItem ); - workbenchTile.setInventorySlotContents( x, currentItem ); - final ItemStack newItemStack = r != null ? (r.matches( testInv, pmp.worldObj ) ? r.getCraftingResult( testInv ) : null) - : (arcaneRecipe.matches(workbenchTile, pmp.worldObj, pmp) ? arcaneRecipe.getCraftingResult(workbenchTile) : null); - testInv.setInventorySlotContents( x, patternItem ); - workbenchTile.setInventorySlotContents( x, patternItem ); + for (int x = 0; x < 9; x++) { + final ItemStack patternItem = testInv.getStackInSlot(x); + ItemStack currentItem = craftMatrix.getStackInSlot(x); + if (currentItem != null) { + testInv.setInventorySlotContents(x, currentItem); + workbenchTile.setInventorySlotContents(x, currentItem); + final ItemStack newItemStack = r != null + ? (r.matches(testInv, pmp.worldObj) ? r.getCraftingResult(testInv) : null) + : (arcaneRecipe.matches(workbenchTile, pmp.worldObj, pmp) + ? arcaneRecipe.getCraftingResult(workbenchTile) + : null); + testInv.setInventorySlotContents(x, patternItem); + workbenchTile.setInventorySlotContents(x, patternItem); - if( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) - { + if (newItemStack == null || !Platform.isSameItemPrecise(newItemStack, is)) { final IAEItemStack in = AEItemStack.create(currentItem); final IAEItemStack out = Platform.poweredInsert(energy, storage, in, as); craftMatrix.setInventorySlotContents(x, out != null ? out.getItemStack() : null); currentItem = craftMatrix.getStackInSlot(x); } } - if( patternItem != null && currentItem == null ) - { - ItemStack whichItem = r != null ? - Platform.extractItemsByRecipe( energy, as, storage, player.worldObj, r, is, testInv, patternItem, x, all, Actionable.MODULATE, filter ) - : extractItemsByArcaneRecipe(energy, as, storage, player.worldObj, arcaneRecipe, is, workbenchTile, patternItem, x, all, Actionable.MODULATE, filter ); - if( whichItem == null && playerInventory != null ) - whichItem = extractItemFromPlayerInventory( player, patternItem ); + if (patternItem != null && currentItem == null) { + ItemStack whichItem = r != null + ? Platform.extractItemsByRecipe( + energy, + as, + storage, + player.worldObj, + r, + is, + testInv, + patternItem, + x, + all, + Actionable.MODULATE, + filter) + : extractItemsByArcaneRecipe( + energy, + as, + storage, + player.worldObj, + arcaneRecipe, + is, + workbenchTile, + patternItem, + x, + all, + Actionable.MODULATE, + filter); + if (whichItem == null && playerInventory != null) + whichItem = extractItemFromPlayerInventory(player, patternItem); - craftMatrix.setInventorySlotContents( x, whichItem ); + craftMatrix.setInventorySlotContents(x, whichItem); } - con.onCraftMatrixChanged( craftMatrix ); + con.onCraftMatrixChanged(craftMatrix); } } } } - ItemStack extractItemsByArcaneRecipe(final IEnergySource energySrc, final BaseActionSource mySrc, - final IMEMonitor src, final World w, final IArcaneRecipe r, final ItemStack output, final TileMagicWorkbench workbenchTile, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter ) - { - if( energySrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) - { - if( providedTemplate == null ) - { + + ItemStack extractItemsByArcaneRecipe( + final IEnergySource energySrc, + final BaseActionSource mySrc, + final IMEMonitor src, + final World w, + final IArcaneRecipe r, + final ItemStack output, + final TileMagicWorkbench workbenchTile, + final ItemStack providedTemplate, + final int slot, + final IItemList items, + final Actionable realForFake, + final IPartitionList filter) { + if (energySrc.extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) > 0.9) { + if (providedTemplate == null) { return null; } - final AEItemStack ae_req = AEItemStack.create( providedTemplate ); - ae_req.setStackSize( 1 ); + final AEItemStack ae_req = AEItemStack.create(providedTemplate); + ae_req.setStackSize(1); - if( filter == null || filter.isListed( ae_req ) ) - { - final IAEItemStack ae_ext = src.extractItems( ae_req, realForFake, mySrc ); - if( ae_ext != null ) - { + if (filter == null || filter.isListed(ae_req)) { + final IAEItemStack ae_ext = src.extractItems(ae_req, realForFake, mySrc); + if (ae_ext != null) { final ItemStack extracted = ae_ext.getItemStack(); - if( extracted != null ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); + if (extracted != null) { + energySrc.extractAEPower(1, realForFake, PowerMultiplier.CONFIG); return extracted; } } } - final boolean checkFuzzy = ae_req.isOre() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); + final boolean checkFuzzy = ae_req.isOre() + || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE + || providedTemplate.hasTagCompound() + || providedTemplate.isItemStackDamageable(); - if( items != null && checkFuzzy ) - { - for( final IAEItemStack x : items ) - { + if (items != null && checkFuzzy) { + for (final IAEItemStack x : items) { final ItemStack sh = x.getItemStack(); - if( ( Platform.isSameItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !Platform.isSameItem( sh, output ) ) - { // Platform.isSameItemType( sh, providedTemplate ) - final ItemStack cp = Platform.cloneItemStack( sh ); + if ((Platform.isSameItemType(providedTemplate, sh) || ae_req.sameOre(x)) + && !Platform.isSameItem(sh, output)) { // Platform.isSameItemType( sh, providedTemplate ) + final ItemStack cp = Platform.cloneItemStack(sh); cp.stackSize = 1; - workbenchTile.setInventorySlotContents( slot, cp ); - if( r.matches( workbenchTile, w, player ) && Platform.isSameItem( r.getCraftingResult( workbenchTile ), output ) ) - { + workbenchTile.setInventorySlotContents(slot, cp); + if (r.matches(workbenchTile, w, player) + && Platform.isSameItem(r.getCraftingResult(workbenchTile), output)) { final IAEItemStack ax = x.copy(); - ax.setStackSize( 1 ); - if( filter == null || filter.isListed( ax ) ) - { - final IAEItemStack ex = src.extractItems( ax, realForFake, mySrc ); - if( ex != null ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); + ax.setStackSize(1); + if (filter == null || filter.isListed(ax)) { + final IAEItemStack ex = src.extractItems(ax, realForFake, mySrc); + if (ex != null) { + energySrc.extractAEPower(1, realForFake, PowerMultiplier.CONFIG); return ex.getItemStack(); } } } - workbenchTile.setInventorySlotContents( slot, providedTemplate ); + workbenchTile.setInventorySlotContents(slot, providedTemplate); } } } } return null; } - private ItemStack extractItemFromPlayerInventory(final EntityPlayer player, final ItemStack patternItem ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - final AEItemStack request = AEItemStack.create( patternItem ); - final boolean checkFuzzy = request.isOre() || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE || patternItem.hasTagCompound() || patternItem.isItemStackDamageable(); - return checkFuzzy ? ia.removeSimilarItems( 1, patternItem, FuzzyMode.IGNORE_ALL, null ) : ia.removeItems( 1, patternItem, null ); + + private ItemStack extractItemFromPlayerInventory(final EntityPlayer player, final ItemStack patternItem) { + final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + final AEItemStack request = AEItemStack.create(patternItem); + final boolean checkFuzzy = request.isOre() + || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE + || patternItem.hasTagCompound() + || patternItem.isItemStackDamageable(); + return checkFuzzy + ? ia.removeSimilarItems(1, patternItem, FuzzyMode.IGNORE_ALL, null) + : ia.removeItems(1, patternItem, null); } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_Priority.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_Priority.java index 69677aec..acaf408a 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_Priority.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_Priority.java @@ -11,137 +11,121 @@ import thaumicenergistics.common.network.NetworkHandler; * @author Nividica * */ -public class Packet_S_Priority - extends ThEServerPacket -{ - private static final byte MODE_SET = 0; - private static final byte MODE_ADJUST = 1; - private static final byte MODE_REQUEST = 2; +public class Packet_S_Priority extends ThEServerPacket { + private static final byte MODE_SET = 0; + private static final byte MODE_ADJUST = 1; + private static final byte MODE_REQUEST = 2; - private int priority; + private int priority; - /** - * Creates the packet - * - * @param player - * @param mode - * @return - */ - private static Packet_S_Priority newPacket( final EntityPlayer player, final byte mode ) - { - // Create the packet - Packet_S_Priority packet = new Packet_S_Priority(); + /** + * Creates the packet + * + * @param player + * @param mode + * @return + */ + private static Packet_S_Priority newPacket(final EntityPlayer player, final byte mode) { + // Create the packet + Packet_S_Priority packet = new Packet_S_Priority(); - // Set the player & mode - packet.player = player; - packet.mode = mode; + // Set the player & mode + packet.player = player; + packet.mode = mode; - return packet; - } + return packet; + } - /** - * Asks the server to set the priority to the specified value. - * - * @param priority - * @param player - * @return - */ - public static void sendPriority( final int priority, final EntityPlayer player ) - { - Packet_S_Priority packet = newPacket( player, MODE_SET ); + /** + * Asks the server to set the priority to the specified value. + * + * @param priority + * @param player + * @return + */ + public static void sendPriority(final int priority, final EntityPlayer player) { + Packet_S_Priority packet = newPacket(player, MODE_SET); - // Set the priority - packet.priority = priority; + // Set the priority + packet.priority = priority; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - /** - * Asks the server to adjust the priority by the specified value. - * - * @param priority - * @param player - * @return - */ - public static void sendPriorityDelta( final int priority, final EntityPlayer player ) - { - Packet_S_Priority packet = newPacket( player, MODE_ADJUST ); + /** + * Asks the server to adjust the priority by the specified value. + * + * @param priority + * @param player + * @return + */ + public static void sendPriorityDelta(final int priority, final EntityPlayer player) { + Packet_S_Priority packet = newPacket(player, MODE_ADJUST); - // Set the priority delta - packet.priority = priority; + // Set the priority delta + packet.priority = priority; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - public static void sendPriorityRequest( final EntityPlayer player ) - { - Packet_S_Priority packet = newPacket( player, MODE_REQUEST ); + public static void sendPriorityRequest(final EntityPlayer player) { + Packet_S_Priority packet = newPacket(player, MODE_REQUEST); - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_Priority.MODE_SET: - case Packet_S_Priority.MODE_ADJUST: - // Read the priority - this.priority = stream.readInt(); - break; - } - } + @Override + protected void readData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_Priority.MODE_SET: + case Packet_S_Priority.MODE_ADJUST: + // Read the priority + this.priority = stream.readInt(); + break; + } + } - @Override - protected void writeData( final ByteBuf stream ) - { - switch ( this.mode ) - { - case Packet_S_Priority.MODE_SET: - case Packet_S_Priority.MODE_ADJUST: - // Write the priority - stream.writeInt( this.priority ); - break; - } + @Override + protected void writeData(final ByteBuf stream) { + switch (this.mode) { + case Packet_S_Priority.MODE_SET: + case Packet_S_Priority.MODE_ADJUST: + // Write the priority + stream.writeInt(this.priority); + break; + } + } - } + @Override + public void execute() { + // Ensure we have a player + if (this.player == null) { + return; + } - @Override - public void execute() - { - // Ensure we have a player - if( this.player == null ) - { - return; - } + // Ensure the player has opened the priority container + if (!(this.player.openContainer instanceof ContainerPriority)) { + return; + } - // Ensure the player has opened the priority container - if( !( this.player.openContainer instanceof ContainerPriority ) ) - { - return; - } + switch (this.mode) { + case Packet_S_Priority.MODE_SET: + // Set the priority + ((ContainerPriority) this.player.openContainer).onClientRequestSetPriority(this.priority); + break; - switch ( this.mode ) - { - case Packet_S_Priority.MODE_SET: - // Set the priority - ( (ContainerPriority)this.player.openContainer ).onClientRequestSetPriority( this.priority ); - break; - - case Packet_S_Priority.MODE_ADJUST: - // Adjust the priority - ( (ContainerPriority)this.player.openContainer ).onClientRequestAdjustPriority( this.priority ); - break; - - case Packet_S_Priority.MODE_REQUEST: - // Request the priority - ( (ContainerPriority)this.player.openContainer ).onClientRequestPriority(); - break; - } - } + case Packet_S_Priority.MODE_ADJUST: + // Adjust the priority + ((ContainerPriority) this.player.openContainer).onClientRequestAdjustPriority(this.priority); + break; + case Packet_S_Priority.MODE_REQUEST: + // Request the priority + ((ContainerPriority) this.player.openContainer).onClientRequestPriority(); + break; + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_WrenchFocus.java b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_WrenchFocus.java index b42f52a4..aeb22a0a 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_WrenchFocus.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/Packet_S_WrenchFocus.java @@ -14,81 +14,74 @@ import thaumicenergistics.common.network.NetworkHandler; * @author Nividica * */ -public class Packet_S_WrenchFocus - extends ThEServerPacket -{ - // Seems redundant, but is used as a safegaurd - private static final byte MODE_FOCUSWRENCH = 1; +public class Packet_S_WrenchFocus extends ThEServerPacket { + // Seems redundant, but is used as a safegaurd + private static final byte MODE_FOCUSWRENCH = 1; - private float eyeHeight; - private int x, y, z, side; + private float eyeHeight; + private int x, y, z, side; - public static void sendWrenchFocusRequest( final EntityPlayer player, final MovingObjectPosition position ) - { - Packet_S_WrenchFocus packet = new Packet_S_WrenchFocus(); + public static void sendWrenchFocusRequest(final EntityPlayer player, final MovingObjectPosition position) { + Packet_S_WrenchFocus packet = new Packet_S_WrenchFocus(); - // Set player - packet.player = player; + // Set player + packet.player = player; - // Set mode - packet.mode = Packet_S_WrenchFocus.MODE_FOCUSWRENCH; + // Set mode + packet.mode = Packet_S_WrenchFocus.MODE_FOCUSWRENCH; - // Set eye height - packet.eyeHeight = Platform.getEyeOffset( player ); + // Set eye height + packet.eyeHeight = Platform.getEyeOffset(player); - // Set position - packet.x = position.blockX; - packet.y = position.blockY; - packet.z = position.blockZ; + // Set position + packet.x = position.blockX; + packet.y = position.blockY; + packet.z = position.blockZ; - // Set side - packet.side = position.sideHit; + // Set side + packet.side = position.sideHit; - // Send it - NetworkHandler.sendPacketToServer( packet ); - } + // Send it + NetworkHandler.sendPacketToServer(packet); + } - @Override - protected void readData( final ByteBuf stream ) - { - if( this.mode == Packet_S_WrenchFocus.MODE_FOCUSWRENCH ) - { - // Read the eye height - this.eyeHeight = stream.readFloat(); + @Override + protected void readData(final ByteBuf stream) { + if (this.mode == Packet_S_WrenchFocus.MODE_FOCUSWRENCH) { + // Read the eye height + this.eyeHeight = stream.readFloat(); - // Read position - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); + // Read position + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); - // Read side - this.side = stream.readInt(); - } - } + // Read side + this.side = stream.readInt(); + } + } - @Override - protected void writeData( final ByteBuf stream ) - { - // Write the eye height - stream.writeFloat( this.eyeHeight ); + @Override + protected void writeData(final ByteBuf stream) { + // Write the eye height + stream.writeFloat(this.eyeHeight); - // Write position - stream.writeInt( this.x ).writeInt( this.y ).writeInt( this.z ); + // Write position + stream.writeInt(this.x).writeInt(this.y).writeInt(this.z); - // Write side - stream.writeInt( this.side ); - } + // Write side + stream.writeInt(this.side); + } - @Override - public void execute() - { - if( this.mode == Packet_S_WrenchFocus.MODE_FOCUSWRENCH ) - { - // Create the MOP - MovingObjectPosition position = new MovingObjectPosition( this.x, this.y, this.z, this.side, Vec3.createVectorHelper( 0, 0, 0 ), true ); + @Override + public void execute() { + if (this.mode == Packet_S_WrenchFocus.MODE_FOCUSWRENCH) { + // Create the MOP + MovingObjectPosition position = + new MovingObjectPosition(this.x, this.y, this.z, this.side, Vec3.createVectorHelper(0, 0, 0), true); - // Call on the wrench focus to handle the dismantle - ItemFocusAEWrench.performDismantleOnPartHost( this.player, this.eyeHeight, position ); - } - } + // Call on the wrench focus to handle the dismantle + ItemFocusAEWrench.performDismantleOnPartHost(this.player, this.eyeHeight, position); + } + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/ThEServerPacket.java b/src/main/java/thaumicenergistics/common/network/packet/server/ThEServerPacket.java index dbe5dfdc..0bc05eff 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/ThEServerPacket.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/ThEServerPacket.java @@ -8,13 +8,10 @@ import thaumicenergistics.common.network.ThEBasePacket; * @author Nividica * */ -public abstract class ThEServerPacket - extends ThEBasePacket -{ +public abstract class ThEServerPacket extends ThEBasePacket { - @Override - protected final boolean includePlayerInStream() - { - return true; - } + @Override + protected final boolean includePlayerInStream() { + return true; + } } diff --git a/src/main/java/thaumicenergistics/common/network/packet/server/WrapperPacket_S.java b/src/main/java/thaumicenergistics/common/network/packet/server/WrapperPacket_S.java index ef220729..45995414 100644 --- a/src/main/java/thaumicenergistics/common/network/packet/server/WrapperPacket_S.java +++ b/src/main/java/thaumicenergistics/common/network/packet/server/WrapperPacket_S.java @@ -8,16 +8,10 @@ import thaumicenergistics.common.network.WrapperPacket; * @author Nividica * */ -public class WrapperPacket_S - extends WrapperPacket -{ - public WrapperPacket_S() - { +public class WrapperPacket_S extends WrapperPacket { + public WrapperPacket_S() {} - } - - public WrapperPacket_S( final ThEServerPacket packet ) - { - super( packet ); - } + public WrapperPacket_S(final ThEServerPacket packet) { + super(packet); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/AEPartsEnum.java b/src/main/java/thaumicenergistics/common/parts/AEPartsEnum.java index 2383e767..fea2722c 100644 --- a/src/main/java/thaumicenergistics/common/parts/AEPartsEnum.java +++ b/src/main/java/thaumicenergistics/common/parts/AEPartsEnum.java @@ -1,12 +1,12 @@ package thaumicenergistics.common.parts; +import appeng.api.config.Upgrades; import java.util.HashMap; import java.util.Map; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import appeng.api.config.Upgrades; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; import thaumicenergistics.common.ThaumicEnergistics; import thaumicenergistics.common.items.ItemEnum; import thaumicenergistics.common.registries.ThEStrings; @@ -17,167 +17,164 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public enum AEPartsEnum -{ - EssentiaImportBus (ThEStrings.Part_EssentiaImportBus, PartEssentiaImportBus.class, ThaumicEnergistics.MOD_ID + ".group.essentia.transport", - generatePair( Upgrades.CAPACITY, 2 ), generatePair( Upgrades.REDSTONE, 1 ), generatePair( Upgrades.SPEED, 2 )), +public enum AEPartsEnum { + EssentiaImportBus( + ThEStrings.Part_EssentiaImportBus, + PartEssentiaImportBus.class, + ThaumicEnergistics.MOD_ID + ".group.essentia.transport", + generatePair(Upgrades.CAPACITY, 2), + generatePair(Upgrades.REDSTONE, 1), + generatePair(Upgrades.SPEED, 2)), - EssentiaLevelEmitter (ThEStrings.Part_EssentiaLevelEmitter, PartEssentiaLevelEmitter.class), + EssentiaLevelEmitter(ThEStrings.Part_EssentiaLevelEmitter, PartEssentiaLevelEmitter.class), - EssentiaStorageBus (ThEStrings.Part_EssentiaStorageBus, PartEssentiaStorageBus.class, null, generatePair( Upgrades.INVERTER, 1 )), + EssentiaStorageBus( + ThEStrings.Part_EssentiaStorageBus, PartEssentiaStorageBus.class, null, generatePair(Upgrades.INVERTER, 1)), - EssentiaExportBus (ThEStrings.Part_EssentiaExportBus, PartEssentiaExportBus.class, ThaumicEnergistics.MOD_ID + ".group.essentia.transport", - generatePair( Upgrades.CAPACITY, 2 ), generatePair( Upgrades.REDSTONE, 1 ), generatePair( Upgrades.SPEED, 2 ), generatePair( Upgrades.CRAFTING, 1 )), + EssentiaExportBus( + ThEStrings.Part_EssentiaExportBus, + PartEssentiaExportBus.class, + ThaumicEnergistics.MOD_ID + ".group.essentia.transport", + generatePair(Upgrades.CAPACITY, 2), + generatePair(Upgrades.REDSTONE, 1), + generatePair(Upgrades.SPEED, 2), + generatePair(Upgrades.CRAFTING, 1)), - EssentiaTerminal (ThEStrings.Part_EssentiaTerminal, PartEssentiaTerminal.class), + EssentiaTerminal(ThEStrings.Part_EssentiaTerminal, PartEssentiaTerminal.class), - ArcaneCraftingTerminal (ThEStrings.Part_ArcaneCraftingTerminal, PartArcaneCraftingTerminal.class), + ArcaneCraftingTerminal(ThEStrings.Part_ArcaneCraftingTerminal, PartArcaneCraftingTerminal.class), - VisInterface (ThEStrings.Part_VisRelayInterface, PartVisInterface.class), + VisInterface(ThEStrings.Part_VisRelayInterface, PartVisInterface.class), - EssentiaStorageMonitor (ThEStrings.Part_EssentiaStorageMonitor, PartEssentiaStorageMonitor.class), + EssentiaStorageMonitor(ThEStrings.Part_EssentiaStorageMonitor, PartEssentiaStorageMonitor.class), - EssentiaConversionMonitor (ThEStrings.Part_EssentiaConversionMonitor, PartEssentiaConversionMonitor.class); + EssentiaConversionMonitor(ThEStrings.Part_EssentiaConversionMonitor, PartEssentiaConversionMonitor.class); - /** - * Cached enum values - */ - public static final AEPartsEnum[] VALUES = AEPartsEnum.values(); + /** + * Cached enum values + */ + public static final AEPartsEnum[] VALUES = AEPartsEnum.values(); - private ThEStrings unlocalizedName; + private ThEStrings unlocalizedName; - private Class partClass; + private Class partClass; - private String groupName; + private String groupName; - private Map upgrades = new HashMap(); + private Map upgrades = new HashMap(); - private AEPartsEnum( final ThEStrings unlocalizedName, final Class partClass ) - { - this( unlocalizedName, partClass, null ); - } + private AEPartsEnum(final ThEStrings unlocalizedName, final Class partClass) { + this(unlocalizedName, partClass, null); + } - private AEPartsEnum( final ThEStrings unlocalizedName, final Class partClass, final String groupName ) - { - // Set the localization string - this.unlocalizedName = unlocalizedName; + private AEPartsEnum( + final ThEStrings unlocalizedName, final Class partClass, final String groupName) { + // Set the localization string + this.unlocalizedName = unlocalizedName; - // Set the class - this.partClass = partClass; + // Set the class + this.partClass = partClass; - // Set the group name - this.groupName = groupName; - } + // Set the group name + this.groupName = groupName; + } - private AEPartsEnum( final ThEStrings unlocalizedName, final Class partClass, final String groupName, - final Pair ... upgrades ) - { - this( unlocalizedName, partClass, groupName ); + private AEPartsEnum( + final ThEStrings unlocalizedName, + final Class partClass, + final String groupName, + final Pair... upgrades) { + this(unlocalizedName, partClass, groupName); - for( Pair pair : upgrades ) - { - // Add the upgrade to the map - this.upgrades.put( pair.getKey(), pair.getValue() ); - } + for (Pair pair : upgrades) { + // Add the upgrade to the map + this.upgrades.put(pair.getKey(), pair.getValue()); + } + } - } + private static Pair generatePair(final Upgrades upgrade, final int maximum) { + return new ImmutablePair(upgrade, Integer.valueOf(maximum)); + } - private static Pair generatePair( final Upgrades upgrade, final int maximum ) - { - return new ImmutablePair( upgrade, Integer.valueOf( maximum ) ); - } + /** + * Gets an AEPart based on an item stacks damage value. + * + * @param damageValue + * @return + */ + public static AEPartsEnum getPartFromDamageValue(final ItemStack itemStack) { + // Clamp the damage + int clamped = MathHelper.clamp_int(itemStack.getItemDamage(), 0, AEPartsEnum.VALUES.length - 1); - /** - * Gets an AEPart based on an item stacks damage value. - * - * @param damageValue - * @return - */ - public static AEPartsEnum getPartFromDamageValue( final ItemStack itemStack ) - { - // Clamp the damage - int clamped = MathHelper.clamp_int( itemStack.getItemDamage(), 0, AEPartsEnum.VALUES.length - 1 ); + // Get the part + return AEPartsEnum.VALUES[clamped]; + } - // Get the part - return AEPartsEnum.VALUES[clamped]; - } + public static int getPartID(final Class partClass) { + int id = -1; - public static int getPartID( final Class partClass ) - { - int id = -1; + // Check each part + for (int i = 0; i < AEPartsEnum.VALUES.length; i++) { + // Is it the same as the specified part? + if (AEPartsEnum.VALUES[i].getPartClass().equals(partClass)) { + // Found the id, set and stop searching + id = i; + break; + } + } - // Check each part - for( int i = 0; i < AEPartsEnum.VALUES.length; i++ ) - { - // Is it the same as the specified part? - if( AEPartsEnum.VALUES[i].getPartClass().equals( partClass ) ) - { - // Found the id, set and stop searching - id = i; - break; - } - } + // Return the id + return id; + } - // Return the id - return id; + public ThEPartBase createPartInstance(final ItemStack itemStack) + throws InstantiationException, IllegalAccessException { + // Create a new instance of the part + ThEPartBase part = this.partClass.newInstance(); - } + // Setup based on the itemStack + part.setupPartFromItem(itemStack); - public ThEPartBase createPartInstance( final ItemStack itemStack ) throws InstantiationException, IllegalAccessException - { - // Create a new instance of the part - ThEPartBase part = this.partClass.newInstance(); + // Return the newly created part + return part; + } - // Setup based on the itemStack - part.setupPartFromItem( itemStack ); + /** + * Gets the group associated with this part. + * + * @return + */ + public String getGroupName() { + return this.groupName; + } - // Return the newly created part - return part; + public String getLocalizedName() { + return this.unlocalizedName.getLocalized(); + } - } + /** + * Gets the class associated with this part. + * + * @return + */ + public Class getPartClass() { + return this.partClass; + } - /** - * Gets the group associated with this part. - * - * @return - */ - public String getGroupName() - { - return this.groupName; - } + public ItemStack getStack() { + return ItemEnum.ITEM_AEPART.getDMGStack(this.ordinal()); + } - public String getLocalizedName() - { - return this.unlocalizedName.getLocalized(); - } + /** + * Gets the unlocalized name for this part. + * + * @return + */ + public String getUnlocalizedName() { + return this.unlocalizedName.getUnlocalized(); + } - /** - * Gets the class associated with this part. - * - * @return - */ - public Class getPartClass() - { - return this.partClass; - } - - public ItemStack getStack() - { - return ItemEnum.ITEM_AEPART.getDMGStack( this.ordinal() ); - } - - /** - * Gets the unlocalized name for this part. - * - * @return - */ - public String getUnlocalizedName() - { - return this.unlocalizedName.getUnlocalized(); - } - - public Map getUpgrades() - { - return this.upgrades; - } + public Map getUpgrades() { + return this.upgrades; + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartArcaneCraftingTerminal.java b/src/main/java/thaumicenergistics/common/parts/PartArcaneCraftingTerminal.java index 025c5cf4..3f47eebc 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartArcaneCraftingTerminal.java +++ b/src/main/java/thaumicenergistics/common/parts/PartArcaneCraftingTerminal.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.parts; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.SecurityPermissions; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -24,6 +22,8 @@ import appeng.api.util.IConfigManager; import appeng.items.storage.ItemViewCell; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -58,976 +58,900 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class PartArcaneCraftingTerminal - extends ThERotateablePart - implements IInventory, IGridTickable, ICraftingIssuerHost, ITerminalHost -{ - /** - * Number of slots in the internal inventory - */ - private static final int MY_INVENTORY_SIZE = 20; - - /** - * Index of the wand, result, and view slot(s) - */ - public static final int WAND_SLOT_INDEX = 9, RESULT_SLOT_INDEX = 10, VIEW_SLOT_MIN = 11, VIEW_SLOT_MAX = 15, ARMOR_SLOT_MIN = 16; - - /** - * Default sorting order. - */ - public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.NAME; - - /** - * Default sorting direction. - */ - public static final SortDir DEFAULT_SORT_DIR = SortDir.ASCENDING; - - /** - * Default view mode. - */ - public static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; - - /** - * Inventory name - */ - private static final String INVENTORY_NBT_KEY = "TEACT_Inventory"; - - /** - * Key used for reading/writing inventory slots to NBT - */ - private static final String SLOT_NBT_KEY = "Slot#"; - - /** - * Key used for reading/writing the sorting order. - */ - private static final String SORT_ORDER_NBT_KEY = "SortOrder"; - - /** - * Key used for reading/writing the sorting direction. - */ - private static final String SORT_DIRECTION_NBT_KEY = "SortDirection"; - - /** - * Key used for reading/writing the view mode. - */ - private static final String VIEW_MODE_NBT_KEY = "ViewMode"; - - /** - * Key used for reading/writing the vis info - */ - private static final String VIS_INTERFACE_NBT_KEY = "VisInterface"; - - /** - * How much AE power is required to keep the part active. - */ - private static final double IDLE_POWER_DRAIN = 0.5D; - - /** - * Inventory slots - */ - private final ItemStack[] slots = new ItemStack[PartArcaneCraftingTerminal.MY_INVENTORY_SIZE]; - - /** - * Containers wishing to be notified on inventory changes - */ - private List listeners = new ArrayList(); - - /** - * How the items are sorted. - */ - private SortOrder sortingOrder = PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER; - - /** - * What direction are the items sorted. - */ - private SortDir sortingDirection = PartArcaneCraftingTerminal.DEFAULT_SORT_DIR; - - /** - * What items types are visible. - */ - private ViewItems viewMode = PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE; - - /** - * Data pertaining to the linked digi-vis source - */ - private DigiVisSourceData visSourceInfo = new DigiVisSourceData(); - - /** - * Creates the terminal - */ - public PartArcaneCraftingTerminal() - { - // Call super - super( AEPartsEnum.ArcaneCraftingTerminal, SecurityPermissions.EXTRACT, SecurityPermissions.INJECT ); - } - - /** - * Validates that a slot is inbounds of the inventory. - * - * @param slotIndex - * @return - */ - private boolean isSlotInRange( final int slotIndex ) - { - // Is the slot in range? - return( ( slotIndex >= 0 ) && ( slotIndex < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE ) ); - } - - /** - * Notifies all listeners that our inventory contents - * have changed. - * - * @param slotIndex - */ - private void notifyListeners( final int slotIndex ) - { - // Did the crafting slots, wand, or results slot change? - boolean notifyCrafting = ( slotIndex <= PartArcaneCraftingTerminal.RESULT_SLOT_INDEX ); - - // Loop over all listeners - for( ContainerPartArcaneCraftingTerminal listener : this.listeners ) - { - // Ensure the listener is still there - if( listener != null ) - { - // Crafting changes? - if( notifyCrafting ) - { - listener.onCraftMatrixChanged( this ); - } - else - { - listener.onViewCellChange(); - } - } - } - } - - /** - * Distance cable should extend to meet this block - */ - @Override - public int cableConnectionRenderTo() - { - return 3; - } - - @Override - public void closeInventory() - { - // Ignored - } - - /** - * Decreases the size of the itemstack in the specified - * slot by the specified amount, and returns the itemstack. - * Can be null. - */ - @Override - public ItemStack decrStackSize( final int slotIndex, final int amount ) - { - ItemStack returnStack = null; - - // Is the slot in range? - if( this.isSlotInRange( slotIndex ) ) - { - // Get the stack - ItemStack slotStack = this.slots[slotIndex]; - - // Is the slot not null? - if( slotStack != null ) - { - - // Is the amount for more than or all of the slot? - // If is it the results stack, the whole stack must be returned, can not 'partially' take the crafting result. - if( ( amount >= slotStack.stackSize ) || ( slotIndex == PartArcaneCraftingTerminal.RESULT_SLOT_INDEX ) ) - { - // Set the return to a copy of the stack - returnStack = slotStack.copy(); - - // Set stack size to 0 - this.slots[slotIndex].stackSize = 0; - } - else - { - // Split the slot stack - returnStack = slotStack.splitStack( amount ); - } - - // Is the size now 0? - if( this.slots[slotIndex].stackSize == 0 ) - { - // Null it out - this.slots[slotIndex] = null; - } - - // Notify the containers - this.notifyListeners( slotIndex ); - } - } - - return returnStack; - } - - /** - * Collision boxes - */ - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - helper.addBox( 2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D ); - - helper.addBox( 5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D ); - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0]; - } - - /** - * Gets the GUI associated with this part - */ - @Override - public Object getClientGuiElement( final EntityPlayer player ) - { - return new GuiArcaneCraftingTerminal( this, player ); - } - - @Override - public IConfigManager getConfigManager() - { - return null; - } - - /** - * Determines if items should be dropped on the ground when - * the part has been removed. - */ - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - // Were we wrenched? - if( wrenched ) - { - // Inventory is saved when wrenched - return; - } - - // Loop over inventory - for( int slotIndex = 0; slotIndex < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; slotIndex++ ) - { - // Skip if this is the output slot - if( slotIndex == PartArcaneCraftingTerminal.RESULT_SLOT_INDEX ) - { - continue; - } - - // Get the stack at this index - ItemStack slotStack = this.slots[slotIndex]; - - // Did we get anything? - if( slotStack != null ) - { - // Add to drops - drops.add( slotStack ); - } - } - } - - @Override - public IMEMonitor getFluidInventory() - { - // Ignored - return null; - } - - @Override - public ItemStack getIcon() - { - return this.associatedItem; - } - - /** - * Determines how much power the part takes for just - * existing. - */ - @Override - public double getIdlePowerUsage() - { - return PartArcaneCraftingTerminal.IDLE_POWER_DRAIN; - } - - /** - * Gets the inventory name. - */ - @Override - public String getInventoryName() - { - return ThaumicEnergistics.MOD_ID + ".arcane.crafting.terminal.inventory"; - } - - /** - * Maximum number of allowed items per stack. - */ - @Override - public int getInventoryStackLimit() - { - return 64; - } - - @Override - public IMEMonitor getItemInventory() - { - return this.getGridBlock().getItemMonitor(); - } - - /** - * Light level based on if the ACT is on or off. - */ - @Override - public int getLightLevel() - { - return( this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0 ); - } - - /** - * Gets the container associated with this part. - */ - @Override - public Object getServerGuiElement( final EntityPlayer player ) - { - return new ContainerPartArcaneCraftingTerminal( this, player ); - } - - /** - * Returns the internal inventory size. - */ - @Override - public int getSizeInventory() - { - return PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; - } - - /** - * Returns the stored sorting direction. - * - * @return - */ - public SortDir getSortingDirection() - { - return this.sortingDirection; - } - - /** - * Returns the stored sorting order. - * - * @return - */ - public SortOrder getSortingOrder() - { - return this.sortingOrder; - } - - /** - * Gets the itemstack in the specified slot index. - * Can be null. - */ - @Override - public ItemStack getStackInSlot( final int slotIndex ) - { - // Is the slot in range? - if( this.isSlotInRange( slotIndex ) ) - { - // Return the contents of the slot - return this.slots[slotIndex]; - } - - // Return null - return null; - } - - /** - * Returns the itemstack in the specified slot, can be null. - */ - @Override - public ItemStack getStackInSlotOnClosing( final int slotIndex ) - { - // Is the slot in range? - if( this.isSlotInRange( slotIndex ) ) - { - return this.slots[slotIndex]; - } - - return null; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode grid ) - { - // We would like a tick ever 2 to 20 MC ticks - return new TickingRequest( 2, 20, false, false ); - } - - /** - * Returns the view mode. - * - * @return - */ - public ViewItems getViewMode() - { - return this.viewMode; - } - - /** - * Gets the world this inventory is in. - * - * @return - */ - public World getWorldObj() - { - return this.getHostTile().getWorldObj(); - } - - /** - * Returns true. - */ - @Override - public boolean hasCustomInventoryName() - { - return true; - } - - /** - * Determines if the specified itemstack is valid for the slot index. - */ - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack proposedStack ) - { - // Is the slot in range? - if( this.isSlotInRange( slotIndex ) ) - { - // Is the stack null? - if( proposedStack == null ) - { - // Can always remove from slot - return true; - } - - // Is this the wand slot? - if( slotIndex == PartArcaneCraftingTerminal.WAND_SLOT_INDEX ) - { - // Is the item a wand? - return ThEUtils.isItemValidWand( proposedStack, false ); - } - // Is this a view slot? - if( ( slotIndex >= PartArcaneCraftingTerminal.VIEW_SLOT_MIN ) && ( slotIndex <= PartArcaneCraftingTerminal.VIEW_SLOT_MAX ) ) - { - // Is the stack a view slot? - return( proposedStack.getItem() instanceof ItemViewCell ); - - } - - // Unrestricted slot - return true; - } - - // Out of range - return false; - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer player ) - { - return this.isPartUseableByPlayer( player ); - } - - @Override - public void launchGUI( final EntityPlayer player ) - { - TileEntity host = this.getHostTile(); - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Launch the gui - ThEGuiHandler.launchGui( this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); - } - else - { - // Ask the server to change the GUI - Packet_S_ChangeGui.sendGuiChangeToPart( this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); - } - } - - /** - * Ensures the inventory is saved. - */ - @Override - public void markDirty() - { - this.markForSave(); - } - - /** - * Player right-clicked the terminal. - */ - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - // Get what the player is holding - ItemStack playerHolding = player.inventory.getCurrentItem(); - - // Are they holding a memory card? - if( ( playerHolding != null ) && ( playerHolding.getItem() instanceof IMemoryCard ) ) - { - // Get the memory card - IMemoryCard memoryCard = (IMemoryCard)playerHolding.getItem(); - - // Get the stored name - String settingsName = memoryCard.getSettingsName( playerHolding ); - - // Does it contain the data about a vis source? - if( settingsName.equals( DigiVisSourceData.SOURCE_UNLOC_NAME ) ) - { - // Get the data - NBTTagCompound data = memoryCard.getData( playerHolding ); - - // Load the info - this.visSourceInfo.readFromNBT( data ); - - // Ensure there was valid data - if( this.visSourceInfo.hasSourceData() ) - { - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - - // Mark that we need to save - this.markDirty(); - } - // Is the memory card empty? - else if( settingsName.equals( "gui.appliedenergistics2.Blank" ) ) - { - // Clear the source info - this.visSourceInfo.clearData(); - - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - - // Mark dirty - this.markDirty(); - } - - return true; - } - - // Pass to super - return super.onActivate( player, position ); - } - - @Override - public void openInventory() - { - // Ignored - } - - /** - * Loads part data from NBT tag - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Does the data tag have the list? - if( data.hasKey( PartArcaneCraftingTerminal.INVENTORY_NBT_KEY ) ) - { - // Get the list - NBTTagList nbtTagList = (NBTTagList)data.getTag( PartArcaneCraftingTerminal.INVENTORY_NBT_KEY ); - - for( int listIndex = 0; listIndex < nbtTagList.tagCount(); listIndex++ ) - { - // Get the compound tag - NBTTagCompound nbtCompound = nbtTagList.getCompoundTagAt( listIndex ); - - // Get the slot list - int slotIndex = nbtCompound.getByte( PartArcaneCraftingTerminal.SLOT_NBT_KEY ); - - // Is it in range? - if( this.isSlotInRange( slotIndex ) ) - { - // Load the stack - ItemStack slotStack = ItemStack.loadItemStackFromNBT( nbtCompound ); - - // Is the slot the wand slot? - if( slotIndex == PartArcaneCraftingTerminal.WAND_SLOT_INDEX ) - { - // Validate the wand - if( !ThEUtils.isItemValidWand( slotStack, false ) ) - { - // Invalid wand data - slotStack = null; - } - } - - // Set the slot - this.slots[slotIndex] = slotStack; - } - } - - } - - // Sort order - if( data.hasKey( PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY ) ) - { - this.sortingOrder = EnumCache.AE_SORT_ORDERS[data.getInteger( PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY )]; - } - - // Sort direction - if( data.hasKey( PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY ) ) - { - this.sortingDirection = EnumCache.AE_SORT_DIRECTIONS[data.getInteger( PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY )]; - } - - // View mode - if( data.hasKey( PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY ) ) - { - this.viewMode = EnumCache.AE_VIEW_ITEMS[data.getInteger( PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY )]; - } - - // Vis source info - if( data.hasKey( PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY ) ) - { - this.visSourceInfo.readFromNBT( data, PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY ); - } - } - - /** - * Adds a listener to the list if not already added. - * - * @param container - */ - public void registerListener( final ContainerPartArcaneCraftingTerminal container ) - { - // Is this already registered? - if( !this.listeners.contains( container ) ) - { - // Add to the list - this.listeners.add( container ); - } - - } - - /** - * Removes a listener from the list. - * - * @param container - */ - public void removeListener( final ContainerPartArcaneCraftingTerminal container ) - { - // Remove the container from the listeners - this.listeners.remove( container ); - } - - /** - * Renders the part while in the inventory - */ - @Override - @SideOnly(Side.CLIENT) - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; - - IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; - - helper.setTexture( side, side, side, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0], side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - helper.setBounds( 2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F ); - ts.setColorOpaque_I( ThEPartBase.INVENTORY_OVERLAY_COLOR ); - helper.renderInventoryFace( BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer ); - - ts.setColorOpaque_I( AEColor.Black.mediumVariant ); - helper.renderInventoryFace( BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer ); - - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderInventoryBusLights( helper, renderer ); - } - - /** - * Renders the part in the world. - */ - @Override - @SideOnly(Side.CLIENT) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator tessellator = Tessellator.instance; - - IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; - - // Main block - helper.setTexture( side, side, side, side, side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Rotate - this.rotateRenderer( renderer, false ); - - // Face - helper.renderFace( x, y, z, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer ); - - if( this.isActive() ) - { - // Set brightness - tessellator.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - - // Draw corners - helper.setBounds( 2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F ); - tessellator.setColorOpaque_I( this.getHost().getColor().blackVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer ); - tessellator.setColorOpaque_I( this.getHost().getColor().mediumVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer ); - - // Draw crafting overlay - tessellator.setBrightness( 0xA000A0 ); - tessellator.setColorOpaque_I( AEColor.Lime.blackVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[4], ForgeDirection.SOUTH, renderer ); - - } - - // Reset rotation - this.rotateRenderer( renderer, true ); - - // Cable lights - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - } - - /** - * Sets the contents of the specified inventory slot and - * updates the listeners. - * - * @param slotIndex - * @param slotStack - * @return - */ - @Override - public void setInventorySlotContents( final int slotIndex, final ItemStack slotStack ) - { - if( this.setInventorySlotContentsWithoutNotify( slotIndex, slotStack ) ) - { - // Inform the listeners - this.notifyListeners( slotIndex ); - } - } - - /** - * Sets the contents of the specified inventory slot without - * updating listeners. - * - * @param slotIndex - * @param slotStack - * @return - */ - public boolean setInventorySlotContentsWithoutNotify( final int slotIndex, final ItemStack slotStack ) - { - // Is the slot in range? - if( this.isSlotInRange( slotIndex ) ) - { - // Set the slot - this.slots[slotIndex] = slotStack; - - return true; - } - - return false; - } - - /** - * Sets the sorting order and direction - * - * @param order - * @param dir - */ - public void setSorts( final SortOrder order, final SortDir dir, final ViewItems viewMode ) - { - this.sortingDirection = dir; - - this.sortingOrder = order; - - this.viewMode = viewMode; - - this.markDirty(); - } - - /** - * Swaps the armor stored in the ACT with what the specified player is - * wearing. - * - * @param player - */ - public void swapStoredArmor( final EntityPlayer player ) - { - - for( int armorSlot = 0; armorSlot < 4; ++armorSlot ) - { - // Get the stored armor - ItemStack storedArmor = this.slots[PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorSlot]; - - // Get the player armor - ItemStack playerArmor = player.inventory.armorInventory[3 - armorSlot]; - - // Swap - player.inventoryContainer.putStackInSlot( 5 + armorSlot, storedArmor ); - this.slots[PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorSlot] = playerArmor; - - } - - player.inventoryContainer.detectAndSendChanges(); - - // Mark for save - this.markForSave(); - } - - /** - * Checks if the wand needs vis, and refills it if possible - */ - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - // Fast exit checks - if( !this.visSourceInfo.hasSourceData() ) - { - // No source data. - return TickRateModulation.IDLE; - } - - // Get the wand slot - ItemStack stack = this.getStackInSlot( PartArcaneCraftingTerminal.WAND_SLOT_INDEX ); - - // Do we have a wand? - if( ( stack == null ) ) - { - // No wand - return TickRateModulation.IDLE; - } - - // Get the wand - ItemWandCasting wand = (ItemWandCasting)stack.getItem(); - - // Does the wand need vis? - AspectList neededVis = wand.getAspectsWithRoom( stack ); - if( neededVis.size() <= 0 ) - { - // Wand is charged - return TickRateModulation.IDLE; - } - - // Get the source - IDigiVisSource visSource = this.visSourceInfo.tryGetSource( this.getGridBlock().getGrid() ); - - // Did we get an active source? - if( visSource == null ) - { - // Invalid source - return TickRateModulation.IDLE; - } - - // Request vis for each aspect that the wand needs - for( Aspect vis : neededVis.getAspects() ) - { - // Calculate the size of the request - int amountToDrain = wand.getMaxVis( stack ) - wand.getVis( stack, vis ); - - // Request the vis - int amountDrained = visSource.consumeVis( vis, amountToDrain ); - - // Did we drain any? - if( amountDrained > 0 ) - { - // Add to the wand - wand.addRealVis( stack, vis, amountDrained, true ); - - // Inform listeners that wand has changed - this.notifyListeners( PartArcaneCraftingTerminal.WAND_SLOT_INDEX ); - } - - } - - // Tick ASAP until the wand is charged. - return TickRateModulation.URGENT; - } - - /** - * Saves part data to NBT tag - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only write NBT data if saving, or wrenched. - if( ( saveType != PartItemStack.World ) && ( saveType != PartItemStack.Wrench ) ) - { - return; - } - - // Create a new tag list - NBTTagList nbtList = new NBTTagList(); - - // Loop over the slots - for( int slotId = 0; slotId < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; slotId++ ) - { - // Is the slot not null? - if( this.slots[slotId] != null ) - { - // Create the compound tag for this stack - NBTTagCompound nbtCompound = new NBTTagCompound(); - - // Set the slot ID - nbtCompound.setByte( PartArcaneCraftingTerminal.SLOT_NBT_KEY, (byte)slotId ); - - // Write the stack into the tag - this.slots[slotId].writeToNBT( nbtCompound ); - - // Append to the list - nbtList.appendTag( nbtCompound ); - } - } - - // Append the list to the data tag - if( nbtList.tagCount() > 0 ) - { - data.setTag( PartArcaneCraftingTerminal.INVENTORY_NBT_KEY, nbtList ); - } - - // Write direction - if( this.sortingDirection != PartArcaneCraftingTerminal.DEFAULT_SORT_DIR ) - { - data.setInteger( PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY, this.sortingDirection.ordinal() ); - } - - // Write order - if( this.sortingOrder != PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER ) - { - data.setInteger( PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY, this.sortingOrder.ordinal() ); - } - - // Write view mode - if( this.viewMode != PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE ) - { - data.setInteger( PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY, this.viewMode.ordinal() ); - } - - // Write the vis source info - if( saveType == PartItemStack.World ) - { - this.visSourceInfo.writeToNBT( data, PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY ); - } - } +public class PartArcaneCraftingTerminal extends ThERotateablePart + implements IInventory, IGridTickable, ICraftingIssuerHost, ITerminalHost { + /** + * Number of slots in the internal inventory + */ + private static final int MY_INVENTORY_SIZE = 20; + + /** + * Index of the wand, result, and view slot(s) + */ + public static final int WAND_SLOT_INDEX = 9, + RESULT_SLOT_INDEX = 10, + VIEW_SLOT_MIN = 11, + VIEW_SLOT_MAX = 15, + ARMOR_SLOT_MIN = 16; + + /** + * Default sorting order. + */ + public static final SortOrder DEFAULT_SORT_ORDER = SortOrder.NAME; + + /** + * Default sorting direction. + */ + public static final SortDir DEFAULT_SORT_DIR = SortDir.ASCENDING; + + /** + * Default view mode. + */ + public static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; + + /** + * Inventory name + */ + private static final String INVENTORY_NBT_KEY = "TEACT_Inventory"; + + /** + * Key used for reading/writing inventory slots to NBT + */ + private static final String SLOT_NBT_KEY = "Slot#"; + + /** + * Key used for reading/writing the sorting order. + */ + private static final String SORT_ORDER_NBT_KEY = "SortOrder"; + + /** + * Key used for reading/writing the sorting direction. + */ + private static final String SORT_DIRECTION_NBT_KEY = "SortDirection"; + + /** + * Key used for reading/writing the view mode. + */ + private static final String VIEW_MODE_NBT_KEY = "ViewMode"; + + /** + * Key used for reading/writing the vis info + */ + private static final String VIS_INTERFACE_NBT_KEY = "VisInterface"; + + /** + * How much AE power is required to keep the part active. + */ + private static final double IDLE_POWER_DRAIN = 0.5D; + + /** + * Inventory slots + */ + private final ItemStack[] slots = new ItemStack[PartArcaneCraftingTerminal.MY_INVENTORY_SIZE]; + + /** + * Containers wishing to be notified on inventory changes + */ + private List listeners = new ArrayList(); + + /** + * How the items are sorted. + */ + private SortOrder sortingOrder = PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER; + + /** + * What direction are the items sorted. + */ + private SortDir sortingDirection = PartArcaneCraftingTerminal.DEFAULT_SORT_DIR; + + /** + * What items types are visible. + */ + private ViewItems viewMode = PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE; + + /** + * Data pertaining to the linked digi-vis source + */ + private DigiVisSourceData visSourceInfo = new DigiVisSourceData(); + + /** + * Creates the terminal + */ + public PartArcaneCraftingTerminal() { + // Call super + super(AEPartsEnum.ArcaneCraftingTerminal, SecurityPermissions.EXTRACT, SecurityPermissions.INJECT); + } + + /** + * Validates that a slot is inbounds of the inventory. + * + * @param slotIndex + * @return + */ + private boolean isSlotInRange(final int slotIndex) { + // Is the slot in range? + return ((slotIndex >= 0) && (slotIndex < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE)); + } + + /** + * Notifies all listeners that our inventory contents + * have changed. + * + * @param slotIndex + */ + private void notifyListeners(final int slotIndex) { + // Did the crafting slots, wand, or results slot change? + boolean notifyCrafting = (slotIndex <= PartArcaneCraftingTerminal.RESULT_SLOT_INDEX); + + // Loop over all listeners + for (ContainerPartArcaneCraftingTerminal listener : this.listeners) { + // Ensure the listener is still there + if (listener != null) { + // Crafting changes? + if (notifyCrafting) { + listener.onCraftMatrixChanged(this); + } else { + listener.onViewCellChange(); + } + } + } + } + + /** + * Distance cable should extend to meet this block + */ + @Override + public int cableConnectionRenderTo() { + return 3; + } + + @Override + public void closeInventory() { + // Ignored + } + + /** + * Decreases the size of the itemstack in the specified + * slot by the specified amount, and returns the itemstack. + * Can be null. + */ + @Override + public ItemStack decrStackSize(final int slotIndex, final int amount) { + ItemStack returnStack = null; + + // Is the slot in range? + if (this.isSlotInRange(slotIndex)) { + // Get the stack + ItemStack slotStack = this.slots[slotIndex]; + + // Is the slot not null? + if (slotStack != null) { + + // Is the amount for more than or all of the slot? + // If is it the results stack, the whole stack must be returned, can not 'partially' take the crafting + // result. + if ((amount >= slotStack.stackSize) || (slotIndex == PartArcaneCraftingTerminal.RESULT_SLOT_INDEX)) { + // Set the return to a copy of the stack + returnStack = slotStack.copy(); + + // Set stack size to 0 + this.slots[slotIndex].stackSize = 0; + } else { + // Split the slot stack + returnStack = slotStack.splitStack(amount); + } + + // Is the size now 0? + if (this.slots[slotIndex].stackSize == 0) { + // Null it out + this.slots[slotIndex] = null; + } + + // Notify the containers + this.notifyListeners(slotIndex); + } + } + + return returnStack; + } + + /** + * Collision boxes + */ + @Override + public void getBoxes(final IPartCollisionHelper helper) { + helper.addBox(2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D); + + helper.addBox(5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0]; + } + + /** + * Gets the GUI associated with this part + */ + @Override + public Object getClientGuiElement(final EntityPlayer player) { + return new GuiArcaneCraftingTerminal(this, player); + } + + @Override + public IConfigManager getConfigManager() { + return null; + } + + /** + * Determines if items should be dropped on the ground when + * the part has been removed. + */ + @Override + public void getDrops(final List drops, final boolean wrenched) { + // Were we wrenched? + if (wrenched) { + // Inventory is saved when wrenched + return; + } + + // Loop over inventory + for (int slotIndex = 0; slotIndex < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; slotIndex++) { + // Skip if this is the output slot + if (slotIndex == PartArcaneCraftingTerminal.RESULT_SLOT_INDEX) { + continue; + } + + // Get the stack at this index + ItemStack slotStack = this.slots[slotIndex]; + + // Did we get anything? + if (slotStack != null) { + // Add to drops + drops.add(slotStack); + } + } + } + + @Override + public IMEMonitor getFluidInventory() { + // Ignored + return null; + } + + @Override + public ItemStack getIcon() { + return this.associatedItem; + } + + /** + * Determines how much power the part takes for just + * existing. + */ + @Override + public double getIdlePowerUsage() { + return PartArcaneCraftingTerminal.IDLE_POWER_DRAIN; + } + + /** + * Gets the inventory name. + */ + @Override + public String getInventoryName() { + return ThaumicEnergistics.MOD_ID + ".arcane.crafting.terminal.inventory"; + } + + /** + * Maximum number of allowed items per stack. + */ + @Override + public int getInventoryStackLimit() { + return 64; + } + + @Override + public IMEMonitor getItemInventory() { + return this.getGridBlock().getItemMonitor(); + } + + /** + * Light level based on if the ACT is on or off. + */ + @Override + public int getLightLevel() { + return (this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0); + } + + /** + * Gets the container associated with this part. + */ + @Override + public Object getServerGuiElement(final EntityPlayer player) { + return new ContainerPartArcaneCraftingTerminal(this, player); + } + + /** + * Returns the internal inventory size. + */ + @Override + public int getSizeInventory() { + return PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; + } + + /** + * Returns the stored sorting direction. + * + * @return + */ + public SortDir getSortingDirection() { + return this.sortingDirection; + } + + /** + * Returns the stored sorting order. + * + * @return + */ + public SortOrder getSortingOrder() { + return this.sortingOrder; + } + + /** + * Gets the itemstack in the specified slot index. + * Can be null. + */ + @Override + public ItemStack getStackInSlot(final int slotIndex) { + // Is the slot in range? + if (this.isSlotInRange(slotIndex)) { + // Return the contents of the slot + return this.slots[slotIndex]; + } + + // Return null + return null; + } + + /** + * Returns the itemstack in the specified slot, can be null. + */ + @Override + public ItemStack getStackInSlotOnClosing(final int slotIndex) { + // Is the slot in range? + if (this.isSlotInRange(slotIndex)) { + return this.slots[slotIndex]; + } + + return null; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode grid) { + // We would like a tick ever 2 to 20 MC ticks + return new TickingRequest(2, 20, false, false); + } + + /** + * Returns the view mode. + * + * @return + */ + public ViewItems getViewMode() { + return this.viewMode; + } + + /** + * Gets the world this inventory is in. + * + * @return + */ + public World getWorldObj() { + return this.getHostTile().getWorldObj(); + } + + /** + * Returns true. + */ + @Override + public boolean hasCustomInventoryName() { + return true; + } + + /** + * Determines if the specified itemstack is valid for the slot index. + */ + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack proposedStack) { + // Is the slot in range? + if (this.isSlotInRange(slotIndex)) { + // Is the stack null? + if (proposedStack == null) { + // Can always remove from slot + return true; + } + + // Is this the wand slot? + if (slotIndex == PartArcaneCraftingTerminal.WAND_SLOT_INDEX) { + // Is the item a wand? + return ThEUtils.isItemValidWand(proposedStack, false); + } + // Is this a view slot? + if ((slotIndex >= PartArcaneCraftingTerminal.VIEW_SLOT_MIN) + && (slotIndex <= PartArcaneCraftingTerminal.VIEW_SLOT_MAX)) { + // Is the stack a view slot? + return (proposedStack.getItem() instanceof ItemViewCell); + } + + // Unrestricted slot + return true; + } + + // Out of range + return false; + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer player) { + return this.isPartUseableByPlayer(player); + } + + @Override + public void launchGUI(final EntityPlayer player) { + TileEntity host = this.getHostTile(); + + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Launch the gui + ThEGuiHandler.launchGui(this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord); + } else { + // Ask the server to change the GUI + Packet_S_ChangeGui.sendGuiChangeToPart( + this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord); + } + } + + /** + * Ensures the inventory is saved. + */ + @Override + public void markDirty() { + this.markForSave(); + } + + /** + * Player right-clicked the terminal. + */ + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + // Get what the player is holding + ItemStack playerHolding = player.inventory.getCurrentItem(); + + // Are they holding a memory card? + if ((playerHolding != null) && (playerHolding.getItem() instanceof IMemoryCard)) { + // Get the memory card + IMemoryCard memoryCard = (IMemoryCard) playerHolding.getItem(); + + // Get the stored name + String settingsName = memoryCard.getSettingsName(playerHolding); + + // Does it contain the data about a vis source? + if (settingsName.equals(DigiVisSourceData.SOURCE_UNLOC_NAME)) { + // Get the data + NBTTagCompound data = memoryCard.getData(playerHolding); + + // Load the info + this.visSourceInfo.readFromNBT(data); + + // Ensure there was valid data + if (this.visSourceInfo.hasSourceData()) { + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } + + // Mark that we need to save + this.markDirty(); + } + // Is the memory card empty? + else if (settingsName.equals("gui.appliedenergistics2.Blank")) { + // Clear the source info + this.visSourceInfo.clearData(); + + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + + // Mark dirty + this.markDirty(); + } + + return true; + } + + // Pass to super + return super.onActivate(player, position); + } + + @Override + public void openInventory() { + // Ignored + } + + /** + * Loads part data from NBT tag + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Does the data tag have the list? + if (data.hasKey(PartArcaneCraftingTerminal.INVENTORY_NBT_KEY)) { + // Get the list + NBTTagList nbtTagList = (NBTTagList) data.getTag(PartArcaneCraftingTerminal.INVENTORY_NBT_KEY); + + for (int listIndex = 0; listIndex < nbtTagList.tagCount(); listIndex++) { + // Get the compound tag + NBTTagCompound nbtCompound = nbtTagList.getCompoundTagAt(listIndex); + + // Get the slot list + int slotIndex = nbtCompound.getByte(PartArcaneCraftingTerminal.SLOT_NBT_KEY); + + // Is it in range? + if (this.isSlotInRange(slotIndex)) { + // Load the stack + ItemStack slotStack = ItemStack.loadItemStackFromNBT(nbtCompound); + + // Is the slot the wand slot? + if (slotIndex == PartArcaneCraftingTerminal.WAND_SLOT_INDEX) { + // Validate the wand + if (!ThEUtils.isItemValidWand(slotStack, false)) { + // Invalid wand data + slotStack = null; + } + } + + // Set the slot + this.slots[slotIndex] = slotStack; + } + } + } + + // Sort order + if (data.hasKey(PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY)) { + this.sortingOrder = + EnumCache.AE_SORT_ORDERS[data.getInteger(PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY)]; + } + + // Sort direction + if (data.hasKey(PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY)) { + this.sortingDirection = + EnumCache.AE_SORT_DIRECTIONS[data.getInteger(PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY)]; + } + + // View mode + if (data.hasKey(PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY)) { + this.viewMode = EnumCache.AE_VIEW_ITEMS[data.getInteger(PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY)]; + } + + // Vis source info + if (data.hasKey(PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY)) { + this.visSourceInfo.readFromNBT(data, PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY); + } + } + + /** + * Adds a listener to the list if not already added. + * + * @param container + */ + public void registerListener(final ContainerPartArcaneCraftingTerminal container) { + // Is this already registered? + if (!this.listeners.contains(container)) { + // Add to the list + this.listeners.add(container); + } + } + + /** + * Removes a listener from the list. + * + * @param container + */ + public void removeListener(final ContainerPartArcaneCraftingTerminal container) { + // Remove the container from the listeners + this.listeners.remove(container); + } + + /** + * Renders the part while in the inventory + */ + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; + + helper.setTexture( + side, side, side, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0], side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderInventoryBox(renderer); + + helper.setBounds(2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F); + ts.setColorOpaque_I(ThEPartBase.INVENTORY_OVERLAY_COLOR); + helper.renderInventoryFace( + BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer); + + ts.setColorOpaque_I(AEColor.Black.mediumVariant); + helper.renderInventoryFace( + BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer); + + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderInventoryBusLights(helper, renderer); + } + + /** + * Renders the part in the world. + */ + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator tessellator = Tessellator.instance; + + IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; + + // Main block + helper.setTexture(side, side, side, side, side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); + + // Rotate + this.rotateRenderer(renderer, false); + + // Face + helper.renderFace( + x, y, z, BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer); + + if (this.isActive()) { + // Set brightness + tessellator.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + + // Draw corners + helper.setBounds(2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F); + tessellator.setColorOpaque_I(this.getHost().getColor().blackVariant); + helper.renderFace( + x, + y, + z, + BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[2], + ForgeDirection.SOUTH, + renderer); + tessellator.setColorOpaque_I(this.getHost().getColor().mediumVariant); + helper.renderFace( + x, + y, + z, + BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[1], + ForgeDirection.SOUTH, + renderer); + + // Draw crafting overlay + tessellator.setBrightness(0xA000A0); + tessellator.setColorOpaque_I(AEColor.Lime.blackVariant); + helper.renderFace( + x, + y, + z, + BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[4], + ForgeDirection.SOUTH, + renderer); + } + + // Reset rotation + this.rotateRenderer(renderer, true); + + // Cable lights + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } + + /** + * Sets the contents of the specified inventory slot and + * updates the listeners. + * + * @param slotIndex + * @param slotStack + * @return + */ + @Override + public void setInventorySlotContents(final int slotIndex, final ItemStack slotStack) { + if (this.setInventorySlotContentsWithoutNotify(slotIndex, slotStack)) { + // Inform the listeners + this.notifyListeners(slotIndex); + } + } + + /** + * Sets the contents of the specified inventory slot without + * updating listeners. + * + * @param slotIndex + * @param slotStack + * @return + */ + public boolean setInventorySlotContentsWithoutNotify(final int slotIndex, final ItemStack slotStack) { + // Is the slot in range? + if (this.isSlotInRange(slotIndex)) { + // Set the slot + this.slots[slotIndex] = slotStack; + + return true; + } + + return false; + } + + /** + * Sets the sorting order and direction + * + * @param order + * @param dir + */ + public void setSorts(final SortOrder order, final SortDir dir, final ViewItems viewMode) { + this.sortingDirection = dir; + + this.sortingOrder = order; + + this.viewMode = viewMode; + + this.markDirty(); + } + + /** + * Swaps the armor stored in the ACT with what the specified player is + * wearing. + * + * @param player + */ + public void swapStoredArmor(final EntityPlayer player) { + + for (int armorSlot = 0; armorSlot < 4; ++armorSlot) { + // Get the stored armor + ItemStack storedArmor = this.slots[PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorSlot]; + + // Get the player armor + ItemStack playerArmor = player.inventory.armorInventory[3 - armorSlot]; + + // Swap + player.inventoryContainer.putStackInSlot(5 + armorSlot, storedArmor); + this.slots[PartArcaneCraftingTerminal.ARMOR_SLOT_MIN + armorSlot] = playerArmor; + } + + player.inventoryContainer.detectAndSendChanges(); + + // Mark for save + this.markForSave(); + } + + /** + * Checks if the wand needs vis, and refills it if possible + */ + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + // Fast exit checks + if (!this.visSourceInfo.hasSourceData()) { + // No source data. + return TickRateModulation.IDLE; + } + + // Get the wand slot + ItemStack stack = this.getStackInSlot(PartArcaneCraftingTerminal.WAND_SLOT_INDEX); + + // Do we have a wand? + if ((stack == null)) { + // No wand + return TickRateModulation.IDLE; + } + + // Get the wand + ItemWandCasting wand = (ItemWandCasting) stack.getItem(); + + // Does the wand need vis? + AspectList neededVis = wand.getAspectsWithRoom(stack); + if (neededVis.size() <= 0) { + // Wand is charged + return TickRateModulation.IDLE; + } + + // Get the source + IDigiVisSource visSource = + this.visSourceInfo.tryGetSource(this.getGridBlock().getGrid()); + + // Did we get an active source? + if (visSource == null) { + // Invalid source + return TickRateModulation.IDLE; + } + + // Request vis for each aspect that the wand needs + for (Aspect vis : neededVis.getAspects()) { + // Calculate the size of the request + int amountToDrain = wand.getMaxVis(stack) - wand.getVis(stack, vis); + + // Request the vis + int amountDrained = visSource.consumeVis(vis, amountToDrain); + + // Did we drain any? + if (amountDrained > 0) { + // Add to the wand + wand.addRealVis(stack, vis, amountDrained, true); + + // Inform listeners that wand has changed + this.notifyListeners(PartArcaneCraftingTerminal.WAND_SLOT_INDEX); + } + } + + // Tick ASAP until the wand is charged. + return TickRateModulation.URGENT; + } + + /** + * Saves part data to NBT tag + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only write NBT data if saving, or wrenched. + if ((saveType != PartItemStack.World) && (saveType != PartItemStack.Wrench)) { + return; + } + + // Create a new tag list + NBTTagList nbtList = new NBTTagList(); + + // Loop over the slots + for (int slotId = 0; slotId < PartArcaneCraftingTerminal.MY_INVENTORY_SIZE; slotId++) { + // Is the slot not null? + if (this.slots[slotId] != null) { + // Create the compound tag for this stack + NBTTagCompound nbtCompound = new NBTTagCompound(); + + // Set the slot ID + nbtCompound.setByte(PartArcaneCraftingTerminal.SLOT_NBT_KEY, (byte) slotId); + + // Write the stack into the tag + this.slots[slotId].writeToNBT(nbtCompound); + + // Append to the list + nbtList.appendTag(nbtCompound); + } + } + + // Append the list to the data tag + if (nbtList.tagCount() > 0) { + data.setTag(PartArcaneCraftingTerminal.INVENTORY_NBT_KEY, nbtList); + } + + // Write direction + if (this.sortingDirection != PartArcaneCraftingTerminal.DEFAULT_SORT_DIR) { + data.setInteger(PartArcaneCraftingTerminal.SORT_DIRECTION_NBT_KEY, this.sortingDirection.ordinal()); + } + + // Write order + if (this.sortingOrder != PartArcaneCraftingTerminal.DEFAULT_SORT_ORDER) { + data.setInteger(PartArcaneCraftingTerminal.SORT_ORDER_NBT_KEY, this.sortingOrder.ordinal()); + } + + // Write view mode + if (this.viewMode != PartArcaneCraftingTerminal.DEFAULT_VIEW_MODE) { + data.setInteger(PartArcaneCraftingTerminal.VIEW_MODE_NBT_KEY, this.viewMode.ordinal()); + } + + // Write the vis source info + if (saveType == PartItemStack.World) { + this.visSourceInfo.writeToNBT(data, PartArcaneCraftingTerminal.VIS_INTERFACE_NBT_KEY); + } + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaConversionMonitor.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaConversionMonitor.java index 1d7d2485..14b2765d 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaConversionMonitor.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaConversionMonitor.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.parts; -import java.util.Collections; -import java.util.List; -import org.apache.commons.lang3.tuple.ImmutablePair; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -10,12 +7,15 @@ import appeng.api.networking.security.PlayerSource; import appeng.client.texture.CableBusTextures; import appeng.util.InventoryAdaptor; import appeng.util.Platform; +import java.util.Collections; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; +import org.apache.commons.lang3.tuple.ImmutablePair; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.IEssentiaContainerItem; import thaumicenergistics.api.grid.IMEEssentiaMonitor; @@ -31,389 +31,358 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class PartEssentiaConversionMonitor - extends PartEssentiaStorageMonitor -{ - /** - * The number of ticks considered to be a double click. - */ - private static long DOUBLE_CLICK_TICKS = 2 * 20L; - - /** - * The last player ID that deposited essentia - */ - private int depositedPlayerID = -1; - - /** - * The tick count of the last deposited essentia - */ - private int depositedTick = 0; - - /** - * The aspect that was last deposited. - */ - private Aspect depositedAspect = null; - - public PartEssentiaConversionMonitor() - { - super( AEPartsEnum.EssentiaConversionMonitor ); - - this.darkCornerTexture = CableBusTextures.PartConversionMonitor_Colored; - this.lightCornerTexture = CableBusTextures.PartConversionMonitor_Dark; - } - - /** - * Drains the container at the specified index. - * - * @param player - * @param slotIndex - * @param mustMatchAspect - * @return - */ - private boolean drainEssentiaContainer( final EntityPlayer player, final int slotIndex, final Aspect mustMatchAspect ) - { - // Get the container - ItemStack container = player.inventory.getStackInSlot( slotIndex ); - - // Create request - IAspectStack request = EssentiaItemContainerHelper.INSTANCE.getAspectStackFromContainer( container ); - - // Is there anything to request? - if( request == null ) - { - return false; - } - - // Is there a must match aspect? - if( mustMatchAspect != null ) - { - // Do the aspects match? - if( request.getAspect() != mustMatchAspect ) - { - // Mismatch - return false; - } - } - - // Get the monitor - IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); - if( essMonitor == null ) - { - return false; - } - - // Inject the essentia - long rejected = essMonitor.injectEssentia( request.getAspect(), request.getStackSize(), Actionable.MODULATE, - new PlayerSource( player, this ), true ); - - // Adjust the request - request.adjustStackSize( -rejected ); - - if( request.isEmpty() ) - { - // Could not inject - return false; - } - - // Drain the container - ImmutablePair drained = EssentiaItemContainerHelper.INSTANCE.extractFromContainer( container, request ); - - // Update the player inventory - player.inventory.decrStackSize( slotIndex, 1 ); - if( drained != null ) - { - player.inventory.addItemStackToInventory( drained.right ); - } - - // Set the last aspect - this.depositedAspect = request.getAspect(); - - return true; - - } - - /** - * Fills the container the player is holding. - * - * @param player - * @param heldItem - * @return - */ - private boolean fillEssentiaContainer( final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType ) - { - // Is the item being held a label? - if( itemType == AspectItemType.JarLabel ) - { - // Set the label type - EssentiaItemContainerHelper.INSTANCE.setLabelAspect( heldItem, this.trackedEssentia.getAspectStack().getAspect() ); - return true; - } - - // Is the item not a container? - if( itemType != AspectItemType.EssentiaContainer ) - { - // Not a container - return false; - } - - // Does the player have extract permission? - if( !this.doesPlayerHavePermission( player, SecurityPermissions.EXTRACT ) ) - { - return false; - } - - // Get how much is in the container - int containerAmount = EssentiaItemContainerHelper.INSTANCE.getContainerStoredAmount( heldItem ); - - // Is there existing essentia in the container? - if( containerAmount > 0 ) - { - // Get the container aspect - Aspect containerAspect = EssentiaItemContainerHelper.INSTANCE.getAspectInContainer( heldItem ); - - // Ensure it matches the tracker - if( this.trackedEssentia.getAspectStack().getAspect() != containerAspect ) - { - return false; - } - } - - // Is there a jar label? - Aspect jarLabelAspect = EssentiaItemContainerHelper.INSTANCE.getJarLabelAspect( heldItem ); - if( jarLabelAspect != null ) - { - // Ensure it matches the tracker - if( this.trackedEssentia.getAspectStack().getAspect() != jarLabelAspect ) - { - return false; - } - } - - // Get the monitor - IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); - if( essMonitor == null ) - { - return false; - } - - // Get how much the container can hold - int containerCapacity = EssentiaItemContainerHelper.INSTANCE.getContainerCapacity( heldItem ); - - // Create the request - IAspectStack fillRequest = new AspectStack( this.trackedEssentia.getAspectStack().getAspect(), containerCapacity - containerAmount ); - - // Is the container full? - if( fillRequest.isEmpty() ) - { - // Container is full - return false; - } - - // Set the player source - PlayerSource playerSource = new PlayerSource( player, this ); - - // Simulate the request - long extractedAmount = essMonitor.extractEssentia( fillRequest.getAspect(), fillRequest.getStackSize(), Actionable.SIMULATE, playerSource, - true ); - - // Was any extracted? - if( extractedAmount <= 0 ) - { - // None extracted - return false; - } - - // Update values based on how much was extracted - fillRequest.setStackSize( extractedAmount ); - - // Fill the container - ImmutablePair filledContainer = EssentiaItemContainerHelper.INSTANCE.injectIntoContainer( heldItem, fillRequest ); - - // Could the container be filled? - if( filledContainer == null ) - { - return false; - } - - // Take original container - player.inventory.decrStackSize( player.inventory.currentItem, 1 ); - - // Add filled container - InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - ItemStack rejectedItem = adaptor.addItems( filledContainer.right ); - if( rejectedItem != null ) - { - // Get the host tile entity and side - TileEntity te = this.getHostTile(); - ForgeDirection side = this.getSide(); - - List list = Collections.singletonList( rejectedItem ); - Platform.spawnDrops( player.worldObj, te.xCoord + side.offsetX, te.yCoord + side.offsetY, te.zCoord + side.offsetZ, list ); - } - - // Update the client - if( player.openContainer != null ) - { - player.openContainer.detectAndSendChanges(); - } - - // Extract the essentia - essMonitor.extractEssentia( fillRequest.getAspect(), fillRequest.getStackSize(), Actionable.MODULATE, playerSource, true ); - - // Done - return true; - } - - /** - * Drains all containers in the players inventory. - * - * @param player - */ - private void insertAllEssentiaIntoNetwork( final EntityPlayer player ) - { - ItemStack tracking = null; - int prevStackSize = 0; - - for( int slotIndex = 0; slotIndex < player.inventory.getSizeInventory(); ++slotIndex ) - { - // Get the stack - tracking = player.inventory.getStackInSlot( slotIndex ); - - // Is it null or empty? - if( ( tracking == null ) || ( ( prevStackSize = tracking.stackSize ) == 0 ) ) - { - // Empty slot - continue; - } - - // Attempt to drain - this.drainEssentiaContainer( player, slotIndex, this.depositedAspect ); - - // Get the updated stack - tracking = player.inventory.getStackInSlot( slotIndex ); - - // Is there anything left - if( ( tracking != null ) && ( tracking.stackSize > 0 ) ) - { - // Did the stack size change? - if( prevStackSize != tracking.stackSize ) - { - // Visit this slot again - --slotIndex; - } - } - - } - } - - /** - * Sets the last interaction trackers. - * - * @param player - */ - private void markFirstClick( final EntityPlayer player ) - { - // Set the ID - this.depositedPlayerID = AEApi.instance().registries().players().getID( player.getGameProfile() ); - - // Set the time - this.depositedTick = MinecraftServer.getServer().getTickCounter(); - } - - /** - * Returns true if double clicked. - * - * @param player - * @return - */ - private boolean wasDoubleClick( final EntityPlayer player ) - { - // Is this the same player that just used the monitor? - if( ( this.depositedPlayerID != -1 ) && - ( this.depositedPlayerID == AEApi.instance().registries().players().getID( player.getGameProfile() ) ) ) - { - // Was it a double click? - if( ( MinecraftServer.getServer().getTickCounter() - this.depositedTick ) <= PartEssentiaConversionMonitor.DOUBLE_CLICK_TICKS ) - { - // Reset last interaction trackers - this.depositedPlayerID = -1; - this.depositedTick = 0; - return true; - } - } - - // Wrong player, or time between clicks to long. - return false; - } - - /** - * Attempts to fill an essentia container if monitor locked - */ - @Override - protected boolean onActivateWithAspectItem( final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType ) - { - // Is there nothing being tracked, or is the monitor unlocked? - if( !this.trackedEssentia.isValid() || !this.isLocked() ) - { - // Pass to super - return super.onActivateWithAspectItem( player, heldItem, itemType ); - } - - // Fill the container - return this.fillEssentiaContainer( player, heldItem, itemType ); - - } - - @Override - public boolean onShiftActivate( final EntityPlayer player, final Vec3 position ) - { - // Ignore client side. - if( EffectiveSide.isClientSide() ) - { - return true; - } - - // Permission and activation checks - if( !this.activationCheck( player ) ) - { - return false; - } - - // Does the player have inject permission? - if( !this.doesPlayerHavePermission( player, SecurityPermissions.INJECT ) ) - { - return false; - } - - // Get the item the player is holding - ItemStack heldItem = player.getCurrentEquippedItem(); - - // Is the player holding an essentia container? - if( EssentiaItemContainerHelper.INSTANCE.getItemType( heldItem ) != AspectItemType.EssentiaContainer ) - { - // Not holding valid container - return false; - } - - // Shift-right-clicking attempts to insert the essentia into the network. - // Shift-double-right-clicking attempts to insert all essentia in the players inventory into the network. - - // Was it a double click? - if( this.wasDoubleClick( player ) ) - { - // Attempt to insert all essentia - this.insertAllEssentiaIntoNetwork( player ); - return true; - } - - // Drain the container - boolean didDrain = this.drainEssentiaContainer( player, player.inventory.currentItem, null ); - if( didDrain ) - { - this.markFirstClick( player ); - } - - return didDrain; - } - +public class PartEssentiaConversionMonitor extends PartEssentiaStorageMonitor { + /** + * The number of ticks considered to be a double click. + */ + private static long DOUBLE_CLICK_TICKS = 2 * 20L; + + /** + * The last player ID that deposited essentia + */ + private int depositedPlayerID = -1; + + /** + * The tick count of the last deposited essentia + */ + private int depositedTick = 0; + + /** + * The aspect that was last deposited. + */ + private Aspect depositedAspect = null; + + public PartEssentiaConversionMonitor() { + super(AEPartsEnum.EssentiaConversionMonitor); + + this.darkCornerTexture = CableBusTextures.PartConversionMonitor_Colored; + this.lightCornerTexture = CableBusTextures.PartConversionMonitor_Dark; + } + + /** + * Drains the container at the specified index. + * + * @param player + * @param slotIndex + * @param mustMatchAspect + * @return + */ + private boolean drainEssentiaContainer( + final EntityPlayer player, final int slotIndex, final Aspect mustMatchAspect) { + // Get the container + ItemStack container = player.inventory.getStackInSlot(slotIndex); + + // Create request + IAspectStack request = EssentiaItemContainerHelper.INSTANCE.getAspectStackFromContainer(container); + + // Is there anything to request? + if (request == null) { + return false; + } + + // Is there a must match aspect? + if (mustMatchAspect != null) { + // Do the aspects match? + if (request.getAspect() != mustMatchAspect) { + // Mismatch + return false; + } + } + + // Get the monitor + IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); + if (essMonitor == null) { + return false; + } + + // Inject the essentia + long rejected = essMonitor.injectEssentia( + request.getAspect(), request.getStackSize(), Actionable.MODULATE, new PlayerSource(player, this), true); + + // Adjust the request + request.adjustStackSize(-rejected); + + if (request.isEmpty()) { + // Could not inject + return false; + } + + // Drain the container + ImmutablePair drained = + EssentiaItemContainerHelper.INSTANCE.extractFromContainer(container, request); + + // Update the player inventory + player.inventory.decrStackSize(slotIndex, 1); + if (drained != null) { + player.inventory.addItemStackToInventory(drained.right); + } + + // Set the last aspect + this.depositedAspect = request.getAspect(); + + return true; + } + + /** + * Fills the container the player is holding. + * + * @param player + * @param heldItem + * @return + */ + private boolean fillEssentiaContainer( + final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType) { + // Is the item being held a label? + if (itemType == AspectItemType.JarLabel) { + // Set the label type + EssentiaItemContainerHelper.INSTANCE.setLabelAspect( + heldItem, this.trackedEssentia.getAspectStack().getAspect()); + return true; + } + + // Is the item not a container? + if (itemType != AspectItemType.EssentiaContainer) { + // Not a container + return false; + } + + // Does the player have extract permission? + if (!this.doesPlayerHavePermission(player, SecurityPermissions.EXTRACT)) { + return false; + } + + // Get how much is in the container + int containerAmount = EssentiaItemContainerHelper.INSTANCE.getContainerStoredAmount(heldItem); + + // Is there existing essentia in the container? + if (containerAmount > 0) { + // Get the container aspect + Aspect containerAspect = EssentiaItemContainerHelper.INSTANCE.getAspectInContainer(heldItem); + + // Ensure it matches the tracker + if (this.trackedEssentia.getAspectStack().getAspect() != containerAspect) { + return false; + } + } + + // Is there a jar label? + Aspect jarLabelAspect = EssentiaItemContainerHelper.INSTANCE.getJarLabelAspect(heldItem); + if (jarLabelAspect != null) { + // Ensure it matches the tracker + if (this.trackedEssentia.getAspectStack().getAspect() != jarLabelAspect) { + return false; + } + } + + // Get the monitor + IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); + if (essMonitor == null) { + return false; + } + + // Get how much the container can hold + int containerCapacity = EssentiaItemContainerHelper.INSTANCE.getContainerCapacity(heldItem); + + // Create the request + IAspectStack fillRequest = + new AspectStack(this.trackedEssentia.getAspectStack().getAspect(), containerCapacity - containerAmount); + + // Is the container full? + if (fillRequest.isEmpty()) { + // Container is full + return false; + } + + // Set the player source + PlayerSource playerSource = new PlayerSource(player, this); + + // Simulate the request + long extractedAmount = essMonitor.extractEssentia( + fillRequest.getAspect(), fillRequest.getStackSize(), Actionable.SIMULATE, playerSource, true); + + // Was any extracted? + if (extractedAmount <= 0) { + // None extracted + return false; + } + + // Update values based on how much was extracted + fillRequest.setStackSize(extractedAmount); + + // Fill the container + ImmutablePair filledContainer = + EssentiaItemContainerHelper.INSTANCE.injectIntoContainer(heldItem, fillRequest); + + // Could the container be filled? + if (filledContainer == null) { + return false; + } + + // Take original container + player.inventory.decrStackSize(player.inventory.currentItem, 1); + + // Add filled container + InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + ItemStack rejectedItem = adaptor.addItems(filledContainer.right); + if (rejectedItem != null) { + // Get the host tile entity and side + TileEntity te = this.getHostTile(); + ForgeDirection side = this.getSide(); + + List list = Collections.singletonList(rejectedItem); + Platform.spawnDrops( + player.worldObj, + te.xCoord + side.offsetX, + te.yCoord + side.offsetY, + te.zCoord + side.offsetZ, + list); + } + + // Update the client + if (player.openContainer != null) { + player.openContainer.detectAndSendChanges(); + } + + // Extract the essentia + essMonitor.extractEssentia( + fillRequest.getAspect(), fillRequest.getStackSize(), Actionable.MODULATE, playerSource, true); + + // Done + return true; + } + + /** + * Drains all containers in the players inventory. + * + * @param player + */ + private void insertAllEssentiaIntoNetwork(final EntityPlayer player) { + ItemStack tracking = null; + int prevStackSize = 0; + + for (int slotIndex = 0; slotIndex < player.inventory.getSizeInventory(); ++slotIndex) { + // Get the stack + tracking = player.inventory.getStackInSlot(slotIndex); + + // Is it null or empty? + if ((tracking == null) || ((prevStackSize = tracking.stackSize) == 0)) { + // Empty slot + continue; + } + + // Attempt to drain + this.drainEssentiaContainer(player, slotIndex, this.depositedAspect); + + // Get the updated stack + tracking = player.inventory.getStackInSlot(slotIndex); + + // Is there anything left + if ((tracking != null) && (tracking.stackSize > 0)) { + // Did the stack size change? + if (prevStackSize != tracking.stackSize) { + // Visit this slot again + --slotIndex; + } + } + } + } + + /** + * Sets the last interaction trackers. + * + * @param player + */ + private void markFirstClick(final EntityPlayer player) { + // Set the ID + this.depositedPlayerID = AEApi.instance().registries().players().getID(player.getGameProfile()); + + // Set the time + this.depositedTick = MinecraftServer.getServer().getTickCounter(); + } + + /** + * Returns true if double clicked. + * + * @param player + * @return + */ + private boolean wasDoubleClick(final EntityPlayer player) { + // Is this the same player that just used the monitor? + if ((this.depositedPlayerID != -1) + && (this.depositedPlayerID + == AEApi.instance().registries().players().getID(player.getGameProfile()))) { + // Was it a double click? + if ((MinecraftServer.getServer().getTickCounter() - this.depositedTick) + <= PartEssentiaConversionMonitor.DOUBLE_CLICK_TICKS) { + // Reset last interaction trackers + this.depositedPlayerID = -1; + this.depositedTick = 0; + return true; + } + } + + // Wrong player, or time between clicks to long. + return false; + } + + /** + * Attempts to fill an essentia container if monitor locked + */ + @Override + protected boolean onActivateWithAspectItem( + final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType) { + // Is there nothing being tracked, or is the monitor unlocked? + if (!this.trackedEssentia.isValid() || !this.isLocked()) { + // Pass to super + return super.onActivateWithAspectItem(player, heldItem, itemType); + } + + // Fill the container + return this.fillEssentiaContainer(player, heldItem, itemType); + } + + @Override + public boolean onShiftActivate(final EntityPlayer player, final Vec3 position) { + // Ignore client side. + if (EffectiveSide.isClientSide()) { + return true; + } + + // Permission and activation checks + if (!this.activationCheck(player)) { + return false; + } + + // Does the player have inject permission? + if (!this.doesPlayerHavePermission(player, SecurityPermissions.INJECT)) { + return false; + } + + // Get the item the player is holding + ItemStack heldItem = player.getCurrentEquippedItem(); + + // Is the player holding an essentia container? + if (EssentiaItemContainerHelper.INSTANCE.getItemType(heldItem) != AspectItemType.EssentiaContainer) { + // Not holding valid container + return false; + } + + // Shift-right-clicking attempts to insert the essentia into the network. + // Shift-double-right-clicking attempts to insert all essentia in the players inventory into the network. + + // Was it a double click? + if (this.wasDoubleClick(player)) { + // Attempt to insert all essentia + this.insertAllEssentiaIntoNetwork(player); + return true; + } + + // Drain the container + boolean didDrain = this.drainEssentiaContainer(player, player.inventory.currentItem, null); + if (didDrain) { + this.markFirstClick(player); + } + + return didDrain; + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaExportBus.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaExportBus.java index 9b3a4802..c2599b8b 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaExportBus.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaExportBus.java @@ -38,412 +38,393 @@ import thaumicenergistics.implementaion.ThEMultiCraftingTracker; * @author Nividica * */ -public class PartEssentiaExportBus - extends ThEPartEssentiaIOBus_Base - implements ICraftingRequester -{ - private final ThEMultiCraftingTracker craftingTracker = new ThEMultiCraftingTracker( this, 9 ); - private static final String NBT_KEY_VOID = "IsVoidAllowed"; - private final BaseActionSource mySrc; +public class PartEssentiaExportBus extends ThEPartEssentiaIOBus_Base implements ICraftingRequester { + private final ThEMultiCraftingTracker craftingTracker = new ThEMultiCraftingTracker(this, 9); + private static final String NBT_KEY_VOID = "IsVoidAllowed"; + private final BaseActionSource mySrc; - /** - * If true, excess essentia will be voided when facing a void jar. - */ - private boolean isVoidAllowed = false; - private boolean isCraftingOnly = false; + /** + * If true, excess essentia will be voided when facing a void jar. + */ + private boolean isVoidAllowed = false; - public PartEssentiaExportBus() - { - super( AEPartsEnum.EssentiaExportBus, SecurityPermissions.EXTRACT ); - this.mySrc = new MachineSource( this ); - } + private boolean isCraftingOnly = false; - @Override - public boolean aspectTransferAllowed( final Aspect aspect ) - { - return true; - } + public PartEssentiaExportBus() { + super(AEPartsEnum.EssentiaExportBus, SecurityPermissions.EXTRACT); + this.mySrc = new MachineSource(this); + } - @Override - public int cableConnectionRenderTo() - { - return 5; - } + @Override + public boolean aspectTransferAllowed(final Aspect aspect) { + return true; + } - /** - * Attempts to transfer essentia out of the network and into the adjacent - * container. - */ - @Override - public boolean doWork( final int amountToFillContainer ) - { - // Ensure we have a container. - if( this.facingContainer == null ) - { - // Invalid container - return false; - } + @Override + public int cableConnectionRenderTo() { + return 5; + } - // Loop over all aspect filters - for(int slot = 0; slot < filteredAspects.size(); ++slot ) - { - Aspect filterAspect = filteredAspects.get(slot); - // Can we transfer? - if( filterAspect == null ) - { - // Invalid or not allowed - continue; - } + /** + * Attempts to transfer essentia out of the network and into the adjacent + * container. + */ + @Override + public boolean doWork(final int amountToFillContainer) { + // Ensure we have a container. + if (this.facingContainer == null) { + // Invalid container + return false; + } - // Can we inject any of this into the container - if( EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer( this.facingContainer, 1, filterAspect, Actionable.SIMULATE ) <= 0 ) - { - if( !( ( this.isVoidAllowed ) && - ( EssentiaTileContainerHelper.INSTANCE.getAspectInContainer( this.facingContainer ) == filterAspect ) ) ) - { - // Container will not accept any of this, and cannot void(essentia type wrong) - continue; - } - } + // Loop over all aspect filters + for (int slot = 0; slot < filteredAspects.size(); ++slot) { + Aspect filterAspect = filteredAspects.get(slot); + // Can we transfer? + if (filterAspect == null) { + // Invalid or not allowed + continue; + } - // Get the monitor - IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); - if( essMonitor == null ) - { - return false; - } - if (isCraftingOnly()) - { - handleCratting(amountToFillContainer, slot, filterAspect); - continue; - } + // Can we inject any of this into the container + if (EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer( + this.facingContainer, 1, filterAspect, Actionable.SIMULATE) + <= 0) { + if (!((this.isVoidAllowed) + && (EssentiaTileContainerHelper.INSTANCE.getAspectInContainer(this.facingContainer) + == filterAspect))) { + // Container will not accept any of this, and cannot void(essentia type wrong) + continue; + } + } - // Simulate a network extraction - long extractedAmount = essMonitor.extractEssentia( filterAspect, amountToFillContainer, Actionable.SIMULATE, this.asMachineSource, true ); + // Get the monitor + IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); + if (essMonitor == null) { + return false; + } + if (isCraftingOnly()) { + handleCratting(amountToFillContainer, slot, filterAspect); + continue; + } - // Was any extracted? - if( extractedAmount <= 0 ) - { - if (hasCraftingCard) - { - handleCratting(amountToFillContainer, slot, filterAspect); - } - // Unable to extract from network - continue; - } + // Simulate a network extraction + long extractedAmount = essMonitor.extractEssentia( + filterAspect, amountToFillContainer, Actionable.SIMULATE, this.asMachineSource, true); - long filledAmount = injectAspect(Actionable.MODULATE, filterAspect, extractedAmount); - // Was the container filled? - if( filledAmount <= 0 ) - { - // Unable to inject into container - continue; - } + // Was any extracted? + if (extractedAmount <= 0) { + if (hasCraftingCard) { + handleCratting(amountToFillContainer, slot, filterAspect); + } + // Unable to extract from network + continue; + } - // Done - return true; - } + long filledAmount = injectAspect(Actionable.MODULATE, filterAspect, extractedAmount); + // Was the container filled? + if (filledAmount <= 0) { + // Unable to inject into container + continue; + } - return false; - } + // Done + return true; + } - private void handleCratting(int amountToFillContainer, int slot, Aspect filterAspect) - { - IGrid grid = getGridNode().getGrid(); - final ICraftingGrid cg = grid.getCache(ICraftingGrid.class); - IAEItemStack result = AEApi.instance().storage().createItemStack(ItemCraftingAspect.createStackForAspect(filterAspect, amountToFillContainer)); - this.craftingTracker.handleCrafting(slot, amountToFillContainer, result, getHostTile().getWorldObj(), grid, cg, this.mySrc); - } + return false; + } - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - // Large chamber and back wall - helper.addBox( 4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 13.5F ); + private void handleCratting(int amountToFillContainer, int slot, Aspect filterAspect) { + IGrid grid = getGridNode().getGrid(); + final ICraftingGrid cg = grid.getCache(ICraftingGrid.class); + IAEItemStack result = AEApi.instance() + .storage() + .createItemStack(ItemCraftingAspect.createStackForAspect(filterAspect, amountToFillContainer)); + this.craftingTracker.handleCrafting( + slot, amountToFillContainer, result, getHostTile().getWorldObj(), grid, cg, this.mySrc); + } - // Small chamber and front wall - helper.addBox( 5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 15.0F ); + @Override + public void getBoxes(final IPartCollisionHelper helper) { + // Large chamber and back wall + helper.addBox(4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 13.5F); - // Face - helper.addBox( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - } + // Small chamber and front wall + helper.addBox(5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 15.0F); - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2]; - } + // Face + helper.addBox(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + } - /** - * Returns if voiding is allowed. - * - * @return - */ - @Override - public boolean isVoidAllowed() - { - return this.isVoidAllowed; - } + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2]; + } - @Override - public boolean isCraftingOnly() { return isCraftingOnly; } + /** + * Returns if voiding is allowed. + * + * @return + */ + @Override + public boolean isVoidAllowed() { + return this.isVoidAllowed; + } - @Override - public void setCraftingOnly(boolean c) - { - isCraftingOnly = c; - } + @Override + public boolean isCraftingOnly() { + return isCraftingOnly; + } - @Override - public void onClientRequestFilterList( final EntityPlayer player ) - { - // Call super - super.onClientRequestFilterList( player ); - } + @Override + public void setCraftingOnly(boolean c) { + isCraftingOnly = c; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); + @Override + public void onClientRequestFilterList(final EntityPlayer player) { + // Call super + super.onClientRequestFilterList(player); + } - // Read void - if( data.hasKey( PartEssentiaExportBus.NBT_KEY_VOID ) ) - { - this.isVoidAllowed = data.getBoolean( PartEssentiaExportBus.NBT_KEY_VOID ); - } - this.craftingTracker.readFromNBT( data ); - if (data.hasKey("isCraftingOnly")) - { - isCraftingOnly = data.getBoolean("isCraftingOnly"); - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; + // Read void + if (data.hasKey(PartEssentiaExportBus.NBT_KEY_VOID)) { + this.isVoidAllowed = data.getBoolean(PartEssentiaExportBus.NBT_KEY_VOID); + } + this.craftingTracker.readFromNBT(data); + if (data.hasKey("isCraftingOnly")) { + isCraftingOnly = data.getBoolean("isCraftingOnly"); + } + } - IIcon busSideTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[3]; + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; - // Set the texture to the side texture - helper.setTexture( busSideTexture ); + IIcon busSideTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[3]; - //Large Chamber back wall - helper.setBounds( 4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 12.5F ); - helper.renderInventoryBox( renderer ); + // Set the texture to the side texture + helper.setTexture(busSideTexture); - // Set the texture to the chamber - helper.setTexture( BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2] ); + // Large Chamber back wall + helper.setBounds(4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 12.5F); + helper.renderInventoryBox(renderer); - // Large chamber - helper.setBounds( 4.0F, 4.0F, 12.5F, 12.0F, 12.0F, 13.5F ); - helper.renderInventoryBox( renderer ); + // Set the texture to the chamber + helper.setTexture(BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2]); - // Small chamber - helper.setBounds( 5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 14.5F ); - helper.renderInventoryBox( renderer ); + // Large chamber + helper.setBounds(4.0F, 4.0F, 12.5F, 12.0F, 12.0F, 13.5F); + helper.renderInventoryBox(renderer); - // Set the texture back to the side texture - helper.setTexture( busSideTexture ); + // Small chamber + helper.setBounds(5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 14.5F); + helper.renderInventoryBox(renderer); - // Small chamber front wall - helper.setBounds( 5.0F, 5.0F, 14.5F, 11.0F, 11.0F, 15.0F ); - helper.renderInventoryBox( renderer ); + // Set the texture back to the side texture + helper.setTexture(busSideTexture); - // Setup the face texture - helper.setTexture( busSideTexture, busSideTexture, busSideTexture, BlockTextureManager.ESSENTIA_EXPORT_BUS.getTexture(), busSideTexture, - busSideTexture ); + // Small chamber front wall + helper.setBounds(5.0F, 5.0F, 14.5F, 11.0F, 11.0F, 15.0F); + helper.renderInventoryBox(renderer); - // Face - helper.setBounds( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - helper.renderInventoryBox( renderer ); + // Setup the face texture + helper.setTexture( + busSideTexture, + busSideTexture, + busSideTexture, + BlockTextureManager.ESSENTIA_EXPORT_BUS.getTexture(), + busSideTexture, + busSideTexture); - // Face overlay - helper.setInvColor( ThEPartBase.INVENTORY_OVERLAY_COLOR ); - ts.setBrightness( 0xF000F0 ); - IIcon faceOverlayTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[1]; - helper.renderInventoryFace( faceOverlayTexture, ForgeDirection.UP, renderer ); - helper.renderInventoryFace( faceOverlayTexture, ForgeDirection.DOWN, renderer ); - helper.renderInventoryFace( faceOverlayTexture, ForgeDirection.EAST, renderer ); - helper.renderInventoryFace( faceOverlayTexture, ForgeDirection.WEST, renderer ); + // Face + helper.setBounds(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + helper.renderInventoryBox(renderer); - // Lights - helper.setBounds( 6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F ); - this.renderInventoryBusLights( helper, renderer ); - } + // Face overlay + helper.setInvColor(ThEPartBase.INVENTORY_OVERLAY_COLOR); + ts.setBrightness(0xF000F0); + IIcon faceOverlayTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[1]; + helper.renderInventoryFace(faceOverlayTexture, ForgeDirection.UP, renderer); + helper.renderInventoryFace(faceOverlayTexture, ForgeDirection.DOWN, renderer); + helper.renderInventoryFace(faceOverlayTexture, ForgeDirection.EAST, renderer); + helper.renderInventoryFace(faceOverlayTexture, ForgeDirection.WEST, renderer); - @Override - @SideOnly(Side.CLIENT) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; + // Lights + helper.setBounds(6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F); + this.renderInventoryBusLights(helper, renderer); + } - IIcon busSideTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[3]; + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; - // Set the texture to the side texture - helper.setTexture( busSideTexture ); + IIcon busSideTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[3]; - //Large Chamber back wall - helper.setBounds( 4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 12.5F ); - helper.renderBlock( x, y, z, renderer ); + // Set the texture to the side texture + helper.setTexture(busSideTexture); - // Set to alpha pass - helper.renderForPass( 1 ); + // Large Chamber back wall + helper.setBounds(4.0F, 4.0F, 12.0F, 12.0F, 12.0F, 12.5F); + helper.renderBlock(x, y, z, renderer); - // Set the texture to the chamber - helper.setTexture( BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2] ); + // Set to alpha pass + helper.renderForPass(1); - // Large chamber - helper.setBounds( 4.0F, 4.0F, 12.5F, 12.0F, 12.0F, 13.5F ); - helper.renderBlock( x, y, z, renderer ); + // Set the texture to the chamber + helper.setTexture(BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[2]); - // Small chamber - helper.setBounds( 5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 14.5F ); - helper.renderBlock( x, y, z, renderer ); + // Large chamber + helper.setBounds(4.0F, 4.0F, 12.5F, 12.0F, 12.0F, 13.5F); + helper.renderBlock(x, y, z, renderer); - // Set back to opaque pass - helper.renderForPass( 0 ); + // Small chamber + helper.setBounds(5.0F, 5.0F, 13.5F, 11.0F, 11.0F, 14.5F); + helper.renderBlock(x, y, z, renderer); - // Set the texture back to the side texture - helper.setTexture( busSideTexture ); + // Set back to opaque pass + helper.renderForPass(0); - // Small chamber front wall - helper.setBounds( 5.0F, 5.0F, 14.5F, 11.0F, 11.0F, 15.0F ); - helper.renderBlock( x, y, z, renderer ); + // Set the texture back to the side texture + helper.setTexture(busSideTexture); - // Setup the face texture - helper.setTexture( busSideTexture, busSideTexture, busSideTexture, BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[0], busSideTexture, - busSideTexture ); + // Small chamber front wall + helper.setBounds(5.0F, 5.0F, 14.5F, 11.0F, 11.0F, 15.0F); + helper.renderBlock(x, y, z, renderer); - // Face - helper.setBounds( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); + // Setup the face texture + helper.setTexture( + busSideTexture, + busSideTexture, + busSideTexture, + BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[0], + busSideTexture, + busSideTexture); - // Face overlay - ts.setColorOpaque_I( this.getHost().getColor().blackVariant ); + // Face + helper.setBounds(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); - if( this.isActive() ) - { - Tessellator.instance.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - } + // Face overlay + ts.setColorOpaque_I(this.getHost().getColor().blackVariant); - IIcon faceOverlayTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[1]; - helper.renderFace( x, y, z, faceOverlayTexture, ForgeDirection.UP, renderer ); - helper.renderFace( x, y, z, faceOverlayTexture, ForgeDirection.DOWN, renderer ); - helper.renderFace( x, y, z, faceOverlayTexture, ForgeDirection.EAST, renderer ); - helper.renderFace( x, y, z, faceOverlayTexture, ForgeDirection.WEST, renderer ); + if (this.isActive()) { + Tessellator.instance.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + } - // Lights - helper.setBounds( 6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - } + IIcon faceOverlayTexture = BlockTextureManager.ESSENTIA_EXPORT_BUS.getTextures()[1]; + helper.renderFace(x, y, z, faceOverlayTexture, ForgeDirection.UP, renderer); + helper.renderFace(x, y, z, faceOverlayTexture, ForgeDirection.DOWN, renderer); + helper.renderFace(x, y, z, faceOverlayTexture, ForgeDirection.EAST, renderer); + helper.renderFace(x, y, z, faceOverlayTexture, ForgeDirection.WEST, renderer); - /** - * Called when a player has requested to change the void mode - */ - public void toggleVoidMode() - { - // Swap void modes - this.isVoidAllowed = !this.isVoidAllowed; - } - public void toggleCraftingMode() - { - isCraftingOnly = !isCraftingOnly; - } + // Lights + helper.setBounds(6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); + /** + * Called when a player has requested to change the void mode + */ + public void toggleVoidMode() { + // Swap void modes + this.isVoidAllowed = !this.isVoidAllowed; + } - boolean doSave = ( saveType == PartItemStack.World ); - if( !doSave ) - { - // Are there any filters? - for( Aspect aspect : this.filteredAspects ) - { - if( aspect != null ) - { - // Only save the void state if filters are set. - doSave = true; - break; - } - } - } + public void toggleCraftingMode() { + isCraftingOnly = !isCraftingOnly; + } - // Write void - if (doSave) - { - data.setBoolean( PartEssentiaExportBus.NBT_KEY_VOID, isVoidAllowed ); - this.craftingTracker.writeToNBT(data); - data.setBoolean( "isCraftingOnly", isCraftingOnly ); - } - } - @Override - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } - @Override - public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - if (getGridNode().isActive() && ItemEnum.CRAFTING_ASPECT.getItem() == items.getItem()) - { - Aspect a = ItemCraftingAspect.getAspect(items.getItemStack()); - if (a != null) - { - long toFill = items.getStackSize(); - long filledAmount = injectAspect(mode, a, toFill); - IAEItemStack c = items.copy(); - c.setStackSize(toFill - filledAmount); - return c; - } - } - return items; - } + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); - private long injectAspect(Actionable mode, Aspect a, long extractedAmount) { - long filledAmount; - if( this.isVoidAllowed && ( this.facingContainer instanceof TileJarFillableVoid) ) - { - // In void mode, we don't care if the jar can hold it or not. - filledAmount = extractedAmount; - } - else - { - // Simulate filling the container - filledAmount = EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer( this.facingContainer, (int)extractedAmount, - a, Actionable.SIMULATE ); - } + boolean doSave = (saveType == PartItemStack.World); + if (!doSave) { + // Are there any filters? + for (Aspect aspect : this.filteredAspects) { + if (aspect != null) { + // Only save the void state if filters are set. + doSave = true; + break; + } + } + } - // Was the container filled? - if( filledAmount <= 0 ) - { - // Unable to inject into container - return 0; - } + // Write void + if (doSave) { + data.setBoolean(PartEssentiaExportBus.NBT_KEY_VOID, isVoidAllowed); + this.craftingTracker.writeToNBT(data); + data.setBoolean("isCraftingOnly", isCraftingOnly); + } + } - if (mode == Actionable.MODULATE) { - // Fill the container - long actualFilledAmount = EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer(this.facingContainer, (int) filledAmount, - a, Actionable.MODULATE); + @Override + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } - // Is voiding not allowed? - if (!this.isVoidAllowed) { - filledAmount = actualFilledAmount; - } - // Take essentia from the network always (because redesigning GridEssentiaCache is too much pain) - getGridBlock().getEssentiaMonitor().extractEssentia( a, filledAmount, Actionable.MODULATE, this.asMachineSource, true ); - } - return filledAmount; - } + @Override + public IAEItemStack injectCraftedItems(final ICraftingLink link, final IAEItemStack items, final Actionable mode) { + if (getGridNode().isActive() && ItemEnum.CRAFTING_ASPECT.getItem() == items.getItem()) { + Aspect a = ItemCraftingAspect.getAspect(items.getItemStack()); + if (a != null) { + long toFill = items.getStackSize(); + long filledAmount = injectAspect(mode, a, toFill); + IAEItemStack c = items.copy(); + c.setStackSize(toFill - filledAmount); + return c; + } + } + return items; + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } + private long injectAspect(Actionable mode, Aspect a, long extractedAmount) { + long filledAmount; + if (this.isVoidAllowed && (this.facingContainer instanceof TileJarFillableVoid)) { + // In void mode, we don't care if the jar can hold it or not. + filledAmount = extractedAmount; + } else { + // Simulate filling the container + filledAmount = EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer( + this.facingContainer, (int) extractedAmount, a, Actionable.SIMULATE); + } + + // Was the container filled? + if (filledAmount <= 0) { + // Unable to inject into container + return 0; + } + + if (mode == Actionable.MODULATE) { + // Fill the container + long actualFilledAmount = EssentiaTileContainerHelper.INSTANCE.injectEssentiaIntoContainer( + this.facingContainer, (int) filledAmount, a, Actionable.MODULATE); + + // Is voiding not allowed? + if (!this.isVoidAllowed) { + filledAmount = actualFilledAmount; + } + // Take essentia from the network always (because redesigning GridEssentiaCache is too much pain) + getGridBlock() + .getEssentiaMonitor() + .extractEssentia(a, filledAmount, Actionable.MODULATE, this.asMachineSource, true); + } + return filledAmount; + } + + @Override + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaImportBus.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaImportBus.java index b62b9561..e1b79b8c 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaImportBus.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaImportBus.java @@ -23,237 +23,227 @@ import thaumicenergistics.common.integration.tc.EssentiaTileContainerHelper; * @author Nividica * */ -public class PartEssentiaImportBus - extends ThEPartEssentiaIOBus_Base -{ +public class PartEssentiaImportBus extends ThEPartEssentiaIOBus_Base { - public PartEssentiaImportBus() - { - super( AEPartsEnum.EssentiaImportBus, SecurityPermissions.INJECT ); - } + public PartEssentiaImportBus() { + super(AEPartsEnum.EssentiaImportBus, SecurityPermissions.INJECT); + } - @Override - public boolean aspectTransferAllowed( final Aspect aspect ) - { - boolean noFilters = true; + @Override + public boolean aspectTransferAllowed(final Aspect aspect) { + boolean noFilters = true; - if( aspect != null ) - { - for( Aspect filterAspect : this.filteredAspects ) - { - // Is the aspect not null? - if( filterAspect != null ) - { - // Does it match this aspect? - if( aspect == filterAspect ) - { - // Found a match, return true - return true; - } + if (aspect != null) { + for (Aspect filterAspect : this.filteredAspects) { + // Is the aspect not null? + if (filterAspect != null) { + // Does it match this aspect? + if (aspect == filterAspect) { + // Found a match, return true + return true; + } - // Mark that there are filtered aspects - noFilters = false; - } - } + // Mark that there are filtered aspects + noFilters = false; + } + } - // Return true if no filters set - return noFilters; - } + // Return true if no filters set + return noFilters; + } - return false; - } + return false; + } - @Override - public int cableConnectionRenderTo() - { - return 5; - } + @Override + public int cableConnectionRenderTo() { + return 5; + } - @Override - public boolean doWork( final int transferAmount ) - { - if( this.facingContainer == null ) - { - return false; - } + @Override + public boolean doWork(final int transferAmount) { + if (this.facingContainer == null) { + return false; + } - // Get the aspect in the container - Aspect aspect = EssentiaTileContainerHelper.INSTANCE.getAspectInContainer( this.facingContainer ); + // Get the aspect in the container + Aspect aspect = EssentiaTileContainerHelper.INSTANCE.getAspectInContainer(this.facingContainer); - // Ensure the aspect is allowed to be transfered - if( ( aspect == null ) || ( !this.aspectTransferAllowed( aspect ) ) ) - { - return false; - } + // Ensure the aspect is allowed to be transfered + if ((aspect == null) || (!this.aspectTransferAllowed(aspect))) { + return false; + } - // Simulate a drain from the container - long drainedAmount = EssentiaTileContainerHelper.INSTANCE.extractFromContainer( this.facingContainer, transferAmount, aspect, - Actionable.SIMULATE ); + // Simulate a drain from the container + long drainedAmount = EssentiaTileContainerHelper.INSTANCE.extractFromContainer( + this.facingContainer, transferAmount, aspect, Actionable.SIMULATE); - // Was any drained? - if( drainedAmount <= 0 ) - { - return false; - } + // Was any drained? + if (drainedAmount <= 0) { + return false; + } - // Get the monitor - IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); - if( essMonitor == null ) - { - return false; - } + // Get the monitor + IMEEssentiaMonitor essMonitor = this.getGridBlock().getEssentiaMonitor(); + if (essMonitor == null) { + return false; + } - // Simulate inject into the network - long rejectedAmount = essMonitor.injectEssentia( aspect, drainedAmount, Actionable.SIMULATE, this.asMachineSource, true ); + // Simulate inject into the network + long rejectedAmount = + essMonitor.injectEssentia(aspect, drainedAmount, Actionable.SIMULATE, this.asMachineSource, true); - // Was any rejected? - if( rejectedAmount > 0 ) - { - // Calculate how much was injected into the network - int amountInjected = (int)( drainedAmount - rejectedAmount ); + // Was any rejected? + if (rejectedAmount > 0) { + // Calculate how much was injected into the network + int amountInjected = (int) (drainedAmount - rejectedAmount); - // None could be injected - if( amountInjected <= 0 ) - { - return false; - } + // None could be injected + if (amountInjected <= 0) { + return false; + } - // Some was unable to be injected, adjust the drain amount - drainedAmount = amountInjected; - } + // Some was unable to be injected, adjust the drain amount + drainedAmount = amountInjected; + } - // Inject - essMonitor.injectEssentia( aspect, drainedAmount, Actionable.MODULATE, this.asMachineSource, true ); + // Inject + essMonitor.injectEssentia(aspect, drainedAmount, Actionable.MODULATE, this.asMachineSource, true); - // Drain - EssentiaTileContainerHelper.INSTANCE.extractFromContainer( this.facingContainer, transferAmount, aspect, Actionable.MODULATE ); + // Drain + EssentiaTileContainerHelper.INSTANCE.extractFromContainer( + this.facingContainer, transferAmount, aspect, Actionable.MODULATE); - return true; - } + return true; + } - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - // Face + Large chamber - helper.addBox( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 16.0F ); + @Override + public void getBoxes(final IPartCollisionHelper helper) { + // Face + Large chamber + helper.addBox(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 16.0F); - // Small chamber - helper.addBox( 5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 14.0F ); + // Small chamber + helper.addBox(5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 14.0F); - // Lights - helper.addBox( 6.0D, 6.0D, 11.0D, 10.0D, 10.0D, 12.0D ); - } + // Lights + helper.addBox(6.0D, 6.0D, 11.0D, 10.0D, 10.0D, 12.0D); + } - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2]; - } + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2]; + } - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Get the tessellator - Tessellator ts = Tessellator.instance; + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + // Get the tessellator + Tessellator ts = Tessellator.instance; - // Get the side texture - IIcon busSideTexture = BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[3]; + // Get the side texture + IIcon busSideTexture = BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[3]; - helper.setTexture( busSideTexture, busSideTexture, busSideTexture, BlockTextureManager.ESSENTIA_IMPORT_BUS.getTexture(), busSideTexture, - busSideTexture ); + helper.setTexture( + busSideTexture, + busSideTexture, + busSideTexture, + BlockTextureManager.ESSENTIA_IMPORT_BUS.getTexture(), + busSideTexture, + busSideTexture); - // Face - helper.setBounds( 4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F ); - helper.renderInventoryBox( renderer ); + // Face + helper.setBounds(4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F); + helper.renderInventoryBox(renderer); - // Set the texture to the chamber - helper.setTexture( BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2] ); + // Set the texture to the chamber + helper.setTexture(BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2]); - // Large chamber - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderInventoryBox( renderer ); + // Large chamber + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderInventoryBox(renderer); - // Small chamber - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - helper.renderInventoryBox( renderer ); + // Small chamber + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + helper.renderInventoryBox(renderer); - // Set the texture back to the side texture - helper.setTexture( busSideTexture ); + // Set the texture back to the side texture + helper.setTexture(busSideTexture); - // Small chamber back wall - helper.setBounds( 5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F ); - helper.renderInventoryBox( renderer ); + // Small chamber back wall + helper.setBounds(5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F); + helper.renderInventoryBox(renderer); - // Face overlay - helper.setBounds( 4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F ); - helper.setInvColor( ThEPartBase.INVENTORY_OVERLAY_COLOR ); - ts.setBrightness( 15728880 ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer ); + // Face overlay + helper.setBounds(4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F); + helper.setInvColor(ThEPartBase.INVENTORY_OVERLAY_COLOR); + ts.setBrightness(15728880); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer); - // Lights - helper.setBounds( 6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F ); - this.renderInventoryBusLights( helper, renderer ); - } + // Lights + helper.setBounds(6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F); + this.renderInventoryBusLights(helper, renderer); + } - @SideOnly(Side.CLIENT) - @Override - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; + @SideOnly(Side.CLIENT) + @Override + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; - IIcon busSideTexture = BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[3]; - helper.setTexture( busSideTexture, busSideTexture, busSideTexture, BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[0], busSideTexture, - busSideTexture ); + IIcon busSideTexture = BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[3]; + helper.setTexture( + busSideTexture, + busSideTexture, + busSideTexture, + BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[0], + busSideTexture, + busSideTexture); - // Face - helper.setBounds( 4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); + // Face + helper.setBounds(4.0F, 4.0F, 15.0F, 12.0F, 12.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); - if( this.getHost().getColor() != AEColor.Transparent ) - { - ts.setColorOpaque_I( this.getHost().getColor().blackVariant ); - } - else - { - ts.setColorOpaque_I( ThEPartBase.INVENTORY_OVERLAY_COLOR ); - } + if (this.getHost().getColor() != AEColor.Transparent) { + ts.setColorOpaque_I(this.getHost().getColor().blackVariant); + } else { + ts.setColorOpaque_I(ThEPartBase.INVENTORY_OVERLAY_COLOR); + } - if( this.isActive() ) - { - Tessellator.instance.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - } + if (this.isActive()) { + Tessellator.instance.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + } - // Face overlay - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer ); + // Face overlay + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer); - // Set the pass to alpha - helper.renderForPass( 1 ); + // Set the pass to alpha + helper.renderForPass(1); - // Set the texture to the chamber - helper.setTexture( BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2] ); + // Set the texture to the chamber + helper.setTexture(BlockTextureManager.ESSENTIA_IMPORT_BUS.getTextures()[2]); - // Large chamber - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderBlock( x, y, z, renderer ); + // Large chamber + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderBlock(x, y, z, renderer); - // Small chamber - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - helper.renderBlock( x, y, z, renderer ); + // Small chamber + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + helper.renderBlock(x, y, z, renderer); - // Set the pass back to opaque - helper.renderForPass( 0 ); + // Set the pass back to opaque + helper.renderForPass(0); - // Set the texture back to the side texture - helper.setTexture( busSideTexture ); + // Set the texture back to the side texture + helper.setTexture(busSideTexture); - // Small chamber back wall - helper.setBounds( 5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Lights - helper.setBounds( 6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - } + // Small chamber back wall + helper.setBounds(5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F); + helper.renderBlock(x, y, z, renderer); + // Lights + helper.setBounds(6.0F, 6.0F, 11.0F, 10.0F, 10.0F, 12.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaLevelEmitter.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaLevelEmitter.java index 0f56d736..6def251e 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaLevelEmitter.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaLevelEmitter.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.parts; -import java.io.IOException; -import java.util.Random; -import javax.annotation.Nullable; import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; import appeng.api.parts.IPartCollisionHelper; @@ -12,6 +9,9 @@ import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.Random; +import javax.annotation.Nullable; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -39,664 +39,634 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class PartEssentiaLevelEmitter - extends ThEPartBase - implements IAspectSlotPart, IEssentiaWatcherHost -{ - /** - * How much AE power is required to keep the part active. - */ - private static final double IDLE_POWER_DRAIN = 0.3D; - - /** - * NBT keys. - */ - private static final String NBT_KEY_ASPECT_FILTER = "aspect", NBT_KEY_REDSTONE_MODE = "mode", NBT_KEY_WANTED_AMOUNT = "wantedAmount", - NBT_KEY_IS_EMITTING = "emitting"; - - /** - * Default redstone mode the part starts with. - */ - private static final RedstoneMode DEFAULT_REDSTONE_MODE = RedstoneMode.HIGH_SIGNAL; - - /** - * Dimensions and offsets - */ - private static final float Base_XY_Min = 7.0F, Base_XY_Max = 9.0F, Base_Z_Min = 11.0F, Base_Z_Max = 13.0F, - // Head Z's - Head_Z_Min = PartEssentiaLevelEmitter.Base_Z_Max, Head_Z_Max = PartEssentiaLevelEmitter.Head_Z_Min + 2.0F, - // Face Z's - Face_Z_Min = PartEssentiaLevelEmitter.Head_Z_Min - 1.0F, FaceZMax = PartEssentiaLevelEmitter.Head_Z_Max + 1.0F, - // Face offsets - FaceOffset_XH_YV = 0.001F, FaceOffset_XV_YH = 1.0F, - // Horizontal faces XY - Face_XH_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XH_YV, - Face_YH_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XV_YH, - Face_XH_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XH_YV, - Face_YH_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XV_YH, - // Vertical faces XY - Face_XV_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XV_YH, - Face_YV_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XH_YV, - Face_XV_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XV_YH, - Face_YV_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XH_YV; - - /** - * Aspect we are watching. - */ - private Aspect trackedAspect; - - /** - * Mode the emitter is in - */ - private RedstoneMode redstoneMode = PartEssentiaLevelEmitter.DEFAULT_REDSTONE_MODE; - - /** - * Threshold value - */ - private long thresholdLevel = 0; - - /** - * Current value - */ - private long currentLevel; - - /** - * True if the emitter is emitting a redstone signal. - */ - private boolean isEmitting = false; - - /** - * Watches the for changes in the essentia grid. - */ - private IEssentiaWatcher essentiaWatcher; - - /** - * Creates the part - */ - public PartEssentiaLevelEmitter() - { - super( AEPartsEnum.EssentiaLevelEmitter, SecurityPermissions.BUILD ); - } - - /** - * Updates the watcher to the tracked essentia. - */ - private void configureWatcher() - { - boolean didSet = false; - - //this.debugTrackingStage = 0; - //this.debugMonID = -1; - - if( this.essentiaWatcher != null ) - { - //this.debugTrackingStage = 1; - - // Clear any existing watched value - this.essentiaWatcher.clear(); - - // Is there an essentia being tracked? - if( this.trackedAspect != null ) - { - //this.debugTrackingStage = 2; - // Configure the watcher - this.essentiaWatcher.add( this.trackedAspect ); - - // Get the essentia monitor - IMEEssentiaMonitor essMon = this.getGridBlock().getEssentiaMonitor(); - - // Ensure there is a grid. - if( essMon != null ) - { - // Update the amount. - this.setCurrentLevel( essMon.getEssentiaAmount( this.trackedAspect ) ); - didSet = true; - //this.debugTrackingStage = 3; - //this.debugMonID = essMon.hashCode(); - - } - } - } - - // Was the current amount set? - if( !didSet ) - { - // Reset - this.setCurrentLevel( 0 ); - } - } - - /** - * Sets the current amount in the network, of the aspect - * we are watching/filtering. - * - * @param amount - */ - private void setCurrentLevel( final long amount ) - { - // Has the amount changed? - if( amount != this.currentLevel ) - { - // Set the current amount - this.currentLevel = amount; - - // Check if we should be emitting - this.updateEmittingState(); - } - } - - /** - * Checks if the emitter should be emitting a redstone signal. - * - * @return - */ - private void updateEmittingState() - { - boolean emitting = false; - - // Are we active? - if( !this.isActive() ) - { - // In the event that we have lost activity, do not change state - return; - } - - switch ( this.redstoneMode ) - { - case HIGH_SIGNAL: - // Is the current amount more than or equal to the wanted amount? - emitting = ( this.currentLevel >= this.thresholdLevel ); - break; - - case LOW_SIGNAL: - // Is the current amount less than the wanted amount? - emitting = ( this.currentLevel < this.thresholdLevel ); - break; - - case IGNORE: - case SIGNAL_PULSE: - break; - - } - - // Did the emitting state change? - if( emitting != this.isEmitting ) - { - // Set the new state - this.isEmitting = emitting; - - // Mark that we need to be saved and updated - this.markForSave(); - this.markForUpdate(); - - // Get the host tile entity & side - TileEntity hte = this.getHostTile(); - ForgeDirection side = this.getSide(); - - // Update the neighbors - Platform.notifyBlocksOfNeighbors( hte.getWorldObj(), hte.xCoord, hte.yCoord, hte.zCoord ); - Platform.notifyBlocksOfNeighbors( hte.getWorldObj(), hte.xCoord + side.offsetX, hte.yCoord + side.offsetX, hte.zCoord + side.offsetX ); - } - } - - /** - * How far the network cable should extend to meet us. - */ - @Override - public int cableConnectionRenderTo() - { - return 8; - } - - @Override - public boolean canConnectRedstone() - { - return true; - } - - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - helper.addBox( PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Base_Z_Min, - PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Head_Z_Max ); - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1]; - } - - /** - * Gets the emitter gui - */ - @Override - public Object getClientGuiElement( final EntityPlayer player ) - { - return new GuiEssentiaLevelEmitter( this, player ); - } - - @Override - public double getIdlePowerUsage() - { - return PartEssentiaLevelEmitter.IDLE_POWER_DRAIN; - } - - /** - * Light level based on if emitter is emitting. - */ - @Override - public int getLightLevel() - { - return( this.isEmitting ? 7 : 0 ); - } - - /** - * Returns the redstone mode. - * - * @return - */ - public RedstoneMode getRedstoneMode() - { - return this.redstoneMode; - } - - /** - * Gets the emitter container - */ - @Override - public Object getServerGuiElement( final EntityPlayer player ) - { - return new ContainerPartEssentiaLevelEmitter( this, player ); - } - - /** - * Returns the threshold level. - * - * @return - */ - public long getThresholdLevel() - { - return this.thresholdLevel; - } - - /** - * Returns the aspect being tracked. - * - * @return - */ - @Nullable - public Aspect getTrackedAspect() - { - return this.trackedAspect; - } - - /** - * Called to see if this is emitting strong redstone power - */ - @Override - public int isProvidingStrongPower() - { - return this.isEmitting ? 15 : 0; - } - - /** - * Called to see if this is emitting weak redstone power - */ - @Override - public int isProvidingWeakPower() - { - return this.isProvidingStrongPower(); - } - - /** - * Called when a player has adjusted the amount wanted via - * gui buttons. - * - * @param adjustmentAmount - * @param player - */ - public void onAdjustThresholdLevel( final int adjustmentAmount, final EntityPlayer player ) - { - this.onSetThresholdLevel( this.thresholdLevel + adjustmentAmount, player ); - } - - /** - * Called when a player has pressed the redstone toggle button in the gui. - * - * @param player - */ - public void onClientToggleRedstoneMode( final EntityPlayer player ) - { - switch ( this.redstoneMode ) - { - case HIGH_SIGNAL: - this.redstoneMode = RedstoneMode.LOW_SIGNAL; - break; - - case LOW_SIGNAL: - this.redstoneMode = RedstoneMode.HIGH_SIGNAL; - break; - - case IGNORE: - case SIGNAL_PULSE: - break; - } - - // Check if we should be emitting - this.updateEmittingState(); - - } - - /** - * Called when essentia levels change. - */ - @Override - public void onEssentiaChange( final Aspect aspect, final long storedAmount, final long changeAmount ) - { - this.setCurrentLevel( storedAmount ); - } - - /** - * Called when a player has changed the wanted amount - * - * @param threshold - * @param player - */ - public void onSetThresholdLevel( final long threshold, final EntityPlayer player ) - { - // Set the wanted amount - this.thresholdLevel = threshold; - - // Bounds check it - if( this.thresholdLevel < 0L ) - { - this.thresholdLevel = 0L; - } - else if( this.thresholdLevel > 9999999999L ) - { - this.thresholdLevel = 9999999999L; - } - - // Mark that we need saving - this.markForSave(); - - // Check if we should be emitting - this.updateEmittingState(); - } - - /** - * Spawns redstone particles when emitting - */ - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - // Is the emitter, emitting? - if( this.isEmitting ) - { - // Get the side - ForgeDirection side = this.getSide(); - - // Calculate a new random coordinate - double particleX = ( side.offsetX * 0.45F ) + ( ( r.nextFloat() - 0.5F ) * 0.2D ); - double particleY = ( side.offsetY * 0.45F ) + ( ( r.nextFloat() - 0.5F ) * 0.2D ); - double particleZ = ( side.offsetZ * 0.45F ) + ( ( r.nextFloat() - 0.5F ) * 0.2D ); - - world.spawnParticle( "reddust", 0.5D + x + particleX, 0.5D + y + particleY, 0.5D + z + particleZ, 0.0D, 0.0D, 0.0D ); - } - } - - /** - * Reads the state of the emitter from an NBT tag - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read the filter - if( data.hasKey( PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER ) ) - { - this.trackedAspect = Aspect.aspects.get( data.getString( PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER ) ); - } - - // Read the redstone mode - if( data.hasKey( PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE ) ) - { - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[data.getInteger( PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE )]; - } - - // Read the wanted amount - if( data.hasKey( PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT ) ) - { - this.thresholdLevel = data.getLong( PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT ); - } - - // Read if emitting - if( data.hasKey( PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING ) ) - { - this.isEmitting = data.getBoolean( PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING ); - } - } - - /** - * Called client side when a sync packet has been received. - * - * @throws IOException - */ - @SideOnly(Side.CLIENT) - @Override - public boolean readFromStream( final ByteBuf stream ) throws IOException - { - boolean redraw = false; - - // Cache the old emitting - boolean oldEmit = this.isEmitting; - - // Call super - redraw |= super.readFromStream( stream ); - - // Read the activity state - this.isEmitting = stream.readBoolean(); - - // Redraw if changed - redraw |= ( this.isEmitting != oldEmit ); - - return redraw; - } - - /** - * Renders the emitter in the inventory - */ - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Set the base texture - helper.setTexture( BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[0] ); - helper.setBounds( 7.0F, 1.0F, 14.0F, 9.0F, 7.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - // Set the active texture - helper.setTexture( BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1] ); - helper.setBounds( 7.0F, 7.0F, 14.0F, 9.0F, 9.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - } - - /** - * Renders the emitter in the world - */ - @SideOnly(Side.CLIENT) - @Override - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Set the base texture - helper.setTexture( BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[0] ); - - // Set shaft bounds - helper.setBounds( PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Base_Z_Min, - PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Base_Z_Max ); - - // Render shaft - helper.renderBlock( x, y, z, renderer ); - - // Is the part emitting? - if( this.isEmitting ) - { - // Set the active texture - IIcon activeTex = BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1]; - helper.setTexture( activeTex ); - - // Set the brightness - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - Tessellator.instance.setBrightness( 0xD000D0 ); - - // Render horizontal faces - helper.setBounds( PartEssentiaLevelEmitter.Face_XH_Min, PartEssentiaLevelEmitter.Face_YH_Min, PartEssentiaLevelEmitter.Face_Z_Min, - PartEssentiaLevelEmitter.Face_XH_Max, PartEssentiaLevelEmitter.Face_YH_Max, PartEssentiaLevelEmitter.FaceZMax ); - helper.renderFace( x, y, z, activeTex, ForgeDirection.EAST, renderer ); - helper.renderFace( x, y, z, activeTex, ForgeDirection.WEST, renderer ); - - // Render vertical faces - helper.setBounds( PartEssentiaLevelEmitter.Face_XV_Min, PartEssentiaLevelEmitter.Face_YV_Min, PartEssentiaLevelEmitter.Face_Z_Min, - PartEssentiaLevelEmitter.Face_XV_Max, PartEssentiaLevelEmitter.Face_YV_Max, PartEssentiaLevelEmitter.FaceZMax ); - helper.renderFace( x, y, z, activeTex, ForgeDirection.UP, renderer ); - helper.renderFace( x, y, z, activeTex, ForgeDirection.DOWN, renderer ); - - } - else - { - // Set the inactive texture - helper.setTexture( BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[2] ); - } - - // Set head bounds - helper.setBounds( PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Base_XY_Min, PartEssentiaLevelEmitter.Head_Z_Min, - PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Base_XY_Max, PartEssentiaLevelEmitter.Head_Z_Max ); - - // Render head - helper.renderBlock( x, y, z, renderer ); - } - - /** - * Set's the aspect we are filtering - */ - @Override - public void setAspect( final int index, final Aspect aspect, final EntityPlayer player ) - { - if( this.trackedAspect != aspect ) - { - // Set the filtered aspect - this.trackedAspect = aspect; - - // Are we client side? - if( EffectiveSide.isClientSide() ) - { - return; - } - - // Mark that we need to be saved and updated - this.markForSave(); - - // Update the watcher - this.configureWatcher(); - } - } - - /** - * Called from the container to set the filter based on an itemstack. - * - * @param player - * @param itemStack - * @return - */ - public boolean setFilteredAspectFromItemstack( final EntityPlayer player, final ItemStack itemStack ) - { - // Get the aspect - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( itemStack ); - - // Ensure we got an aspect - if( itemAspect == null ) - { - return false; - } - - // Set the aspect - this.setAspect( 0, itemAspect, player ); - - return true; - } - - @Override - public void updateWatcher( final IEssentiaWatcher newWatcher ) - { - // Set the watcher - this.essentiaWatcher = newWatcher; - - // And configure it - this.configureWatcher(); - } - - /** - * Writes the state of the emitter to the tag - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only write NBT data if saving, or wrenched. - if( ( saveType != PartItemStack.World ) && ( saveType != PartItemStack.Wrench ) ) - { - return; - } - - // Is there a filter? - if( this.trackedAspect != null ) - { - // Write the name of the aspect - data.setString( PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER, this.trackedAspect.getTag() ); - } - - // Only save the rest on world save, or if there is a tracked aspect - if( ( saveType == PartItemStack.World ) || ( this.trackedAspect != null ) ) - { - // Write the redstone mode ordinal - if( this.redstoneMode != PartEssentiaLevelEmitter.DEFAULT_REDSTONE_MODE ) - { - data.setInteger( PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE, this.redstoneMode.ordinal() ); - } - - // Write the threshold amount - if( this.thresholdLevel > 0 ) - { - data.setLong( PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT, this.thresholdLevel ); - } - } - - // Write if emitting - if( ( saveType == PartItemStack.World ) && this.isEmitting ) - { - data.setBoolean( PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING, true ); - } - - } - - /** - * Called when a packet to sync client and server is being created. - * - * @throws IOException - */ - @Override - public void writeToStream( final ByteBuf stream ) throws IOException - { - // Call super - super.writeToStream( stream ); - - // Write the activity state - stream.writeBoolean( this.isEmitting ); - } +public class PartEssentiaLevelEmitter extends ThEPartBase implements IAspectSlotPart, IEssentiaWatcherHost { + /** + * How much AE power is required to keep the part active. + */ + private static final double IDLE_POWER_DRAIN = 0.3D; + + /** + * NBT keys. + */ + private static final String NBT_KEY_ASPECT_FILTER = "aspect", + NBT_KEY_REDSTONE_MODE = "mode", + NBT_KEY_WANTED_AMOUNT = "wantedAmount", + NBT_KEY_IS_EMITTING = "emitting"; + + /** + * Default redstone mode the part starts with. + */ + private static final RedstoneMode DEFAULT_REDSTONE_MODE = RedstoneMode.HIGH_SIGNAL; + + /** + * Dimensions and offsets + */ + private static final float Base_XY_Min = 7.0F, + Base_XY_Max = 9.0F, + Base_Z_Min = 11.0F, + Base_Z_Max = 13.0F, + // Head Z's + Head_Z_Min = PartEssentiaLevelEmitter.Base_Z_Max, + Head_Z_Max = PartEssentiaLevelEmitter.Head_Z_Min + 2.0F, + // Face Z's + Face_Z_Min = PartEssentiaLevelEmitter.Head_Z_Min - 1.0F, + FaceZMax = PartEssentiaLevelEmitter.Head_Z_Max + 1.0F, + // Face offsets + FaceOffset_XH_YV = 0.001F, + FaceOffset_XV_YH = 1.0F, + // Horizontal faces XY + Face_XH_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XH_YV, + Face_YH_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XV_YH, + Face_XH_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XH_YV, + Face_YH_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XV_YH, + // Vertical faces XY + Face_XV_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XV_YH, + Face_YV_Min = PartEssentiaLevelEmitter.Base_XY_Min - PartEssentiaLevelEmitter.FaceOffset_XH_YV, + Face_XV_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XV_YH, + Face_YV_Max = PartEssentiaLevelEmitter.Base_XY_Max + PartEssentiaLevelEmitter.FaceOffset_XH_YV; + + /** + * Aspect we are watching. + */ + private Aspect trackedAspect; + + /** + * Mode the emitter is in + */ + private RedstoneMode redstoneMode = PartEssentiaLevelEmitter.DEFAULT_REDSTONE_MODE; + + /** + * Threshold value + */ + private long thresholdLevel = 0; + + /** + * Current value + */ + private long currentLevel; + + /** + * True if the emitter is emitting a redstone signal. + */ + private boolean isEmitting = false; + + /** + * Watches the for changes in the essentia grid. + */ + private IEssentiaWatcher essentiaWatcher; + + /** + * Creates the part + */ + public PartEssentiaLevelEmitter() { + super(AEPartsEnum.EssentiaLevelEmitter, SecurityPermissions.BUILD); + } + + /** + * Updates the watcher to the tracked essentia. + */ + private void configureWatcher() { + boolean didSet = false; + + // this.debugTrackingStage = 0; + // this.debugMonID = -1; + + if (this.essentiaWatcher != null) { + // this.debugTrackingStage = 1; + + // Clear any existing watched value + this.essentiaWatcher.clear(); + + // Is there an essentia being tracked? + if (this.trackedAspect != null) { + // this.debugTrackingStage = 2; + // Configure the watcher + this.essentiaWatcher.add(this.trackedAspect); + + // Get the essentia monitor + IMEEssentiaMonitor essMon = this.getGridBlock().getEssentiaMonitor(); + + // Ensure there is a grid. + if (essMon != null) { + // Update the amount. + this.setCurrentLevel(essMon.getEssentiaAmount(this.trackedAspect)); + didSet = true; + // this.debugTrackingStage = 3; + // this.debugMonID = essMon.hashCode(); + + } + } + } + + // Was the current amount set? + if (!didSet) { + // Reset + this.setCurrentLevel(0); + } + } + + /** + * Sets the current amount in the network, of the aspect + * we are watching/filtering. + * + * @param amount + */ + private void setCurrentLevel(final long amount) { + // Has the amount changed? + if (amount != this.currentLevel) { + // Set the current amount + this.currentLevel = amount; + + // Check if we should be emitting + this.updateEmittingState(); + } + } + + /** + * Checks if the emitter should be emitting a redstone signal. + * + * @return + */ + private void updateEmittingState() { + boolean emitting = false; + + // Are we active? + if (!this.isActive()) { + // In the event that we have lost activity, do not change state + return; + } + + switch (this.redstoneMode) { + case HIGH_SIGNAL: + // Is the current amount more than or equal to the wanted amount? + emitting = (this.currentLevel >= this.thresholdLevel); + break; + + case LOW_SIGNAL: + // Is the current amount less than the wanted amount? + emitting = (this.currentLevel < this.thresholdLevel); + break; + + case IGNORE: + case SIGNAL_PULSE: + break; + } + + // Did the emitting state change? + if (emitting != this.isEmitting) { + // Set the new state + this.isEmitting = emitting; + + // Mark that we need to be saved and updated + this.markForSave(); + this.markForUpdate(); + + // Get the host tile entity & side + TileEntity hte = this.getHostTile(); + ForgeDirection side = this.getSide(); + + // Update the neighbors + Platform.notifyBlocksOfNeighbors(hte.getWorldObj(), hte.xCoord, hte.yCoord, hte.zCoord); + Platform.notifyBlocksOfNeighbors( + hte.getWorldObj(), hte.xCoord + side.offsetX, hte.yCoord + side.offsetX, hte.zCoord + side.offsetX); + } + } + + /** + * How far the network cable should extend to meet us. + */ + @Override + public int cableConnectionRenderTo() { + return 8; + } + + @Override + public boolean canConnectRedstone() { + return true; + } + + @Override + public void getBoxes(final IPartCollisionHelper helper) { + helper.addBox( + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Base_Z_Min, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Head_Z_Max); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1]; + } + + /** + * Gets the emitter gui + */ + @Override + public Object getClientGuiElement(final EntityPlayer player) { + return new GuiEssentiaLevelEmitter(this, player); + } + + @Override + public double getIdlePowerUsage() { + return PartEssentiaLevelEmitter.IDLE_POWER_DRAIN; + } + + /** + * Light level based on if emitter is emitting. + */ + @Override + public int getLightLevel() { + return (this.isEmitting ? 7 : 0); + } + + /** + * Returns the redstone mode. + * + * @return + */ + public RedstoneMode getRedstoneMode() { + return this.redstoneMode; + } + + /** + * Gets the emitter container + */ + @Override + public Object getServerGuiElement(final EntityPlayer player) { + return new ContainerPartEssentiaLevelEmitter(this, player); + } + + /** + * Returns the threshold level. + * + * @return + */ + public long getThresholdLevel() { + return this.thresholdLevel; + } + + /** + * Returns the aspect being tracked. + * + * @return + */ + @Nullable + public Aspect getTrackedAspect() { + return this.trackedAspect; + } + + /** + * Called to see if this is emitting strong redstone power + */ + @Override + public int isProvidingStrongPower() { + return this.isEmitting ? 15 : 0; + } + + /** + * Called to see if this is emitting weak redstone power + */ + @Override + public int isProvidingWeakPower() { + return this.isProvidingStrongPower(); + } + + /** + * Called when a player has adjusted the amount wanted via + * gui buttons. + * + * @param adjustmentAmount + * @param player + */ + public void onAdjustThresholdLevel(final int adjustmentAmount, final EntityPlayer player) { + this.onSetThresholdLevel(this.thresholdLevel + adjustmentAmount, player); + } + + /** + * Called when a player has pressed the redstone toggle button in the gui. + * + * @param player + */ + public void onClientToggleRedstoneMode(final EntityPlayer player) { + switch (this.redstoneMode) { + case HIGH_SIGNAL: + this.redstoneMode = RedstoneMode.LOW_SIGNAL; + break; + + case LOW_SIGNAL: + this.redstoneMode = RedstoneMode.HIGH_SIGNAL; + break; + + case IGNORE: + case SIGNAL_PULSE: + break; + } + + // Check if we should be emitting + this.updateEmittingState(); + } + + /** + * Called when essentia levels change. + */ + @Override + public void onEssentiaChange(final Aspect aspect, final long storedAmount, final long changeAmount) { + this.setCurrentLevel(storedAmount); + } + + /** + * Called when a player has changed the wanted amount + * + * @param threshold + * @param player + */ + public void onSetThresholdLevel(final long threshold, final EntityPlayer player) { + // Set the wanted amount + this.thresholdLevel = threshold; + + // Bounds check it + if (this.thresholdLevel < 0L) { + this.thresholdLevel = 0L; + } else if (this.thresholdLevel > 9999999999L) { + this.thresholdLevel = 9999999999L; + } + + // Mark that we need saving + this.markForSave(); + + // Check if we should be emitting + this.updateEmittingState(); + } + + /** + * Spawns redstone particles when emitting + */ + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) { + // Is the emitter, emitting? + if (this.isEmitting) { + // Get the side + ForgeDirection side = this.getSide(); + + // Calculate a new random coordinate + double particleX = (side.offsetX * 0.45F) + ((r.nextFloat() - 0.5F) * 0.2D); + double particleY = (side.offsetY * 0.45F) + ((r.nextFloat() - 0.5F) * 0.2D); + double particleZ = (side.offsetZ * 0.45F) + ((r.nextFloat() - 0.5F) * 0.2D); + + world.spawnParticle( + "reddust", 0.5D + x + particleX, 0.5D + y + particleY, 0.5D + z + particleZ, 0.0D, 0.0D, 0.0D); + } + } + + /** + * Reads the state of the emitter from an NBT tag + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Read the filter + if (data.hasKey(PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER)) { + this.trackedAspect = Aspect.aspects.get(data.getString(PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER)); + } + + // Read the redstone mode + if (data.hasKey(PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE)) { + this.redstoneMode = + EnumCache.AE_REDSTONE_MODES[data.getInteger(PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE)]; + } + + // Read the wanted amount + if (data.hasKey(PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT)) { + this.thresholdLevel = data.getLong(PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT); + } + + // Read if emitting + if (data.hasKey(PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING)) { + this.isEmitting = data.getBoolean(PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING); + } + } + + /** + * Called client side when a sync packet has been received. + * + * @throws IOException + */ + @SideOnly(Side.CLIENT) + @Override + public boolean readFromStream(final ByteBuf stream) throws IOException { + boolean redraw = false; + + // Cache the old emitting + boolean oldEmit = this.isEmitting; + + // Call super + redraw |= super.readFromStream(stream); + + // Read the activity state + this.isEmitting = stream.readBoolean(); + + // Redraw if changed + redraw |= (this.isEmitting != oldEmit); + + return redraw; + } + + /** + * Renders the emitter in the inventory + */ + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + // Set the base texture + helper.setTexture(BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[0]); + helper.setBounds(7.0F, 1.0F, 14.0F, 9.0F, 7.0F, 16.0F); + helper.renderInventoryBox(renderer); + + // Set the active texture + helper.setTexture(BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1]); + helper.setBounds(7.0F, 7.0F, 14.0F, 9.0F, 9.0F, 16.0F); + helper.renderInventoryBox(renderer); + } + + /** + * Renders the emitter in the world + */ + @SideOnly(Side.CLIENT) + @Override + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + // Set the base texture + helper.setTexture(BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[0]); + + // Set shaft bounds + helper.setBounds( + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Base_Z_Min, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Base_Z_Max); + + // Render shaft + helper.renderBlock(x, y, z, renderer); + + // Is the part emitting? + if (this.isEmitting) { + // Set the active texture + IIcon activeTex = BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[1]; + helper.setTexture(activeTex); + + // Set the brightness + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + Tessellator.instance.setBrightness(0xD000D0); + + // Render horizontal faces + helper.setBounds( + PartEssentiaLevelEmitter.Face_XH_Min, + PartEssentiaLevelEmitter.Face_YH_Min, + PartEssentiaLevelEmitter.Face_Z_Min, + PartEssentiaLevelEmitter.Face_XH_Max, + PartEssentiaLevelEmitter.Face_YH_Max, + PartEssentiaLevelEmitter.FaceZMax); + helper.renderFace(x, y, z, activeTex, ForgeDirection.EAST, renderer); + helper.renderFace(x, y, z, activeTex, ForgeDirection.WEST, renderer); + + // Render vertical faces + helper.setBounds( + PartEssentiaLevelEmitter.Face_XV_Min, + PartEssentiaLevelEmitter.Face_YV_Min, + PartEssentiaLevelEmitter.Face_Z_Min, + PartEssentiaLevelEmitter.Face_XV_Max, + PartEssentiaLevelEmitter.Face_YV_Max, + PartEssentiaLevelEmitter.FaceZMax); + helper.renderFace(x, y, z, activeTex, ForgeDirection.UP, renderer); + helper.renderFace(x, y, z, activeTex, ForgeDirection.DOWN, renderer); + + } else { + // Set the inactive texture + helper.setTexture(BlockTextureManager.ESSENTIA_LEVEL_EMITTER.getTextures()[2]); + } + + // Set head bounds + helper.setBounds( + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Base_XY_Min, + PartEssentiaLevelEmitter.Head_Z_Min, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Base_XY_Max, + PartEssentiaLevelEmitter.Head_Z_Max); + + // Render head + helper.renderBlock(x, y, z, renderer); + } + + /** + * Set's the aspect we are filtering + */ + @Override + public void setAspect(final int index, final Aspect aspect, final EntityPlayer player) { + if (this.trackedAspect != aspect) { + // Set the filtered aspect + this.trackedAspect = aspect; + + // Are we client side? + if (EffectiveSide.isClientSide()) { + return; + } + + // Mark that we need to be saved and updated + this.markForSave(); + + // Update the watcher + this.configureWatcher(); + } + } + + /** + * Called from the container to set the filter based on an itemstack. + * + * @param player + * @param itemStack + * @return + */ + public boolean setFilteredAspectFromItemstack(final EntityPlayer player, final ItemStack itemStack) { + // Get the aspect + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(itemStack); + + // Ensure we got an aspect + if (itemAspect == null) { + return false; + } + + // Set the aspect + this.setAspect(0, itemAspect, player); + + return true; + } + + @Override + public void updateWatcher(final IEssentiaWatcher newWatcher) { + // Set the watcher + this.essentiaWatcher = newWatcher; + + // And configure it + this.configureWatcher(); + } + + /** + * Writes the state of the emitter to the tag + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only write NBT data if saving, or wrenched. + if ((saveType != PartItemStack.World) && (saveType != PartItemStack.Wrench)) { + return; + } + + // Is there a filter? + if (this.trackedAspect != null) { + // Write the name of the aspect + data.setString(PartEssentiaLevelEmitter.NBT_KEY_ASPECT_FILTER, this.trackedAspect.getTag()); + } + + // Only save the rest on world save, or if there is a tracked aspect + if ((saveType == PartItemStack.World) || (this.trackedAspect != null)) { + // Write the redstone mode ordinal + if (this.redstoneMode != PartEssentiaLevelEmitter.DEFAULT_REDSTONE_MODE) { + data.setInteger(PartEssentiaLevelEmitter.NBT_KEY_REDSTONE_MODE, this.redstoneMode.ordinal()); + } + + // Write the threshold amount + if (this.thresholdLevel > 0) { + data.setLong(PartEssentiaLevelEmitter.NBT_KEY_WANTED_AMOUNT, this.thresholdLevel); + } + } + + // Write if emitting + if ((saveType == PartItemStack.World) && this.isEmitting) { + data.setBoolean(PartEssentiaLevelEmitter.NBT_KEY_IS_EMITTING, true); + } + } + + /** + * Called when a packet to sync client and server is being created. + * + * @throws IOException + */ + @Override + public void writeToStream(final ByteBuf stream) throws IOException { + // Call super + super.writeToStream(stream); + + // Write the activity state + stream.writeBoolean(this.isEmitting); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageBus.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageBus.java index 95ae275f..ffa7d763 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageBus.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageBus.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.parts; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -28,6 +25,9 @@ import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -54,577 +54,524 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class PartEssentiaStorageBus - extends ThEPartBase - implements IGridTickable, ICellContainer, IAspectSlotPart, IAEAppEngInventory, IPriorityHost -{ - /** - * Number of filtered aspects we can have - */ - public static final int FILTER_SIZE = 9; - - /** - * How much AE power is required to keep the part active. - */ - private static final double IDLE_POWER_DRAIN = 1.0D; - - /** - * NBT Keys - */ - private static final String NBT_KEY_PRIORITY = "Priority", NBT_KEY_FILTER = "FilterAspects#", NBT_KEY_UPGRADES = "UpgradeInventory", - NBT_KEY_VOID = "IsVoidAllowed"; - - /** - * "Cell" handler for the storage bus. - */ - private final HandlerEssentiaStorageBusBase handler = new HandlerEssentiaStorageBusDuality( this ); - - /** - * Filter list - */ - private final ArrayList filteredAspects = new ArrayList( PartEssentiaStorageBus.FILTER_SIZE ); - - /** - * Upgrade inventory - */ - private final UpgradeInventory upgradeInventory = new StackUpgradeInventory( this.associatedItem, this, 1 ); - - /** - * Storage bus priority - */ - private int priority = 0; - - /** - * Creates the bus - */ - public PartEssentiaStorageBus() - { - // Call super - super( AEPartsEnum.EssentiaStorageBus, SecurityPermissions.EXTRACT, SecurityPermissions.INJECT ); - - // Pre-fill the list with nulls - for( int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++ ) - { - this.filteredAspects.add( null ); - } - } - - /** - * Updates the handler on the inverted state. - */ - private void updateInverterState() - { - boolean inverted = AEApi.instance().definitions().materials().cardInverter().isSameAs( this.upgradeInventory.getStackInSlot( 0 ) ); - this.handler.setInverted( inverted ); - } - - /** - * Adds a new filter from the specified itemstack. - * - * @param player - * @param itemStack - * @return - */ - public boolean addFilteredAspectFromItemstack( final EntityPlayer player, final ItemStack itemStack ) - { - // Get the aspect of the item - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( itemStack ); - - // Is there an aspect? - if( itemAspect != null ) - { - // Are we already filtering this aspect? - if( this.filteredAspects.contains( itemAspect ) ) - { - return true; - } - - // Add to the first open slot - for( int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++ ) - { - // Is this space empty? - if( this.filteredAspects.get( index ) == null ) - { - // Set the filter - this.setAspect( index, itemAspect, player ); - - return true; - } - } - } - - return false; - } - - /** - * Ignored - */ - @Override - public void blinkCell( final int slot ) - { - // Ignored - } - - /** - * How far out from the cable bus to draw the cable graphic. - */ - @Override - public int cableConnectionRenderTo() - { - return 3; - } - - /** - * Extracts power from the network proportional to the specified essentia - * amount. - * - * @param essentiaAmount - * @param mode - * @return - */ - public boolean extractPowerForEssentiaTransfer( final int essentiaAmount, final Actionable mode ) - { - // Get the energy grid - IEnergyGrid eGrid = this.getGridBlock().getEnergyGrid(); - - // Ensure we have a grid - if( eGrid == null ) - { - return false; - } - - // Calculate amount of power to take - double powerDrain = EssentiaMonitor.AE_PER_ESSENTIA * essentiaAmount; - - // Extract - return( eGrid.extractAEPower( powerDrain, mode, PowerMultiplier.CONFIG ) >= powerDrain ); - } - - /** - * Hit/Collision boxes. - */ - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - // Face - helper.addBox( 1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F ); - - // Mid - helper.addBox( 4.0D, 4.0D, 14.0D, 12.0D, 12.0D, 15.0D ); - - // Back - helper.addBox( 5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D ); - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[0]; - } - - /** - * Gets the 'cell' handler for the storage bus. - */ - @Override - public List getCellArray( final StorageChannel channel ) - { - // Create a new list - List list = new ArrayList(); - - // Is this the fluid channel? - if( channel == StorageChannel.FLUIDS ) - { - // Add our handler - list.add( this.handler ); - } - - // Return the list - return list; - - } - - /** - * Returns the client portion of the gui. - */ - @Override - public Object getClientGuiElement( final EntityPlayer player ) - { - return new GuiEssentiaStorageBus( this, player ); - } - - /** - * What do we drop when removed from the world. - */ - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - // Get the upgrade card - ItemStack slotStack = this.upgradeInventory.getStackInSlot( 0 ); - - // Is it not null? - if( ( slotStack != null ) && ( slotStack.stackSize > 0 ) ) - { - // Add to the drops - drops.add( slotStack ); - } - } - - /** - * Returns the aspect in the filter slot. - * - * @return - */ - @Nullable - public Aspect getFilteredAspect( final int slotIndex ) - { - return this.filteredAspects.get( slotIndex ); - } - - /** - * Determines how much power the part takes for just existing. - */ - @Override - public double getIdlePowerUsage() - { - return PartEssentiaStorageBus.IDLE_POWER_DRAIN; - } - - /** - * Does not produce light. - */ - @Override - public int getLightLevel() - { - return 0; - } - - /** - * Gets the priority for this storage bus. - */ - @Override - public int getPriority() - { - return this.priority; - } - - /** - * Gets the server part of the gui. - */ - @Override - public Object getServerGuiElement( final EntityPlayer player ) - { - return new ContainerPartEssentiaStorageBus( this, player ); - } - - /** - * Sets how often we would like ticks. - */ - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - // We would like a tick ever 20 MC ticks - return new TickingRequest( 20, 20, false, false ); - } - - /** - * Gets the inventory that holds our upgrades. - * - * @return - */ - public UpgradeInventory getUpgradeInventory() - { - return this.upgradeInventory; - } - - /** - * Is voiding of essentia allowed? - * - * @return - */ - public boolean isVoidAllowed() - { - return this.handler.isVoidAllowed(); - } - - /** - * Called when the upgrade inventory changes. - */ - @Override - public void onChangeInventory( final IInventory inv, final int arg1, final InvOperation arg2, final ItemStack arg3, final ItemStack arg4 ) - { - this.updateInverterState(); - } - - /** - * Called when a player has changed void mode via gui. - * - * @param player - * @param isVoidAllowed - */ - public void onClientRequestSetVoidMode( final EntityPlayer player, final boolean isVoidAllowed ) - { - // Set the mode - this.handler.setVoidAllowed( isVoidAllowed ); - - this.saveChanges(); - } - - /** - * /** Updates the grid and handler that a neighbor has changed. - */ - @Override - public void onNeighborChanged() - { - // Send grid update event on server side - if( EffectiveSide.isServerSide() && this.isActive() ) - { - // Update the handler - if( this.handler.onNeighborChange() ) - { - // Send the update event - this.postGridUpdateEvent(); - } - } - } - - /** - * Notifies the grid that the storage bus contents have changed. - */ - public void postGridUpdateEvent() - { - // Does the storage bus have a grid node? - if( this.getActionableNode() != null ) - { - // Get the grid. - IGrid grid = this.getActionableNode().getGrid(); - - // Does the grid node have a grid? - if( grid != null ) - { - // Post an update to the grid - grid.postEvent( new MENetworkCellArrayUpdate() ); - } - } - } - - /** - * /** Reads the part data from NBT - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read the priority - if( data.hasKey( PartEssentiaStorageBus.NBT_KEY_PRIORITY ) ) - { - this.priority = data.getInteger( PartEssentiaStorageBus.NBT_KEY_PRIORITY ); - } - - // Read the filter list - for( int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++ ) - { - if( data.hasKey( PartEssentiaStorageBus.NBT_KEY_FILTER + index ) ) - { - this.filteredAspects.set( index, Aspect.aspects.get( data.getString( PartEssentiaStorageBus.NBT_KEY_FILTER + index ) ) ); - } - else - { - this.filteredAspects.set( index, null ); - } - } - - // Read the upgrade inventory - if( data.hasKey( PartEssentiaStorageBus.NBT_KEY_UPGRADES ) ) - { - this.upgradeInventory.readFromNBT( data, PartEssentiaStorageBus.NBT_KEY_UPGRADES ); - - // Update the handler inverted - this.updateInverterState(); - } - - // Read void - if( data.hasKey( PartEssentiaStorageBus.NBT_KEY_VOID ) ) - { - this.handler.setVoidAllowed( data.getBoolean( PartEssentiaStorageBus.NBT_KEY_VOID ) ); - } - - // Update the handler filter list - this.handler.setPrioritizedAspects( this.filteredAspects ); - } - - /** - * Renders the storage bus in the player inventory - */ - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; - - IIcon side = BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[2]; - helper.setTexture( side, side, side, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[0], side, side ); - - // Face - helper.setBounds( 1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - // Mid - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderInventoryBox( renderer ); - - // Color overlay - helper.setBounds( 2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F ); - helper.setInvColor( ThEPartBase.INVENTORY_OVERLAY_COLOR ); - ts.setBrightness( 0xF000F0 ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer ); - - // Back - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderInventoryBusLights( helper, renderer ); - } - - /** - * Renders the storage bus int he world. - */ - @SideOnly(Side.CLIENT) - @Override - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator tessellator = Tessellator.instance; - - IIcon side = BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[2]; - helper.setTexture( side, side, side, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTexture(), side, side ); - - // Front (facing jar) - helper.setBounds( 1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); - - tessellator.setColorOpaque_I( this.getHost().getColor().blackVariant ); - - if( this.isActive() ) - { - tessellator.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - } - - // Mid - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer ); - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Back (facing bus) - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - } - - @Override - public void saveChanges() - { - this.markForSave(); - } - - /** - * Ensures the storage bus gets saved. - */ - @Override - public void saveChanges( final IMEInventory inventory ) - { - this.saveChanges(); - } - - /** - * Sets one of the filters. - */ - @Override - public void setAspect( final int index, final Aspect aspect, final EntityPlayer player ) - { - this.filteredAspects.set( index, aspect ); - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Update the handler - this.handler.setPrioritizedAspects( this.filteredAspects ); - - // Update the grid - this.postGridUpdateEvent(); - - // Mark for save - this.markForSave(); - } - } - - @Override - public void setPriority( final int priority ) - { - this.priority = priority; - this.postGridUpdateEvent(); - } - - /** - * Called periodically by AE2. Passes the tick to the handler. - */ - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - // Update the handler. - this.handler.tickingRequest( node, TicksSinceLastCall ); - - // Keep chugging along - return TickRateModulation.SAME; - } - - /** - * Writes the storage busses state to NBT. - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only write NBT data if saving, or wrenched. - if( ( saveType != PartItemStack.World ) && ( saveType != PartItemStack.Wrench ) ) - { - return; - } - - // Write the filters - boolean hasFilters = false; - for( int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++ ) - { - Aspect aspect = this.filteredAspects.get( index ); - - if( aspect != null ) - { - data.setString( PartEssentiaStorageBus.NBT_KEY_FILTER + index, aspect.getTag() ); - hasFilters = true; - } - } - - // Only save the rest if filters are set, or world save - if( hasFilters || ( saveType == PartItemStack.World ) ) - { - // Write the priority - if( this.priority != 0 ) - { - data.setInteger( PartEssentiaStorageBus.NBT_KEY_PRIORITY, this.priority ); - } - - // Write void - if( this.handler.isVoidAllowed() ) - { - data.setBoolean( PartEssentiaStorageBus.NBT_KEY_VOID, this.handler.isVoidAllowed() ); - } - } - - // Write upgrades - if( ( saveType == PartItemStack.World ) && !this.upgradeInventory.isEmpty() ) - { - this.upgradeInventory.writeToNBT( data, PartEssentiaStorageBus.NBT_KEY_UPGRADES ); - } - - } - +public class PartEssentiaStorageBus extends ThEPartBase + implements IGridTickable, ICellContainer, IAspectSlotPart, IAEAppEngInventory, IPriorityHost { + /** + * Number of filtered aspects we can have + */ + public static final int FILTER_SIZE = 9; + + /** + * How much AE power is required to keep the part active. + */ + private static final double IDLE_POWER_DRAIN = 1.0D; + + /** + * NBT Keys + */ + private static final String NBT_KEY_PRIORITY = "Priority", + NBT_KEY_FILTER = "FilterAspects#", + NBT_KEY_UPGRADES = "UpgradeInventory", + NBT_KEY_VOID = "IsVoidAllowed"; + + /** + * "Cell" handler for the storage bus. + */ + private final HandlerEssentiaStorageBusBase handler = new HandlerEssentiaStorageBusDuality(this); + + /** + * Filter list + */ + private final ArrayList filteredAspects = new ArrayList(PartEssentiaStorageBus.FILTER_SIZE); + + /** + * Upgrade inventory + */ + private final UpgradeInventory upgradeInventory = new StackUpgradeInventory(this.associatedItem, this, 1); + + /** + * Storage bus priority + */ + private int priority = 0; + + /** + * Creates the bus + */ + public PartEssentiaStorageBus() { + // Call super + super(AEPartsEnum.EssentiaStorageBus, SecurityPermissions.EXTRACT, SecurityPermissions.INJECT); + + // Pre-fill the list with nulls + for (int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++) { + this.filteredAspects.add(null); + } + } + + /** + * Updates the handler on the inverted state. + */ + private void updateInverterState() { + boolean inverted = AEApi.instance() + .definitions() + .materials() + .cardInverter() + .isSameAs(this.upgradeInventory.getStackInSlot(0)); + this.handler.setInverted(inverted); + } + + /** + * Adds a new filter from the specified itemstack. + * + * @param player + * @param itemStack + * @return + */ + public boolean addFilteredAspectFromItemstack(final EntityPlayer player, final ItemStack itemStack) { + // Get the aspect of the item + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(itemStack); + + // Is there an aspect? + if (itemAspect != null) { + // Are we already filtering this aspect? + if (this.filteredAspects.contains(itemAspect)) { + return true; + } + + // Add to the first open slot + for (int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++) { + // Is this space empty? + if (this.filteredAspects.get(index) == null) { + // Set the filter + this.setAspect(index, itemAspect, player); + + return true; + } + } + } + + return false; + } + + /** + * Ignored + */ + @Override + public void blinkCell(final int slot) { + // Ignored + } + + /** + * How far out from the cable bus to draw the cable graphic. + */ + @Override + public int cableConnectionRenderTo() { + return 3; + } + + /** + * Extracts power from the network proportional to the specified essentia + * amount. + * + * @param essentiaAmount + * @param mode + * @return + */ + public boolean extractPowerForEssentiaTransfer(final int essentiaAmount, final Actionable mode) { + // Get the energy grid + IEnergyGrid eGrid = this.getGridBlock().getEnergyGrid(); + + // Ensure we have a grid + if (eGrid == null) { + return false; + } + + // Calculate amount of power to take + double powerDrain = EssentiaMonitor.AE_PER_ESSENTIA * essentiaAmount; + + // Extract + return (eGrid.extractAEPower(powerDrain, mode, PowerMultiplier.CONFIG) >= powerDrain); + } + + /** + * Hit/Collision boxes. + */ + @Override + public void getBoxes(final IPartCollisionHelper helper) { + // Face + helper.addBox(1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F); + + // Mid + helper.addBox(4.0D, 4.0D, 14.0D, 12.0D, 12.0D, 15.0D); + + // Back + helper.addBox(5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[0]; + } + + /** + * Gets the 'cell' handler for the storage bus. + */ + @Override + public List getCellArray(final StorageChannel channel) { + // Create a new list + List list = new ArrayList(); + + // Is this the fluid channel? + if (channel == StorageChannel.FLUIDS) { + // Add our handler + list.add(this.handler); + } + + // Return the list + return list; + } + + /** + * Returns the client portion of the gui. + */ + @Override + public Object getClientGuiElement(final EntityPlayer player) { + return new GuiEssentiaStorageBus(this, player); + } + + /** + * What do we drop when removed from the world. + */ + @Override + public void getDrops(final List drops, final boolean wrenched) { + // Get the upgrade card + ItemStack slotStack = this.upgradeInventory.getStackInSlot(0); + + // Is it not null? + if ((slotStack != null) && (slotStack.stackSize > 0)) { + // Add to the drops + drops.add(slotStack); + } + } + + /** + * Returns the aspect in the filter slot. + * + * @return + */ + @Nullable + public Aspect getFilteredAspect(final int slotIndex) { + return this.filteredAspects.get(slotIndex); + } + + /** + * Determines how much power the part takes for just existing. + */ + @Override + public double getIdlePowerUsage() { + return PartEssentiaStorageBus.IDLE_POWER_DRAIN; + } + + /** + * Does not produce light. + */ + @Override + public int getLightLevel() { + return 0; + } + + /** + * Gets the priority for this storage bus. + */ + @Override + public int getPriority() { + return this.priority; + } + + /** + * Gets the server part of the gui. + */ + @Override + public Object getServerGuiElement(final EntityPlayer player) { + return new ContainerPartEssentiaStorageBus(this, player); + } + + /** + * Sets how often we would like ticks. + */ + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + // We would like a tick ever 20 MC ticks + return new TickingRequest(20, 20, false, false); + } + + /** + * Gets the inventory that holds our upgrades. + * + * @return + */ + public UpgradeInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + /** + * Is voiding of essentia allowed? + * + * @return + */ + public boolean isVoidAllowed() { + return this.handler.isVoidAllowed(); + } + + /** + * Called when the upgrade inventory changes. + */ + @Override + public void onChangeInventory( + final IInventory inv, final int arg1, final InvOperation arg2, final ItemStack arg3, final ItemStack arg4) { + this.updateInverterState(); + } + + /** + * Called when a player has changed void mode via gui. + * + * @param player + * @param isVoidAllowed + */ + public void onClientRequestSetVoidMode(final EntityPlayer player, final boolean isVoidAllowed) { + // Set the mode + this.handler.setVoidAllowed(isVoidAllowed); + + this.saveChanges(); + } + + /** + * /** Updates the grid and handler that a neighbor has changed. + */ + @Override + public void onNeighborChanged() { + // Send grid update event on server side + if (EffectiveSide.isServerSide() && this.isActive()) { + // Update the handler + if (this.handler.onNeighborChange()) { + // Send the update event + this.postGridUpdateEvent(); + } + } + } + + /** + * Notifies the grid that the storage bus contents have changed. + */ + public void postGridUpdateEvent() { + // Does the storage bus have a grid node? + if (this.getActionableNode() != null) { + // Get the grid. + IGrid grid = this.getActionableNode().getGrid(); + + // Does the grid node have a grid? + if (grid != null) { + // Post an update to the grid + grid.postEvent(new MENetworkCellArrayUpdate()); + } + } + } + + /** + * /** Reads the part data from NBT + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Read the priority + if (data.hasKey(PartEssentiaStorageBus.NBT_KEY_PRIORITY)) { + this.priority = data.getInteger(PartEssentiaStorageBus.NBT_KEY_PRIORITY); + } + + // Read the filter list + for (int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++) { + if (data.hasKey(PartEssentiaStorageBus.NBT_KEY_FILTER + index)) { + this.filteredAspects.set( + index, Aspect.aspects.get(data.getString(PartEssentiaStorageBus.NBT_KEY_FILTER + index))); + } else { + this.filteredAspects.set(index, null); + } + } + + // Read the upgrade inventory + if (data.hasKey(PartEssentiaStorageBus.NBT_KEY_UPGRADES)) { + this.upgradeInventory.readFromNBT(data, PartEssentiaStorageBus.NBT_KEY_UPGRADES); + + // Update the handler inverted + this.updateInverterState(); + } + + // Read void + if (data.hasKey(PartEssentiaStorageBus.NBT_KEY_VOID)) { + this.handler.setVoidAllowed(data.getBoolean(PartEssentiaStorageBus.NBT_KEY_VOID)); + } + + // Update the handler filter list + this.handler.setPrioritizedAspects(this.filteredAspects); + } + + /** + * Renders the storage bus in the player inventory + */ + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[2]; + helper.setTexture( + side, side, side, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[0], side, side); + + // Face + helper.setBounds(1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F); + helper.renderInventoryBox(renderer); + + // Mid + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderInventoryBox(renderer); + + // Color overlay + helper.setBounds(2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F); + helper.setInvColor(ThEPartBase.INVENTORY_OVERLAY_COLOR); + ts.setBrightness(0xF000F0); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer); + + // Back + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderInventoryBusLights(helper, renderer); + } + + /** + * Renders the storage bus int he world. + */ + @SideOnly(Side.CLIENT) + @Override + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator tessellator = Tessellator.instance; + + IIcon side = BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[2]; + helper.setTexture(side, side, side, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTexture(), side, side); + + // Front (facing jar) + helper.setBounds(1.0F, 1.0F, 15.0F, 15.0F, 15.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); + + tessellator.setColorOpaque_I(this.getHost().getColor().blackVariant); + + if (this.isActive()) { + tessellator.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + } + + // Mid + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_STORAGE_BUS.getTextures()[1], ForgeDirection.SOUTH, renderer); + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderBlock(x, y, z, renderer); + + // Back (facing bus) + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } + + @Override + public void saveChanges() { + this.markForSave(); + } + + /** + * Ensures the storage bus gets saved. + */ + @Override + public void saveChanges(final IMEInventory inventory) { + this.saveChanges(); + } + + /** + * Sets one of the filters. + */ + @Override + public void setAspect(final int index, final Aspect aspect, final EntityPlayer player) { + this.filteredAspects.set(index, aspect); + + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Update the handler + this.handler.setPrioritizedAspects(this.filteredAspects); + + // Update the grid + this.postGridUpdateEvent(); + + // Mark for save + this.markForSave(); + } + } + + @Override + public void setPriority(final int priority) { + this.priority = priority; + this.postGridUpdateEvent(); + } + + /** + * Called periodically by AE2. Passes the tick to the handler. + */ + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + // Update the handler. + this.handler.tickingRequest(node, TicksSinceLastCall); + + // Keep chugging along + return TickRateModulation.SAME; + } + + /** + * Writes the storage busses state to NBT. + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only write NBT data if saving, or wrenched. + if ((saveType != PartItemStack.World) && (saveType != PartItemStack.Wrench)) { + return; + } + + // Write the filters + boolean hasFilters = false; + for (int index = 0; index < PartEssentiaStorageBus.FILTER_SIZE; index++) { + Aspect aspect = this.filteredAspects.get(index); + + if (aspect != null) { + data.setString(PartEssentiaStorageBus.NBT_KEY_FILTER + index, aspect.getTag()); + hasFilters = true; + } + } + + // Only save the rest if filters are set, or world save + if (hasFilters || (saveType == PartItemStack.World)) { + // Write the priority + if (this.priority != 0) { + data.setInteger(PartEssentiaStorageBus.NBT_KEY_PRIORITY, this.priority); + } + + // Write void + if (this.handler.isVoidAllowed()) { + data.setBoolean(PartEssentiaStorageBus.NBT_KEY_VOID, this.handler.isVoidAllowed()); + } + } + + // Write upgrades + if ((saveType == PartItemStack.World) && !this.upgradeInventory.isEmpty()) { + this.upgradeInventory.writeToNBT(data, PartEssentiaStorageBus.NBT_KEY_UPGRADES); + } + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageMonitor.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageMonitor.java index 34f40252..b3012393 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageMonitor.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaStorageMonitor.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.parts; -import java.awt.Color; -import java.io.IOException; -import org.lwjgl.opengl.GL11; import appeng.api.AEApi; import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.parts.IPartStorageMonitor; @@ -20,6 +17,8 @@ import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.awt.Color; +import java.io.IOException; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GLAllocation; @@ -37,6 +36,7 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; +import org.lwjgl.opengl.GL11; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.grid.IEssentiaWatcher; import thaumicenergistics.api.grid.IEssentiaWatcherHost; @@ -55,1034 +55,952 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class PartEssentiaStorageMonitor - extends ThEPartBase - implements IPartStorageMonitor, IEssentiaWatcherHost, IPowerChannelState -{ - /** - * All the data about what is being tracked. - * - * @author Nividica - * - */ - protected class TrackingInformation - { - /** - * Faux itemstack - */ - private IAEItemStack asItemStack; - - /** - * Aspect stack - */ - private IAspectStack asAspectStack; - - public TrackingInformation() - { - // Create the faux itemstack - ItemStack is = new ItemStack( new Item() - { - @Override - public String getItemStackDisplayName( final ItemStack ignored_ ) - { - return this.getUnlocalizedName(); - } - - @Override - public String getUnlocalizedName() - { - return getAspectStack() == null ? "Invalid aspect stack" : getAspectStack().getAspectName(); - } - - @Override - public String getUnlocalizedName( final ItemStack ignored ) - { - return this.getUnlocalizedName(); - } - } ); - - // Set the AE item stack - this.asItemStack = AEApi.instance().storage().createItemStack( is ); - } - - /** - * Gets the aspect stack associated with the essentia. - * - * @return - */ - public IAspectStack getAspectStack() - { - return this.asAspectStack; - } - - /** - * Gets an itemstack representing the essentia being tracked. - * Note: The only valid methods on the itemstack are the name accessors. - * - * @return - */ - public IAEItemStack getItemStack() - { - return this.asItemStack; - } - - /** - * Returns true if their is an essentia being tracked. - * - * @return - */ - public boolean isValid() - { - return( this.asAspectStack != null ); - } - - /** - * Sets what is being tracked, or clears the data if null. - * - * @param as - * @return Returns true if the tracker was changed, false otherwise. - */ - @SuppressWarnings("null") - public Boolean setTracked( final IAspectStack as ) - { - Boolean didChange = false; - Boolean trackedNull = ( this.asAspectStack == null ); - Boolean asNull = ( as == null ); - - // Are both not null? - if( !( trackedNull || asNull ) ) - { - // Check if anything changed - didChange = ( ( this.asAspectStack.getStackSize() != as.getStackSize() ) || ( this.asAspectStack.getAspect() != as.getAspect() ) ); - if( didChange ) - { - // Update - this.asAspectStack.setAll( as ); - } - } - // Is the tracked null, but input not? - else if( trackedNull && !asNull ) - { - // Set to the input stack - this.asAspectStack = as; - didChange = true; - } - // Is the input stack null, but tracked not? - else if( asNull && !trackedNull ) - { - // Clear the tracker - this.asAspectStack = null; - didChange = true; - } - - return didChange; - } - - /** - * Updates the aspect amount. - * - * @param aspectAmount - */ - public void updateTrackedAmount( final long aspectAmount ) - { - // Ensure there is a valid tracker - if( this.isValid() ) - { - // Update amount - this.asAspectStack.setStackSize( aspectAmount ); - } - } - - } - - /** - * How much power does the monitor require? - */ - private static final double IDLE_DRAIN = 0.5; - - /** - * NBT Keys - */ - private static final String NBT_KEY_LOCKED = "Locked", NBT_KEY_TRACKED_ASPECT = "TrackedAspect"; - - /*** - * Locked texture. - */ - private static final ResourceLocation TEXTURE_LOCKED = new ResourceLocation( ThaumicEnergistics.MOD_ID, - "textures/blocks/parts/monitor.locked.png" ); - - /** - * Watches the for changes in the essentia grid. - */ - private IEssentiaWatcher essentiaWatcher; - - /** - * True if the monitor is locked, and can not have its tracked essentia - * changed. - */ - private boolean monitorLocked = false; - - /** - * What is being tracked? - */ - protected final TrackingInformation trackedEssentia = new TrackingInformation(); - - /** - * If true the cached render list needs to be updated. - */ - private boolean updateDisplayList = false; - - /** - * ID of the cached render list. - */ - private Integer cachedDisplayList = null; - - CableBusTextures darkCornerTexture; - CableBusTextures lightCornerTexture; - - /** - * Constructor for conversion monitor. - * - * @param subPart - */ - protected PartEssentiaStorageMonitor( final AEPartsEnum subPart ) - { - super( subPart ); - - this.lightCornerTexture = CableBusTextures.PartConversionMonitor_Colored; - this.darkCornerTexture = CableBusTextures.PartConversionMonitor_Dark; - } - - /** - * Default constructor - */ - public PartEssentiaStorageMonitor() - { - this( AEPartsEnum.EssentiaStorageMonitor ); - } - - /** - * Updates the watcher to the tracked essentia. - */ - private void configureWatcher() - { - if( this.essentiaWatcher != null ) - { - // Clear any existing watched value - this.essentiaWatcher.clear(); - - // Is there an essentia being tracked? - if( this.trackedEssentia.isValid() ) - { - // Configure the watcher - this.essentiaWatcher.add( this.trackedEssentia.getAspectStack().getAspect() ); - - // Get the essentia monitor - IMEEssentiaMonitor essMon = this.getGridBlock().getEssentiaMonitor(); - - // Ensure there is a grid. - if( essMon != null ) - { - // Update the amount. - this.updateTrackedEssentiaAmount( essMon ); - } - } - } - } - - /** - * Returns true if the lock state was changed by this activation. - * - * @param player - * @param heldItem - * @return - */ - private boolean didActivateChangeLockState( final EntityPlayer player, final ItemStack heldItem ) - { - // Get the host tile entity - TileEntity hte = this.getHostTile(); - - // Is the item a wrench? - if( !player.isSneaking() && Platform.isWrench( player, heldItem, hte.xCoord, hte.yCoord, hte.zCoord ) ) - { - // Update the locked state - this.monitorLocked = !this.monitorLocked; - - // Report to the player - if( this.monitorLocked ) - { - // Locked - player.addChatMessage( PlayerMessages.isNowLocked.get() ); - } - else - { - // Unlocked - player.addChatMessage( PlayerMessages.isNowUnlocked.get() ); - } - - // Mark for sync & save - this.markForUpdate(); - this.markForSave(); - - return true; - - } - - return false; - } - - /** - * Renders the aspect onto the screen. - * - * @param tessellator - * @param aspect - */ - @SideOnly(Side.CLIENT) - private void renderAspect( final Tessellator tessellator, final Aspect aspect ) - { - // Get the aspect color - Color aspectColor = new Color( aspect.getColor() ); - - // Disable lighting - GL11.glDisable( GL11.GL_LIGHTING ); - - // Only draw if the image alpha is greater than the magic number - GL11.glAlphaFunc( GL11.GL_GREATER, 0.004F ); - - // Enable blending - GL11.glEnable( GL11.GL_BLEND ); - - // Specify the blending mode - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - - // Set the color - GL11.glColor4f( aspectColor.getRed() / 255.0F, aspectColor.getGreen() / 255.0F, aspectColor.getBlue() / 255.0F, 0.9F ); - tessellator.setColorRGBA_F( aspectColor.getRed() / 255.0F, aspectColor.getGreen() / 255.0F, aspectColor.getBlue() / 255.0F, 0.9F ); - - // Center the aspect - GL11.glTranslated( -0.20D, -0.25D, 0.0D ); - - // Bind the aspect image - Minecraft.getMinecraft().renderEngine.bindTexture( aspect.getImage() ); - - // Add the vertex points - double size = 0.38D; - double zDepth = -0.265D; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV( 0.0D, size, zDepth, 0.0D, 1.0D ); // Bottom left - tessellator.addVertexWithUV( size, size, zDepth, 1.0D, 1.0D ); // Bottom right - tessellator.addVertexWithUV( size, 0.0D, zDepth, 1.0D, 0.0D ); // Top right - tessellator.addVertexWithUV( 0.0D, 0.0D, zDepth, 0.0D, 0.0D ); // Top left - - // Draw! - tessellator.draw(); - - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - - // Enable lighting - GL11.glEnable( GL11.GL_LIGHTING ); - } - - /** - * Renders the lock. - * Note: This must come after renderAspect, as it depends on the - * GL position state that renderAspect sets up. - * - * @param tessellator - */ - private void renderLock( final Tessellator tessellator ) - { - // Enable blending - GL11.glEnable( GL11.GL_BLEND ); - - // Specify the blending mode - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - - // Set white - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 0.5f ); - - // Move to the top right corner - GL11.glTranslatef( 0.4f, -0.06f, 0.0f ); - - // Scale - float scale = 0.10f; - float invScale = 1.0f / scale; - GL11.glScalef( scale, scale, scale ); - - // Bind the block texture - Minecraft.getMinecraft().renderEngine.bindTexture( TEXTURE_LOCKED ); - - // Locked state - float txUMax = 0.5f; - float txUMin = 0.0f; - if( !this.isLocked() ) - { - txUMin = 0.5f; - txUMax = 1.0f; - } - - // Add the vertex points - double size = 1.0D; - double zDepth = -0.268D * invScale; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV( 0.0D, size, zDepth, txUMin, 1.0D ); // Bottom left - tessellator.addVertexWithUV( size, size, zDepth, txUMax, 1.0D ); // Bottom right - tessellator.addVertexWithUV( size, 0.0D, zDepth, txUMax, 0.0D ); // Top right - tessellator.addVertexWithUV( 0.0D, 0.0D, zDepth, txUMin, 0.0D ); // Top left - - // Draw - tessellator.draw(); - - // Restore - GL11.glScalef( invScale, invScale, invScale ); - GL11.glTranslatef( -0.4f, 0.06f, 0.0f ); - - // Disable blending - GL11.glDisable( GL11.GL_BLEND ); - } - - /** - * Renders the aspect and amount onto the screen. - * Note: Method originally from Applied Energistics 2, - * PartStorageMonitor.java - * - * @param tessellator - * @param aspect - */ - @SideOnly(Side.CLIENT) - private void renderScreen( final Tessellator tessellator, final IAspectStack aspectStack ) - { - // Get the side - ForgeDirection side = this.getSide(); - - // Adjust position based on cable side - GL11.glTranslated( side.offsetX * 0.77, side.offsetY * 0.77, side.offsetZ * 0.77 ); - - // Adjust scale and/or rotation based on cable side - switch ( side ) - { - case DOWN: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); - break; - - case EAST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); - break; - - case NORTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - break; - - case SOUTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); - break; - - case UP: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); - break; - - case WEST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - break; - - default: - break; - - } - - try - { - // Calculate the brightness for the lightmap - int brightness = ( 16 << 20 ) | ( 16 << 4 ); - int brightnessComponent1 = brightness % 65536; - int brightnessComponent2 = brightness / 65536; - - // Set the lightmap - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, brightnessComponent1 * 0.8F, brightnessComponent2 * 0.8F ); - - // Render the aspect - this.renderAspect( tessellator, aspectStack.getAspect() ); - - // Render the lock - this.renderLock( tessellator ); - - } - catch( Exception e ) - { - } - - // Move below the screen image - GL11.glTranslatef( 0.2f, 0.4f, -0.25f ); - GL11.glScalef( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); - - // Convert the amount to a string - final String renderedStackSize = ReadableNumberConverter.INSTANCE.toWideReadableForm( aspectStack.getStackSize() ); - - // Get the font renderer - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - - // Adjust position based on string width - GL11.glTranslatef( -0.5f * fr.getStringWidth( renderedStackSize ), 0.0f, -1.0f ); - - // Render the string - fr.drawString( renderedStackSize, 0, 0, 0 ); - } - - /** - * Updates the tracked essentia amount. - * - * @param essMonitor - */ - private void updateTrackedEssentiaAmount( final IMEEssentiaMonitor essMonitor ) - { - // Ensure there is something to track - if( !this.trackedEssentia.isValid() ) - { - return; - } - - // Reset the amount - this.trackedEssentia.updateTrackedAmount( 0 ); - - // Get the amount in the network - long stored = essMonitor.getEssentiaAmount( this.trackedEssentia.getAspectStack().getAspect() ); - - // Was there anything found? - if( stored > 0 ) - { - // Set the amount - this.trackedEssentia.updateTrackedAmount( stored ); - } - } - - /** - * Permission and activation checks. - * - * @param player - * @return - */ - protected boolean activationCheck( final EntityPlayer player ) - { - // Ignore fake players - if( player instanceof FakePlayer ) - { - return false; - } - - // Is the monitor off? - if( !this.isActive() ) - { - return false; - } - - // Does the player have permission to interact with this device? - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } - - return true; - } - - @SideOnly(Side.CLIENT) - @Override - protected void finalize() throws Throwable - { - // Call super - super.finalize(); - - // Dealoc the cached render list - if( this.cachedDisplayList != null ) - { - GLAllocation.deleteDisplayLists( this.cachedDisplayList ); - } - } - - /** - * Called when the monitor is right-clicked with an empty hand. - * Clears the tracker. - * - * @return - */ - protected boolean onActivatedWithEmptyHand() - { - // Is the monitor locked? - if( this.monitorLocked ) - { - return false; - } - - // Clear the tracker - this.trackedEssentia.setTracked( null ); - - // Update watcher - this.configureWatcher(); - - // Mark for sync & save - this.markForUpdate(); - this.markForSave(); - - return true; - } - - /** - * Called when the monitor is right-clicked with an essentia container or - * label. - * Sets the tracker to the items contained aspect, or clears if the - * container is empty. - * - * @param player - * @param heldItem - * @param itemType - * @return - */ - protected boolean onActivateWithAspectItem( final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType ) - { - // Is the monitor locked? - if( this.monitorLocked ) - { - return false; - } - - // Get the aspect - Aspect heldAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( heldItem ); - - // Ensure there is an aspect - if( heldAspect == null ) - { - // Empty container, clear the tracker - return this.onActivatedWithEmptyHand(); - } - - // Create an aspect stack of size 0, and set it as the tracked aspect - this.trackedEssentia.setTracked( new AspectStack( heldAspect, 0 ) ); - - // Reconfigure the watcher - this.configureWatcher(); - - // Mark for sync & save - this.markForUpdate(); - this.markForSave(); - - return true; - } - - @Override - public int cableConnectionRenderTo() - { - return 3; - } - - /** - * Collision boxes - */ - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - helper.addBox( 2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D ); - - helper.addBox( 5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D ); - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; - } - - /** - * What essentia gas is being displayed? - */ - @Override - public IAEStack getDisplayed() - { - if( this.trackedEssentia.isValid() ) - { - return this.trackedEssentia.getItemStack(); - } - - return null; - } - - /** - * Gets how much power the monitor requires. - */ - @Override - public double getIdlePowerUsage() - { - return PartEssentiaStorageMonitor.IDLE_DRAIN; - } - - /** - * Get the monitor brightness. - */ - @Override - public int getLightLevel() - { - return( this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0 ); - } - - /** - * Is the monitor locked? - */ - @Override - public boolean isLocked() - { - return this.monitorLocked; - } - - /** - * Is the monitor on? - */ - @Override - public boolean isPowered() - { - return this.isActive(); - } - - /** - * Called when a player right clicks the monitor. - */ - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - - // Ignore client side. - if( EffectiveSide.isClientSide() ) - { - return true; - } - - // Permission and activation checks - if( !this.activationCheck( player ) ) - { - return false; - } - - // Get the item the player is holding - ItemStack heldItem = player.getCurrentEquippedItem(); - - // Was the lock state changed? - if( this.didActivateChangeLockState( player, heldItem ) ) - { - return true; - } - - // Is the players hand empty? - if( heldItem == null ) - { - return this.onActivatedWithEmptyHand(); - } - - // Get the type - AspectItemType itemType = EssentiaItemContainerHelper.INSTANCE.getItemType( heldItem ); - - // Is the item valid? - if( itemType != AspectItemType.Invalid ) - { - return this.onActivateWithAspectItem( player, heldItem, itemType ); - } - - return false; - } - - /** - * Called by the watcher when the essentia amount changes. - */ - @Override - public void onEssentiaChange( final Aspect aspect, final long storedAmount, final long changeAmount ) - { - // Is there an essentia being tracked? - if( !this.trackedEssentia.isValid() ) - { - // Not tracking anything - return; - } - - // Did the amount change? - if( this.trackedEssentia.getAspectStack().getStackSize() != storedAmount ) - { - // Update the amount - this.trackedEssentia.updateTrackedAmount( storedAmount ); - - // Mark for sync - this.markForUpdate(); - } - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read locked - if( data.hasKey( PartEssentiaStorageMonitor.NBT_KEY_LOCKED ) ) - { - this.monitorLocked = data.getBoolean( PartEssentiaStorageMonitor.NBT_KEY_LOCKED ); - } - - // Read tracked - if( data.hasKey( PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT ) ) - { - // Read the aspect - Aspect trackedAspect = Aspect.getAspect( data.getString( PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT ) ); - - // Set the tracker - this.trackedEssentia.setTracked( new AspectStack( trackedAspect, 0 ) ); - } - } - - @SideOnly(Side.CLIENT) - @Override - public boolean readFromStream( final ByteBuf stream ) throws IOException - { - boolean redraw = false; - - // Call super - redraw |= super.readFromStream( stream ); - - // Read locked state - boolean newLockState = stream.readBoolean(); - if( this.monitorLocked != newLockState ) - { - // Mark for screen redraw - redraw |= this.updateDisplayList = true; - } - this.monitorLocked = newLockState; - - // Is there any tracking info to read? - if( stream.readBoolean() ) - { - // Read the tracked stack - IAspectStack as = AspectStack.loadAspectStackFromNBT( ByteBufUtils.readTag( stream ) ); - - // Did the stack change? - if( this.trackedEssentia.setTracked( as ) ) - { - // Mark for screen redraw - redraw |= this.updateDisplayList = true; - } - } - else - { - // Clear the tracker - this.trackedEssentia.setTracked( null ); - - // Mark for screen redraw - redraw |= this.updateDisplayList = true; - } - - return redraw; - } - - @SideOnly(Side.CLIENT) - @Override - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Skip if nothing to draw - if( ( !this.isActive() ) || ( !this.trackedEssentia.isValid() ) ) - { - return; - } - - // Does the cached display list need to be created? - if( this.cachedDisplayList == null ) - { - // Ask OpenGL for a display list - this.cachedDisplayList = GLAllocation.generateDisplayLists( 1 ); - - // Mark for update - this.updateDisplayList = true; - } - - // Push the OpenGL matrix - GL11.glPushMatrix(); - - // Move to the center of the monitor - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - - // Does the display list need to be updated? - if( this.updateDisplayList ) - { - // Mark that it is being updated - this.updateDisplayList = false; - - // Ask OpenGL to create a new compiled list, and run it when done. - GL11.glNewList( this.cachedDisplayList, GL11.GL_COMPILE_AND_EXECUTE ); - - // Add the screen render to the list - this.renderScreen( Tessellator.instance, this.trackedEssentia.getAspectStack() ); - - // End the list and run it - GL11.glEndList(); - } - else - { - // Run the cached list - GL11.glCallList( this.cachedDisplayList ); - } - - // Pop the OpenGL matrix - GL11.glPopMatrix(); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4]; - - helper.setTexture( side, side, side, side, side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - // Face bounds - helper.setBounds( 2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F ); - - // Dark corners - helper.setInvColor( AEColor.Transparent.blackVariant ); - helper.renderInventoryFace( this.darkCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Light corners - helper.setInvColor( AEColor.Transparent.mediumVariant ); - helper.renderInventoryFace( this.lightCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Main face - helper.setInvColor( AEColor.Transparent.whiteVariant ); - helper.renderInventoryFace( CableBusTextures.PartConversionMonitor_Bright.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Phial - helper.setInvColor( AEColor.Black.blackVariant ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer ); - - // Cable lights - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderInventoryBusLights( helper, renderer ); - - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator tessellator = Tessellator.instance; - - IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; - - // Main block - helper.setTexture( side, side, side, side, side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Light up if active - if( this.isActive() ) - { - Tessellator.instance.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - } - - // Dark corners - tessellator.setColorOpaque_I( this.getHost().getColor().blackVariant ); - helper.renderFace( x, y, z, this.darkCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Light corners - tessellator.setColorOpaque_I( this.getHost().getColor().mediumVariant ); - helper.renderFace( x, y, z, this.lightCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Main face - tessellator.setColorOpaque_I( this.getHost().getColor().whiteVariant ); - helper.renderFace( x, y, z, CableBusTextures.PartConversionMonitor_Bright.getIcon(), ForgeDirection.SOUTH, renderer ); - - // Phial - if( !this.trackedEssentia.isValid() ) - { - tessellator.setColorOpaque_I( this.getHost().getColor().mediumVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer ); - } - - // Cable lights - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - - } - - /** - * Needs dynamic renderer. - */ - @Override - public boolean requireDynamicRender() - { - return true; - } - - @Override - public boolean showNetworkInfo( final MovingObjectPosition where ) - { - return false; - } - - /** - * Called when a new watcher is provided. - */ - @Override - public void updateWatcher( final IEssentiaWatcher newWatcher ) - { - // Set the watcher - this.essentiaWatcher = newWatcher; - - // Configure it - this.configureWatcher(); - } - - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only save on world - if( saveType != PartItemStack.World ) - { - return; - } - - // Write locked - if( this.monitorLocked ) - { - data.setBoolean( PartEssentiaStorageMonitor.NBT_KEY_LOCKED, this.monitorLocked ); - } - - // Write tracked data if valid - if( this.trackedEssentia.isValid() ) - { - // Write the aspect - data.setString( PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT, this.trackedEssentia.getAspectStack().getAspectTag() ); - } - } - - @Override - public void writeToStream( final ByteBuf stream ) throws IOException - { - // Call super - super.writeToStream( stream ); - - // Write locked - stream.writeBoolean( this.monitorLocked ); - - // Write if valid - stream.writeBoolean( this.trackedEssentia.isValid() ); - - if( this.trackedEssentia.isValid() ) - { - // Write the tracker - ByteBufUtils.writeTag( stream, this.trackedEssentia.getAspectStack().writeToNBT( new NBTTagCompound() ) ); - } - - } +public class PartEssentiaStorageMonitor extends ThEPartBase + implements IPartStorageMonitor, IEssentiaWatcherHost, IPowerChannelState { + /** + * All the data about what is being tracked. + * + * @author Nividica + * + */ + protected class TrackingInformation { + /** + * Faux itemstack + */ + private IAEItemStack asItemStack; + + /** + * Aspect stack + */ + private IAspectStack asAspectStack; + + public TrackingInformation() { + // Create the faux itemstack + ItemStack is = new ItemStack(new Item() { + @Override + public String getItemStackDisplayName(final ItemStack ignored_) { + return this.getUnlocalizedName(); + } + + @Override + public String getUnlocalizedName() { + return getAspectStack() == null + ? "Invalid aspect stack" + : getAspectStack().getAspectName(); + } + + @Override + public String getUnlocalizedName(final ItemStack ignored) { + return this.getUnlocalizedName(); + } + }); + + // Set the AE item stack + this.asItemStack = AEApi.instance().storage().createItemStack(is); + } + + /** + * Gets the aspect stack associated with the essentia. + * + * @return + */ + public IAspectStack getAspectStack() { + return this.asAspectStack; + } + + /** + * Gets an itemstack representing the essentia being tracked. + * Note: The only valid methods on the itemstack are the name accessors. + * + * @return + */ + public IAEItemStack getItemStack() { + return this.asItemStack; + } + + /** + * Returns true if their is an essentia being tracked. + * + * @return + */ + public boolean isValid() { + return (this.asAspectStack != null); + } + + /** + * Sets what is being tracked, or clears the data if null. + * + * @param as + * @return Returns true if the tracker was changed, false otherwise. + */ + @SuppressWarnings("null") + public Boolean setTracked(final IAspectStack as) { + Boolean didChange = false; + Boolean trackedNull = (this.asAspectStack == null); + Boolean asNull = (as == null); + + // Are both not null? + if (!(trackedNull || asNull)) { + // Check if anything changed + didChange = ((this.asAspectStack.getStackSize() != as.getStackSize()) + || (this.asAspectStack.getAspect() != as.getAspect())); + if (didChange) { + // Update + this.asAspectStack.setAll(as); + } + } + // Is the tracked null, but input not? + else if (trackedNull && !asNull) { + // Set to the input stack + this.asAspectStack = as; + didChange = true; + } + // Is the input stack null, but tracked not? + else if (asNull && !trackedNull) { + // Clear the tracker + this.asAspectStack = null; + didChange = true; + } + + return didChange; + } + + /** + * Updates the aspect amount. + * + * @param aspectAmount + */ + public void updateTrackedAmount(final long aspectAmount) { + // Ensure there is a valid tracker + if (this.isValid()) { + // Update amount + this.asAspectStack.setStackSize(aspectAmount); + } + } + } + + /** + * How much power does the monitor require? + */ + private static final double IDLE_DRAIN = 0.5; + + /** + * NBT Keys + */ + private static final String NBT_KEY_LOCKED = "Locked", NBT_KEY_TRACKED_ASPECT = "TrackedAspect"; + + /*** + * Locked texture. + */ + private static final ResourceLocation TEXTURE_LOCKED = + new ResourceLocation(ThaumicEnergistics.MOD_ID, "textures/blocks/parts/monitor.locked.png"); + + /** + * Watches the for changes in the essentia grid. + */ + private IEssentiaWatcher essentiaWatcher; + + /** + * True if the monitor is locked, and can not have its tracked essentia + * changed. + */ + private boolean monitorLocked = false; + + /** + * What is being tracked? + */ + protected final TrackingInformation trackedEssentia = new TrackingInformation(); + + /** + * If true the cached render list needs to be updated. + */ + private boolean updateDisplayList = false; + + /** + * ID of the cached render list. + */ + private Integer cachedDisplayList = null; + + CableBusTextures darkCornerTexture; + CableBusTextures lightCornerTexture; + + /** + * Constructor for conversion monitor. + * + * @param subPart + */ + protected PartEssentiaStorageMonitor(final AEPartsEnum subPart) { + super(subPart); + + this.lightCornerTexture = CableBusTextures.PartConversionMonitor_Colored; + this.darkCornerTexture = CableBusTextures.PartConversionMonitor_Dark; + } + + /** + * Default constructor + */ + public PartEssentiaStorageMonitor() { + this(AEPartsEnum.EssentiaStorageMonitor); + } + + /** + * Updates the watcher to the tracked essentia. + */ + private void configureWatcher() { + if (this.essentiaWatcher != null) { + // Clear any existing watched value + this.essentiaWatcher.clear(); + + // Is there an essentia being tracked? + if (this.trackedEssentia.isValid()) { + // Configure the watcher + this.essentiaWatcher.add(this.trackedEssentia.getAspectStack().getAspect()); + + // Get the essentia monitor + IMEEssentiaMonitor essMon = this.getGridBlock().getEssentiaMonitor(); + + // Ensure there is a grid. + if (essMon != null) { + // Update the amount. + this.updateTrackedEssentiaAmount(essMon); + } + } + } + } + + /** + * Returns true if the lock state was changed by this activation. + * + * @param player + * @param heldItem + * @return + */ + private boolean didActivateChangeLockState(final EntityPlayer player, final ItemStack heldItem) { + // Get the host tile entity + TileEntity hte = this.getHostTile(); + + // Is the item a wrench? + if (!player.isSneaking() && Platform.isWrench(player, heldItem, hte.xCoord, hte.yCoord, hte.zCoord)) { + // Update the locked state + this.monitorLocked = !this.monitorLocked; + + // Report to the player + if (this.monitorLocked) { + // Locked + player.addChatMessage(PlayerMessages.isNowLocked.get()); + } else { + // Unlocked + player.addChatMessage(PlayerMessages.isNowUnlocked.get()); + } + + // Mark for sync & save + this.markForUpdate(); + this.markForSave(); + + return true; + } + + return false; + } + + /** + * Renders the aspect onto the screen. + * + * @param tessellator + * @param aspect + */ + @SideOnly(Side.CLIENT) + private void renderAspect(final Tessellator tessellator, final Aspect aspect) { + // Get the aspect color + Color aspectColor = new Color(aspect.getColor()); + + // Disable lighting + GL11.glDisable(GL11.GL_LIGHTING); + + // Only draw if the image alpha is greater than the magic number + GL11.glAlphaFunc(GL11.GL_GREATER, 0.004F); + + // Enable blending + GL11.glEnable(GL11.GL_BLEND); + + // Specify the blending mode + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + // Set the color + GL11.glColor4f( + aspectColor.getRed() / 255.0F, aspectColor.getGreen() / 255.0F, aspectColor.getBlue() / 255.0F, 0.9F); + tessellator.setColorRGBA_F( + aspectColor.getRed() / 255.0F, aspectColor.getGreen() / 255.0F, aspectColor.getBlue() / 255.0F, 0.9F); + + // Center the aspect + GL11.glTranslated(-0.20D, -0.25D, 0.0D); + + // Bind the aspect image + Minecraft.getMinecraft().renderEngine.bindTexture(aspect.getImage()); + + // Add the vertex points + double size = 0.38D; + double zDepth = -0.265D; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(0.0D, size, zDepth, 0.0D, 1.0D); // Bottom left + tessellator.addVertexWithUV(size, size, zDepth, 1.0D, 1.0D); // Bottom right + tessellator.addVertexWithUV(size, 0.0D, zDepth, 1.0D, 0.0D); // Top right + tessellator.addVertexWithUV(0.0D, 0.0D, zDepth, 0.0D, 0.0D); // Top left + + // Draw! + tessellator.draw(); + + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + + // Enable lighting + GL11.glEnable(GL11.GL_LIGHTING); + } + + /** + * Renders the lock. + * Note: This must come after renderAspect, as it depends on the + * GL position state that renderAspect sets up. + * + * @param tessellator + */ + private void renderLock(final Tessellator tessellator) { + // Enable blending + GL11.glEnable(GL11.GL_BLEND); + + // Specify the blending mode + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + + // Set white + GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f); + + // Move to the top right corner + GL11.glTranslatef(0.4f, -0.06f, 0.0f); + + // Scale + float scale = 0.10f; + float invScale = 1.0f / scale; + GL11.glScalef(scale, scale, scale); + + // Bind the block texture + Minecraft.getMinecraft().renderEngine.bindTexture(TEXTURE_LOCKED); + + // Locked state + float txUMax = 0.5f; + float txUMin = 0.0f; + if (!this.isLocked()) { + txUMin = 0.5f; + txUMax = 1.0f; + } + + // Add the vertex points + double size = 1.0D; + double zDepth = -0.268D * invScale; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(0.0D, size, zDepth, txUMin, 1.0D); // Bottom left + tessellator.addVertexWithUV(size, size, zDepth, txUMax, 1.0D); // Bottom right + tessellator.addVertexWithUV(size, 0.0D, zDepth, txUMax, 0.0D); // Top right + tessellator.addVertexWithUV(0.0D, 0.0D, zDepth, txUMin, 0.0D); // Top left + + // Draw + tessellator.draw(); + + // Restore + GL11.glScalef(invScale, invScale, invScale); + GL11.glTranslatef(-0.4f, 0.06f, 0.0f); + + // Disable blending + GL11.glDisable(GL11.GL_BLEND); + } + + /** + * Renders the aspect and amount onto the screen. + * Note: Method originally from Applied Energistics 2, + * PartStorageMonitor.java + * + * @param tessellator + * @param aspect + */ + @SideOnly(Side.CLIENT) + private void renderScreen(final Tessellator tessellator, final IAspectStack aspectStack) { + // Get the side + ForgeDirection side = this.getSide(); + + // Adjust position based on cable side + GL11.glTranslated(side.offsetX * 0.77, side.offsetY * 0.77, side.offsetZ * 0.77); + + // Adjust scale and/or rotation based on cable side + switch (side) { + case DOWN: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); + break; + + case EAST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + break; + + case NORTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + break; + + case SOUTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + break; + + case UP: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + break; + + case WEST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + break; + + default: + break; + } + + try { + // Calculate the brightness for the lightmap + int brightness = (16 << 20) | (16 << 4); + int brightnessComponent1 = brightness % 65536; + int brightnessComponent2 = brightness / 65536; + + // Set the lightmap + OpenGlHelper.setLightmapTextureCoords( + OpenGlHelper.lightmapTexUnit, brightnessComponent1 * 0.8F, brightnessComponent2 * 0.8F); + + // Render the aspect + this.renderAspect(tessellator, aspectStack.getAspect()); + + // Render the lock + this.renderLock(tessellator); + + } catch (Exception e) { + } + + // Move below the screen image + GL11.glTranslatef(0.2f, 0.4f, -0.25f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + + // Convert the amount to a string + final String renderedStackSize = + ReadableNumberConverter.INSTANCE.toWideReadableForm(aspectStack.getStackSize()); + + // Get the font renderer + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + + // Adjust position based on string width + GL11.glTranslatef(-0.5f * fr.getStringWidth(renderedStackSize), 0.0f, -1.0f); + + // Render the string + fr.drawString(renderedStackSize, 0, 0, 0); + } + + /** + * Updates the tracked essentia amount. + * + * @param essMonitor + */ + private void updateTrackedEssentiaAmount(final IMEEssentiaMonitor essMonitor) { + // Ensure there is something to track + if (!this.trackedEssentia.isValid()) { + return; + } + + // Reset the amount + this.trackedEssentia.updateTrackedAmount(0); + + // Get the amount in the network + long stored = essMonitor.getEssentiaAmount( + this.trackedEssentia.getAspectStack().getAspect()); + + // Was there anything found? + if (stored > 0) { + // Set the amount + this.trackedEssentia.updateTrackedAmount(stored); + } + } + + /** + * Permission and activation checks. + * + * @param player + * @return + */ + protected boolean activationCheck(final EntityPlayer player) { + // Ignore fake players + if (player instanceof FakePlayer) { + return false; + } + + // Is the monitor off? + if (!this.isActive()) { + return false; + } + + // Does the player have permission to interact with this device? + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } + + return true; + } + + @SideOnly(Side.CLIENT) + @Override + protected void finalize() throws Throwable { + // Call super + super.finalize(); + + // Dealoc the cached render list + if (this.cachedDisplayList != null) { + GLAllocation.deleteDisplayLists(this.cachedDisplayList); + } + } + + /** + * Called when the monitor is right-clicked with an empty hand. + * Clears the tracker. + * + * @return + */ + protected boolean onActivatedWithEmptyHand() { + // Is the monitor locked? + if (this.monitorLocked) { + return false; + } + + // Clear the tracker + this.trackedEssentia.setTracked(null); + + // Update watcher + this.configureWatcher(); + + // Mark for sync & save + this.markForUpdate(); + this.markForSave(); + + return true; + } + + /** + * Called when the monitor is right-clicked with an essentia container or + * label. + * Sets the tracker to the items contained aspect, or clears if the + * container is empty. + * + * @param player + * @param heldItem + * @param itemType + * @return + */ + protected boolean onActivateWithAspectItem( + final EntityPlayer player, final ItemStack heldItem, final AspectItemType itemType) { + // Is the monitor locked? + if (this.monitorLocked) { + return false; + } + + // Get the aspect + Aspect heldAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(heldItem); + + // Ensure there is an aspect + if (heldAspect == null) { + // Empty container, clear the tracker + return this.onActivatedWithEmptyHand(); + } + + // Create an aspect stack of size 0, and set it as the tracked aspect + this.trackedEssentia.setTracked(new AspectStack(heldAspect, 0)); + + // Reconfigure the watcher + this.configureWatcher(); + + // Mark for sync & save + this.markForUpdate(); + this.markForSave(); + + return true; + } + + @Override + public int cableConnectionRenderTo() { + return 3; + } + + /** + * Collision boxes + */ + @Override + public void getBoxes(final IPartCollisionHelper helper) { + helper.addBox(2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D); + + helper.addBox(5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; + } + + /** + * What essentia gas is being displayed? + */ + @Override + public IAEStack getDisplayed() { + if (this.trackedEssentia.isValid()) { + return this.trackedEssentia.getItemStack(); + } + + return null; + } + + /** + * Gets how much power the monitor requires. + */ + @Override + public double getIdlePowerUsage() { + return PartEssentiaStorageMonitor.IDLE_DRAIN; + } + + /** + * Get the monitor brightness. + */ + @Override + public int getLightLevel() { + return (this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0); + } + + /** + * Is the monitor locked? + */ + @Override + public boolean isLocked() { + return this.monitorLocked; + } + + /** + * Is the monitor on? + */ + @Override + public boolean isPowered() { + return this.isActive(); + } + + /** + * Called when a player right clicks the monitor. + */ + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + + // Ignore client side. + if (EffectiveSide.isClientSide()) { + return true; + } + + // Permission and activation checks + if (!this.activationCheck(player)) { + return false; + } + + // Get the item the player is holding + ItemStack heldItem = player.getCurrentEquippedItem(); + + // Was the lock state changed? + if (this.didActivateChangeLockState(player, heldItem)) { + return true; + } + + // Is the players hand empty? + if (heldItem == null) { + return this.onActivatedWithEmptyHand(); + } + + // Get the type + AspectItemType itemType = EssentiaItemContainerHelper.INSTANCE.getItemType(heldItem); + + // Is the item valid? + if (itemType != AspectItemType.Invalid) { + return this.onActivateWithAspectItem(player, heldItem, itemType); + } + + return false; + } + + /** + * Called by the watcher when the essentia amount changes. + */ + @Override + public void onEssentiaChange(final Aspect aspect, final long storedAmount, final long changeAmount) { + // Is there an essentia being tracked? + if (!this.trackedEssentia.isValid()) { + // Not tracking anything + return; + } + + // Did the amount change? + if (this.trackedEssentia.getAspectStack().getStackSize() != storedAmount) { + // Update the amount + this.trackedEssentia.updateTrackedAmount(storedAmount); + + // Mark for sync + this.markForUpdate(); + } + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Read locked + if (data.hasKey(PartEssentiaStorageMonitor.NBT_KEY_LOCKED)) { + this.monitorLocked = data.getBoolean(PartEssentiaStorageMonitor.NBT_KEY_LOCKED); + } + + // Read tracked + if (data.hasKey(PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT)) { + // Read the aspect + Aspect trackedAspect = Aspect.getAspect(data.getString(PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT)); + + // Set the tracker + this.trackedEssentia.setTracked(new AspectStack(trackedAspect, 0)); + } + } + + @SideOnly(Side.CLIENT) + @Override + public boolean readFromStream(final ByteBuf stream) throws IOException { + boolean redraw = false; + + // Call super + redraw |= super.readFromStream(stream); + + // Read locked state + boolean newLockState = stream.readBoolean(); + if (this.monitorLocked != newLockState) { + // Mark for screen redraw + redraw |= this.updateDisplayList = true; + } + this.monitorLocked = newLockState; + + // Is there any tracking info to read? + if (stream.readBoolean()) { + // Read the tracked stack + IAspectStack as = AspectStack.loadAspectStackFromNBT(ByteBufUtils.readTag(stream)); + + // Did the stack change? + if (this.trackedEssentia.setTracked(as)) { + // Mark for screen redraw + redraw |= this.updateDisplayList = true; + } + } else { + // Clear the tracker + this.trackedEssentia.setTracked(null); + + // Mark for screen redraw + redraw |= this.updateDisplayList = true; + } + + return redraw; + } + + @SideOnly(Side.CLIENT) + @Override + public void renderDynamic( + final double x, + final double y, + final double z, + final IPartRenderHelper helper, + final RenderBlocks renderer) { + // Skip if nothing to draw + if ((!this.isActive()) || (!this.trackedEssentia.isValid())) { + return; + } + + // Does the cached display list need to be created? + if (this.cachedDisplayList == null) { + // Ask OpenGL for a display list + this.cachedDisplayList = GLAllocation.generateDisplayLists(1); + + // Mark for update + this.updateDisplayList = true; + } + + // Push the OpenGL matrix + GL11.glPushMatrix(); + + // Move to the center of the monitor + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + + // Does the display list need to be updated? + if (this.updateDisplayList) { + // Mark that it is being updated + this.updateDisplayList = false; + + // Ask OpenGL to create a new compiled list, and run it when done. + GL11.glNewList(this.cachedDisplayList, GL11.GL_COMPILE_AND_EXECUTE); + + // Add the screen render to the list + this.renderScreen(Tessellator.instance, this.trackedEssentia.getAspectStack()); + + // End the list and run it + GL11.glEndList(); + } else { + // Run the cached list + GL11.glCallList(this.cachedDisplayList); + } + + // Pop the OpenGL matrix + GL11.glPopMatrix(); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4]; + + helper.setTexture(side, side, side, side, side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderInventoryBox(renderer); + + // Face bounds + helper.setBounds(2.0F, 2.0F, 15.0F, 14.0F, 14.0F, 16.0F); + + // Dark corners + helper.setInvColor(AEColor.Transparent.blackVariant); + helper.renderInventoryFace(this.darkCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer); + + // Light corners + helper.setInvColor(AEColor.Transparent.mediumVariant); + helper.renderInventoryFace(this.lightCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer); + + // Main face + helper.setInvColor(AEColor.Transparent.whiteVariant); + helper.renderInventoryFace( + CableBusTextures.PartConversionMonitor_Bright.getIcon(), ForgeDirection.SOUTH, renderer); + + // Phial + helper.setInvColor(AEColor.Black.blackVariant); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer); + + // Cable lights + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderInventoryBusLights(helper, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator tessellator = Tessellator.instance; + + IIcon side = BlockTextureManager.ARCANE_CRAFTING_TERMINAL.getTextures()[3]; + + // Main block + helper.setTexture(side, side, side, side, side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); + + // Light up if active + if (this.isActive()) { + Tessellator.instance.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + } + + // Dark corners + tessellator.setColorOpaque_I(this.getHost().getColor().blackVariant); + helper.renderFace(x, y, z, this.darkCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer); + + // Light corners + tessellator.setColorOpaque_I(this.getHost().getColor().mediumVariant); + helper.renderFace(x, y, z, this.lightCornerTexture.getIcon(), ForgeDirection.SOUTH, renderer); + + // Main face + tessellator.setColorOpaque_I(this.getHost().getColor().whiteVariant); + helper.renderFace( + x, y, z, CableBusTextures.PartConversionMonitor_Bright.getIcon(), ForgeDirection.SOUTH, renderer); + + // Phial + if (!this.trackedEssentia.isValid()) { + tessellator.setColorOpaque_I(this.getHost().getColor().mediumVariant); + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer); + } + + // Cable lights + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } + + /** + * Needs dynamic renderer. + */ + @Override + public boolean requireDynamicRender() { + return true; + } + + @Override + public boolean showNetworkInfo(final MovingObjectPosition where) { + return false; + } + + /** + * Called when a new watcher is provided. + */ + @Override + public void updateWatcher(final IEssentiaWatcher newWatcher) { + // Set the watcher + this.essentiaWatcher = newWatcher; + + // Configure it + this.configureWatcher(); + } + + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only save on world + if (saveType != PartItemStack.World) { + return; + } + + // Write locked + if (this.monitorLocked) { + data.setBoolean(PartEssentiaStorageMonitor.NBT_KEY_LOCKED, this.monitorLocked); + } + + // Write tracked data if valid + if (this.trackedEssentia.isValid()) { + // Write the aspect + data.setString( + PartEssentiaStorageMonitor.NBT_KEY_TRACKED_ASPECT, + this.trackedEssentia.getAspectStack().getAspectTag()); + } + } + + @Override + public void writeToStream(final ByteBuf stream) throws IOException { + // Call super + super.writeToStream(stream); + + // Write locked + stream.writeBoolean(this.monitorLocked); + + // Write if valid + stream.writeBoolean(this.trackedEssentia.isValid()); + + if (this.trackedEssentia.isValid()) { + // Write the tracker + ByteBufUtils.writeTag(stream, this.trackedEssentia.getAspectStack().writeToNBT(new NBTTagCompound())); + } + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartEssentiaTerminal.java b/src/main/java/thaumicenergistics/common/parts/PartEssentiaTerminal.java index f3ce1319..218c1995 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartEssentiaTerminal.java +++ b/src/main/java/thaumicenergistics/common/parts/PartEssentiaTerminal.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.parts; -import java.util.ArrayList; -import java.util.List; import appeng.api.config.Settings; import appeng.api.config.ViewItems; import appeng.api.parts.IPartCollisionHelper; @@ -15,6 +13,8 @@ import appeng.api.util.IConfigManager; import appeng.util.Platform; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -45,430 +45,392 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class PartEssentiaTerminal - extends ThERotateablePart - implements ICraftingIssuerHost -{ - - /** - * How much AE power is required to keep the part active. - */ - private static final double IDLE_POWER_DRAIN = 0.5D; - - /** - * NBT Keys - */ - private static final String NBT_KEY_SORT_MODE = "sortMode", NBT_KEY_INVENTORY = "slots", NBT_KEY_VIEW_MODE = "ViewMode"; - - /** - * Default sorting mode for the terminal. - */ - private static final AspectStackComparatorMode DEFAULT_SORT_MODE = AspectStackComparatorMode.MODE_ALPHABETIC; - - /** - * Default view mode for the terminal. - */ - private static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; - - /** - * List of currently opened containers. - */ - private List listeners = new ArrayList(); - - /** - * The sorting mode used to display aspects. - */ - private AspectStackComparatorMode sortMode = DEFAULT_SORT_MODE; - - /** - * The viewing mode used to display aspects. - */ - private ViewItems viewMode = DEFAULT_VIEW_MODE; - - /** - * The selected aspect in the GUI. - * Only stored while the part is loaded. - */ - public Aspect selectedAspect = null; - - private TheInternalInventory inventory = new TheInternalInventory( ThaumicEnergistics.MOD_ID + ".part.aspect.terminal", 2, 64 ) - { - @Override - public boolean isItemValidForSlot( final int slotId, final ItemStack itemStack ) - { - // Get the type - AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType( itemStack ); - - // True if jar or jar label - return ( iType == AspectItemType.EssentiaContainer ) || ( iType == AspectItemType.JarLabel ); - } - }; - - public PartEssentiaTerminal() - { - super( AEPartsEnum.EssentiaTerminal ); - } - - /** - * Informs all open containers to update their respective clients - * that the mode has changed. - */ - private void notifyListenersOfModeChanged() - { - for( ContainerEssentiaTerminal listener : this.listeners ) - { - listener.onModeChanged( this.sortMode, this.viewMode ); - } - } - - public void addListener( final ContainerEssentiaCellTerminalBase container ) - { - if( container instanceof ContainerEssentiaTerminal ) - { - this.listeners.add( (ContainerEssentiaTerminal)container ); - } - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - helper.addBox( 2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D ); - - helper.addBox( 4.0D, 4.0D, 13.0D, 12.0D, 12.0D, 14.0D ); - - helper.addBox( 5.0D, 5.0D, 12.0D, 11.0D, 11.0D, 13.0D ); - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; - } - - @Override - public Object getClientGuiElement( final EntityPlayer player ) - { - return GuiEssentiaCellTerminal.NewEssentiaTerminalGui( this, player ); - } - - @Override - public IConfigManager getConfigManager() - { - return null; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - // Inventory is saved when wrenched. - if( wrenched ) - { - return; - } - - // Loop over inventory - for( int slotIndex = 0; slotIndex < 2; slotIndex++ ) - { - // Get the stack at this index - ItemStack slotStack = this.inventory.getStackInSlot( slotIndex ); - - // Did we get anything? - if( slotStack != null ) - { - // Add to drops - drops.add( slotStack ); - } - } - } - - @Override - public IMEMonitor getFluidInventory() - { - // Ignored - return null; - } - - @Override - public ItemStack getIcon() - { - return this.associatedItem; - } - - /** - * Determines how much power the part takes for just - * existing. - */ - @Override - public double getIdlePowerUsage() - { - return PartEssentiaTerminal.IDLE_POWER_DRAIN; - } - - public TheInternalInventory getInventory() - { - return this.inventory; - } - - @Override - public IMEMonitor getItemInventory() - { - return this.getGridBlock().getItemMonitor(); - } - - /** - * Light level based on if terminal is active. - */ - @Override - public int getLightLevel() - { - return( this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0 ); - } - - @Override - public Object getServerGuiElement( final EntityPlayer player ) - { - return new ContainerEssentiaTerminal( this, player ); - } - - /** - * Gets the current sorting mode - * - * @return - */ - public AspectStackComparatorMode getSortingMode() - { - return this.sortMode; - } - - /** - * Gets the view mode. - * - * @return - */ - public ViewItems getViewMode() - { - return this.viewMode; - } - - @Override - public void launchGUI( final EntityPlayer player ) - { - TileEntity host = this.getHostTile(); - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Launch the gui - ThEGuiHandler.launchGui( this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); - } - else - { - // Ask the server to change the GUI - Packet_S_ChangeGui.sendGuiChangeToPart( this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord ); - } - } - - /** - * Called when a player has changed sorting modes. - * - * @param sortMode - */ - public void onClientRequestSortingModeChange( final boolean backwards ) - { - // Change the sorting mode - if( backwards ) - { - this.sortMode = this.sortMode.previousMode(); - } - else - { - this.sortMode = this.sortMode.nextMode(); - } - - // Update clients - this.notifyListenersOfModeChanged(); - - // Mark that we need saving - this.markForSave(); - - } - - /** - * Called when a player has changed viewing modes. - */ - public void onClientRequestViewModeChange( final boolean backwards ) - { - // Change the view mode - this.viewMode = Platform.rotateEnum( this.viewMode, backwards, Settings.VIEW_MODE.getPossibleValues() ); - - // Update clients - this.notifyListenersOfModeChanged(); - - // Mark for save - this.markForSave(); - } - - /** - * Called to read our saved state - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read the sorting mode - if( data.hasKey( NBT_KEY_SORT_MODE ) ) - { - this.sortMode = AspectStackComparatorMode.VALUES[data.getInteger( NBT_KEY_SORT_MODE )]; - } - - // Read inventory - if( data.hasKey( PartEssentiaTerminal.NBT_KEY_INVENTORY ) ) - { - this.inventory.readFromNBT( data, PartEssentiaTerminal.NBT_KEY_INVENTORY ); - } - - // Read view mode - if( data.hasKey( NBT_KEY_VIEW_MODE ) ) - { - this.viewMode = EnumCache.AE_VIEW_ITEMS[data.getInteger( NBT_KEY_VIEW_MODE )]; - } - } - - public void removeListener( final ContainerEssentiaTerminal containerAspectTerminal ) - { - this.listeners.remove( containerAspectTerminal ); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; - - IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; - - helper.setTexture( side ); - helper.setBounds( 4.0F, 4.0F, 13.0F, 12.0F, 12.0F, 14.0F ); - helper.renderInventoryBox( renderer ); - - helper.setTexture( side, side, side, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - ts.setBrightness( 0xD000D0 ); - - helper.setInvColor( 0xFFFFFF ); - - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], ForgeDirection.SOUTH, renderer ); - - helper.setBounds( 3.0F, 3.0F, 15.0F, 13.0F, 13.0F, 16.0F ); - - helper.setInvColor( AEColor.Transparent.blackVariant ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer ); - - helper.setInvColor( AEColor.Transparent.mediumVariant ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer ); - - helper.setInvColor( AEColor.Transparent.whiteVariant ); - helper.renderInventoryFace( BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer ); - - helper.setBounds( 5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F ); - this.renderInventoryBusLights( helper, renderer ); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator ts = Tessellator.instance; - - IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; - - // Cable connector - helper.setTexture( side ); - helper.setBounds( 4.0F, 4.0F, 13.0F, 12.0F, 12.0F, 14.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Mid-block - helper.setTexture( side, side, side, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], side, side ); - helper.setBounds( 2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Light up if active - if( this.isActive() ) - { - Tessellator.instance.setBrightness( ThEPartBase.ACTIVE_FACE_BRIGHTNESS ); - } - - // Rotate the face texture - this.rotateRenderer( renderer, false ); - - // Base face - ts.setColorOpaque_I( 0xFFFFFF ); - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], ForgeDirection.SOUTH, renderer ); - - // Dark colored face - helper.setBounds( 3.0F, 3.0F, 15.0F, 13.0F, 13.0F, 16.0F ); - ts.setColorOpaque_I( this.getHost().getColor().blackVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer ); - - // Standard colored face - ts.setColorOpaque_I( this.getHost().getColor().mediumVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer ); - - // Light colored face - ts.setColorOpaque_I( this.getHost().getColor().whiteVariant ); - helper.renderFace( x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer ); - - // Reset rotation - this.rotateRenderer( renderer, true ); - - // Cable lights - helper.setBounds( 5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - - } - - /** - * Called to save our state - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only write NBT data if saving, or wrenched. - if( ( saveType != PartItemStack.World ) && ( saveType != PartItemStack.Wrench ) ) - { - return; - } - - // Write the sorting mode - if( this.sortMode != DEFAULT_SORT_MODE ) - { - data.setInteger( NBT_KEY_SORT_MODE, this.sortMode.ordinal() ); - } - - // Write inventory - if( !this.inventory.isEmpty() ) - { - this.inventory.writeToNBT( data, NBT_KEY_INVENTORY ); - } - - // Write view mode - if( this.viewMode != DEFAULT_VIEW_MODE ) - { - data.setInteger( NBT_KEY_VIEW_MODE, this.viewMode.ordinal() ); - } - } - +public class PartEssentiaTerminal extends ThERotateablePart implements ICraftingIssuerHost { + + /** + * How much AE power is required to keep the part active. + */ + private static final double IDLE_POWER_DRAIN = 0.5D; + + /** + * NBT Keys + */ + private static final String NBT_KEY_SORT_MODE = "sortMode", + NBT_KEY_INVENTORY = "slots", + NBT_KEY_VIEW_MODE = "ViewMode"; + + /** + * Default sorting mode for the terminal. + */ + private static final AspectStackComparatorMode DEFAULT_SORT_MODE = AspectStackComparatorMode.MODE_ALPHABETIC; + + /** + * Default view mode for the terminal. + */ + private static final ViewItems DEFAULT_VIEW_MODE = ViewItems.ALL; + + /** + * List of currently opened containers. + */ + private List listeners = new ArrayList(); + + /** + * The sorting mode used to display aspects. + */ + private AspectStackComparatorMode sortMode = DEFAULT_SORT_MODE; + + /** + * The viewing mode used to display aspects. + */ + private ViewItems viewMode = DEFAULT_VIEW_MODE; + + /** + * The selected aspect in the GUI. + * Only stored while the part is loaded. + */ + public Aspect selectedAspect = null; + + private TheInternalInventory inventory = + new TheInternalInventory(ThaumicEnergistics.MOD_ID + ".part.aspect.terminal", 2, 64) { + @Override + public boolean isItemValidForSlot(final int slotId, final ItemStack itemStack) { + // Get the type + AspectItemType iType = EssentiaItemContainerHelper.INSTANCE.getItemType(itemStack); + + // True if jar or jar label + return (iType == AspectItemType.EssentiaContainer) || (iType == AspectItemType.JarLabel); + } + }; + + public PartEssentiaTerminal() { + super(AEPartsEnum.EssentiaTerminal); + } + + /** + * Informs all open containers to update their respective clients + * that the mode has changed. + */ + private void notifyListenersOfModeChanged() { + for (ContainerEssentiaTerminal listener : this.listeners) { + listener.onModeChanged(this.sortMode, this.viewMode); + } + } + + public void addListener(final ContainerEssentiaCellTerminalBase container) { + if (container instanceof ContainerEssentiaTerminal) { + this.listeners.add((ContainerEssentiaTerminal) container); + } + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + @Override + public void getBoxes(final IPartCollisionHelper helper) { + helper.addBox(2.0D, 2.0D, 14.0D, 14.0D, 14.0D, 16.0D); + + helper.addBox(4.0D, 4.0D, 13.0D, 12.0D, 12.0D, 14.0D); + + helper.addBox(5.0D, 5.0D, 12.0D, 11.0D, 11.0D, 13.0D); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; + } + + @Override + public Object getClientGuiElement(final EntityPlayer player) { + return GuiEssentiaCellTerminal.NewEssentiaTerminalGui(this, player); + } + + @Override + public IConfigManager getConfigManager() { + return null; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + // Inventory is saved when wrenched. + if (wrenched) { + return; + } + + // Loop over inventory + for (int slotIndex = 0; slotIndex < 2; slotIndex++) { + // Get the stack at this index + ItemStack slotStack = this.inventory.getStackInSlot(slotIndex); + + // Did we get anything? + if (slotStack != null) { + // Add to drops + drops.add(slotStack); + } + } + } + + @Override + public IMEMonitor getFluidInventory() { + // Ignored + return null; + } + + @Override + public ItemStack getIcon() { + return this.associatedItem; + } + + /** + * Determines how much power the part takes for just + * existing. + */ + @Override + public double getIdlePowerUsage() { + return PartEssentiaTerminal.IDLE_POWER_DRAIN; + } + + public TheInternalInventory getInventory() { + return this.inventory; + } + + @Override + public IMEMonitor getItemInventory() { + return this.getGridBlock().getItemMonitor(); + } + + /** + * Light level based on if terminal is active. + */ + @Override + public int getLightLevel() { + return (this.isActive() ? ThEPartBase.ACTIVE_TERMINAL_LIGHT_LEVEL : 0); + } + + @Override + public Object getServerGuiElement(final EntityPlayer player) { + return new ContainerEssentiaTerminal(this, player); + } + + /** + * Gets the current sorting mode + * + * @return + */ + public AspectStackComparatorMode getSortingMode() { + return this.sortMode; + } + + /** + * Gets the view mode. + * + * @return + */ + public ViewItems getViewMode() { + return this.viewMode; + } + + @Override + public void launchGUI(final EntityPlayer player) { + TileEntity host = this.getHostTile(); + + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Launch the gui + ThEGuiHandler.launchGui(this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord); + } else { + // Ask the server to change the GUI + Packet_S_ChangeGui.sendGuiChangeToPart( + this, player, host.getWorldObj(), host.xCoord, host.yCoord, host.zCoord); + } + } + + /** + * Called when a player has changed sorting modes. + * + * @param sortMode + */ + public void onClientRequestSortingModeChange(final boolean backwards) { + // Change the sorting mode + if (backwards) { + this.sortMode = this.sortMode.previousMode(); + } else { + this.sortMode = this.sortMode.nextMode(); + } + + // Update clients + this.notifyListenersOfModeChanged(); + + // Mark that we need saving + this.markForSave(); + } + + /** + * Called when a player has changed viewing modes. + */ + public void onClientRequestViewModeChange(final boolean backwards) { + // Change the view mode + this.viewMode = Platform.rotateEnum(this.viewMode, backwards, Settings.VIEW_MODE.getPossibleValues()); + + // Update clients + this.notifyListenersOfModeChanged(); + + // Mark for save + this.markForSave(); + } + + /** + * Called to read our saved state + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Read the sorting mode + if (data.hasKey(NBT_KEY_SORT_MODE)) { + this.sortMode = AspectStackComparatorMode.VALUES[data.getInteger(NBT_KEY_SORT_MODE)]; + } + + // Read inventory + if (data.hasKey(PartEssentiaTerminal.NBT_KEY_INVENTORY)) { + this.inventory.readFromNBT(data, PartEssentiaTerminal.NBT_KEY_INVENTORY); + } + + // Read view mode + if (data.hasKey(NBT_KEY_VIEW_MODE)) { + this.viewMode = EnumCache.AE_VIEW_ITEMS[data.getInteger(NBT_KEY_VIEW_MODE)]; + } + } + + public void removeListener(final ContainerEssentiaTerminal containerAspectTerminal) { + this.listeners.remove(containerAspectTerminal); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; + + helper.setTexture(side); + helper.setBounds(4.0F, 4.0F, 13.0F, 12.0F, 12.0F, 14.0F); + helper.renderInventoryBox(renderer); + + helper.setTexture( + side, side, side, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderInventoryBox(renderer); + + ts.setBrightness(0xD000D0); + + helper.setInvColor(0xFFFFFF); + + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], ForgeDirection.SOUTH, renderer); + + helper.setBounds(3.0F, 3.0F, 15.0F, 13.0F, 13.0F, 16.0F); + + helper.setInvColor(AEColor.Transparent.blackVariant); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer); + + helper.setInvColor(AEColor.Transparent.mediumVariant); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer); + + helper.setInvColor(AEColor.Transparent.whiteVariant); + helper.renderInventoryFace( + BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer); + + helper.setBounds(5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F); + this.renderInventoryBusLights(helper, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[3]; + + // Cable connector + helper.setTexture(side); + helper.setBounds(4.0F, 4.0F, 13.0F, 12.0F, 12.0F, 14.0F); + helper.renderBlock(x, y, z, renderer); + + // Mid-block + helper.setTexture( + side, side, side, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], side, side); + helper.setBounds(2.0F, 2.0F, 14.0F, 14.0F, 14.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); + + // Light up if active + if (this.isActive()) { + Tessellator.instance.setBrightness(ThEPartBase.ACTIVE_FACE_BRIGHTNESS); + } + + // Rotate the face texture + this.rotateRenderer(renderer, false); + + // Base face + ts.setColorOpaque_I(0xFFFFFF); + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[4], ForgeDirection.SOUTH, renderer); + + // Dark colored face + helper.setBounds(3.0F, 3.0F, 15.0F, 13.0F, 13.0F, 16.0F); + ts.setColorOpaque_I(this.getHost().getColor().blackVariant); + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[0], ForgeDirection.SOUTH, renderer); + + // Standard colored face + ts.setColorOpaque_I(this.getHost().getColor().mediumVariant); + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[1], ForgeDirection.SOUTH, renderer); + + // Light colored face + ts.setColorOpaque_I(this.getHost().getColor().whiteVariant); + helper.renderFace( + x, y, z, BlockTextureManager.ESSENTIA_TERMINAL.getTextures()[2], ForgeDirection.SOUTH, renderer); + + // Reset rotation + this.rotateRenderer(renderer, true); + + // Cable lights + helper.setBounds(5.0F, 5.0F, 12.0F, 11.0F, 11.0F, 13.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } + + /** + * Called to save our state + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only write NBT data if saving, or wrenched. + if ((saveType != PartItemStack.World) && (saveType != PartItemStack.Wrench)) { + return; + } + + // Write the sorting mode + if (this.sortMode != DEFAULT_SORT_MODE) { + data.setInteger(NBT_KEY_SORT_MODE, this.sortMode.ordinal()); + } + + // Write inventory + if (!this.inventory.isEmpty()) { + this.inventory.writeToNBT(data, NBT_KEY_INVENTORY); + } + + // Write view mode + if (this.viewMode != DEFAULT_VIEW_MODE) { + data.setInteger(NBT_KEY_VIEW_MODE, this.viewMode.ordinal()); + } + } } diff --git a/src/main/java/thaumicenergistics/common/parts/PartVisInterface.java b/src/main/java/thaumicenergistics/common/parts/PartVisInterface.java index 4c3c054c..fdb2992e 100644 --- a/src/main/java/thaumicenergistics/common/parts/PartVisInterface.java +++ b/src/main/java/thaumicenergistics/common/parts/PartVisInterface.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.parts; -import java.io.IOException; -import java.lang.ref.WeakReference; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.implementations.items.IMemoryCard; @@ -18,6 +16,8 @@ import appeng.api.parts.PartItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.lang.ref.WeakReference; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; @@ -41,742 +41,658 @@ import thaumicenergistics.common.integration.tc.VisProviderProxy; * @author Nividica * */ -public class PartVisInterface - extends ThEPartBase - implements IGridTickable, IDigiVisSource -{ - /** - * NBT key for the unique ID - */ - private static final String NBT_KEY_UID = "uid"; - - /** - * NBT key for if the interface is a source or not. - */ - private static final String NBT_KEY_IS_PROVIDER = "isProvider"; - - /** - * NBT key for the source of this provider. - */ - private static final String NBT_KEY_PROVIDER_SOURCE = "linkedSource"; - - /** - * The amount of time to display the color when not receiving updates - */ - private static final int TIME_TO_CLEAR = 500; - - /** - * The amount of power to use per each vis of a request. - * The amount of vis doesn't matter. - */ - private static final int POWER_PER_REQUESTED_VIS = 4; - - /** - * Unique ID for this interface - */ - private long UID = 0; - - /** - * The aspect color we are currently draining - */ - private int visDrainingColor = 0; - - /** - * The last time the color was refreshed. - */ - private long lastColorUpdate = 0; - - /** - * Cached reference to the relay we are facing. - */ - private WeakReference cachedRelay = new WeakReference( null ); - - /** - * True if this end of the P2P is a vis provider. - */ - private boolean isProvider = false; - - /** - * If this end is a provider, this stores the source. - */ - private DigiVisSourceData visP2PSourceInfo = new DigiVisSourceData(); - - /** - * If this end is a provider, this interacts with the vis network. - */ - private VisProviderProxy visProviderSubTile = null; - - /** - * Creates the interface. - */ - public PartVisInterface() - { - super( AEPartsEnum.VisInterface ); - - this.UID = System.currentTimeMillis() ^ this.hashCode(); - } - - /** - * Requests that the interface drain vis from the relay - * - * @param digiVisAspect - * @param amount - * @return - */ - private int consumeVisFromVisNetwork( final Aspect digiVisAspect, final int amount ) - { - // Get the relay - TileVisRelay visRelay = this.getRelay(); - - // Ensure there is a relay - if( visRelay == null ) - { - return 0; - } - - // Get the power grid - IEnergyGrid eGrid = this.getGridBlock().getEnergyGrid(); - - // Ensure we got the grid - if( eGrid == null ) - { - return 0; - } - - // Simulate a power drain - double drainedPower = eGrid.extractAEPower( PartVisInterface.POWER_PER_REQUESTED_VIS, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - // Ensure we got the power we need - if( drainedPower < PartVisInterface.POWER_PER_REQUESTED_VIS ) - { - return 0; - } - - // Ask it for vis - int amountReceived = visRelay.consumeVis( digiVisAspect, amount ); - - // Did we get any vis? - if( amountReceived > 0 ) - { - // Drain the power - eGrid.extractAEPower( PartVisInterface.POWER_PER_REQUESTED_VIS, Actionable.MODULATE, PowerMultiplier.CONFIG ); - } - - // Return the amount we received - return amountReceived; - } - - /** - * Verifies that a p2p source is valid - * - * @return - */ - private boolean isP2PSourceValid() - { - // Is there anything even linked to? - if( !this.visP2PSourceInfo.hasSourceData() ) - { - return false; - } - - // Get the source - IDigiVisSource p2pSource = this.visP2PSourceInfo.tryGetSource( this.getGrid() ); - - // There must be source data - if( p2pSource == null ) - { - return false; - } - - // Source must be a vis interface - if( !( p2pSource instanceof PartVisInterface ) ) - { - return false; - } - - // Can't link to self - if( this.equals( p2pSource ) ) - { - return false; - } - - // Source must not be a provider - if( ( (PartVisInterface)p2pSource ).isVisProvider() ) - { - return false; - } - - // Source seems valid - return true; - } - - /** - * Sets the color we are draining. - * - * @param color - */ - private void setDrainColor( final int color ) - { - - // Are we setting the color? - if( color != 0 ) - { - // Does it match what we already have? - if( color == this.visDrainingColor ) - { - // Set the update time - this.lastColorUpdate = System.currentTimeMillis(); - - return; - } - - // Has the alloted time passed for a change? - if( ( System.currentTimeMillis() - this.lastColorUpdate ) <= ( PartVisInterface.TIME_TO_CLEAR / 2 ) ) - { - return; - } - - // Set the update time - this.lastColorUpdate = System.currentTimeMillis(); - - } - - // Set the color - this.visDrainingColor = color; - - // Update - this.markForUpdate(); - } - - private void setIsVisProvider( final boolean isProviding ) - { - - // Is the interface to be a provider? - if( !isProviding ) - { - // Clear the source info - this.visP2PSourceInfo.clearData(); - - // Null the subtile - if( this.visProviderSubTile != null ) - { - this.visProviderSubTile.invalidate(); - this.visProviderSubTile = null; - } - - } - - this.isProvider = isProviding; - - } - - /** - * How far to extend the cable. - */ - @Override - public int cableConnectionRenderTo() - { - return 2; - } - - /** - * Drains vis from either the vis relay network, or from the p2p source. - * - * @param digiVisAspect - * @param amount - * @return - */ - @Override - public int consumeVis( final Aspect digiVisAspect, final int amount ) - { - // Ensure the interface is active - if( !this.isActive() ) - { - return 0; - } - - int amountReceived = 0; - - // Is the interface a provider? - if( this.isProvider ) - { - if( this.isP2PSourceValid() ) - { - // Get the p2p source - IDigiVisSource source = this.visP2PSourceInfo.tryGetSource( this.getGrid() ); - - // Ask the source for vis - amountReceived = source.consumeVis( digiVisAspect, amount ); - } - } - else - { - amountReceived = this.consumeVisFromVisNetwork( digiVisAspect, amount ); - } - - // Was any vis received? - if( amountReceived > 0 ) - { - // Set the color - this.setDrainColor( digiVisAspect.getColor() ); - } - - return amountReceived; - } - - /** - * Hit boxes. - */ - @Override - public void getBoxes( final IPartCollisionHelper helper ) - { - // Face - helper.addBox( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - - // Mid - helper.addBox( 4.0D, 4.0D, 14.0D, 12.0D, 12.0D, 15.0D ); - - // Back - helper.addBox( 5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D ); - - } - - @Override - public IIcon getBreakingTexture() - { - return BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[0]; - } - - /** - * Gets the grid the interface is attached to - * - * @return - */ - @Override - public IGrid getGrid() - { - // Ensure the interface has a gridblock - if( this.getGridBlock() == null ) - { - return null; - } - - // Return the grid - return this.getGridBlock().getGrid(); - } - - /** - * No idle power usage. - */ - @Override - public double getIdlePowerUsage() - { - return 0; - } - - /** - * Produces a small amount of light. - */ - @Override - public int getLightLevel() - { - return 8; - } - - /** - * Gets the relay the interface is facing. If any. - * - * @return - */ - public TileVisRelay getRelay() - { - // Get the cached relay - TileVisRelay tVR = this.cachedRelay.get(); - - // Is there a cached relay? - if( tVR != null ) - { - // Ensure it is still there - if( tVR == this.getHostTile().getWorldObj().getTileEntity( tVR.xCoord, tVR.yCoord, tVR.zCoord ) ) - { - return tVR; - } - } - - // Get the tile we are facing - TileEntity facingTile = this.getFacingTile(); - - // Is it a relay? - if( facingTile instanceof TileVisRelay ) - { - // Get the relay - tVR = (TileVisRelay)facingTile; - - // Is it facing the same direction as we are? - if( tVR.orientation == this.getSide().ordinal() ) - { - // Set the cache - this.cachedRelay = new WeakReference( tVR ); - - // Return it - return tVR; - } - } - - return null; - } - - /** - * How often should we tick? - */ - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( 30, 30, false, false ); - } - - /** - * Gets the unique ID for this interface - * - * @return - */ - @Override - public long getUID() - { - return this.UID; - } - - /** - * Is the interface on and active? - * - * @return - */ - @Override - public boolean isActive() - { - return super.isActive(); - } - - public Boolean isVisProvider() - { - return this.isProvider; - } - - /** - * Player right-clicked the interface. - */ - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - // Get what the player is holding - ItemStack playerHolding = player.inventory.getCurrentItem(); - - // Are they holding a memory card? - if( ( playerHolding != null ) && ( playerHolding.getItem() instanceof IMemoryCard ) ) - { - // Get the memory card - IMemoryCard memoryCard = (IMemoryCard)playerHolding.getItem(); - - // Get the stored name - String settingsName = memoryCard.getSettingsName( playerHolding ); - - // Does it contain the data about a vis source? - if( settingsName.equals( DigiVisSourceData.SOURCE_UNLOC_NAME ) ) - { - // Get the data - NBTTagCompound data = memoryCard.getData( playerHolding ); - - // Load the info - this.visP2PSourceInfo.readFromNBT( data ); - - // Ensure there is valid data - if( this.visP2PSourceInfo.hasSourceData() ) - { - // Can the link be established? - if( !this.isP2PSourceValid() ) - { - // Unable to link - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - - // Clear the source data - this.visP2PSourceInfo.clearData(); - } - else - { - // Mark that we are now a provider - this.setIsVisProvider( true ); - - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - } - - // Mark for a save - this.markForSave(); - } - // Is the memory card empty? - else if( settingsName.equals( "gui.appliedenergistics2.Blank" ) && this.isProvider ) - { - // Mark that we are not a provider - this.setIsVisProvider( false ); - - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - - // Mark for save - this.markForSave(); - } - - return true; - } - - return false; - } - - /** - * Player shift-right-clicked the interface. - */ - @Override - public boolean onShiftActivate( final EntityPlayer player, final Vec3 position ) - { - // Get what the player is holding - ItemStack playerHolding = player.inventory.getCurrentItem(); - - // Are they holding a memory card? - if( ( playerHolding != null ) && ( playerHolding.getItem() instanceof IMemoryCard ) ) - { - // Get the memory card - IMemoryCard memoryCard = (IMemoryCard)playerHolding.getItem(); - - // Create the info data - DigiVisSourceData data = new DigiVisSourceData( this ); - - // Write into the memory card - memoryCard.setMemoryCardContents( playerHolding, DigiVisSourceData.SOURCE_UNLOC_NAME, data.writeToNBT() ); - - // Notify the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - - // Mark that we are not a provider - this.setIsVisProvider( false ); - - // Mark for save - this.markForSave(); - - return true; - } - - return false; - } - - /** - * Reads the interface data from the tag - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Does it contain the UID? - if( data.hasKey( PartVisInterface.NBT_KEY_UID ) ) - { - // Read the UID - this.UID = data.getLong( PartVisInterface.NBT_KEY_UID ); - } - - // Is there provider data? - if( data.hasKey( PartVisInterface.NBT_KEY_IS_PROVIDER ) ) - { - // Set provider status - this.isProvider = data.getBoolean( PartVisInterface.NBT_KEY_IS_PROVIDER ); - - // Read source information - if( data.hasKey( PartVisInterface.NBT_KEY_PROVIDER_SOURCE ) ) - { - this.visP2PSourceInfo.readFromNBT( data, PartVisInterface.NBT_KEY_PROVIDER_SOURCE ); - } - } - } - - /** - * Reads server-sent data - */ - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - boolean redraw = false; - - // Call super - redraw |= super.readFromStream( data ); - - // Cache old color - int oldColor = this.visDrainingColor; - - // Read the drain color - this.visDrainingColor = data.readInt(); - - // Redraw if colors changed - redraw |= ( this.visDrainingColor != oldColor ); - - return redraw; - - } - - /** - * Draws the interface in the inventory. - */ - @Override - @SideOnly(Side.CLIENT) - public void renderInventory( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - IIcon side = BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[2]; - helper.setTexture( side, side, side, BlockTextureManager.VIS_RELAY_INTERFACE.getTexture(), side, side ); - - // Face - helper.setBounds( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - helper.renderInventoryBox( renderer ); - - // Mid - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderInventoryBox( renderer ); - - // Back - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderInventoryBusLights( helper, renderer ); - - } - - /** - * Draws the interface in the world. - */ - @Override - @SideOnly(Side.CLIENT) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - Tessellator tessellator = Tessellator.instance; - - IIcon side = BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[2]; - helper.setTexture( side, side, side, BlockTextureManager.VIS_RELAY_INTERFACE.getTexture(), side, side ); - - // Face - helper.setBounds( 6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F ); - helper.renderBlock( x, y, z, renderer ); - - // Mid - helper.setBounds( 4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F ); - helper.renderBlock( x, y, z, renderer );// Mid face - - if( this.visDrainingColor != 0 ) - { - tessellator.setColorOpaque_I( this.visDrainingColor ); - helper.renderFace( x, y, z, BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[1], ForgeDirection.SOUTH, renderer ); - } - - // Back (facing bus) - helper.setBounds( 5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F ); - this.renderStaticBusLights( x, y, z, helper, renderer ); - } - - /** - * Called when the interface ticks - */ - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - if( this.visDrainingColor != 0 ) - { - if( ( System.currentTimeMillis() - this.lastColorUpdate ) > PartVisInterface.TIME_TO_CLEAR ) - { - this.setDrainColor( 0 ); - } - } - - // Is the interface a provider? - if( this.isProvider ) - { - boolean hasProvider = ( this.visProviderSubTile != null ); - - // Validate the P2P Settings - if( !this.isP2PSourceValid() ) - { - // Invalid source, remove provider - if( hasProvider ) - { - this.visProviderSubTile.invalidate(); - this.visProviderSubTile = null; - } - } - else - { - boolean hasRelay = ( this.getRelay() != null ); - - // Invalid: Can't have a provider without a relay - if( !hasRelay && hasProvider ) - { - // Remove the provider - this.visProviderSubTile.invalidate(); - this.visProviderSubTile = null; - } - // Has relay but no provider - else if( hasRelay && !hasProvider ) - { - // Create the provider - this.visProviderSubTile = new VisProviderProxy( this ); - - // Register the provider - VisNetHandler.addSource( this.getHostTile().getWorldObj(), this.visProviderSubTile ); - } - else if( hasProvider ) - { - this.visProviderSubTile.updateEntity(); - } - } - } - - return TickRateModulation.SAME; - } - - /** - * Write the interface data to the tag - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - // Only write NBT if world save - if( saveType != PartItemStack.World ) - { - return; - } - - // Write the UID - data.setLong( PartVisInterface.NBT_KEY_UID, this.UID ); - - if( this.isProvider ) - { - // Write provider status - data.setBoolean( PartVisInterface.NBT_KEY_IS_PROVIDER, this.isProvider ); - - // Write source data - this.visP2PSourceInfo.writeToNBT( data, PartVisInterface.NBT_KEY_PROVIDER_SOURCE ); - } - - } - - /** - * Sends data to the client - */ - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - // Call super - super.writeToStream( data ); - - // Write the drain color - data.writeInt( this.visDrainingColor ); - } - +public class PartVisInterface extends ThEPartBase implements IGridTickable, IDigiVisSource { + /** + * NBT key for the unique ID + */ + private static final String NBT_KEY_UID = "uid"; + + /** + * NBT key for if the interface is a source or not. + */ + private static final String NBT_KEY_IS_PROVIDER = "isProvider"; + + /** + * NBT key for the source of this provider. + */ + private static final String NBT_KEY_PROVIDER_SOURCE = "linkedSource"; + + /** + * The amount of time to display the color when not receiving updates + */ + private static final int TIME_TO_CLEAR = 500; + + /** + * The amount of power to use per each vis of a request. + * The amount of vis doesn't matter. + */ + private static final int POWER_PER_REQUESTED_VIS = 4; + + /** + * Unique ID for this interface + */ + private long UID = 0; + + /** + * The aspect color we are currently draining + */ + private int visDrainingColor = 0; + + /** + * The last time the color was refreshed. + */ + private long lastColorUpdate = 0; + + /** + * Cached reference to the relay we are facing. + */ + private WeakReference cachedRelay = new WeakReference(null); + + /** + * True if this end of the P2P is a vis provider. + */ + private boolean isProvider = false; + + /** + * If this end is a provider, this stores the source. + */ + private DigiVisSourceData visP2PSourceInfo = new DigiVisSourceData(); + + /** + * If this end is a provider, this interacts with the vis network. + */ + private VisProviderProxy visProviderSubTile = null; + + /** + * Creates the interface. + */ + public PartVisInterface() { + super(AEPartsEnum.VisInterface); + + this.UID = System.currentTimeMillis() ^ this.hashCode(); + } + + /** + * Requests that the interface drain vis from the relay + * + * @param digiVisAspect + * @param amount + * @return + */ + private int consumeVisFromVisNetwork(final Aspect digiVisAspect, final int amount) { + // Get the relay + TileVisRelay visRelay = this.getRelay(); + + // Ensure there is a relay + if (visRelay == null) { + return 0; + } + + // Get the power grid + IEnergyGrid eGrid = this.getGridBlock().getEnergyGrid(); + + // Ensure we got the grid + if (eGrid == null) { + return 0; + } + + // Simulate a power drain + double drainedPower = eGrid.extractAEPower( + PartVisInterface.POWER_PER_REQUESTED_VIS, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + // Ensure we got the power we need + if (drainedPower < PartVisInterface.POWER_PER_REQUESTED_VIS) { + return 0; + } + + // Ask it for vis + int amountReceived = visRelay.consumeVis(digiVisAspect, amount); + + // Did we get any vis? + if (amountReceived > 0) { + // Drain the power + eGrid.extractAEPower(PartVisInterface.POWER_PER_REQUESTED_VIS, Actionable.MODULATE, PowerMultiplier.CONFIG); + } + + // Return the amount we received + return amountReceived; + } + + /** + * Verifies that a p2p source is valid + * + * @return + */ + private boolean isP2PSourceValid() { + // Is there anything even linked to? + if (!this.visP2PSourceInfo.hasSourceData()) { + return false; + } + + // Get the source + IDigiVisSource p2pSource = this.visP2PSourceInfo.tryGetSource(this.getGrid()); + + // There must be source data + if (p2pSource == null) { + return false; + } + + // Source must be a vis interface + if (!(p2pSource instanceof PartVisInterface)) { + return false; + } + + // Can't link to self + if (this.equals(p2pSource)) { + return false; + } + + // Source must not be a provider + if (((PartVisInterface) p2pSource).isVisProvider()) { + return false; + } + + // Source seems valid + return true; + } + + /** + * Sets the color we are draining. + * + * @param color + */ + private void setDrainColor(final int color) { + + // Are we setting the color? + if (color != 0) { + // Does it match what we already have? + if (color == this.visDrainingColor) { + // Set the update time + this.lastColorUpdate = System.currentTimeMillis(); + + return; + } + + // Has the alloted time passed for a change? + if ((System.currentTimeMillis() - this.lastColorUpdate) <= (PartVisInterface.TIME_TO_CLEAR / 2)) { + return; + } + + // Set the update time + this.lastColorUpdate = System.currentTimeMillis(); + } + + // Set the color + this.visDrainingColor = color; + + // Update + this.markForUpdate(); + } + + private void setIsVisProvider(final boolean isProviding) { + + // Is the interface to be a provider? + if (!isProviding) { + // Clear the source info + this.visP2PSourceInfo.clearData(); + + // Null the subtile + if (this.visProviderSubTile != null) { + this.visProviderSubTile.invalidate(); + this.visProviderSubTile = null; + } + } + + this.isProvider = isProviding; + } + + /** + * How far to extend the cable. + */ + @Override + public int cableConnectionRenderTo() { + return 2; + } + + /** + * Drains vis from either the vis relay network, or from the p2p source. + * + * @param digiVisAspect + * @param amount + * @return + */ + @Override + public int consumeVis(final Aspect digiVisAspect, final int amount) { + // Ensure the interface is active + if (!this.isActive()) { + return 0; + } + + int amountReceived = 0; + + // Is the interface a provider? + if (this.isProvider) { + if (this.isP2PSourceValid()) { + // Get the p2p source + IDigiVisSource source = this.visP2PSourceInfo.tryGetSource(this.getGrid()); + + // Ask the source for vis + amountReceived = source.consumeVis(digiVisAspect, amount); + } + } else { + amountReceived = this.consumeVisFromVisNetwork(digiVisAspect, amount); + } + + // Was any vis received? + if (amountReceived > 0) { + // Set the color + this.setDrainColor(digiVisAspect.getColor()); + } + + return amountReceived; + } + + /** + * Hit boxes. + */ + @Override + public void getBoxes(final IPartCollisionHelper helper) { + // Face + helper.addBox(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + + // Mid + helper.addBox(4.0D, 4.0D, 14.0D, 12.0D, 12.0D, 15.0D); + + // Back + helper.addBox(5.0D, 5.0D, 13.0D, 11.0D, 11.0D, 14.0D); + } + + @Override + public IIcon getBreakingTexture() { + return BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[0]; + } + + /** + * Gets the grid the interface is attached to + * + * @return + */ + @Override + public IGrid getGrid() { + // Ensure the interface has a gridblock + if (this.getGridBlock() == null) { + return null; + } + + // Return the grid + return this.getGridBlock().getGrid(); + } + + /** + * No idle power usage. + */ + @Override + public double getIdlePowerUsage() { + return 0; + } + + /** + * Produces a small amount of light. + */ + @Override + public int getLightLevel() { + return 8; + } + + /** + * Gets the relay the interface is facing. If any. + * + * @return + */ + public TileVisRelay getRelay() { + // Get the cached relay + TileVisRelay tVR = this.cachedRelay.get(); + + // Is there a cached relay? + if (tVR != null) { + // Ensure it is still there + if (tVR == this.getHostTile().getWorldObj().getTileEntity(tVR.xCoord, tVR.yCoord, tVR.zCoord)) { + return tVR; + } + } + + // Get the tile we are facing + TileEntity facingTile = this.getFacingTile(); + + // Is it a relay? + if (facingTile instanceof TileVisRelay) { + // Get the relay + tVR = (TileVisRelay) facingTile; + + // Is it facing the same direction as we are? + if (tVR.orientation == this.getSide().ordinal()) { + // Set the cache + this.cachedRelay = new WeakReference(tVR); + + // Return it + return tVR; + } + } + + return null; + } + + /** + * How often should we tick? + */ + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest(30, 30, false, false); + } + + /** + * Gets the unique ID for this interface + * + * @return + */ + @Override + public long getUID() { + return this.UID; + } + + /** + * Is the interface on and active? + * + * @return + */ + @Override + public boolean isActive() { + return super.isActive(); + } + + public Boolean isVisProvider() { + return this.isProvider; + } + + /** + * Player right-clicked the interface. + */ + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + // Get what the player is holding + ItemStack playerHolding = player.inventory.getCurrentItem(); + + // Are they holding a memory card? + if ((playerHolding != null) && (playerHolding.getItem() instanceof IMemoryCard)) { + // Get the memory card + IMemoryCard memoryCard = (IMemoryCard) playerHolding.getItem(); + + // Get the stored name + String settingsName = memoryCard.getSettingsName(playerHolding); + + // Does it contain the data about a vis source? + if (settingsName.equals(DigiVisSourceData.SOURCE_UNLOC_NAME)) { + // Get the data + NBTTagCompound data = memoryCard.getData(playerHolding); + + // Load the info + this.visP2PSourceInfo.readFromNBT(data); + + // Ensure there is valid data + if (this.visP2PSourceInfo.hasSourceData()) { + // Can the link be established? + if (!this.isP2PSourceValid()) { + // Unable to link + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + + // Clear the source data + this.visP2PSourceInfo.clearData(); + } else { + // Mark that we are now a provider + this.setIsVisProvider(true); + + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } + } + + // Mark for a save + this.markForSave(); + } + // Is the memory card empty? + else if (settingsName.equals("gui.appliedenergistics2.Blank") && this.isProvider) { + // Mark that we are not a provider + this.setIsVisProvider(false); + + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + + // Mark for save + this.markForSave(); + } + + return true; + } + + return false; + } + + /** + * Player shift-right-clicked the interface. + */ + @Override + public boolean onShiftActivate(final EntityPlayer player, final Vec3 position) { + // Get what the player is holding + ItemStack playerHolding = player.inventory.getCurrentItem(); + + // Are they holding a memory card? + if ((playerHolding != null) && (playerHolding.getItem() instanceof IMemoryCard)) { + // Get the memory card + IMemoryCard memoryCard = (IMemoryCard) playerHolding.getItem(); + + // Create the info data + DigiVisSourceData data = new DigiVisSourceData(this); + + // Write into the memory card + memoryCard.setMemoryCardContents(playerHolding, DigiVisSourceData.SOURCE_UNLOC_NAME, data.writeToNBT()); + + // Notify the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + + // Mark that we are not a provider + this.setIsVisProvider(false); + + // Mark for save + this.markForSave(); + + return true; + } + + return false; + } + + /** + * Reads the interface data from the tag + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Does it contain the UID? + if (data.hasKey(PartVisInterface.NBT_KEY_UID)) { + // Read the UID + this.UID = data.getLong(PartVisInterface.NBT_KEY_UID); + } + + // Is there provider data? + if (data.hasKey(PartVisInterface.NBT_KEY_IS_PROVIDER)) { + // Set provider status + this.isProvider = data.getBoolean(PartVisInterface.NBT_KEY_IS_PROVIDER); + + // Read source information + if (data.hasKey(PartVisInterface.NBT_KEY_PROVIDER_SOURCE)) { + this.visP2PSourceInfo.readFromNBT(data, PartVisInterface.NBT_KEY_PROVIDER_SOURCE); + } + } + } + + /** + * Reads server-sent data + */ + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + boolean redraw = false; + + // Call super + redraw |= super.readFromStream(data); + + // Cache old color + int oldColor = this.visDrainingColor; + + // Read the drain color + this.visDrainingColor = data.readInt(); + + // Redraw if colors changed + redraw |= (this.visDrainingColor != oldColor); + + return redraw; + } + + /** + * Draws the interface in the inventory. + */ + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper helper, final RenderBlocks renderer) { + IIcon side = BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[2]; + helper.setTexture(side, side, side, BlockTextureManager.VIS_RELAY_INTERFACE.getTexture(), side, side); + + // Face + helper.setBounds(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + helper.renderInventoryBox(renderer); + + // Mid + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderInventoryBox(renderer); + + // Back + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderInventoryBusLights(helper, renderer); + } + + /** + * Draws the interface in the world. + */ + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + Tessellator tessellator = Tessellator.instance; + + IIcon side = BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[2]; + helper.setTexture(side, side, side, BlockTextureManager.VIS_RELAY_INTERFACE.getTexture(), side, side); + + // Face + helper.setBounds(6.0F, 6.0F, 15.0F, 10.0F, 10.0F, 16.0F); + helper.renderBlock(x, y, z, renderer); + + // Mid + helper.setBounds(4.0F, 4.0F, 14.0F, 12.0F, 12.0F, 15.0F); + helper.renderBlock(x, y, z, renderer); // Mid face + + if (this.visDrainingColor != 0) { + tessellator.setColorOpaque_I(this.visDrainingColor); + helper.renderFace( + x, y, z, BlockTextureManager.VIS_RELAY_INTERFACE.getTextures()[1], ForgeDirection.SOUTH, renderer); + } + + // Back (facing bus) + helper.setBounds(5.0F, 5.0F, 13.0F, 11.0F, 11.0F, 14.0F); + this.renderStaticBusLights(x, y, z, helper, renderer); + } + + /** + * Called when the interface ticks + */ + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + if (this.visDrainingColor != 0) { + if ((System.currentTimeMillis() - this.lastColorUpdate) > PartVisInterface.TIME_TO_CLEAR) { + this.setDrainColor(0); + } + } + + // Is the interface a provider? + if (this.isProvider) { + boolean hasProvider = (this.visProviderSubTile != null); + + // Validate the P2P Settings + if (!this.isP2PSourceValid()) { + // Invalid source, remove provider + if (hasProvider) { + this.visProviderSubTile.invalidate(); + this.visProviderSubTile = null; + } + } else { + boolean hasRelay = (this.getRelay() != null); + + // Invalid: Can't have a provider without a relay + if (!hasRelay && hasProvider) { + // Remove the provider + this.visProviderSubTile.invalidate(); + this.visProviderSubTile = null; + } + // Has relay but no provider + else if (hasRelay && !hasProvider) { + // Create the provider + this.visProviderSubTile = new VisProviderProxy(this); + + // Register the provider + VisNetHandler.addSource(this.getHostTile().getWorldObj(), this.visProviderSubTile); + } else if (hasProvider) { + this.visProviderSubTile.updateEntity(); + } + } + } + + return TickRateModulation.SAME; + } + + /** + * Write the interface data to the tag + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + // Only write NBT if world save + if (saveType != PartItemStack.World) { + return; + } + + // Write the UID + data.setLong(PartVisInterface.NBT_KEY_UID, this.UID); + + if (this.isProvider) { + // Write provider status + data.setBoolean(PartVisInterface.NBT_KEY_IS_PROVIDER, this.isProvider); + + // Write source data + this.visP2PSourceInfo.writeToNBT(data, PartVisInterface.NBT_KEY_PROVIDER_SOURCE); + } + } + + /** + * Sends data to the client + */ + @Override + public void writeToStream(final ByteBuf data) throws IOException { + // Call super + super.writeToStream(data); + + // Write the drain color + data.writeInt(this.visDrainingColor); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/ThEPartBase.java b/src/main/java/thaumicenergistics/common/parts/ThEPartBase.java index 06d7603f..fc3ffd5c 100644 --- a/src/main/java/thaumicenergistics/common/parts/ThEPartBase.java +++ b/src/main/java/thaumicenergistics/common/parts/ThEPartBase.java @@ -1,9 +1,5 @@ package thaumicenergistics.common.parts; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.implementations.IPowerChannelState; @@ -22,6 +18,10 @@ import appeng.api.util.DimensionalCoord; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.Entity; @@ -47,843 +47,743 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public abstract class ThEPartBase - implements IPart, IGridHost, IActionHost, IPowerChannelState -{ - private final static String NBT_KEY_OWNER = "Owner"; - - protected final static int INVENTORY_OVERLAY_COLOR = AEColor.Black.blackVariant; - - /** - * Texture brightness when active. - */ - protected final static int ACTIVE_FACE_BRIGHTNESS = 0xD000D0; - - /** - * Light level of active terminals. - */ - protected final static int ACTIVE_TERMINAL_LIGHT_LEVEL = 9; - - /** - * Permission levels required to interact with the part. - */ - private final SecurityPermissions[] interactionPermissions; - - /** - * The PartHost attached to. - */ - private IPartHost host; - - /** - * The PartHost tile entity. - */ - private TileEntity hostTile; - - /** - * Which side of the cable is the part attached to. - */ - private ForgeDirection cableSide; - - /** - * Is the part powered and connected? - */ - private boolean isActive; - - /** - * Is the network powered? - */ - private boolean isPowered; - - /** - * The parts grid node. - */ - private IGridNode node; - - /** - * The IGridBlock for this part. - */ - private final AEPartGridBlock gridBlock; - - /** - * AE2 player ID for the owner of this part. - */ - private int ownerID = -1; - - /** - * The item that represents this part. - */ - public final ItemStack associatedItem; - - /** - * Creates the part. - * - * @param associatedPart - * @param interactionPermissions - * Permissions required to interact with the part. - */ - public ThEPartBase( final AEPartsEnum associatedPart, final SecurityPermissions ... interactionPermissions ) - { - // Set the associated item - this.associatedItem = associatedPart.getStack(); - - // Set clearance - if( ( interactionPermissions != null ) && ( interactionPermissions.length > 0 ) ) - { - this.interactionPermissions = interactionPermissions; - } - else - { - this.interactionPermissions = null; - } - - if( EffectiveSide.isServerSide() ) - { - // Create the grid block - this.gridBlock = new AEPartGridBlock( this ); - } - else - { - this.gridBlock = null; - } - } - - private void updateStatus() - { - // Ignored client side - if( EffectiveSide.isClientSide() ) - { - return; - } - - // Do we have a node? - if( this.node != null ) - { - // Get the active state - boolean currentlyActive = this.node.isActive(); - - // Has that state changed? - if( currentlyActive != this.isActive ) - { - // Set our active state - this.isActive = currentlyActive; - - // Mark the host for an update - this.host.markForUpdate(); - } - } - - // Fire the neighbor changed event - this.onNeighborChanged(); - } - - /** - * Checks if the specifies player has clearance for the specified - * permission. - * - * @param player - * @param permission - * @return - */ - protected boolean doesPlayerHavePermission( final EntityPlayer player, final SecurityPermissions permission ) - { - if( EffectiveSide.isClientSide() ) - { - return false; - } - - // Get the security grid - ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); - - // Did we get the grid? - if( sGrid == null ) - { - // No security grid to check against. - return false; - } - - // Return the permission - return sGrid.hasPermission( player, permission ); - } - - /** - * Checks if the specifies player has clearance for the specified - * permission. - * - * @param playerID - * @param permission - * @return - */ - protected boolean doesPlayerHavePermission( final int playerID, final SecurityPermissions permission ) - { - if( EffectiveSide.isClientSide() ) - { - return false; - } - - // Get the security grid - ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); - - // Did we get the grid? - if( sGrid == null ) - { - // No security grid to check against. - return false; - } - - // Return the permission - return sGrid.hasPermission( playerID, permission ); - } - - /** - * Gets the tile entity the part is facing, if any. - * - * @return - */ - protected TileEntity getFacingTile() - { - if( this.hostTile == null ) - return null; - - // Get the world - World world = this.hostTile.getWorldObj(); - if (world == null) // may happen during unload - return null; - - // Get our location - int x = this.hostTile.xCoord; - int y = this.hostTile.yCoord; - int z = this.hostTile.zCoord; - - // Get the tile entity we are facing - return world.getTileEntity( x + this.cableSide.offsetX, y + this.cableSide.offsetY, z + this.cableSide.offsetZ ); - } - - /** - * Called when the part is added to the world. - */ - @Override - public void addToWorld() - { - // Ignored on client side - if( EffectiveSide.isClientSide() ) - { - return; - } - // Create the node - this.node = AEApi.instance().createGridNode( this.gridBlock ); - - // Set the player id - this.node.setPlayerID( this.ownerID ); - - // Update state - if( ( this.hostTile != null ) && ( this.host != null ) && ( this.hostTile.getWorldObj() != null ) ) - { - try - { - this.node.updateState(); - } - catch( Exception e ) - { - ThELog.error( e, "Part (%s) was unable to update it's node. The part may not function correctly", - this.associatedItem.getDisplayName() ); - } - } - - // Update the part - this.updateStatus(); - } - - @Override - public abstract int cableConnectionRenderTo(); - - @Override - public boolean canBePlacedOn( final BusSupport type ) - { - // Can only be placed on normal cable - return type == BusSupport.CABLE; - } - - @Override - public boolean canConnectRedstone() - { - return false; - } - - @Override - public IGridNode getActionableNode() - { - return this.node; - } - - @Override - public abstract void getBoxes( IPartCollisionHelper helper ); - - @SideOnly(Side.CLIENT) - @Override - public abstract IIcon getBreakingTexture(); - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - public Object getClientGuiElement( final EntityPlayer player ) - { - return null; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - } - - @Override - public final IGridNode getExternalFacingNode() - { - return null; - } - - /** - * Gets the parts grid block. - * - * @return - */ - public AEPartGridBlock getGridBlock() - { - return this.gridBlock; - } - - @Override - public IGridNode getGridNode() - { - return this.node; - } - - @Override - public IGridNode getGridNode( final ForgeDirection direction ) - { - return this.node; - } - - public final IPartHost getHost() - { - return this.host; - } - - /** - * Gets the host tile entity of this part. - * - * @return - */ - public final TileEntity getHostTile() - { - return this.hostTile; - } - - /** - * Determines how much power the part takes for being active. - */ - public abstract double getIdlePowerUsage(); - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - // Get the itemstack - ItemStack itemStack = this.associatedItem.copy(); - - // Save NBT data if the part was wrenched - if( type == PartItemStack.Wrench ) - { - // Create the item tag - NBTTagCompound itemNBT = new NBTTagCompound(); - - // Write the data - this.writeToNBT( itemNBT, PartItemStack.Wrench ); - - // Set the tag - if( !itemNBT.hasNoTags() ) - { - itemStack.setTagCompound( itemNBT ); - } - } - - return itemStack; - } - - /** - * Gets the block light level for this part. - */ - @Override - public abstract int getLightLevel(); - - /** - * Gets the location of this part. - * - * @return - */ - public final DimensionalCoord getLocation() - { - return new DimensionalCoord( this.hostTile.getWorldObj(), this.hostTile.xCoord, this.hostTile.yCoord, this.hostTile.zCoord ); - } - - public Object getServerGuiElement( final EntityPlayer player ) - { - return null; - } - - /** - * Gets the side of the host that this part is attached to. - * - * @return - */ - public ForgeDirection getSide() - { - return this.cableSide; - } - - /** - * Gets the unlocalized name of this part. - * - * @return - */ - public String getUnlocalizedName() - { - return this.associatedItem.getUnlocalizedName() + ".name"; - } - - /** - * Checks if the part is active and powered. - * - * @return - */ - @Override - public boolean isActive() - { - // Are we server side? - if( EffectiveSide.isServerSide() ) - { - // Do we have a node? - if( this.node != null ) - { - // Get it's activity - this.isActive = this.node.isActive(); - } - else - { - this.isActive = false; - } - } - - return this.isActive; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - /** - * Called the player interact with this part? - * - * @param player - * @return - */ - public final boolean isPartUseableByPlayer( final EntityPlayer player ) - { - if( EffectiveSide.isClientSide() ) - { - return false; - } - - // Null check host - if( ( this.hostTile == null ) || ( this.host == null ) ) - { - return false; - } - - // Does the host still exist in the world and the player in range of it? - if( !ThEUtils.canPlayerInteractWith( player, this.hostTile ) ) - { - return false; - } - - // Is the part still attached? - if( this.host.getPart( this.cableSide ) != this ) - { - return false; - } - - // Are there any permissions to check? - if( this.interactionPermissions != null ) - { - // Get the security grid - ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); - if( sGrid == null ) - { - // Security grid was unaccessible. - return false; - } - - // Check each permission - for( SecurityPermissions perm : this.interactionPermissions ) - { - if( !sGrid.hasPermission( player, perm ) ) - { - return false; - } - } - } - - return true; - } - - @Override - public boolean isPowered() - { - try - { - // Server side? - if( EffectiveSide.isServerSide() && ( this.gridBlock != null ) ) - { - // Get the energy grid - IEnergyGrid eGrid = this.gridBlock.getEnergyGrid(); - if( eGrid != null ) - { - this.isPowered = eGrid.isNetworkPowered(); - } - else - { - this.isPowered = false; - } - } - } - catch( Exception e ) - { - // Network unavailable, return cached value. - } - - return this.isPowered; - } - - @Override - public int isProvidingStrongPower() - { - return 0; - } - - @Override - public int isProvidingWeakPower() - { - return 0; - } - - /** - * Returns true if the part is receiving any level of redstone power. - * - * @return - */ - public boolean isReceivingRedstonePower() - { - if( this.host != null ) - { - // Get redstone state - return this.host.hasRedstone( this.cableSide ); - } - return false; - } - - @Override - public boolean isSolid() - { - return false; - } - - /** - * Marks that the host tile needs to be saved to disk. - */ - public final void markForSave() - { - // Ensure there is a host - if( this.host != null ) - { - // Mark - this.host.markForSave(); - } - } - - /** - * Marks that clients needs to be updated. - */ - public final void markForUpdate() - { - if( this.host != null ) - { - this.host.markForUpdate(); - } - } - - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - // Is the player sneaking? - if( player.isSneaking() ) - { - return false; - } - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Launch the gui - ThEGuiHandler.launchGui( this, player, this.hostTile.getWorldObj(), this.hostTile.xCoord, this.hostTile.yCoord, this.hostTile.zCoord ); - } - - return true; - } - - @Override - public void onEntityCollision( final Entity entity ) - { - } - - @Override - public void onNeighborChanged() - { - } - - @Override - public final void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - // Set the owner - this.ownerID = AEApi.instance().registries().players().getID( player.getGameProfile() ); - } - - @Override - public boolean onShiftActivate( final EntityPlayer player, final Vec3 position ) - { - return false; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Read the owner - if( data.hasKey( ThEPartBase.NBT_KEY_OWNER ) ) - { - this.ownerID = data.getInteger( ThEPartBase.NBT_KEY_OWNER ); - } - } - - @SideOnly(Side.CLIENT) - @Override - public boolean readFromStream( final ByteBuf stream ) throws IOException - { - // Cache old values - boolean oldActive = this.isActive; - boolean oldPowered = this.isPowered; - - // Read the new values - this.isActive = stream.readBoolean(); - this.isPowered = stream.readBoolean(); - - // Redraw if they don't match. - return( ( oldActive != this.isActive ) || ( oldPowered != this.isPowered ) ); - } - - @Override - public void removeFromWorld() - { - if( this.node != null ) - { - this.node.destroy(); - } - } - - @SideOnly(Side.CLIENT) - @Override - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Ignored - } - - @SideOnly(Side.CLIENT) - @Override - public abstract void renderInventory( IPartRenderHelper helper, RenderBlocks renderer ); - - @SideOnly(Side.CLIENT) - public void renderInventoryBusLights( final IPartRenderHelper helper, final RenderBlocks renderer ) - { - // Set color to white - helper.setInvColor( 0xFFFFFF ); - - IIcon busColorTexture = BlockTextureManager.BUS_COLOR.getTextures()[0]; - - IIcon sideTexture = BlockTextureManager.BUS_COLOR.getTextures()[2]; - - helper.setTexture( busColorTexture, busColorTexture, sideTexture, sideTexture, busColorTexture, busColorTexture ); - - // Rend the box - helper.renderInventoryBox( renderer ); - - // Set the brightness - Tessellator.instance.setBrightness( 0xD000D0 ); - - helper.setInvColor( AEColor.Transparent.blackVariant ); - - IIcon lightTexture = BlockTextureManager.BUS_COLOR.getTextures()[1]; - - // Render the lights - helper.renderInventoryFace( lightTexture, ForgeDirection.UP, renderer ); - helper.renderInventoryFace( lightTexture, ForgeDirection.DOWN, renderer ); - helper.renderInventoryFace( lightTexture, ForgeDirection.NORTH, renderer ); - helper.renderInventoryFace( lightTexture, ForgeDirection.EAST, renderer ); - helper.renderInventoryFace( lightTexture, ForgeDirection.SOUTH, renderer ); - helper.renderInventoryFace( lightTexture, ForgeDirection.WEST, renderer ); - } - - @SideOnly(Side.CLIENT) - @Override - public abstract void renderStatic( int x, int y, int z, IPartRenderHelper helper, RenderBlocks renderer ); - - @SideOnly(Side.CLIENT) - public void renderStaticBusLights( final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer ) - { - IIcon busColorTexture = BlockTextureManager.BUS_COLOR.getTextures()[0]; - - IIcon sideTexture = BlockTextureManager.BUS_COLOR.getTextures()[2]; - - helper.setTexture( busColorTexture, busColorTexture, sideTexture, sideTexture, busColorTexture, busColorTexture ); - - // Render the box - helper.renderBlock( x, y, z, renderer ); - - // Are we active? - if( this.isActive() ) - { - // Set the brightness - Tessellator.instance.setBrightness( 0xD000D0 ); - - // Set the color to match the cable - Tessellator.instance.setColorOpaque_I( this.host.getColor().blackVariant ); - } - else - { - // Set the color to black - Tessellator.instance.setColorOpaque_I( 0 ); - } - - IIcon lightTexture = BlockTextureManager.BUS_COLOR.getTextures()[1]; - - // Render the lights - helper.renderFace( x, y, z, lightTexture, ForgeDirection.UP, renderer ); - helper.renderFace( x, y, z, lightTexture, ForgeDirection.DOWN, renderer ); - helper.renderFace( x, y, z, lightTexture, ForgeDirection.NORTH, renderer ); - helper.renderFace( x, y, z, lightTexture, ForgeDirection.EAST, renderer ); - helper.renderFace( x, y, z, lightTexture, ForgeDirection.SOUTH, renderer ); - helper.renderFace( x, y, z, lightTexture, ForgeDirection.WEST, renderer ); - } - - @Override - public boolean requireDynamicRender() - { - return false; - } - - @Override - public void securityBreak() - { - List drops = new ArrayList(); - - // Get this item - drops.add( this.getItemStack( PartItemStack.Break ) ); - - // Get the drops for this part - this.getDrops( drops, false ); - - // Drop it - appeng.util.Platform.spawnDrops( this.hostTile.getWorldObj(), this.hostTile.xCoord, this.hostTile.yCoord, this.hostTile.zCoord, drops ); - - // Remove the part - this.host.removePart( this.cableSide, false ); - - } - - @Override - public final void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - this.cableSide = side; - this.host = host; - this.hostTile = tile; - - } - - @MENetworkEventSubscribe - public final void setPower( final MENetworkPowerStatusChange event ) - { - this.updateStatus(); - } - - /** - * Setup the part based on the passed item. - * - * @param itemPart - */ - public void setupPartFromItem( final ItemStack itemPart ) - { - if( itemPart.hasTagCompound() ) - { - this.readFromNBT( itemPart.getTagCompound() ); - } - } - - @MENetworkEventSubscribe - public void updateChannels( final MENetworkChannelsChanged event ) - { - this.updateStatus(); - } - - /** - * General call to WriteNBT, assumes a world save. DO NOT call this from a - * subclass's writeToNBT method. - */ - @Override - public final void writeToNBT( final NBTTagCompound data ) - { - // Assume world saving. - this.writeToNBT( data, PartItemStack.World ); - } - - /** - * Saves NBT data specific to the save type. - * - * @param data - * @param saveType - */ - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - if( saveType == PartItemStack.World ) - { - // Set the owner ID - data.setInteger( ThEPartBase.NBT_KEY_OWNER, this.ownerID ); - } - - } - - @Override - public void writeToStream( final ByteBuf stream ) throws IOException - { - // Write active - stream.writeBoolean( this.isActive() ); - - // Write powered - stream.writeBoolean( this.isPowered() ); - } - +public abstract class ThEPartBase implements IPart, IGridHost, IActionHost, IPowerChannelState { + private static final String NBT_KEY_OWNER = "Owner"; + + protected static final int INVENTORY_OVERLAY_COLOR = AEColor.Black.blackVariant; + + /** + * Texture brightness when active. + */ + protected static final int ACTIVE_FACE_BRIGHTNESS = 0xD000D0; + + /** + * Light level of active terminals. + */ + protected static final int ACTIVE_TERMINAL_LIGHT_LEVEL = 9; + + /** + * Permission levels required to interact with the part. + */ + private final SecurityPermissions[] interactionPermissions; + + /** + * The PartHost attached to. + */ + private IPartHost host; + + /** + * The PartHost tile entity. + */ + private TileEntity hostTile; + + /** + * Which side of the cable is the part attached to. + */ + private ForgeDirection cableSide; + + /** + * Is the part powered and connected? + */ + private boolean isActive; + + /** + * Is the network powered? + */ + private boolean isPowered; + + /** + * The parts grid node. + */ + private IGridNode node; + + /** + * The IGridBlock for this part. + */ + private final AEPartGridBlock gridBlock; + + /** + * AE2 player ID for the owner of this part. + */ + private int ownerID = -1; + + /** + * The item that represents this part. + */ + public final ItemStack associatedItem; + + /** + * Creates the part. + * + * @param associatedPart + * @param interactionPermissions + * Permissions required to interact with the part. + */ + public ThEPartBase(final AEPartsEnum associatedPart, final SecurityPermissions... interactionPermissions) { + // Set the associated item + this.associatedItem = associatedPart.getStack(); + + // Set clearance + if ((interactionPermissions != null) && (interactionPermissions.length > 0)) { + this.interactionPermissions = interactionPermissions; + } else { + this.interactionPermissions = null; + } + + if (EffectiveSide.isServerSide()) { + // Create the grid block + this.gridBlock = new AEPartGridBlock(this); + } else { + this.gridBlock = null; + } + } + + private void updateStatus() { + // Ignored client side + if (EffectiveSide.isClientSide()) { + return; + } + + // Do we have a node? + if (this.node != null) { + // Get the active state + boolean currentlyActive = this.node.isActive(); + + // Has that state changed? + if (currentlyActive != this.isActive) { + // Set our active state + this.isActive = currentlyActive; + + // Mark the host for an update + this.host.markForUpdate(); + } + } + + // Fire the neighbor changed event + this.onNeighborChanged(); + } + + /** + * Checks if the specifies player has clearance for the specified + * permission. + * + * @param player + * @param permission + * @return + */ + protected boolean doesPlayerHavePermission(final EntityPlayer player, final SecurityPermissions permission) { + if (EffectiveSide.isClientSide()) { + return false; + } + + // Get the security grid + ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); + + // Did we get the grid? + if (sGrid == null) { + // No security grid to check against. + return false; + } + + // Return the permission + return sGrid.hasPermission(player, permission); + } + + /** + * Checks if the specifies player has clearance for the specified + * permission. + * + * @param playerID + * @param permission + * @return + */ + protected boolean doesPlayerHavePermission(final int playerID, final SecurityPermissions permission) { + if (EffectiveSide.isClientSide()) { + return false; + } + + // Get the security grid + ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); + + // Did we get the grid? + if (sGrid == null) { + // No security grid to check against. + return false; + } + + // Return the permission + return sGrid.hasPermission(playerID, permission); + } + + /** + * Gets the tile entity the part is facing, if any. + * + * @return + */ + protected TileEntity getFacingTile() { + if (this.hostTile == null) return null; + + // Get the world + World world = this.hostTile.getWorldObj(); + if (world == null) // may happen during unload + return null; + + // Get our location + int x = this.hostTile.xCoord; + int y = this.hostTile.yCoord; + int z = this.hostTile.zCoord; + + // Get the tile entity we are facing + return world.getTileEntity(x + this.cableSide.offsetX, y + this.cableSide.offsetY, z + this.cableSide.offsetZ); + } + + /** + * Called when the part is added to the world. + */ + @Override + public void addToWorld() { + // Ignored on client side + if (EffectiveSide.isClientSide()) { + return; + } + // Create the node + this.node = AEApi.instance().createGridNode(this.gridBlock); + + // Set the player id + this.node.setPlayerID(this.ownerID); + + // Update state + if ((this.hostTile != null) && (this.host != null) && (this.hostTile.getWorldObj() != null)) { + try { + this.node.updateState(); + } catch (Exception e) { + ThELog.error( + e, + "Part (%s) was unable to update it's node. The part may not function correctly", + this.associatedItem.getDisplayName()); + } + } + + // Update the part + this.updateStatus(); + } + + @Override + public abstract int cableConnectionRenderTo(); + + @Override + public boolean canBePlacedOn(final BusSupport type) { + // Can only be placed on normal cable + return type == BusSupport.CABLE; + } + + @Override + public boolean canConnectRedstone() { + return false; + } + + @Override + public IGridNode getActionableNode() { + return this.node; + } + + @Override + public abstract void getBoxes(IPartCollisionHelper helper); + + @SideOnly(Side.CLIENT) + @Override + public abstract IIcon getBreakingTexture(); + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + public Object getClientGuiElement(final EntityPlayer player) { + return null; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) {} + + @Override + public final IGridNode getExternalFacingNode() { + return null; + } + + /** + * Gets the parts grid block. + * + * @return + */ + public AEPartGridBlock getGridBlock() { + return this.gridBlock; + } + + @Override + public IGridNode getGridNode() { + return this.node; + } + + @Override + public IGridNode getGridNode(final ForgeDirection direction) { + return this.node; + } + + public final IPartHost getHost() { + return this.host; + } + + /** + * Gets the host tile entity of this part. + * + * @return + */ + public final TileEntity getHostTile() { + return this.hostTile; + } + + /** + * Determines how much power the part takes for being active. + */ + public abstract double getIdlePowerUsage(); + + @Override + public ItemStack getItemStack(final PartItemStack type) { + // Get the itemstack + ItemStack itemStack = this.associatedItem.copy(); + + // Save NBT data if the part was wrenched + if (type == PartItemStack.Wrench) { + // Create the item tag + NBTTagCompound itemNBT = new NBTTagCompound(); + + // Write the data + this.writeToNBT(itemNBT, PartItemStack.Wrench); + + // Set the tag + if (!itemNBT.hasNoTags()) { + itemStack.setTagCompound(itemNBT); + } + } + + return itemStack; + } + + /** + * Gets the block light level for this part. + */ + @Override + public abstract int getLightLevel(); + + /** + * Gets the location of this part. + * + * @return + */ + public final DimensionalCoord getLocation() { + return new DimensionalCoord( + this.hostTile.getWorldObj(), this.hostTile.xCoord, this.hostTile.yCoord, this.hostTile.zCoord); + } + + public Object getServerGuiElement(final EntityPlayer player) { + return null; + } + + /** + * Gets the side of the host that this part is attached to. + * + * @return + */ + public ForgeDirection getSide() { + return this.cableSide; + } + + /** + * Gets the unlocalized name of this part. + * + * @return + */ + public String getUnlocalizedName() { + return this.associatedItem.getUnlocalizedName() + ".name"; + } + + /** + * Checks if the part is active and powered. + * + * @return + */ + @Override + public boolean isActive() { + // Are we server side? + if (EffectiveSide.isServerSide()) { + // Do we have a node? + if (this.node != null) { + // Get it's activity + this.isActive = this.node.isActive(); + } else { + this.isActive = false; + } + } + + return this.isActive; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } + + /** + * Called the player interact with this part? + * + * @param player + * @return + */ + public final boolean isPartUseableByPlayer(final EntityPlayer player) { + if (EffectiveSide.isClientSide()) { + return false; + } + + // Null check host + if ((this.hostTile == null) || (this.host == null)) { + return false; + } + + // Does the host still exist in the world and the player in range of it? + if (!ThEUtils.canPlayerInteractWith(player, this.hostTile)) { + return false; + } + + // Is the part still attached? + if (this.host.getPart(this.cableSide) != this) { + return false; + } + + // Are there any permissions to check? + if (this.interactionPermissions != null) { + // Get the security grid + ISecurityGrid sGrid = this.gridBlock.getSecurityGrid(); + if (sGrid == null) { + // Security grid was unaccessible. + return false; + } + + // Check each permission + for (SecurityPermissions perm : this.interactionPermissions) { + if (!sGrid.hasPermission(player, perm)) { + return false; + } + } + } + + return true; + } + + @Override + public boolean isPowered() { + try { + // Server side? + if (EffectiveSide.isServerSide() && (this.gridBlock != null)) { + // Get the energy grid + IEnergyGrid eGrid = this.gridBlock.getEnergyGrid(); + if (eGrid != null) { + this.isPowered = eGrid.isNetworkPowered(); + } else { + this.isPowered = false; + } + } + } catch (Exception e) { + // Network unavailable, return cached value. + } + + return this.isPowered; + } + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + /** + * Returns true if the part is receiving any level of redstone power. + * + * @return + */ + public boolean isReceivingRedstonePower() { + if (this.host != null) { + // Get redstone state + return this.host.hasRedstone(this.cableSide); + } + return false; + } + + @Override + public boolean isSolid() { + return false; + } + + /** + * Marks that the host tile needs to be saved to disk. + */ + public final void markForSave() { + // Ensure there is a host + if (this.host != null) { + // Mark + this.host.markForSave(); + } + } + + /** + * Marks that clients needs to be updated. + */ + public final void markForUpdate() { + if (this.host != null) { + this.host.markForUpdate(); + } + } + + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + // Is the player sneaking? + if (player.isSneaking()) { + return false; + } + + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Launch the gui + ThEGuiHandler.launchGui( + this, + player, + this.hostTile.getWorldObj(), + this.hostTile.xCoord, + this.hostTile.yCoord, + this.hostTile.zCoord); + } + + return true; + } + + @Override + public void onEntityCollision(final Entity entity) {} + + @Override + public void onNeighborChanged() {} + + @Override + public final void onPlacement(final EntityPlayer player, final ItemStack held, final ForgeDirection side) { + // Set the owner + this.ownerID = AEApi.instance().registries().players().getID(player.getGameProfile()); + } + + @Override + public boolean onShiftActivate(final EntityPlayer player, final Vec3 position) { + return false; + } + + @Override + public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random r) {} + + @Override + public void readFromNBT(final NBTTagCompound data) { + // Read the owner + if (data.hasKey(ThEPartBase.NBT_KEY_OWNER)) { + this.ownerID = data.getInteger(ThEPartBase.NBT_KEY_OWNER); + } + } + + @SideOnly(Side.CLIENT) + @Override + public boolean readFromStream(final ByteBuf stream) throws IOException { + // Cache old values + boolean oldActive = this.isActive; + boolean oldPowered = this.isPowered; + + // Read the new values + this.isActive = stream.readBoolean(); + this.isPowered = stream.readBoolean(); + + // Redraw if they don't match. + return ((oldActive != this.isActive) || (oldPowered != this.isPowered)); + } + + @Override + public void removeFromWorld() { + if (this.node != null) { + this.node.destroy(); + } + } + + @SideOnly(Side.CLIENT) + @Override + public void renderDynamic( + final double x, + final double y, + final double z, + final IPartRenderHelper helper, + final RenderBlocks renderer) { + // Ignored + } + + @SideOnly(Side.CLIENT) + @Override + public abstract void renderInventory(IPartRenderHelper helper, RenderBlocks renderer); + + @SideOnly(Side.CLIENT) + public void renderInventoryBusLights(final IPartRenderHelper helper, final RenderBlocks renderer) { + // Set color to white + helper.setInvColor(0xFFFFFF); + + IIcon busColorTexture = BlockTextureManager.BUS_COLOR.getTextures()[0]; + + IIcon sideTexture = BlockTextureManager.BUS_COLOR.getTextures()[2]; + + helper.setTexture(busColorTexture, busColorTexture, sideTexture, sideTexture, busColorTexture, busColorTexture); + + // Rend the box + helper.renderInventoryBox(renderer); + + // Set the brightness + Tessellator.instance.setBrightness(0xD000D0); + + helper.setInvColor(AEColor.Transparent.blackVariant); + + IIcon lightTexture = BlockTextureManager.BUS_COLOR.getTextures()[1]; + + // Render the lights + helper.renderInventoryFace(lightTexture, ForgeDirection.UP, renderer); + helper.renderInventoryFace(lightTexture, ForgeDirection.DOWN, renderer); + helper.renderInventoryFace(lightTexture, ForgeDirection.NORTH, renderer); + helper.renderInventoryFace(lightTexture, ForgeDirection.EAST, renderer); + helper.renderInventoryFace(lightTexture, ForgeDirection.SOUTH, renderer); + helper.renderInventoryFace(lightTexture, ForgeDirection.WEST, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public abstract void renderStatic(int x, int y, int z, IPartRenderHelper helper, RenderBlocks renderer); + + @SideOnly(Side.CLIENT) + public void renderStaticBusLights( + final int x, final int y, final int z, final IPartRenderHelper helper, final RenderBlocks renderer) { + IIcon busColorTexture = BlockTextureManager.BUS_COLOR.getTextures()[0]; + + IIcon sideTexture = BlockTextureManager.BUS_COLOR.getTextures()[2]; + + helper.setTexture(busColorTexture, busColorTexture, sideTexture, sideTexture, busColorTexture, busColorTexture); + + // Render the box + helper.renderBlock(x, y, z, renderer); + + // Are we active? + if (this.isActive()) { + // Set the brightness + Tessellator.instance.setBrightness(0xD000D0); + + // Set the color to match the cable + Tessellator.instance.setColorOpaque_I(this.host.getColor().blackVariant); + } else { + // Set the color to black + Tessellator.instance.setColorOpaque_I(0); + } + + IIcon lightTexture = BlockTextureManager.BUS_COLOR.getTextures()[1]; + + // Render the lights + helper.renderFace(x, y, z, lightTexture, ForgeDirection.UP, renderer); + helper.renderFace(x, y, z, lightTexture, ForgeDirection.DOWN, renderer); + helper.renderFace(x, y, z, lightTexture, ForgeDirection.NORTH, renderer); + helper.renderFace(x, y, z, lightTexture, ForgeDirection.EAST, renderer); + helper.renderFace(x, y, z, lightTexture, ForgeDirection.SOUTH, renderer); + helper.renderFace(x, y, z, lightTexture, ForgeDirection.WEST, renderer); + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + @Override + public void securityBreak() { + List drops = new ArrayList(); + + // Get this item + drops.add(this.getItemStack(PartItemStack.Break)); + + // Get the drops for this part + this.getDrops(drops, false); + + // Drop it + appeng.util.Platform.spawnDrops( + this.hostTile.getWorldObj(), this.hostTile.xCoord, this.hostTile.yCoord, this.hostTile.zCoord, drops); + + // Remove the part + this.host.removePart(this.cableSide, false); + } + + @Override + public final void setPartHostInfo(final ForgeDirection side, final IPartHost host, final TileEntity tile) { + this.cableSide = side; + this.host = host; + this.hostTile = tile; + } + + @MENetworkEventSubscribe + public final void setPower(final MENetworkPowerStatusChange event) { + this.updateStatus(); + } + + /** + * Setup the part based on the passed item. + * + * @param itemPart + */ + public void setupPartFromItem(final ItemStack itemPart) { + if (itemPart.hasTagCompound()) { + this.readFromNBT(itemPart.getTagCompound()); + } + } + + @MENetworkEventSubscribe + public void updateChannels(final MENetworkChannelsChanged event) { + this.updateStatus(); + } + + /** + * General call to WriteNBT, assumes a world save. DO NOT call this from a + * subclass's writeToNBT method. + */ + @Override + public final void writeToNBT(final NBTTagCompound data) { + // Assume world saving. + this.writeToNBT(data, PartItemStack.World); + } + + /** + * Saves NBT data specific to the save type. + * + * @param data + * @param saveType + */ + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + if (saveType == PartItemStack.World) { + // Set the owner ID + data.setInteger(ThEPartBase.NBT_KEY_OWNER, this.ownerID); + } + } + + @Override + public void writeToStream(final ByteBuf stream) throws IOException { + // Write active + stream.writeBoolean(this.isActive()); + + // Write powered + stream.writeBoolean(this.isPowered()); + } } diff --git a/src/main/java/thaumicenergistics/common/parts/ThEPartEssentiaIOBus_Base.java b/src/main/java/thaumicenergistics/common/parts/ThEPartEssentiaIOBus_Base.java index e3490fe9..50bf7ca7 100644 --- a/src/main/java/thaumicenergistics/common/parts/ThEPartEssentiaIOBus_Base.java +++ b/src/main/java/thaumicenergistics/common/parts/ThEPartEssentiaIOBus_Base.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.parts; -import java.util.ArrayList; -import java.util.List; import appeng.api.AEApi; import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; @@ -20,6 +18,8 @@ import appeng.tile.inventory.IAEAppEngInventory; import appeng.tile.inventory.InvOperation; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -43,637 +43,546 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public abstract class ThEPartEssentiaIOBus_Base - extends ThEPartBase - implements IGridTickable, IAspectSlotPart, IAEAppEngInventory -{ - /** - * How much essentia can be transfered per second. - */ - private final static int BASE_TRANSFER_PER_SECOND = 4; +public abstract class ThEPartEssentiaIOBus_Base extends ThEPartBase + implements IGridTickable, IAspectSlotPart, IAEAppEngInventory { + /** + * How much essentia can be transfered per second. + */ + private static final int BASE_TRANSFER_PER_SECOND = 4; - /** - * How much additional essentia can be transfered per upgrade. - */ - private final static int ADDITIONAL_TRANSFER_PER_SECOND = 8; + /** + * How much additional essentia can be transfered per upgrade. + */ + private static final int ADDITIONAL_TRANSFER_PER_SECOND = 8; - private final static int MINIMUM_TICKS_PER_OPERATION = 10; + private static final int MINIMUM_TICKS_PER_OPERATION = 10; - private final static int MAXIMUM_TICKS_PER_OPERATION = 40; + private static final int MAXIMUM_TICKS_PER_OPERATION = 40; - private final static int MAXIMUM_TRANSFER_PER_SECOND = 64; + private static final int MAXIMUM_TRANSFER_PER_SECOND = 64; - private final static int MINIMUM_TRANSFER_PER_SECOND = 1; + private static final int MINIMUM_TRANSFER_PER_SECOND = 1; - /** - * Maximum number of filter slots. - */ - private final static int MAX_FILTER_SIZE = 9; + /** + * Maximum number of filter slots. + */ + private static final int MAX_FILTER_SIZE = 9; - private final static int BASE_SLOT_INDEX = 4; + private static final int BASE_SLOT_INDEX = 4; - private final static int[] TIER2_INDEXS = { 0, 2, 6, 8 }; + private static final int[] TIER2_INDEXS = {0, 2, 6, 8}; - private final static int[] TIER1_INDEXS = { 1, 3, 5, 7 }; + private static final int[] TIER1_INDEXS = {1, 3, 5, 7}; - private final static int UPGRADE_INVENTORY_SIZE = 4; + private static final int UPGRADE_INVENTORY_SIZE = 4; - /** - * How much AE power is required to keep the part active. - */ - private static final double IDLE_POWER_DRAIN = 0.7; + /** + * How much AE power is required to keep the part active. + */ + private static final double IDLE_POWER_DRAIN = 0.7; - /** - * Default redstone mode for the bus. - */ - private static final RedstoneMode DEFAULT_REDSTONE_MODE = RedstoneMode.IGNORE; + /** + * Default redstone mode for the bus. + */ + private static final RedstoneMode DEFAULT_REDSTONE_MODE = RedstoneMode.IGNORE; - /** - * NBT Keys - */ - private static final String NBT_KEY_REDSTONE_MODE = "redstoneMode", NBT_KEY_FILTER_NUMBER = "AspectFilter#", - NBT_KEY_UPGRADE_INV = "upgradeInventory"; + /** + * NBT Keys + */ + private static final String NBT_KEY_REDSTONE_MODE = "redstoneMode", + NBT_KEY_FILTER_NUMBER = "AspectFilter#", + NBT_KEY_UPGRADE_INV = "upgradeInventory"; - private boolean lastRedstone; + private boolean lastRedstone; - private int[] availableFilterSlots = { ThEPartEssentiaIOBus_Base.BASE_SLOT_INDEX }; + private int[] availableFilterSlots = {ThEPartEssentiaIOBus_Base.BASE_SLOT_INDEX}; - private UpgradeInventory upgradeInventory = new StackUpgradeInventory( this.associatedItem, this, - ThEPartEssentiaIOBus_Base.UPGRADE_INVENTORY_SIZE ); + private UpgradeInventory upgradeInventory = + new StackUpgradeInventory(this.associatedItem, this, ThEPartEssentiaIOBus_Base.UPGRADE_INVENTORY_SIZE); - private List listeners = new ArrayList(); + private List listeners = new ArrayList(); - /** - * How the bus responds to redstone. - */ - private RedstoneMode redstoneMode = ThEPartEssentiaIOBus_Base.DEFAULT_REDSTONE_MODE; + /** + * How the bus responds to redstone. + */ + private RedstoneMode redstoneMode = ThEPartEssentiaIOBus_Base.DEFAULT_REDSTONE_MODE; - /** - * Network source representing this part. - */ - protected MachineSource asMachineSource; + /** + * Network source representing this part. + */ + protected MachineSource asMachineSource; - protected List filteredAspects = new ArrayList( ThEPartEssentiaIOBus_Base.MAX_FILTER_SIZE ); + protected List filteredAspects = new ArrayList(ThEPartEssentiaIOBus_Base.MAX_FILTER_SIZE); - protected IAspectContainer facingContainer; + protected IAspectContainer facingContainer; - protected byte filterSize; + protected byte filterSize; - protected byte upgradeSpeedCount = 0; + protected byte upgradeSpeedCount = 0; - protected boolean redstoneControlled; + protected boolean redstoneControlled; - protected boolean hasCraftingCard = false; + protected boolean hasCraftingCard = false; + + public ThEPartEssentiaIOBus_Base( + final AEPartsEnum associatedPart, final SecurityPermissions... interactionPermissions) { + super(associatedPart, interactionPermissions); - public ThEPartEssentiaIOBus_Base( final AEPartsEnum associatedPart, final SecurityPermissions ... interactionPermissions ) - { - super( associatedPart, interactionPermissions ); - - // Initialize the list - for( int index = 0; index < ThEPartEssentiaIOBus_Base.MAX_FILTER_SIZE; index++ ) - { - this.filteredAspects.add( null ); - } - - // Create the source - this.asMachineSource = new MachineSource( this ); - } - - private boolean canDoWork() - { - boolean canWork = true; - - if( this.redstoneControlled ) - { - switch ( this.getRedstoneMode() ) - { - case HIGH_SIGNAL: - canWork = this.isReceivingRedstonePower(); - - break; - case IGNORE: - break; - - case LOW_SIGNAL: - canWork = !this.isReceivingRedstonePower(); - - break; - case SIGNAL_PULSE: - canWork = false; - break; - } - } - - return canWork; - - } - - private int getTransferAmountPerSecond() - { - return BASE_TRANSFER_PER_SECOND + ( this.upgradeSpeedCount * ADDITIONAL_TRANSFER_PER_SECOND ); - } - - private void notifyListenersOfFilterAspectChange() - { - for( ContainerPartEssentiaIOBus listener : this.listeners ) - { - listener.setFilteredAspect( this.filteredAspects ); - } - } - - private void notifyListenersOfFilterSizeChange() - { - for( ContainerPartEssentiaIOBus listener : this.listeners ) - { - listener.setFilterSize( this.filterSize ); - } - } - - private void notifyListenersOfRedstoneControlledChange() - { - for( ContainerPartEssentiaIOBus listener : this.listeners ) - { - listener.setRedstoneControlled( this.redstoneControlled ); - } - } - - private void notifyListenersOfHasCraftingCardChange() - { - for( ContainerPartEssentiaIOBus listener : this.listeners ) - { - listener.setHasCraftingCard( this.hasCraftingCard ); - } - } - - private void notifyListenersOfRedstoneModeChange() - { - for( ContainerPartEssentiaIOBus listener : this.listeners ) - { - listener.setRedstoneMode( this.redstoneMode ); - } - - } - - private void resizeAvailableArray() - { - // Resize the available slots - this.availableFilterSlots = new int[1 + ( this.filterSize * 4 )]; - - // Add the base slot - this.availableFilterSlots[0] = ThEPartEssentiaIOBus_Base.BASE_SLOT_INDEX; - - if( this.filterSize < 2 ) - { - // Reset tier 2 slots - for( int i = 0; i < ThEPartEssentiaIOBus_Base.TIER2_INDEXS.length; i++ ) - { - this.filteredAspects.set( ThEPartEssentiaIOBus_Base.TIER2_INDEXS[i], null ); - } - - if( this.filterSize < 1 ) - { - // Reset tier 1 slots - for( int i = 0; i < ThEPartEssentiaIOBus_Base.TIER1_INDEXS.length; i++ ) - { - this.filteredAspects.set( ThEPartEssentiaIOBus_Base.TIER1_INDEXS[i], null ); - } - } - else - { - // Tier 1 slots - System.arraycopy( ThEPartEssentiaIOBus_Base.TIER1_INDEXS, 0, this.availableFilterSlots, 1, 4 ); - } - } - else - { - // Add both - System.arraycopy( ThEPartEssentiaIOBus_Base.TIER1_INDEXS, 0, this.availableFilterSlots, 1, 4 ); - System.arraycopy( ThEPartEssentiaIOBus_Base.TIER2_INDEXS, 0, this.availableFilterSlots, 5, 4 ); - } - } - - private void updateUpgradeState() - { - int oldFilterSize = this.filterSize; - - this.filterSize = 0; - this.redstoneControlled = false; - this.upgradeSpeedCount = 0; - hasCraftingCard = false; - - IMaterials aeMaterals = AEApi.instance().definitions().materials(); - - for( int i = 0; i < this.upgradeInventory.getSizeInventory(); i++ ) - { - ItemStack slotStack = this.upgradeInventory.getStackInSlot( i ); - - if( slotStack != null ) - { - if( aeMaterals.cardCapacity().isSameAs( slotStack ) ) - { - this.filterSize++ ; - } - else if( aeMaterals.cardRedstone().isSameAs( slotStack ) ) - { - this.redstoneControlled = true; - } - else if( aeMaterals.cardSpeed().isSameAs( slotStack ) ) - { - this.upgradeSpeedCount++ ; - } - else if( aeMaterals.cardCrafting().isSameAs( slotStack ) ) - { - this.hasCraftingCard = true; - } - } - } - - // Did the filter size change? - if( oldFilterSize != this.filterSize ) - { - this.resizeAvailableArray(); - } - - // Is this client side? - if( EffectiveSide.isClientSide() ) - { - return; - } - if (!hasCraftingCard) - setCraftingOnly(false); - - this.notifyListenersOfFilterSizeChange(); - this.notifyListenersOfRedstoneControlledChange(); - this.notifyListenersOfHasCraftingCardChange(); - } - - public boolean addFilteredAspectFromItemstack( final EntityPlayer player, final ItemStack itemStack ) - { - Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem( itemStack ); - - if( itemAspect != null ) - { - // Are we already filtering this aspect? - if( this.filteredAspects.contains( itemAspect ) ) - { - return true; - } - - // Add to the first open slot - for( int avalibleIndex = 0; avalibleIndex < this.availableFilterSlots.length; avalibleIndex++ ) - { - int filterIndex = this.availableFilterSlots[avalibleIndex]; - - // Is this space empty? - if( this.filteredAspects.get( filterIndex ) == null ) - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Set the filter - this.setAspect( filterIndex, itemAspect, player ); - } - - return true; - } - } - } - - return false; - } - - public void addListener( final ContainerPartEssentiaIOBus container ) - { - if( !this.listeners.contains( container ) ) - { - this.listeners.add( container ); - } - } - - public abstract boolean aspectTransferAllowed( Aspect aspect ); - - @Override - public int cableConnectionRenderTo() - { - return 5; - } - - public abstract boolean doWork( int transferAmount ); - - @Override - public Object getClientGuiElement( final EntityPlayer player ) - { - return new GuiEssentiaIO( this, player ); - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - // Add upgrades to drops - for( int slotIndex = 0; slotIndex < ThEPartEssentiaIOBus_Base.UPGRADE_INVENTORY_SIZE; slotIndex++ ) - { - // Get the upgrade card in this slot - ItemStack slotStack = this.upgradeInventory.getStackInSlot( slotIndex ); - - // Is it not null? - if( ( slotStack != null ) && ( slotStack.stackSize > 0 ) ) - { - // Add to the drops - drops.add( slotStack ); - } - } - } - - /** - * Determines how much power the part takes for just - * existing. - */ - @Override - public double getIdlePowerUsage() - { - return ThEPartEssentiaIOBus_Base.IDLE_POWER_DRAIN; - } - - /** - * Produces a small amount of light when active. - */ - @Override - public int getLightLevel() - { - return( this.isActive() ? 4 : 0 ); - } - - public RedstoneMode getRedstoneMode() - { - return this.redstoneMode; - } - - @Override - public Object getServerGuiElement( final EntityPlayer player ) - { - return new ContainerPartEssentiaIOBus( this, player ); - } - - @Override - public TickingRequest getTickingRequest( final IGridNode arg0 ) - { - return new TickingRequest( MINIMUM_TICKS_PER_OPERATION, MAXIMUM_TICKS_PER_OPERATION, false, false ); - } - - public UpgradeInventory getUpgradeInventory() - { - return this.upgradeInventory; - } - - public boolean isVoidAllowed() - { - return false; - } - - public boolean isCraftingOnly() - { - return false; - } - public void setCraftingOnly(boolean c) - { - } - - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - boolean activated = super.onActivate( player, position ); - - this.updateUpgradeState(); - - return activated; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, - final ItemStack newStack ) - { - if( inv == this.upgradeInventory ) - { - this.updateUpgradeState(); - } - } - - /** - * Called when a player has clicked the redstone button in the gui. - */ - public void onClientRequestChangeRedstoneMode() - { - // Get the current ordinal, and increment it - int nextOrdinal = this.redstoneMode.ordinal() + 1; - - // Bounds check - if( nextOrdinal >= EnumCache.AE_REDSTONE_MODES.length ) - { - nextOrdinal = 0; - } - - // Set the mode - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[nextOrdinal]; - - // Notify listeners - this.notifyListenersOfRedstoneModeChange(); - } - - /** - * Called when a client gui is requesting a full update. - * - * @param player - */ - public void onClientRequestFilterList( final EntityPlayer player ) - { - // Set the filter list - Packet_C_AspectSlot.setFilterList( this.filteredAspects, player ); - - // Set the state of the bus - Packet_C_EssentiaIOBus.sendBusState( player, this.redstoneMode, this.filterSize, this.redstoneControlled, hasCraftingCard, isCraftingOnly() ); - } - - @Override - public void onNeighborChanged() - { - // Ignored client side - if( EffectiveSide.isClientSide() ) - { - return; - } - - // Set that we are not facing a container - this.facingContainer = null; - - // Get the tile we are facing - TileEntity tileEntity = this.getFacingTile(); - - // Are we facing a container? - if( tileEntity instanceof IAspectContainer ) - { - this.facingContainer = (IAspectContainer)tileEntity; - } - - // Is the bus pulse controlled? - if( this.redstoneMode == RedstoneMode.SIGNAL_PULSE ) - { - // Did the state of the redstone change? - if( this.isReceivingRedstonePower() != this.lastRedstone ) - { - // Set the previous redstone state - this.lastRedstone = this.isReceivingRedstonePower(); - - // Do work - this.doWork( this.getTransferAmountPerSecond() ); - } - } - } - - /** - * Called client-side to keep the client-side part in sync - * with the server-side part. This aids in keeping the - * gui in sync even in high network lag enviroments. - * - * @param filteredAspects - */ - @SideOnly(Side.CLIENT) - public void onReceiveFilterList( final List filteredAspects ) - { - this.filteredAspects = filteredAspects; - } - - /** - * Called client-side to keep the client-side part in sync - * with the server-side part. This aids in keeping the - * gui in sync even in high network lag enviroments. - * - * @param filterSize - */ - @SideOnly(Side.CLIENT) - public void onReceiveFilterSize( final byte filterSize ) - { - this.filterSize = filterSize; - - this.resizeAvailableArray(); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read redstone mode - if( data.hasKey( NBT_KEY_REDSTONE_MODE ) ) - { - this.redstoneMode = EnumCache.AE_REDSTONE_MODES[data.getInteger( NBT_KEY_REDSTONE_MODE )]; - } - - // Read filters - for( int index = 0; index < MAX_FILTER_SIZE; index++ ) - { - if( data.hasKey( NBT_KEY_FILTER_NUMBER + index ) ) - { - // Get the aspect - this.filteredAspects.set( index, Aspect.aspects.get( data.getString( NBT_KEY_FILTER_NUMBER + index ) ) ); - } - } - - // Read upgrade inventory - if( data.hasKey( ThEPartEssentiaIOBus_Base.NBT_KEY_UPGRADE_INV ) ) - { - this.upgradeInventory.readFromNBT( data, ThEPartEssentiaIOBus_Base.NBT_KEY_UPGRADE_INV ); - - this.updateUpgradeState(); - } - } - - public void removeListener( final ContainerPartEssentiaIOBus container ) - { - this.listeners.remove( container ); - } - - /** - * Called when the internal inventory changes. - */ - @Override - public void saveChanges() - { - this.markForSave(); - } - - @Override - public final void setAspect( final int index, final Aspect aspect, final EntityPlayer player ) - { - // Set the filter - this.filteredAspects.set( index, aspect ); - - // Update the listeners - this.notifyListenersOfFilterAspectChange(); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.canDoWork() ) - { - // Calculate the amount to transfer per second - int transferAmountPerSecond = this.getTransferAmountPerSecond(); - - // Calculate amount to transfer this operation - int transferAmount = (int)( transferAmountPerSecond * ( ticksSinceLastCall / 20.F ) ); - - // Clamp - if( transferAmount < MINIMUM_TRANSFER_PER_SECOND ) - { - transferAmount = MINIMUM_TRANSFER_PER_SECOND; - } - else if( transferAmount > MAXIMUM_TRANSFER_PER_SECOND ) - { - transferAmount = MAXIMUM_TRANSFER_PER_SECOND; - } - - if( this.doWork( transferAmount ) ) - { - return TickRateModulation.URGENT; - } - } - - return TickRateModulation.IDLE; - } - - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); - - if( ( saveType == PartItemStack.World ) || ( saveType == PartItemStack.Wrench ) ) - { - // Write each filter - for( int i = 0; i < MAX_FILTER_SIZE; i++ ) - { - Aspect aspect = this.filteredAspects.get( i ); - if( aspect != null ) - { - data.setString( NBT_KEY_FILTER_NUMBER + i, aspect.getTag() ); - } - } - - if( saveType == PartItemStack.World ) - { - // Write the redstone mode - if( this.redstoneMode != DEFAULT_REDSTONE_MODE ) - { - data.setInteger( NBT_KEY_REDSTONE_MODE, this.redstoneMode.ordinal() ); - } - - // Write the upgrade inventory - if( !this.upgradeInventory.isEmpty() ) - { - this.upgradeInventory.writeToNBT( data, NBT_KEY_UPGRADE_INV ); - } - } - } - } + // Initialize the list + for (int index = 0; index < ThEPartEssentiaIOBus_Base.MAX_FILTER_SIZE; index++) { + this.filteredAspects.add(null); + } + + // Create the source + this.asMachineSource = new MachineSource(this); + } + + private boolean canDoWork() { + boolean canWork = true; + + if (this.redstoneControlled) { + switch (this.getRedstoneMode()) { + case HIGH_SIGNAL: + canWork = this.isReceivingRedstonePower(); + + break; + case IGNORE: + break; + + case LOW_SIGNAL: + canWork = !this.isReceivingRedstonePower(); + + break; + case SIGNAL_PULSE: + canWork = false; + break; + } + } + + return canWork; + } + + private int getTransferAmountPerSecond() { + return BASE_TRANSFER_PER_SECOND + (this.upgradeSpeedCount * ADDITIONAL_TRANSFER_PER_SECOND); + } + + private void notifyListenersOfFilterAspectChange() { + for (ContainerPartEssentiaIOBus listener : this.listeners) { + listener.setFilteredAspect(this.filteredAspects); + } + } + + private void notifyListenersOfFilterSizeChange() { + for (ContainerPartEssentiaIOBus listener : this.listeners) { + listener.setFilterSize(this.filterSize); + } + } + + private void notifyListenersOfRedstoneControlledChange() { + for (ContainerPartEssentiaIOBus listener : this.listeners) { + listener.setRedstoneControlled(this.redstoneControlled); + } + } + + private void notifyListenersOfHasCraftingCardChange() { + for (ContainerPartEssentiaIOBus listener : this.listeners) { + listener.setHasCraftingCard(this.hasCraftingCard); + } + } + + private void notifyListenersOfRedstoneModeChange() { + for (ContainerPartEssentiaIOBus listener : this.listeners) { + listener.setRedstoneMode(this.redstoneMode); + } + } + + private void resizeAvailableArray() { + // Resize the available slots + this.availableFilterSlots = new int[1 + (this.filterSize * 4)]; + + // Add the base slot + this.availableFilterSlots[0] = ThEPartEssentiaIOBus_Base.BASE_SLOT_INDEX; + + if (this.filterSize < 2) { + // Reset tier 2 slots + for (int i = 0; i < ThEPartEssentiaIOBus_Base.TIER2_INDEXS.length; i++) { + this.filteredAspects.set(ThEPartEssentiaIOBus_Base.TIER2_INDEXS[i], null); + } + + if (this.filterSize < 1) { + // Reset tier 1 slots + for (int i = 0; i < ThEPartEssentiaIOBus_Base.TIER1_INDEXS.length; i++) { + this.filteredAspects.set(ThEPartEssentiaIOBus_Base.TIER1_INDEXS[i], null); + } + } else { + // Tier 1 slots + System.arraycopy(ThEPartEssentiaIOBus_Base.TIER1_INDEXS, 0, this.availableFilterSlots, 1, 4); + } + } else { + // Add both + System.arraycopy(ThEPartEssentiaIOBus_Base.TIER1_INDEXS, 0, this.availableFilterSlots, 1, 4); + System.arraycopy(ThEPartEssentiaIOBus_Base.TIER2_INDEXS, 0, this.availableFilterSlots, 5, 4); + } + } + + private void updateUpgradeState() { + int oldFilterSize = this.filterSize; + + this.filterSize = 0; + this.redstoneControlled = false; + this.upgradeSpeedCount = 0; + hasCraftingCard = false; + + IMaterials aeMaterals = AEApi.instance().definitions().materials(); + + for (int i = 0; i < this.upgradeInventory.getSizeInventory(); i++) { + ItemStack slotStack = this.upgradeInventory.getStackInSlot(i); + + if (slotStack != null) { + if (aeMaterals.cardCapacity().isSameAs(slotStack)) { + this.filterSize++; + } else if (aeMaterals.cardRedstone().isSameAs(slotStack)) { + this.redstoneControlled = true; + } else if (aeMaterals.cardSpeed().isSameAs(slotStack)) { + this.upgradeSpeedCount++; + } else if (aeMaterals.cardCrafting().isSameAs(slotStack)) { + this.hasCraftingCard = true; + } + } + } + + // Did the filter size change? + if (oldFilterSize != this.filterSize) { + this.resizeAvailableArray(); + } + + // Is this client side? + if (EffectiveSide.isClientSide()) { + return; + } + if (!hasCraftingCard) setCraftingOnly(false); + + this.notifyListenersOfFilterSizeChange(); + this.notifyListenersOfRedstoneControlledChange(); + this.notifyListenersOfHasCraftingCardChange(); + } + + public boolean addFilteredAspectFromItemstack(final EntityPlayer player, final ItemStack itemStack) { + Aspect itemAspect = EssentiaItemContainerHelper.INSTANCE.getFilterAspectFromItem(itemStack); + + if (itemAspect != null) { + // Are we already filtering this aspect? + if (this.filteredAspects.contains(itemAspect)) { + return true; + } + + // Add to the first open slot + for (int avalibleIndex = 0; avalibleIndex < this.availableFilterSlots.length; avalibleIndex++) { + int filterIndex = this.availableFilterSlots[avalibleIndex]; + + // Is this space empty? + if (this.filteredAspects.get(filterIndex) == null) { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Set the filter + this.setAspect(filterIndex, itemAspect, player); + } + + return true; + } + } + } + + return false; + } + + public void addListener(final ContainerPartEssentiaIOBus container) { + if (!this.listeners.contains(container)) { + this.listeners.add(container); + } + } + + public abstract boolean aspectTransferAllowed(Aspect aspect); + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + public abstract boolean doWork(int transferAmount); + + @Override + public Object getClientGuiElement(final EntityPlayer player) { + return new GuiEssentiaIO(this, player); + } + + @Override + public void getDrops(final List drops, final boolean wrenched) { + // Add upgrades to drops + for (int slotIndex = 0; slotIndex < ThEPartEssentiaIOBus_Base.UPGRADE_INVENTORY_SIZE; slotIndex++) { + // Get the upgrade card in this slot + ItemStack slotStack = this.upgradeInventory.getStackInSlot(slotIndex); + + // Is it not null? + if ((slotStack != null) && (slotStack.stackSize > 0)) { + // Add to the drops + drops.add(slotStack); + } + } + } + + /** + * Determines how much power the part takes for just + * existing. + */ + @Override + public double getIdlePowerUsage() { + return ThEPartEssentiaIOBus_Base.IDLE_POWER_DRAIN; + } + + /** + * Produces a small amount of light when active. + */ + @Override + public int getLightLevel() { + return (this.isActive() ? 4 : 0); + } + + public RedstoneMode getRedstoneMode() { + return this.redstoneMode; + } + + @Override + public Object getServerGuiElement(final EntityPlayer player) { + return new ContainerPartEssentiaIOBus(this, player); + } + + @Override + public TickingRequest getTickingRequest(final IGridNode arg0) { + return new TickingRequest(MINIMUM_TICKS_PER_OPERATION, MAXIMUM_TICKS_PER_OPERATION, false, false); + } + + public UpgradeInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + public boolean isVoidAllowed() { + return false; + } + + public boolean isCraftingOnly() { + return false; + } + + public void setCraftingOnly(boolean c) {} + + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + boolean activated = super.onActivate(player, position); + + this.updateUpgradeState(); + + return activated; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack) { + if (inv == this.upgradeInventory) { + this.updateUpgradeState(); + } + } + + /** + * Called when a player has clicked the redstone button in the gui. + */ + public void onClientRequestChangeRedstoneMode() { + // Get the current ordinal, and increment it + int nextOrdinal = this.redstoneMode.ordinal() + 1; + + // Bounds check + if (nextOrdinal >= EnumCache.AE_REDSTONE_MODES.length) { + nextOrdinal = 0; + } + + // Set the mode + this.redstoneMode = EnumCache.AE_REDSTONE_MODES[nextOrdinal]; + + // Notify listeners + this.notifyListenersOfRedstoneModeChange(); + } + + /** + * Called when a client gui is requesting a full update. + * + * @param player + */ + public void onClientRequestFilterList(final EntityPlayer player) { + // Set the filter list + Packet_C_AspectSlot.setFilterList(this.filteredAspects, player); + + // Set the state of the bus + Packet_C_EssentiaIOBus.sendBusState( + player, this.redstoneMode, this.filterSize, this.redstoneControlled, hasCraftingCard, isCraftingOnly()); + } + + @Override + public void onNeighborChanged() { + // Ignored client side + if (EffectiveSide.isClientSide()) { + return; + } + + // Set that we are not facing a container + this.facingContainer = null; + + // Get the tile we are facing + TileEntity tileEntity = this.getFacingTile(); + + // Are we facing a container? + if (tileEntity instanceof IAspectContainer) { + this.facingContainer = (IAspectContainer) tileEntity; + } + + // Is the bus pulse controlled? + if (this.redstoneMode == RedstoneMode.SIGNAL_PULSE) { + // Did the state of the redstone change? + if (this.isReceivingRedstonePower() != this.lastRedstone) { + // Set the previous redstone state + this.lastRedstone = this.isReceivingRedstonePower(); + + // Do work + this.doWork(this.getTransferAmountPerSecond()); + } + } + } + + /** + * Called client-side to keep the client-side part in sync + * with the server-side part. This aids in keeping the + * gui in sync even in high network lag enviroments. + * + * @param filteredAspects + */ + @SideOnly(Side.CLIENT) + public void onReceiveFilterList(final List filteredAspects) { + this.filteredAspects = filteredAspects; + } + + /** + * Called client-side to keep the client-side part in sync + * with the server-side part. This aids in keeping the + * gui in sync even in high network lag enviroments. + * + * @param filterSize + */ + @SideOnly(Side.CLIENT) + public void onReceiveFilterSize(final byte filterSize) { + this.filterSize = filterSize; + + this.resizeAvailableArray(); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); + + // Read redstone mode + if (data.hasKey(NBT_KEY_REDSTONE_MODE)) { + this.redstoneMode = EnumCache.AE_REDSTONE_MODES[data.getInteger(NBT_KEY_REDSTONE_MODE)]; + } + + // Read filters + for (int index = 0; index < MAX_FILTER_SIZE; index++) { + if (data.hasKey(NBT_KEY_FILTER_NUMBER + index)) { + // Get the aspect + this.filteredAspects.set(index, Aspect.aspects.get(data.getString(NBT_KEY_FILTER_NUMBER + index))); + } + } + + // Read upgrade inventory + if (data.hasKey(ThEPartEssentiaIOBus_Base.NBT_KEY_UPGRADE_INV)) { + this.upgradeInventory.readFromNBT(data, ThEPartEssentiaIOBus_Base.NBT_KEY_UPGRADE_INV); + + this.updateUpgradeState(); + } + } + + public void removeListener(final ContainerPartEssentiaIOBus container) { + this.listeners.remove(container); + } + + /** + * Called when the internal inventory changes. + */ + @Override + public void saveChanges() { + this.markForSave(); + } + + @Override + public final void setAspect(final int index, final Aspect aspect, final EntityPlayer player) { + // Set the filter + this.filteredAspects.set(index, aspect); + + // Update the listeners + this.notifyListenersOfFilterAspectChange(); + } + + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.canDoWork()) { + // Calculate the amount to transfer per second + int transferAmountPerSecond = this.getTransferAmountPerSecond(); + + // Calculate amount to transfer this operation + int transferAmount = (int) (transferAmountPerSecond * (ticksSinceLastCall / 20.F)); + + // Clamp + if (transferAmount < MINIMUM_TRANSFER_PER_SECOND) { + transferAmount = MINIMUM_TRANSFER_PER_SECOND; + } else if (transferAmount > MAXIMUM_TRANSFER_PER_SECOND) { + transferAmount = MAXIMUM_TRANSFER_PER_SECOND; + } + + if (this.doWork(transferAmount)) { + return TickRateModulation.URGENT; + } + } + + return TickRateModulation.IDLE; + } + + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); + + if ((saveType == PartItemStack.World) || (saveType == PartItemStack.Wrench)) { + // Write each filter + for (int i = 0; i < MAX_FILTER_SIZE; i++) { + Aspect aspect = this.filteredAspects.get(i); + if (aspect != null) { + data.setString(NBT_KEY_FILTER_NUMBER + i, aspect.getTag()); + } + } + + if (saveType == PartItemStack.World) { + // Write the redstone mode + if (this.redstoneMode != DEFAULT_REDSTONE_MODE) { + data.setInteger(NBT_KEY_REDSTONE_MODE, this.redstoneMode.ordinal()); + } + + // Write the upgrade inventory + if (!this.upgradeInventory.isEmpty()) { + this.upgradeInventory.writeToNBT(data, NBT_KEY_UPGRADE_INV); + } + } + } + } } diff --git a/src/main/java/thaumicenergistics/common/parts/ThERotateablePart.java b/src/main/java/thaumicenergistics/common/parts/ThERotateablePart.java index efdf1e6c..ed1c01fa 100644 --- a/src/main/java/thaumicenergistics/common/parts/ThERotateablePart.java +++ b/src/main/java/thaumicenergistics/common/parts/ThERotateablePart.java @@ -1,10 +1,10 @@ package thaumicenergistics.common.parts; -import java.io.IOException; import appeng.api.config.SecurityPermissions; import appeng.api.parts.PartItemStack; import appeng.util.Platform; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; @@ -18,150 +18,136 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public abstract class ThERotateablePart - extends ThEPartBase -{ - /** - * NBT keys - */ - private static final String NBT_KEY_ROT_DIR = "partRotation"; +public abstract class ThERotateablePart extends ThEPartBase { + /** + * NBT keys + */ + private static final String NBT_KEY_ROT_DIR = "partRotation"; - /** - * What direction should be rotated to. - * Valid values are 0,1,2,3. - */ - private byte renderRotation = 0; + /** + * What direction should be rotated to. + * Valid values are 0,1,2,3. + */ + private byte renderRotation = 0; - public ThERotateablePart( final AEPartsEnum associatedPart, final SecurityPermissions ... interactionPermissions ) - { - super( associatedPart, interactionPermissions ); - } + public ThERotateablePart(final AEPartsEnum associatedPart, final SecurityPermissions... interactionPermissions) { + super(associatedPart, interactionPermissions); + } - /** - * Rotates the renderer. - * - * @param renderer - * @param reset - */ - protected void rotateRenderer( final RenderBlocks renderer, final boolean reset ) - { - int rot = ( reset ? 0 : this.renderRotation ); - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = rot; - } + /** + * Rotates the renderer. + * + * @param renderer + * @param reset + */ + protected void rotateRenderer(final RenderBlocks renderer, final boolean reset) { + int rot = (reset ? 0 : this.renderRotation); + renderer.uvRotateBottom = renderer.uvRotateEast = + renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = rot; + } - /** - * Called when the part is right-clicked - */ - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 position ) - { - // Get the host tile entity - TileEntity hte = this.getHostTile(); + /** + * Called when the part is right-clicked + */ + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 position) { + // Get the host tile entity + TileEntity hte = this.getHostTile(); - // Is the player not sneaking and using a wrench? - if( !player.isSneaking() && Platform.isWrench( player, player.inventory.getCurrentItem(), hte.xCoord, hte.yCoord, hte.zCoord ) ) - { - if( EffectiveSide.isServerSide() ) - { - // Bounds check the rotation - if( ( this.renderRotation > 3 ) || ( this.renderRotation < 0 ) ) - { - this.renderRotation = 0; - } + // Is the player not sneaking and using a wrench? + if (!player.isSneaking() + && Platform.isWrench(player, player.inventory.getCurrentItem(), hte.xCoord, hte.yCoord, hte.zCoord)) { + if (EffectiveSide.isServerSide()) { + // Bounds check the rotation + if ((this.renderRotation > 3) || (this.renderRotation < 0)) { + this.renderRotation = 0; + } - // Rotate - switch ( this.renderRotation ) - { - case 0: - this.renderRotation = 1; - break; - case 1: - this.renderRotation = 3; - break; - case 2: - this.renderRotation = 0; - break; - case 3: - this.renderRotation = 2; - break; - } + // Rotate + switch (this.renderRotation) { + case 0: + this.renderRotation = 1; + break; + case 1: + this.renderRotation = 3; + break; + case 2: + this.renderRotation = 0; + break; + case 3: + this.renderRotation = 2; + break; + } - // Mark for sync & save - this.markForUpdate(); - this.markForSave(); - } - return true; - } + // Mark for sync & save + this.markForUpdate(); + this.markForSave(); + } + return true; + } - return super.onActivate( player, position ); - } + return super.onActivate(player, position); + } - /** - * Reads the rotation - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); + /** + * Reads the rotation + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); - // Read rotation - if( data.hasKey( ThERotateablePart.NBT_KEY_ROT_DIR ) ) - { - this.renderRotation = data.getByte( ThERotateablePart.NBT_KEY_ROT_DIR ); - } - } + // Read rotation + if (data.hasKey(ThERotateablePart.NBT_KEY_ROT_DIR)) { + this.renderRotation = data.getByte(ThERotateablePart.NBT_KEY_ROT_DIR); + } + } - /** - * Reads the rotation from the stream. - */ - @Override - public boolean readFromStream( final ByteBuf stream ) throws IOException - { - boolean redraw = false; + /** + * Reads the rotation from the stream. + */ + @Override + public boolean readFromStream(final ByteBuf stream) throws IOException { + boolean redraw = false; - // Call super - redraw |= super.readFromStream( stream ); + // Call super + redraw |= super.readFromStream(stream); - // Read the rotation - byte streamRot = stream.readByte(); + // Read the rotation + byte streamRot = stream.readByte(); - // Did the rotaion change? - if( this.renderRotation != streamRot ) - { - this.renderRotation = streamRot; - redraw |= true; - } + // Did the rotaion change? + if (this.renderRotation != streamRot) { + this.renderRotation = streamRot; + redraw |= true; + } - return redraw; - } + return redraw; + } - /** - * Saves the rotation - */ - @Override - public void writeToNBT( final NBTTagCompound data, final PartItemStack saveType ) - { - // Call super - super.writeToNBT( data, saveType ); + /** + * Saves the rotation + */ + @Override + public void writeToNBT(final NBTTagCompound data, final PartItemStack saveType) { + // Call super + super.writeToNBT(data, saveType); - // Write the rotation - if( ( saveType == PartItemStack.World ) && ( this.renderRotation != 0 ) ) - { - data.setByte( ThERotateablePart.NBT_KEY_ROT_DIR, this.renderRotation ); - } - } + // Write the rotation + if ((saveType == PartItemStack.World) && (this.renderRotation != 0)) { + data.setByte(ThERotateablePart.NBT_KEY_ROT_DIR, this.renderRotation); + } + } - /** - * Writes the rotation to the stream. - */ - @Override - public void writeToStream( final ByteBuf stream ) throws IOException - { - // Call super - super.writeToStream( stream ); + /** + * Writes the rotation to the stream. + */ + @Override + public void writeToStream(final ByteBuf stream) throws IOException { + // Call super + super.writeToStream(stream); - // Write the rotation - stream.writeByte( this.renderRotation ); - } + // Write the rotation + stream.writeByte(this.renderRotation); + } } diff --git a/src/main/java/thaumicenergistics/common/registries/AEAspectRegister.java b/src/main/java/thaumicenergistics/common/registries/AEAspectRegister.java index e2750983..804830f5 100644 --- a/src/main/java/thaumicenergistics/common/registries/AEAspectRegister.java +++ b/src/main/java/thaumicenergistics/common/registries/AEAspectRegister.java @@ -1,9 +1,5 @@ package thaumicenergistics.common.registries; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.*; import appeng.api.features.IGrinderEntry; @@ -13,6 +9,10 @@ import appeng.api.util.AEColoredItemDefinition; import appeng.core.features.registries.entries.InscriberRecipe; import appeng.recipes.GroupIngredient; import appeng.recipes.Ingredient; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; @@ -32,1325 +32,1163 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class AEAspectRegister -{ - /** - * Helper class to derive aspects from an item definition. - * - * @author Nividica - * - */ - private class AEItemInfo - { - /** - * Human readable name of the item. - */ - private String displayName = ""; - - /** - * Selected ingredients used to craft this item. - */ - private ItemStack[] ingredients = null; - - /** - * Aspects derived from the ingredients. - */ - private AspectList ingredientAspects = new AspectList(); - - /** - * Recipe used to craft this item. - */ - private Object recipe = null; - - /** - * Definition of the item. - */ - private IItemDefinition definition; - - /** - * Aspects manually added to the item. - */ - public AspectList bonusAspects = new AspectList(); - - /** - * Itemstack holding the item. - */ - public ItemStack itemStack = null; - - /** - * The current trial pass. - */ - private int pass; - - /** - * Creates the info. - * - * @param itemDef - */ - public AEItemInfo( final IItemDefinition itemDef ) - { - // Set the definition - this.definition = itemDef; - - // Is the def available? - if( itemDef.maybeStack( 1 ).isPresent() ) - { - this.itemStack = itemDef.maybeStack( 1 ).get(); - } - - if( this.itemStack != null ) - { - this.displayName = this.itemStack.getDisplayName(); - } - } - - /** - * Adds bonus aspects for certain types. - */ - private void addPredefinedBonuses() - { - IBlocks aeBlocks = AEApi.instance().definitions().blocks(); - IMaterials aeMats = AEApi.instance().definitions().materials(); - //IItems aeItems = AEApi.instance().definitions().items(); - - // Grinder recipe? - if( this.recipe instanceof IGrinderEntry ) - { - // Add a bonus aspect for grinding - this.bonusAspects.add( Aspect.ENTROPY, 1 ); - - // Remove any Terra - this.ingredientAspects.remove( Aspect.EARTH ); - } - - // Molecular Assembler - else if( this.definition.equals( aeBlocks.molecularAssembler() ) ) - { - // Add extra craft, machina, potentia and vitrius - this.bonusAspects.add( Aspect.CRAFT, 4 ); - this.bonusAspects.add( Aspect.ENERGY, 6 ); - this.bonusAspects.add( Aspect.MECHANISM, 2 ); - this.bonusAspects.add( Aspect.CRYSTAL, 1 ); - } - - // Sky stone - else if( this.definition.equals( aeBlocks.skyStone() ) ) - { - // Add tene - this.bonusAspects.add( Aspect.DARKNESS, 3 ); - } - - // Sky chest - else if( this.definition.equals( aeBlocks.skyChest() ) ) - { - // Add vac - this.bonusAspects.add( Aspect.VOID, 4 ); - - // Remove terra - this.ingredientAspects.remove( Aspect.EARTH ); - } - - // Quartz glass - else if( this.definition.equals( aeBlocks.quartzGlass() ) ) - { - // Add vit - this.bonusAspects.add( Aspect.CRYSTAL, 4 ); - } - - // ME Controller - else if( this.definition.equals( aeBlocks.controller() ) ) - { - // Add mach, sense, mind - this.bonusAspects.add( Aspect.MECHANISM, 3 ); - this.bonusAspects.add( Aspect.SENSES, 1 ); - this.bonusAspects.add( Aspect.MIND, 9 ); - - // Remove fire, order - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - } - - // ME Drive - else if( this.definition.equals( aeBlocks.drive() ) ) - { - // Add vac - this.bonusAspects.add( Aspect.VOID, 4 ); - - // Remove fire, order, sense, mach - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - this.ingredientAspects.remove( Aspect.SENSES ); - this.ingredientAspects.remove( Aspect.MECHANISM ); - } - - // ME Chest - else if( this.definition.equals( aeBlocks.chest() ) ) - { - // Add vac - this.bonusAspects.add( Aspect.VOID, 4 ); - - // Remove fire, order, sense, mach - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - this.ingredientAspects.remove( Aspect.SENSES ); - this.ingredientAspects.remove( Aspect.MECHANISM ); - } - - // ME IO Port - else if( this.definition.equals( aeBlocks.iOPort() ) ) - { - // Add perm - this.bonusAspects.add( Aspect.EXCHANGE, 4 ); - - // Remove fire, order, sense, mach - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - this.ingredientAspects.remove( Aspect.SENSES ); - this.ingredientAspects.remove( Aspect.MECHANISM ); - } - - // ME IO Port - else if( this.definition.equals( aeBlocks.condenser() ) ) - { - // Add vac - this.bonusAspects.add( Aspect.VOID, 10 ); - } - // Redstone card - else if( this.definition.equals( aeMats.cardRedstone() ) ) - { - // Add sense - this.bonusAspects.add( Aspect.SENSES, 2 ); - } - // Cell workbench - else if( this.definition.equals( aeBlocks.cellWorkbench() ) ) - { - // Add cloth - this.bonusAspects.add( Aspect.CLOTH, 2 ); - } - // ME Interface - else if( this.definition.equals( aeBlocks.iface() ) ) - { - // Add permutatio - this.bonusAspects.add( Aspect.EXCHANGE, 6 ); - } - // Logic processor - else if( this.definition.equals( aeMats.logicProcessor() ) ) - { - // Remove metal & fire & ordo - this.ingredientAspects.remove( Aspect.METAL ); - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - - // Add mind & metal - this.bonusAspects.add( Aspect.MIND, 3 ); - this.bonusAspects.add( Aspect.METAL, 1 ); - } - // Calc processor - else if( this.definition.equals( aeMats.calcProcessor() ) ) - { - // Remove metal & fire & ordo - this.ingredientAspects.remove( Aspect.METAL ); - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - - // Add mind & metal - this.bonusAspects.add( Aspect.MIND, 6 ); - this.bonusAspects.add( Aspect.METAL, 1 ); - } - // Eng processor - else if( this.definition.equals( aeMats.engProcessor() ) ) - { - // Remove metal & fire & ordo - this.ingredientAspects.remove( Aspect.METAL ); - this.ingredientAspects.remove( Aspect.FIRE ); - this.ingredientAspects.remove( Aspect.ORDER ); - - // Add mind - this.bonusAspects.add( Aspect.MIND, 9 ); - } - - } - - /** - * Attempts to build the aspects for the item via recipe => ingredients - */ - private void buildAspects() - { - // Grinder recipes - if( AEAspectRegister.this.GRINDER_RECIPES != null ) - { - if( this.buildAspectsFromGrinder() ) - { - return; - } - } - - // Inscriber recipes - if( AEAspectRegister.this.INSCRIBER_RECIPES != null ) - { - if( this.buildAspectsFromInscriber() ) - { - return; - } - } - - // Regular crafting recipes - if( AEAspectRegister.this.NORMAL_RECIPES != null ) - { - if( this.buildAspectsFromNormal() ) - { - return; - } - } - } - - /** - * Attempts to build the aspects for the item via grinder recipes. - * - * @return - */ - private boolean buildAspectsFromGrinder() - { - try - { - for( IGrinderEntry recipe : AEAspectRegister.this.GRINDER_RECIPES ) - { - ItemStack recipeOutput = recipe.getOutput(); - - // Skip null items - if( ( recipeOutput == null ) || ( recipeOutput.getItem() == null ) ) - { - continue; - } - - if( ThEUtils.areStacksEqualIgnoreAmount( recipeOutput, this.itemStack ) ) - { - if( this.isRecipeUsable( recipe ) ) - { - return true; - } - } - } - } - catch( Exception e ) - { - } - - return false; - } - - /** - * Attempts to build the aspects for the item via inscriber recipes. - * - * @return - */ - private boolean buildAspectsFromInscriber() - { - try - { - for( IInscriberRecipe recipe : AEAspectRegister.this.INSCRIBER_RECIPES ) - { - ItemStack recipeOutput = recipe.getOutput(); - - // Skip null items - if( ( recipeOutput == null ) || ( recipeOutput.getItem() == null ) ) - { - continue; - } - - if( ThEUtils.areStacksEqualIgnoreAmount( recipeOutput, this.itemStack ) ) - { - if( this.isRecipeUsable( recipe ) ) - { - return true; - } - } - } - } - catch( Exception e ) - { - } - return false; - } - - /** - * Attempts to build the aspects for the item via normal recipes. - * - * @return - */ - private boolean buildAspectsFromNormal() - { - - try - { - for( IRecipe recipe : AEAspectRegister.this.NORMAL_RECIPES ) - { - // Get the recipe's result - ItemStack recipeOutput = recipe.getRecipeOutput(); - - // Skip null items - if( ( recipeOutput == null ) || ( recipeOutput.getItem() == null ) ) - { - continue; - } - - // Is this what we are looking for? - if( !ThEUtils.areStacksEqualIgnoreAmount( recipeOutput, this.itemStack ) ) - { - continue; - } - - if( this.isRecipeUsable( recipe ) ) - { - return true; - } - } - - } - catch( Exception e ) - { - } - - return false; - } - - /** - * Builds the aspect list from the items ingredients. - * - * @param itemInfo - */ - private void findAspectsForIngredients() - { - for( ItemStack stack : this.ingredients ) - { - // Get the aspects for the stack - AspectList stackAspects = ThaumcraftApiHelper.getObjectAspects( stack ); - - // Are there no aspects for this item? - if( ( stackAspects == null ) || ( stackAspects.size() == 0 ) ) - { - // Is the item an AE item? - AEItemInfo ingInfo = AEAspectRegister.this.getInfoForDefinitionOrStack( stack ); - - if( ingInfo != null ) - { - // Ensure the item is not in the dependency chain. - if( !AEAspectRegister.this.DEPENDENCY_CHAIN.contains( ingInfo ) ) - { - // Register the item - ingInfo.registerItem( this.pass ); - - // Attempt to get the aspects again - stackAspects = ThaumcraftApiHelper.getObjectAspects( stack ); - } - } - } - - // Are there still no aspects to add? - if( ( stackAspects == null ) || ( stackAspects.size() == 0 ) ) - { - continue; - } - - // Assign each aspect - for( Aspect currentStackAspect : stackAspects.getAspects() ) - { - // Get the current amount - int existingAmount = this.ingredientAspects.getAmount( currentStackAspect ); - - // Get the ingredient amount - int ingredientAspectAmount = stackAspects.getAmount( currentStackAspect ); - - // Merge - if( existingAmount < ingredientAspectAmount ) - { - this.ingredientAspects.add( currentStackAspect, ( ingredientAspectAmount - existingAmount ) ); - } - } - } - } - - /** - * Builds a list of ingredients for this item. - */ - private void getIngredientsForRecipe() - { - Object[] ingredientObjects = null; - - // What kind of recipe is this? - if( this.recipe instanceof appeng.recipes.game.ShapedRecipe ) - { - // Get ingredients - ingredientObjects = ( (appeng.recipes.game.ShapedRecipe)this.recipe ).getInput(); - } - - else if( this.recipe instanceof appeng.recipes.game.ShapelessRecipe ) - { - // Get ingredients - ingredientObjects = ( (appeng.recipes.game.ShapelessRecipe)this.recipe ).getInput().toArray(); - } - - else if( this.recipe instanceof IGrinderEntry ) - { - // Get ingredient - ingredientObjects = new Object[] { ( (IGrinderEntry)this.recipe ).getInput() }; - - // Add a bonus aspect for grinding - this.bonusAspects.add( Aspect.ENTROPY, 1 ); - } - - else if( this.recipe instanceof InscriberRecipe ) - { - // Cast - InscriberRecipe iRec = (InscriberRecipe)this.recipe; - - // Get inputs - List inputs = new ArrayList( iRec.getInputs() ); - - // Is there a top? - if( iRec.getTopOptional().isPresent() ) - { - // Add top - inputs.add( iRec.getTopOptional().get() ); - } - - // Is there a bottom? - if( iRec.getBottomOptional().isPresent() ) - { - // Add bottom - inputs.add( iRec.getBottomOptional().get() ); - } - - // Create array - ingredientObjects = inputs.toArray( new Object[inputs.size()] ); - - } - - else if( this.recipe instanceof net.minecraft.item.crafting.ShapedRecipes ) - { - // Get ingredients - ingredientObjects = ( (net.minecraft.item.crafting.ShapedRecipes)this.recipe ).recipeItems; - } - - else if( this.recipe instanceof net.minecraft.item.crafting.ShapelessRecipes ) - { - // Get ingredients - ingredientObjects = ( (net.minecraft.item.crafting.ShapelessRecipes)this.recipe ).recipeItems.toArray(); - } - - // Did we get the object list? - if( ingredientObjects != null ) - { - ItemStack currentIngredientStack; - List ingredientStackList = new ArrayList(); - - // Get the itemstack of each one - for( int i = 0; i < ingredientObjects.length; i++ ) - { - // Get the ingredient - Object ing = ingredientObjects[i]; - - // What is the ingredient? - if( ing == null ) - { - continue; - } - - // Clear the stack - currentIngredientStack = null; - try - { - if( ing instanceof Ingredient ) - { - if( ( (Ingredient)ing ).getNameSpace().equalsIgnoreCase( "oreDictionary" ) ) - { - currentIngredientStack = ( (Ingredient)ing ).getItemStackSet()[0]; - } - else - { - currentIngredientStack = ( (Ingredient)ing ).getItemStack(); - } - } - else if( ing instanceof GroupIngredient ) - { - currentIngredientStack = ( (GroupIngredient)ing ).getItemStackSet()[0]; - } - else if( ing instanceof ItemStack ) - { - currentIngredientStack = (ItemStack)ing; - } - - } - catch( Exception e ) - { - } - - // Skip null stacks - if( currentIngredientStack == null ) - { - continue; - } - - // Add to the list - ingredientStackList.add( currentIngredientStack ); - } - - // Was anything added? - if( ingredientStackList.size() > 0 ) - { - // Convert to array - this.ingredients = new ItemStack[ingredientStackList.size()]; - this.ingredients = ingredientStackList.toArray( this.ingredients ); - } - } - } - - /** - * Determines if the recipe is valid, and aspects - * can be derived from it. - * - * @param recipe - * @return - */ - private boolean isRecipeUsable( final Object recipe ) - { - // Set the recipe - this.recipe = recipe; - - // Get the ingredients - this.getIngredientsForRecipe(); - - // Did we get the ingredients? - if( this.ingredients != null ) - { - // Get the aspects - this.findAspectsForIngredients(); - - // Did we get aspects? - if( this.ingredientAspects.size() != 0 ) - { - return true; - } - } - - this.recipe = null; - return false; - } - - /** - * Checks if this item matches the specified object. - */ - @Override - public boolean equals( final Object obj ) - { - if( obj instanceof AEItemInfo ) - { - return this.isMatch( ( (AEItemInfo)obj ).itemStack ); - } - else if( obj instanceof ItemStack ) - { - return this.isMatch( (ItemStack)obj ); - } - else if( obj instanceof IItemDefinition ) - { - return this.isMatch( ( (IItemDefinition)obj ).maybeStack( 1 ).orNull() ); - } - - return false; - } - - /** - * Builds the final aspect list used for this item. - * - * @return - */ - public AspectList getFinalAspects() - { - AspectList finalAspects = new AspectList(); - - // Add ingredient aspects - if( this.ingredientAspects != null ) - { - for( Aspect aspect : this.ingredientAspects.getAspects() ) - { - if( aspect == null ) - { - continue; - } - - finalAspects.add( aspect, this.ingredientAspects.getAmount( aspect ) ); - } - } - - // Add bonus aspects - if( this.bonusAspects != null ) - { - for( Aspect aspect : this.bonusAspects.getAspects() ) - { - if( aspect == null ) - { - continue; - } - - finalAspects.add( aspect, this.bonusAspects.getAmount( aspect ) ); - } - } - - // Get the final aspect count - int aspectCount = finalAspects.size(); - - if( aspectCount == 0 ) - { - return finalAspects; - } - - // Can only have 6 aspects - if( aspectCount > 6 ) - { - Aspect[] aspects = finalAspects.getAspectsSortedAmount(); - - // Remove the lowest aspects - for( int index = 6; index < aspects.length; index++ ) - { - finalAspects.remove( aspects[index] ); - } - } - - return finalAspects; - } - - /** - * Hashcode - */ - @Override - public int hashCode() - { - return this.itemStack.getItem().hashCode() + this.itemStack.getItemDamage(); - } - - /** - * Compares the specified itemstack with this itemstack. - * - * @param stack - * @return - */ - public boolean isMatch( final ItemStack stack ) - { - return ThEUtils.areStacksEqualIgnoreAmount( stack, this.itemStack ); - } - - /** - * Builds this items aspect list, then registers it with Thaumcraft. - */ - public void registerItem( final int pass ) - { - // Set the pass - this.pass = pass; - - if( this.itemStack != null ) - { - // Skip anything that is not from AE - if( !this.itemStack.getItem().getClass().getCanonicalName().startsWith( "appeng" ) ) - { - //ThELog.info( "Skipping registration for non AE item: %s (%s) ", this.itemStack.getDisplayName(), this.itemStack.getItem().getClass().getCanonicalName() ); - return; - } - - // Add to the dependency chain - AEAspectRegister.this.DEPENDENCY_CHAIN.add( this ); - - // Get the ingredients - this.buildAspects(); - - // Calculate the preset bonuses - this.addPredefinedBonuses(); - - // Remove from the dependency chain - AEAspectRegister.this.DEPENDENCY_CHAIN.remove( this ); - } - - // Are there aspects? - if( ( this.ingredientAspects.size() == 0 ) && ( this.bonusAspects.size() == 0 ) ) - { - // Was this pass one? - if( pass == 1 ) - { - // Add to the unregisterable list for trial again later. - AEAspectRegister.this.UNREGISTERABLE.add( this ); - } - else - { - // Still could not register on pass 2. - if( !this.displayName.isEmpty() ) - { - ThELog.info( "Could not register \"%s\" for TC scanning.", this.displayName ); - } - } - return; - } - - // Register the item - AEAspectRegister.this.registerItem( this ); - } - - /** - * Friendly name. - */ - @Override - public String toString() - { - return this.displayName; - } - } - - /** - * Instance of the registry. - */ - public static final AEAspectRegister INSTANCE = new AEAspectRegister(); - - /** - * Common aspect amounts - */ - private static int CRYSTAL_BASE = 2; - private static int CRYSTAL_PURE = 5; - private static int FLUIX_CHARGE = 6; - - /** - * All discovered items from AE. - */ - private List ALL_ITEMS = new ArrayList(); - - /** - * Items that have not yet been added. - */ - private List ITEMS_TO_ADD = new ArrayList(); - - /** - * Items that have been added. - */ - private List ITEMS_REGISTERED = new ArrayList(); - - /** - * Used to prevent stack overflows when two items depend on each other. - */ - List DEPENDENCY_CHAIN = new ArrayList(); - - /** - * Tracks items that could not be registered. - */ - List UNREGISTERABLE = new ArrayList(); - - /** - * Recipe caches - */ - List NORMAL_RECIPES = null; - List GRINDER_RECIPES = null; - Collection INSCRIBER_RECIPES = null; - - /** - * Private constructor. - */ - private AEAspectRegister() - { - - } - - private boolean getGrinderRecipes() - { - // Get the recipes - this.GRINDER_RECIPES = AEApi.instance().registries().grinder().getRecipes(); - - return( ( this.GRINDER_RECIPES != null ) && !this.GRINDER_RECIPES.isEmpty() ); - } - - private boolean getInscriberRecipes() - { - // Get the recipes - this.INSCRIBER_RECIPES = AEApi.instance().registries().inscriber().getRecipes(); - - return( ( this.INSCRIBER_RECIPES != null ) && !this.INSCRIBER_RECIPES.isEmpty() ); - } - - /** - * Registers the base items from AE. Those without a usable crafting - * ancestry, world crafted, or multi-part. - */ - private void registerBase() - { - IMaterials aeMats = AEApi.instance().definitions().materials(); - IBlocks aeBlocks = AEApi.instance().definitions().blocks(); - IParts aeParts = AEApi.instance().definitions().parts(); - IItems aeItems = AEApi.instance().definitions().items(); - - AspectList aspects; - - // Certus Quartz Crystal - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE ); - this.registerItem( aeMats.certusQuartzCrystal(), aspects ); - - // Charged Certus Quartz Crystal - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE ); - aspects.add( Aspect.ENERGY, 4 ); - this.registerItem( aeMats.certusQuartzCrystalCharged(), aspects ); - - // Pure Certus Quartz Crystal - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE ); - this.registerItem( aeMats.purifiedCertusQuartzCrystal(), aspects ); - - // Certus Quartz Ore - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE ); - aspects.add( Aspect.EARTH, 1 ); - this.registerItem( aeBlocks.quartzOre(), aspects ); - - // Charged Certus Quartz Ore - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE ); - aspects.add( Aspect.EARTH, 1 ); - aspects.add( Aspect.ENERGY, 4 ); - this.registerItem( aeBlocks.quartzOreCharged(), aspects ); - - // Crystal Seed - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, 1 ); - aspects.add( Aspect.EXCHANGE, 1 ); - this.registerItem( AEApi.instance().definitions().items().crystalSeed(), aspects ); - - // Fluix Crystal - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE ); - aspects.add( Aspect.ENERGY, AEAspectRegister.FLUIX_CHARGE ); - this.registerItem( aeMats.fluixCrystal(), aspects ); - - // Pure Fluix Crystal - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE ); - aspects.add( Aspect.ENERGY, AEAspectRegister.FLUIX_CHARGE ); - this.registerItem( aeMats.purifiedFluixCrystal(), aspects ); - - // Enderdust - aspects = new AspectList(); - aspects.add( Aspect.ELDRITCH, 2 ); - aspects.add( Aspect.MOTION, 2 ); - aspects.add( Aspect.MAGIC, 1 ); - aspects.add( Aspect.ENTROPY, 1 ); - this.registerItem( aeMats.enderDust(), aspects ); - - // Pure Nether Quartz - aspects = new AspectList(); - aspects.add( Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE ); - aspects.add( Aspect.ENERGY, 1 ); - this.registerItem( aeMats.purifiedNetherQuartzCrystal(), aspects ); - - // Silicon - aspects = new AspectList(); - aspects.add( Aspect.FIRE, 1 ); - aspects.add( Aspect.SENSES, 1 ); - aspects.add( Aspect.ORDER, 1 ); - this.registerItem( aeMats.silicon(), aspects ); - - // Skystone - Item skyStone = aeBlocks.skyStone().maybeItem().orNull(); - if( skyStone != null ) - { - aspects = new AspectList(); - aspects.add( Aspect.ELDRITCH, 2 ); - aspects.add( Aspect.EARTH, 1 ); - aspects.add( Aspect.DARKNESS, 1 ); - this.registerItem( aeBlocks.skyStone(), aspects ); - ThaumcraftApi.registerObjectTag( new ItemStack( skyStone, 1, 1 ), aspects ); - ThaumcraftApi.registerObjectTag( new ItemStack( skyStone, 1, 2 ), aspects ); - ThaumcraftApi.registerObjectTag( new ItemStack( skyStone, 1, 3 ), aspects ); - } - - // Matter ball - aspects = new AspectList(); - aspects.add( Aspect.SLIME, 4 ); - aspects.add( Aspect.EARTH, 4 ); - aspects.add( Aspect.FLIGHT, 4 ); - this.registerItem( aeMats.matterBall(), aspects ); - - // Facade - aspects = new AspectList(); - aspects.add( Aspect.METAL, 1 ); - this.registerItem( aeItems.facade(), aspects ); - - // Cables ----------------------------------------- - - // Setup base aspect list - AspectList cableAspects = new AspectList(); - cableAspects.add( Aspect.CRYSTAL, 1 ); - cableAspects.add( Aspect.ENERGY, 2 ); - - // Pseudo-register it - this.registerItem( aeBlocks.multiPart(), cableAspects ); - - // Glass - aspects = cableAspects.copy(); - this.registerCableSet( aeParts.cableGlass(), aspects ); - - // Covered - aspects = cableAspects.copy(); - aspects.add( Aspect.CLOTH, 1 ); - this.registerCableSet( aeParts.cableCovered(), aspects ); - - // Smart - aspects = cableAspects.copy(); - aspects.add( Aspect.CLOTH, 1 ); - aspects.add( Aspect.LIGHT, 1 ); - aspects.add( Aspect.ENERGY, 1 ); - this.registerCableSet( aeParts.cableSmart(), aspects ); - - // Dense - aspects = cableAspects.copy(); - aspects.add( Aspect.CLOTH, 1 ); - aspects.add( Aspect.LIGHT, 2 ); - aspects.add( Aspect.ENERGY, 3 ); - this.registerCableSet( aeParts.cableDense(), aspects ); - - // Anchor - aspects = new AspectList(); - aspects.add( Aspect.METAL, 1 ); - this.registerItem( aeParts.cableAnchor(), aspects ); - - // P2P tunnels ------------------------------------ - // Setup base list - AspectList p2pAspects = new AspectList(); - p2pAspects.add( Aspect.METAL, 6 ); - p2pAspects.add( Aspect.ENERGY, 6 ); - p2pAspects.add( Aspect.CRYSTAL, 4 ); - p2pAspects.add( Aspect.GREED, 4 ); - p2pAspects.add( Aspect.ORDER, 4 ); - p2pAspects.add( Aspect.SENSES, 4 ); - - // ME & Items - this.registerItem( aeParts.p2PTunnelME(), p2pAspects ); - this.registerItem( aeParts.p2PTunnelItems(), p2pAspects ); - // Fluid - aspects = p2pAspects.copy(); - aspects.add( Aspect.WATER, 4 ); - this.registerItem( aeParts.p2PTunnelLiquids(), aspects ); - // Light - aspects = p2pAspects.copy(); - aspects.add( Aspect.LIGHT, 4 ); - this.registerItem( aeParts.p2PTunnelLight(), aspects ); - // Redstone & Power - aspects = p2pAspects.copy(); - aspects.add( Aspect.ENERGY, 2 ); - this.registerItem( aeParts.p2PTunnelRedstone(), aspects ); - this.registerItem( aeParts.p2PTunnelRF(), aspects ); - this.registerItem( aeParts.p2PTunnelEU(), aspects ); - - // Singularity ------------------------------------ - aspects = new AspectList(); - aspects.add( Aspect.DARKNESS, 10 ); - aspects.add( Aspect.VOID, 10 ); - aspects.add( Aspect.ENTROPY, 10 ); - this.registerItem( aeMats.singularity(), aspects ); - // Entangled - aspects = new AspectList(); - aspects.add( Aspect.ENERGY, 8 ); - aspects.add( Aspect.EXCHANGE, 8 ); - aspects.add( Aspect.MOTION, 4 ); - aspects.add( Aspect.ELDRITCH, 4 ); - this.registerItem( aeMats.qESingularity(), aspects ); - - // Encoded Pattern -------------------------------- - aspects = new AspectList(); - aspects.add( Aspect.CRAFT, 3 ); - aspects.add( Aspect.MIND, 3 ); - this.registerItem( aeItems.encodedPattern(), aspects ); - - } - - /** - * Registers all cable colors of this set with the specified aspects. - * - * @param cableSet - * @param aspects - */ - private void registerCableSet( final AEColoredItemDefinition cableSet, final AspectList aspects ) - { - // Get the colors - AEColor[] colors = AEColor.values(); - - // Register each color - for( AEColor color : colors ) - { - ThaumcraftApi.registerObjectTag( cableSet.stack( color, 1 ), aspects ); - } - } - - /** - * Registers the item def with thaumcraft. - * - * @param itemDef - * @param aspects - */ - private void registerItem( final IItemDefinition itemDef, final AspectList aspects ) - { - // Get the info for the def - AEItemInfo itemInfo = this.getInfoForDefinitionOrStack( itemDef ); - - if( itemInfo == null ) - { - // Should not happen - return; - } - - // Set the aspects - itemInfo.bonusAspects = aspects; - - // Register it - this.registerItem( itemInfo ); - - } - - /** - * Updates the aspects for the thaumic energistics items. - */ - private void registerThEItems() - { - IThEItems teItems = ThEApi.instance().items(); - thaumicenergistics.api.IThEBlocks teBlocks = ThEApi.instance().blocks(); - - // Get an AE 1K Cell - ItemStack aeCell = AEApi.instance().definitions().items().cell1k().maybeStack( 1 ).orNull(); - AspectList cellAspects = null; - if( aeCell != null ) - { - // Get the aspect list for a 1k cell - AspectList aeCellAspects = ThaumcraftApiHelper.getObjectAspects( aeCell ); - if( aeCellAspects != null ) - { - // Copy the aspects - cellAspects = aeCellAspects.copy(); - int aspectCount = cellAspects.size(); - - // Is there too many aspects? - if( aspectCount > 4 ) - { - Aspect[] OrderedAspects = cellAspects.getAspectsSortedAmount(); - - // Remove lowest - cellAspects.remove( OrderedAspects[aspectCount - 1] ); - - // Still not enough room? - if( aspectCount > 5 ) - { - - // Remove lowest - cellAspects.remove( OrderedAspects[aspectCount - 2] ); - } - } - - // Add magic and aura - cellAspects.add( Aspect.MAGIC, 3 ); - cellAspects.add( Aspect.AURA, 5 ); - ThaumcraftApi.registerObjectTag( teItems.EssentiaCell_1k.getStack(), cellAspects ); - ThaumcraftApi.registerObjectTag( teItems.EssentiaCell_4k.getStack(), cellAspects ); - ThaumcraftApi.registerObjectTag( teItems.EssentiaCell_16k.getStack(), cellAspects ); - ThaumcraftApi.registerObjectTag( teItems.EssentiaCell_64k.getStack(), cellAspects ); - } - } - - // Were the cells registered? - if( ( aeCell == null ) || ( cellAspects == null ) ) - { - ThELog.info( "Could not register \"%s\" for TC scanning.", "Essentia Cells" ); - } - - // Set the aspects for the iron gearbox - AspectList ironGearboxAspects = new AspectList(); - ironGearboxAspects.add( Aspect.METAL, 7 ); - ironGearboxAspects.add( Aspect.MECHANISM, 5 ); - ironGearboxAspects.add( Aspect.EARTH, 2 ); - ironGearboxAspects.add( Aspect.ENTROPY, 2 ); - ThaumcraftApi.registerObjectTag( teBlocks.IronGearBox.getStack(), ironGearboxAspects ); - - // Set the aspects for the thaumium gearbox - AspectList thaumGearbox = ironGearboxAspects.copy(); - thaumGearbox.add( Aspect.MAGIC, 10 ); - thaumGearbox.add( Aspect.MECHANISM, 5 ); - thaumGearbox.add( Aspect.METAL, 3 ); - ThaumcraftApi.registerObjectTag( teBlocks.ThaumiumGearBox.getStack(), thaumGearbox ); - - } - - /** - * Gets the item info for the item def or itemstack. - * - * @param itemDef - * @return - */ - AEItemInfo getInfoForDefinitionOrStack( final Object itemDefinitionOrStack ) - { - AEItemInfo itemInfo = null; - - // Get the index from the list of items to add - int index = -1; - for( int i = 0; i < this.ALL_ITEMS.size(); i++ ) - { - // Match? - if( this.ALL_ITEMS.get( i ).equals( itemDefinitionOrStack ) ) - { - index = i; - break; - } - } - - // Found match? - if( index >= 0 ) - { - itemInfo = this.ALL_ITEMS.get( index ); - } - - return itemInfo; - } - - /** - * Gets the declared items from an AE registry. - * - * @param AEDefinitionInstance - */ - void getItemsFromAERegistryClass( final Object AEDefinitionInstance ) - { - AEItemInfo itemInfo; - - // Get the item fields - Field[] fields = AEDefinitionInstance.getClass().getDeclaredFields(); - - // Loop over all fields - for( Field f : fields ) - { - try - { - // Set accessible - f.setAccessible( true ); - - // Get the field - Object fObj = f.get( AEDefinitionInstance ); - - // Ensure it is an item def - if( fObj instanceof IItemDefinition ) - { - // Create the info - itemInfo = new AEItemInfo( (IItemDefinition)fObj ); - - // Has the stack already been registered? - if( this.ITEMS_REGISTERED.contains( itemInfo ) ) - { - // Skip it - continue; - } - - // Add to the list - this.ITEMS_TO_ADD.add( itemInfo ); - this.ALL_ITEMS.add( itemInfo ); - - } - } - catch( Exception e ) - { - continue; - } - } - } - - /** - * Registers the item info with thaumcraft. - * - * @param itemInfo - * @param aspects - */ - void registerItem( final AEItemInfo itemInfo ) - { - // Remove from the add list - this.ITEMS_TO_ADD.remove( itemInfo ); - - // Ensure it has not already been registered - if( !this.ITEMS_REGISTERED.contains( itemInfo ) ) - { - // Add to the registered list - this.ITEMS_REGISTERED.add( itemInfo ); - - // Register it - ThaumcraftApi.registerObjectTag( itemInfo.itemStack, itemInfo.getFinalAspects() ); - } - } - - /** - * Gives AppliedEnergistics blocks and items Thaumcraft aspects. - */ - public void registerAEAspects() - { - // Log - long sectionStartTime = ThELog.beginSection( "AE Scanables" ); - - // Get the normal recipes - this.NORMAL_RECIPES = CraftingManager.getInstance().getRecipeList(); - - // Get the grinder recipes - if( !this.getGrinderRecipes() ) - { - ThELog.warning( "Unable to load AE2 Grinder recipes, aspect registration will be incomplete" ); - } - - // Get the inscriber recipes - if( !this.getInscriberRecipes() ) - { - ThELog.warning( "Unable to load AE2 Inscriber recipes, aspect registration will be incomplete" ); - } - - // Build the list of items to give aspects to - this.getItemsFromAERegistryClass( AEApi.instance().definitions().materials() ); - this.getItemsFromAERegistryClass( AEApi.instance().definitions().items() ); - this.getItemsFromAERegistryClass( AEApi.instance().definitions().blocks() ); - this.getItemsFromAERegistryClass( AEApi.instance().definitions().parts() ); - - // Give base AE items & materials aspects - this.registerBase(); - - // Register the remaining items - for( int pass = 1; pass <= 2; pass++ ) - { - while( this.ITEMS_TO_ADD.size() > 0 ) - { - // Get the next item - AEItemInfo itemInfo = this.ITEMS_TO_ADD.get( 0 ); - - // Remove - this.ITEMS_TO_ADD.remove( 0 ); - - // Register it - itemInfo.registerItem( pass ); - - } - - // Upon completion of pass 1, move all unregisterable items back into the items to add, and try again. - if( pass == 1 ) - { - this.ITEMS_TO_ADD.addAll( this.UNREGISTERABLE ); - this.UNREGISTERABLE.clear(); - } - } - - // Finally register my items - this.registerThEItems(); - - // Cleanup - this.NORMAL_RECIPES = null; - this.GRINDER_RECIPES = null; - this.ALL_ITEMS = null; - this.ITEMS_REGISTERED = null; - this.ITEMS_TO_ADD = null; - this.DEPENDENCY_CHAIN = null; - this.UNREGISTERABLE = null; - - // Log - ThELog.endSection( "AE Scanables", sectionStartTime ); - } +public class AEAspectRegister { + /** + * Helper class to derive aspects from an item definition. + * + * @author Nividica + * + */ + private class AEItemInfo { + /** + * Human readable name of the item. + */ + private String displayName = ""; + + /** + * Selected ingredients used to craft this item. + */ + private ItemStack[] ingredients = null; + + /** + * Aspects derived from the ingredients. + */ + private AspectList ingredientAspects = new AspectList(); + + /** + * Recipe used to craft this item. + */ + private Object recipe = null; + + /** + * Definition of the item. + */ + private IItemDefinition definition; + + /** + * Aspects manually added to the item. + */ + public AspectList bonusAspects = new AspectList(); + + /** + * Itemstack holding the item. + */ + public ItemStack itemStack = null; + + /** + * The current trial pass. + */ + private int pass; + + /** + * Creates the info. + * + * @param itemDef + */ + public AEItemInfo(final IItemDefinition itemDef) { + // Set the definition + this.definition = itemDef; + + // Is the def available? + if (itemDef.maybeStack(1).isPresent()) { + this.itemStack = itemDef.maybeStack(1).get(); + } + + if (this.itemStack != null) { + this.displayName = this.itemStack.getDisplayName(); + } + } + + /** + * Adds bonus aspects for certain types. + */ + private void addPredefinedBonuses() { + IBlocks aeBlocks = AEApi.instance().definitions().blocks(); + IMaterials aeMats = AEApi.instance().definitions().materials(); + // IItems aeItems = AEApi.instance().definitions().items(); + + // Grinder recipe? + if (this.recipe instanceof IGrinderEntry) { + // Add a bonus aspect for grinding + this.bonusAspects.add(Aspect.ENTROPY, 1); + + // Remove any Terra + this.ingredientAspects.remove(Aspect.EARTH); + } + + // Molecular Assembler + else if (this.definition.equals(aeBlocks.molecularAssembler())) { + // Add extra craft, machina, potentia and vitrius + this.bonusAspects.add(Aspect.CRAFT, 4); + this.bonusAspects.add(Aspect.ENERGY, 6); + this.bonusAspects.add(Aspect.MECHANISM, 2); + this.bonusAspects.add(Aspect.CRYSTAL, 1); + } + + // Sky stone + else if (this.definition.equals(aeBlocks.skyStone())) { + // Add tene + this.bonusAspects.add(Aspect.DARKNESS, 3); + } + + // Sky chest + else if (this.definition.equals(aeBlocks.skyChest())) { + // Add vac + this.bonusAspects.add(Aspect.VOID, 4); + + // Remove terra + this.ingredientAspects.remove(Aspect.EARTH); + } + + // Quartz glass + else if (this.definition.equals(aeBlocks.quartzGlass())) { + // Add vit + this.bonusAspects.add(Aspect.CRYSTAL, 4); + } + + // ME Controller + else if (this.definition.equals(aeBlocks.controller())) { + // Add mach, sense, mind + this.bonusAspects.add(Aspect.MECHANISM, 3); + this.bonusAspects.add(Aspect.SENSES, 1); + this.bonusAspects.add(Aspect.MIND, 9); + + // Remove fire, order + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + } + + // ME Drive + else if (this.definition.equals(aeBlocks.drive())) { + // Add vac + this.bonusAspects.add(Aspect.VOID, 4); + + // Remove fire, order, sense, mach + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + this.ingredientAspects.remove(Aspect.SENSES); + this.ingredientAspects.remove(Aspect.MECHANISM); + } + + // ME Chest + else if (this.definition.equals(aeBlocks.chest())) { + // Add vac + this.bonusAspects.add(Aspect.VOID, 4); + + // Remove fire, order, sense, mach + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + this.ingredientAspects.remove(Aspect.SENSES); + this.ingredientAspects.remove(Aspect.MECHANISM); + } + + // ME IO Port + else if (this.definition.equals(aeBlocks.iOPort())) { + // Add perm + this.bonusAspects.add(Aspect.EXCHANGE, 4); + + // Remove fire, order, sense, mach + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + this.ingredientAspects.remove(Aspect.SENSES); + this.ingredientAspects.remove(Aspect.MECHANISM); + } + + // ME IO Port + else if (this.definition.equals(aeBlocks.condenser())) { + // Add vac + this.bonusAspects.add(Aspect.VOID, 10); + } + // Redstone card + else if (this.definition.equals(aeMats.cardRedstone())) { + // Add sense + this.bonusAspects.add(Aspect.SENSES, 2); + } + // Cell workbench + else if (this.definition.equals(aeBlocks.cellWorkbench())) { + // Add cloth + this.bonusAspects.add(Aspect.CLOTH, 2); + } + // ME Interface + else if (this.definition.equals(aeBlocks.iface())) { + // Add permutatio + this.bonusAspects.add(Aspect.EXCHANGE, 6); + } + // Logic processor + else if (this.definition.equals(aeMats.logicProcessor())) { + // Remove metal & fire & ordo + this.ingredientAspects.remove(Aspect.METAL); + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + + // Add mind & metal + this.bonusAspects.add(Aspect.MIND, 3); + this.bonusAspects.add(Aspect.METAL, 1); + } + // Calc processor + else if (this.definition.equals(aeMats.calcProcessor())) { + // Remove metal & fire & ordo + this.ingredientAspects.remove(Aspect.METAL); + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + + // Add mind & metal + this.bonusAspects.add(Aspect.MIND, 6); + this.bonusAspects.add(Aspect.METAL, 1); + } + // Eng processor + else if (this.definition.equals(aeMats.engProcessor())) { + // Remove metal & fire & ordo + this.ingredientAspects.remove(Aspect.METAL); + this.ingredientAspects.remove(Aspect.FIRE); + this.ingredientAspects.remove(Aspect.ORDER); + + // Add mind + this.bonusAspects.add(Aspect.MIND, 9); + } + } + + /** + * Attempts to build the aspects for the item via recipe => ingredients + */ + private void buildAspects() { + // Grinder recipes + if (AEAspectRegister.this.GRINDER_RECIPES != null) { + if (this.buildAspectsFromGrinder()) { + return; + } + } + + // Inscriber recipes + if (AEAspectRegister.this.INSCRIBER_RECIPES != null) { + if (this.buildAspectsFromInscriber()) { + return; + } + } + + // Regular crafting recipes + if (AEAspectRegister.this.NORMAL_RECIPES != null) { + if (this.buildAspectsFromNormal()) { + return; + } + } + } + + /** + * Attempts to build the aspects for the item via grinder recipes. + * + * @return + */ + private boolean buildAspectsFromGrinder() { + try { + for (IGrinderEntry recipe : AEAspectRegister.this.GRINDER_RECIPES) { + ItemStack recipeOutput = recipe.getOutput(); + + // Skip null items + if ((recipeOutput == null) || (recipeOutput.getItem() == null)) { + continue; + } + + if (ThEUtils.areStacksEqualIgnoreAmount(recipeOutput, this.itemStack)) { + if (this.isRecipeUsable(recipe)) { + return true; + } + } + } + } catch (Exception e) { + } + + return false; + } + + /** + * Attempts to build the aspects for the item via inscriber recipes. + * + * @return + */ + private boolean buildAspectsFromInscriber() { + try { + for (IInscriberRecipe recipe : AEAspectRegister.this.INSCRIBER_RECIPES) { + ItemStack recipeOutput = recipe.getOutput(); + + // Skip null items + if ((recipeOutput == null) || (recipeOutput.getItem() == null)) { + continue; + } + + if (ThEUtils.areStacksEqualIgnoreAmount(recipeOutput, this.itemStack)) { + if (this.isRecipeUsable(recipe)) { + return true; + } + } + } + } catch (Exception e) { + } + return false; + } + + /** + * Attempts to build the aspects for the item via normal recipes. + * + * @return + */ + private boolean buildAspectsFromNormal() { + + try { + for (IRecipe recipe : AEAspectRegister.this.NORMAL_RECIPES) { + // Get the recipe's result + ItemStack recipeOutput = recipe.getRecipeOutput(); + + // Skip null items + if ((recipeOutput == null) || (recipeOutput.getItem() == null)) { + continue; + } + + // Is this what we are looking for? + if (!ThEUtils.areStacksEqualIgnoreAmount(recipeOutput, this.itemStack)) { + continue; + } + + if (this.isRecipeUsable(recipe)) { + return true; + } + } + + } catch (Exception e) { + } + + return false; + } + + /** + * Builds the aspect list from the items ingredients. + * + * @param itemInfo + */ + private void findAspectsForIngredients() { + for (ItemStack stack : this.ingredients) { + // Get the aspects for the stack + AspectList stackAspects = ThaumcraftApiHelper.getObjectAspects(stack); + + // Are there no aspects for this item? + if ((stackAspects == null) || (stackAspects.size() == 0)) { + // Is the item an AE item? + AEItemInfo ingInfo = AEAspectRegister.this.getInfoForDefinitionOrStack(stack); + + if (ingInfo != null) { + // Ensure the item is not in the dependency chain. + if (!AEAspectRegister.this.DEPENDENCY_CHAIN.contains(ingInfo)) { + // Register the item + ingInfo.registerItem(this.pass); + + // Attempt to get the aspects again + stackAspects = ThaumcraftApiHelper.getObjectAspects(stack); + } + } + } + + // Are there still no aspects to add? + if ((stackAspects == null) || (stackAspects.size() == 0)) { + continue; + } + + // Assign each aspect + for (Aspect currentStackAspect : stackAspects.getAspects()) { + // Get the current amount + int existingAmount = this.ingredientAspects.getAmount(currentStackAspect); + + // Get the ingredient amount + int ingredientAspectAmount = stackAspects.getAmount(currentStackAspect); + + // Merge + if (existingAmount < ingredientAspectAmount) { + this.ingredientAspects.add(currentStackAspect, (ingredientAspectAmount - existingAmount)); + } + } + } + } + + /** + * Builds a list of ingredients for this item. + */ + private void getIngredientsForRecipe() { + Object[] ingredientObjects = null; + + // What kind of recipe is this? + if (this.recipe instanceof appeng.recipes.game.ShapedRecipe) { + // Get ingredients + ingredientObjects = ((appeng.recipes.game.ShapedRecipe) this.recipe).getInput(); + } else if (this.recipe instanceof appeng.recipes.game.ShapelessRecipe) { + // Get ingredients + ingredientObjects = ((appeng.recipes.game.ShapelessRecipe) this.recipe) + .getInput() + .toArray(); + } else if (this.recipe instanceof IGrinderEntry) { + // Get ingredient + ingredientObjects = new Object[] {((IGrinderEntry) this.recipe).getInput()}; + + // Add a bonus aspect for grinding + this.bonusAspects.add(Aspect.ENTROPY, 1); + } else if (this.recipe instanceof InscriberRecipe) { + // Cast + InscriberRecipe iRec = (InscriberRecipe) this.recipe; + + // Get inputs + List inputs = new ArrayList(iRec.getInputs()); + + // Is there a top? + if (iRec.getTopOptional().isPresent()) { + // Add top + inputs.add(iRec.getTopOptional().get()); + } + + // Is there a bottom? + if (iRec.getBottomOptional().isPresent()) { + // Add bottom + inputs.add(iRec.getBottomOptional().get()); + } + + // Create array + ingredientObjects = inputs.toArray(new Object[inputs.size()]); + + } else if (this.recipe instanceof net.minecraft.item.crafting.ShapedRecipes) { + // Get ingredients + ingredientObjects = ((net.minecraft.item.crafting.ShapedRecipes) this.recipe).recipeItems; + } else if (this.recipe instanceof net.minecraft.item.crafting.ShapelessRecipes) { + // Get ingredients + ingredientObjects = ((net.minecraft.item.crafting.ShapelessRecipes) this.recipe).recipeItems.toArray(); + } + + // Did we get the object list? + if (ingredientObjects != null) { + ItemStack currentIngredientStack; + List ingredientStackList = new ArrayList(); + + // Get the itemstack of each one + for (int i = 0; i < ingredientObjects.length; i++) { + // Get the ingredient + Object ing = ingredientObjects[i]; + + // What is the ingredient? + if (ing == null) { + continue; + } + + // Clear the stack + currentIngredientStack = null; + try { + if (ing instanceof Ingredient) { + if (((Ingredient) ing).getNameSpace().equalsIgnoreCase("oreDictionary")) { + currentIngredientStack = ((Ingredient) ing).getItemStackSet()[0]; + } else { + currentIngredientStack = ((Ingredient) ing).getItemStack(); + } + } else if (ing instanceof GroupIngredient) { + currentIngredientStack = ((GroupIngredient) ing).getItemStackSet()[0]; + } else if (ing instanceof ItemStack) { + currentIngredientStack = (ItemStack) ing; + } + + } catch (Exception e) { + } + + // Skip null stacks + if (currentIngredientStack == null) { + continue; + } + + // Add to the list + ingredientStackList.add(currentIngredientStack); + } + + // Was anything added? + if (ingredientStackList.size() > 0) { + // Convert to array + this.ingredients = new ItemStack[ingredientStackList.size()]; + this.ingredients = ingredientStackList.toArray(this.ingredients); + } + } + } + + /** + * Determines if the recipe is valid, and aspects + * can be derived from it. + * + * @param recipe + * @return + */ + private boolean isRecipeUsable(final Object recipe) { + // Set the recipe + this.recipe = recipe; + + // Get the ingredients + this.getIngredientsForRecipe(); + + // Did we get the ingredients? + if (this.ingredients != null) { + // Get the aspects + this.findAspectsForIngredients(); + + // Did we get aspects? + if (this.ingredientAspects.size() != 0) { + return true; + } + } + + this.recipe = null; + return false; + } + + /** + * Checks if this item matches the specified object. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof AEItemInfo) { + return this.isMatch(((AEItemInfo) obj).itemStack); + } else if (obj instanceof ItemStack) { + return this.isMatch((ItemStack) obj); + } else if (obj instanceof IItemDefinition) { + return this.isMatch(((IItemDefinition) obj).maybeStack(1).orNull()); + } + + return false; + } + + /** + * Builds the final aspect list used for this item. + * + * @return + */ + public AspectList getFinalAspects() { + AspectList finalAspects = new AspectList(); + + // Add ingredient aspects + if (this.ingredientAspects != null) { + for (Aspect aspect : this.ingredientAspects.getAspects()) { + if (aspect == null) { + continue; + } + + finalAspects.add(aspect, this.ingredientAspects.getAmount(aspect)); + } + } + + // Add bonus aspects + if (this.bonusAspects != null) { + for (Aspect aspect : this.bonusAspects.getAspects()) { + if (aspect == null) { + continue; + } + + finalAspects.add(aspect, this.bonusAspects.getAmount(aspect)); + } + } + + // Get the final aspect count + int aspectCount = finalAspects.size(); + + if (aspectCount == 0) { + return finalAspects; + } + + // Can only have 6 aspects + if (aspectCount > 6) { + Aspect[] aspects = finalAspects.getAspectsSortedAmount(); + + // Remove the lowest aspects + for (int index = 6; index < aspects.length; index++) { + finalAspects.remove(aspects[index]); + } + } + + return finalAspects; + } + + /** + * Hashcode + */ + @Override + public int hashCode() { + return this.itemStack.getItem().hashCode() + this.itemStack.getItemDamage(); + } + + /** + * Compares the specified itemstack with this itemstack. + * + * @param stack + * @return + */ + public boolean isMatch(final ItemStack stack) { + return ThEUtils.areStacksEqualIgnoreAmount(stack, this.itemStack); + } + + /** + * Builds this items aspect list, then registers it with Thaumcraft. + */ + public void registerItem(final int pass) { + // Set the pass + this.pass = pass; + + if (this.itemStack != null) { + // Skip anything that is not from AE + if (!this.itemStack.getItem().getClass().getCanonicalName().startsWith("appeng")) { + // ThELog.info( "Skipping registration for non AE item: %s (%s) ", this.itemStack.getDisplayName(), + // this.itemStack.getItem().getClass().getCanonicalName() ); + return; + } + + // Add to the dependency chain + AEAspectRegister.this.DEPENDENCY_CHAIN.add(this); + + // Get the ingredients + this.buildAspects(); + + // Calculate the preset bonuses + this.addPredefinedBonuses(); + + // Remove from the dependency chain + AEAspectRegister.this.DEPENDENCY_CHAIN.remove(this); + } + + // Are there aspects? + if ((this.ingredientAspects.size() == 0) && (this.bonusAspects.size() == 0)) { + // Was this pass one? + if (pass == 1) { + // Add to the unregisterable list for trial again later. + AEAspectRegister.this.UNREGISTERABLE.add(this); + } else { + // Still could not register on pass 2. + if (!this.displayName.isEmpty()) { + ThELog.info("Could not register \"%s\" for TC scanning.", this.displayName); + } + } + return; + } + + // Register the item + AEAspectRegister.this.registerItem(this); + } + + /** + * Friendly name. + */ + @Override + public String toString() { + return this.displayName; + } + } + + /** + * Instance of the registry. + */ + public static final AEAspectRegister INSTANCE = new AEAspectRegister(); + + /** + * Common aspect amounts + */ + private static int CRYSTAL_BASE = 2; + + private static int CRYSTAL_PURE = 5; + private static int FLUIX_CHARGE = 6; + + /** + * All discovered items from AE. + */ + private List ALL_ITEMS = new ArrayList(); + + /** + * Items that have not yet been added. + */ + private List ITEMS_TO_ADD = new ArrayList(); + + /** + * Items that have been added. + */ + private List ITEMS_REGISTERED = new ArrayList(); + + /** + * Used to prevent stack overflows when two items depend on each other. + */ + List DEPENDENCY_CHAIN = new ArrayList(); + + /** + * Tracks items that could not be registered. + */ + List UNREGISTERABLE = new ArrayList(); + + /** + * Recipe caches + */ + List NORMAL_RECIPES = null; + + List GRINDER_RECIPES = null; + Collection INSCRIBER_RECIPES = null; + + /** + * Private constructor. + */ + private AEAspectRegister() {} + + private boolean getGrinderRecipes() { + // Get the recipes + this.GRINDER_RECIPES = AEApi.instance().registries().grinder().getRecipes(); + + return ((this.GRINDER_RECIPES != null) && !this.GRINDER_RECIPES.isEmpty()); + } + + private boolean getInscriberRecipes() { + // Get the recipes + this.INSCRIBER_RECIPES = AEApi.instance().registries().inscriber().getRecipes(); + + return ((this.INSCRIBER_RECIPES != null) && !this.INSCRIBER_RECIPES.isEmpty()); + } + + /** + * Registers the base items from AE. Those without a usable crafting + * ancestry, world crafted, or multi-part. + */ + private void registerBase() { + IMaterials aeMats = AEApi.instance().definitions().materials(); + IBlocks aeBlocks = AEApi.instance().definitions().blocks(); + IParts aeParts = AEApi.instance().definitions().parts(); + IItems aeItems = AEApi.instance().definitions().items(); + + AspectList aspects; + + // Certus Quartz Crystal + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE); + this.registerItem(aeMats.certusQuartzCrystal(), aspects); + + // Charged Certus Quartz Crystal + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE); + aspects.add(Aspect.ENERGY, 4); + this.registerItem(aeMats.certusQuartzCrystalCharged(), aspects); + + // Pure Certus Quartz Crystal + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE); + this.registerItem(aeMats.purifiedCertusQuartzCrystal(), aspects); + + // Certus Quartz Ore + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE); + aspects.add(Aspect.EARTH, 1); + this.registerItem(aeBlocks.quartzOre(), aspects); + + // Charged Certus Quartz Ore + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE); + aspects.add(Aspect.EARTH, 1); + aspects.add(Aspect.ENERGY, 4); + this.registerItem(aeBlocks.quartzOreCharged(), aspects); + + // Crystal Seed + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, 1); + aspects.add(Aspect.EXCHANGE, 1); + this.registerItem(AEApi.instance().definitions().items().crystalSeed(), aspects); + + // Fluix Crystal + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_BASE); + aspects.add(Aspect.ENERGY, AEAspectRegister.FLUIX_CHARGE); + this.registerItem(aeMats.fluixCrystal(), aspects); + + // Pure Fluix Crystal + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE); + aspects.add(Aspect.ENERGY, AEAspectRegister.FLUIX_CHARGE); + this.registerItem(aeMats.purifiedFluixCrystal(), aspects); + + // Enderdust + aspects = new AspectList(); + aspects.add(Aspect.ELDRITCH, 2); + aspects.add(Aspect.MOTION, 2); + aspects.add(Aspect.MAGIC, 1); + aspects.add(Aspect.ENTROPY, 1); + this.registerItem(aeMats.enderDust(), aspects); + + // Pure Nether Quartz + aspects = new AspectList(); + aspects.add(Aspect.CRYSTAL, AEAspectRegister.CRYSTAL_PURE); + aspects.add(Aspect.ENERGY, 1); + this.registerItem(aeMats.purifiedNetherQuartzCrystal(), aspects); + + // Silicon + aspects = new AspectList(); + aspects.add(Aspect.FIRE, 1); + aspects.add(Aspect.SENSES, 1); + aspects.add(Aspect.ORDER, 1); + this.registerItem(aeMats.silicon(), aspects); + + // Skystone + Item skyStone = aeBlocks.skyStone().maybeItem().orNull(); + if (skyStone != null) { + aspects = new AspectList(); + aspects.add(Aspect.ELDRITCH, 2); + aspects.add(Aspect.EARTH, 1); + aspects.add(Aspect.DARKNESS, 1); + this.registerItem(aeBlocks.skyStone(), aspects); + ThaumcraftApi.registerObjectTag(new ItemStack(skyStone, 1, 1), aspects); + ThaumcraftApi.registerObjectTag(new ItemStack(skyStone, 1, 2), aspects); + ThaumcraftApi.registerObjectTag(new ItemStack(skyStone, 1, 3), aspects); + } + + // Matter ball + aspects = new AspectList(); + aspects.add(Aspect.SLIME, 4); + aspects.add(Aspect.EARTH, 4); + aspects.add(Aspect.FLIGHT, 4); + this.registerItem(aeMats.matterBall(), aspects); + + // Facade + aspects = new AspectList(); + aspects.add(Aspect.METAL, 1); + this.registerItem(aeItems.facade(), aspects); + + // Cables ----------------------------------------- + + // Setup base aspect list + AspectList cableAspects = new AspectList(); + cableAspects.add(Aspect.CRYSTAL, 1); + cableAspects.add(Aspect.ENERGY, 2); + + // Pseudo-register it + this.registerItem(aeBlocks.multiPart(), cableAspects); + + // Glass + aspects = cableAspects.copy(); + this.registerCableSet(aeParts.cableGlass(), aspects); + + // Covered + aspects = cableAspects.copy(); + aspects.add(Aspect.CLOTH, 1); + this.registerCableSet(aeParts.cableCovered(), aspects); + + // Smart + aspects = cableAspects.copy(); + aspects.add(Aspect.CLOTH, 1); + aspects.add(Aspect.LIGHT, 1); + aspects.add(Aspect.ENERGY, 1); + this.registerCableSet(aeParts.cableSmart(), aspects); + + // Dense + aspects = cableAspects.copy(); + aspects.add(Aspect.CLOTH, 1); + aspects.add(Aspect.LIGHT, 2); + aspects.add(Aspect.ENERGY, 3); + this.registerCableSet(aeParts.cableDense(), aspects); + + // Anchor + aspects = new AspectList(); + aspects.add(Aspect.METAL, 1); + this.registerItem(aeParts.cableAnchor(), aspects); + + // P2P tunnels ------------------------------------ + // Setup base list + AspectList p2pAspects = new AspectList(); + p2pAspects.add(Aspect.METAL, 6); + p2pAspects.add(Aspect.ENERGY, 6); + p2pAspects.add(Aspect.CRYSTAL, 4); + p2pAspects.add(Aspect.GREED, 4); + p2pAspects.add(Aspect.ORDER, 4); + p2pAspects.add(Aspect.SENSES, 4); + + // ME & Items + this.registerItem(aeParts.p2PTunnelME(), p2pAspects); + this.registerItem(aeParts.p2PTunnelItems(), p2pAspects); + // Fluid + aspects = p2pAspects.copy(); + aspects.add(Aspect.WATER, 4); + this.registerItem(aeParts.p2PTunnelLiquids(), aspects); + // Light + aspects = p2pAspects.copy(); + aspects.add(Aspect.LIGHT, 4); + this.registerItem(aeParts.p2PTunnelLight(), aspects); + // Redstone & Power + aspects = p2pAspects.copy(); + aspects.add(Aspect.ENERGY, 2); + this.registerItem(aeParts.p2PTunnelRedstone(), aspects); + this.registerItem(aeParts.p2PTunnelRF(), aspects); + this.registerItem(aeParts.p2PTunnelEU(), aspects); + + // Singularity ------------------------------------ + aspects = new AspectList(); + aspects.add(Aspect.DARKNESS, 10); + aspects.add(Aspect.VOID, 10); + aspects.add(Aspect.ENTROPY, 10); + this.registerItem(aeMats.singularity(), aspects); + // Entangled + aspects = new AspectList(); + aspects.add(Aspect.ENERGY, 8); + aspects.add(Aspect.EXCHANGE, 8); + aspects.add(Aspect.MOTION, 4); + aspects.add(Aspect.ELDRITCH, 4); + this.registerItem(aeMats.qESingularity(), aspects); + + // Encoded Pattern -------------------------------- + aspects = new AspectList(); + aspects.add(Aspect.CRAFT, 3); + aspects.add(Aspect.MIND, 3); + this.registerItem(aeItems.encodedPattern(), aspects); + } + + /** + * Registers all cable colors of this set with the specified aspects. + * + * @param cableSet + * @param aspects + */ + private void registerCableSet(final AEColoredItemDefinition cableSet, final AspectList aspects) { + // Get the colors + AEColor[] colors = AEColor.values(); + + // Register each color + for (AEColor color : colors) { + ThaumcraftApi.registerObjectTag(cableSet.stack(color, 1), aspects); + } + } + + /** + * Registers the item def with thaumcraft. + * + * @param itemDef + * @param aspects + */ + private void registerItem(final IItemDefinition itemDef, final AspectList aspects) { + // Get the info for the def + AEItemInfo itemInfo = this.getInfoForDefinitionOrStack(itemDef); + + if (itemInfo == null) { + // Should not happen + return; + } + + // Set the aspects + itemInfo.bonusAspects = aspects; + + // Register it + this.registerItem(itemInfo); + } + + /** + * Updates the aspects for the thaumic energistics items. + */ + private void registerThEItems() { + IThEItems teItems = ThEApi.instance().items(); + thaumicenergistics.api.IThEBlocks teBlocks = ThEApi.instance().blocks(); + + // Get an AE 1K Cell + ItemStack aeCell = + AEApi.instance().definitions().items().cell1k().maybeStack(1).orNull(); + AspectList cellAspects = null; + if (aeCell != null) { + // Get the aspect list for a 1k cell + AspectList aeCellAspects = ThaumcraftApiHelper.getObjectAspects(aeCell); + if (aeCellAspects != null) { + // Copy the aspects + cellAspects = aeCellAspects.copy(); + int aspectCount = cellAspects.size(); + + // Is there too many aspects? + if (aspectCount > 4) { + Aspect[] OrderedAspects = cellAspects.getAspectsSortedAmount(); + + // Remove lowest + cellAspects.remove(OrderedAspects[aspectCount - 1]); + + // Still not enough room? + if (aspectCount > 5) { + + // Remove lowest + cellAspects.remove(OrderedAspects[aspectCount - 2]); + } + } + + // Add magic and aura + cellAspects.add(Aspect.MAGIC, 3); + cellAspects.add(Aspect.AURA, 5); + ThaumcraftApi.registerObjectTag(teItems.EssentiaCell_1k.getStack(), cellAspects); + ThaumcraftApi.registerObjectTag(teItems.EssentiaCell_4k.getStack(), cellAspects); + ThaumcraftApi.registerObjectTag(teItems.EssentiaCell_16k.getStack(), cellAspects); + ThaumcraftApi.registerObjectTag(teItems.EssentiaCell_64k.getStack(), cellAspects); + } + } + + // Were the cells registered? + if ((aeCell == null) || (cellAspects == null)) { + ThELog.info("Could not register \"%s\" for TC scanning.", "Essentia Cells"); + } + + // Set the aspects for the iron gearbox + AspectList ironGearboxAspects = new AspectList(); + ironGearboxAspects.add(Aspect.METAL, 7); + ironGearboxAspects.add(Aspect.MECHANISM, 5); + ironGearboxAspects.add(Aspect.EARTH, 2); + ironGearboxAspects.add(Aspect.ENTROPY, 2); + ThaumcraftApi.registerObjectTag(teBlocks.IronGearBox.getStack(), ironGearboxAspects); + + // Set the aspects for the thaumium gearbox + AspectList thaumGearbox = ironGearboxAspects.copy(); + thaumGearbox.add(Aspect.MAGIC, 10); + thaumGearbox.add(Aspect.MECHANISM, 5); + thaumGearbox.add(Aspect.METAL, 3); + ThaumcraftApi.registerObjectTag(teBlocks.ThaumiumGearBox.getStack(), thaumGearbox); + } + + /** + * Gets the item info for the item def or itemstack. + * + * @param itemDef + * @return + */ + AEItemInfo getInfoForDefinitionOrStack(final Object itemDefinitionOrStack) { + AEItemInfo itemInfo = null; + + // Get the index from the list of items to add + int index = -1; + for (int i = 0; i < this.ALL_ITEMS.size(); i++) { + // Match? + if (this.ALL_ITEMS.get(i).equals(itemDefinitionOrStack)) { + index = i; + break; + } + } + + // Found match? + if (index >= 0) { + itemInfo = this.ALL_ITEMS.get(index); + } + + return itemInfo; + } + + /** + * Gets the declared items from an AE registry. + * + * @param AEDefinitionInstance + */ + void getItemsFromAERegistryClass(final Object AEDefinitionInstance) { + AEItemInfo itemInfo; + + // Get the item fields + Field[] fields = AEDefinitionInstance.getClass().getDeclaredFields(); + + // Loop over all fields + for (Field f : fields) { + try { + // Set accessible + f.setAccessible(true); + + // Get the field + Object fObj = f.get(AEDefinitionInstance); + + // Ensure it is an item def + if (fObj instanceof IItemDefinition) { + // Create the info + itemInfo = new AEItemInfo((IItemDefinition) fObj); + + // Has the stack already been registered? + if (this.ITEMS_REGISTERED.contains(itemInfo)) { + // Skip it + continue; + } + + // Add to the list + this.ITEMS_TO_ADD.add(itemInfo); + this.ALL_ITEMS.add(itemInfo); + } + } catch (Exception e) { + continue; + } + } + } + + /** + * Registers the item info with thaumcraft. + * + * @param itemInfo + * @param aspects + */ + void registerItem(final AEItemInfo itemInfo) { + // Remove from the add list + this.ITEMS_TO_ADD.remove(itemInfo); + + // Ensure it has not already been registered + if (!this.ITEMS_REGISTERED.contains(itemInfo)) { + // Add to the registered list + this.ITEMS_REGISTERED.add(itemInfo); + + // Register it + ThaumcraftApi.registerObjectTag(itemInfo.itemStack, itemInfo.getFinalAspects()); + } + } + + /** + * Gives AppliedEnergistics blocks and items Thaumcraft aspects. + */ + public void registerAEAspects() { + // Log + long sectionStartTime = ThELog.beginSection("AE Scanables"); + + // Get the normal recipes + this.NORMAL_RECIPES = CraftingManager.getInstance().getRecipeList(); + + // Get the grinder recipes + if (!this.getGrinderRecipes()) { + ThELog.warning("Unable to load AE2 Grinder recipes, aspect registration will be incomplete"); + } + + // Get the inscriber recipes + if (!this.getInscriberRecipes()) { + ThELog.warning("Unable to load AE2 Inscriber recipes, aspect registration will be incomplete"); + } + + // Build the list of items to give aspects to + this.getItemsFromAERegistryClass(AEApi.instance().definitions().materials()); + this.getItemsFromAERegistryClass(AEApi.instance().definitions().items()); + this.getItemsFromAERegistryClass(AEApi.instance().definitions().blocks()); + this.getItemsFromAERegistryClass(AEApi.instance().definitions().parts()); + + // Give base AE items & materials aspects + this.registerBase(); + + // Register the remaining items + for (int pass = 1; pass <= 2; pass++) { + while (this.ITEMS_TO_ADD.size() > 0) { + // Get the next item + AEItemInfo itemInfo = this.ITEMS_TO_ADD.get(0); + + // Remove + this.ITEMS_TO_ADD.remove(0); + + // Register it + itemInfo.registerItem(pass); + } + + // Upon completion of pass 1, move all unregisterable items back into the items to add, and try again. + if (pass == 1) { + this.ITEMS_TO_ADD.addAll(this.UNREGISTERABLE); + this.UNREGISTERABLE.clear(); + } + } + + // Finally register my items + this.registerThEItems(); + + // Cleanup + this.NORMAL_RECIPES = null; + this.GRINDER_RECIPES = null; + this.ALL_ITEMS = null; + this.ITEMS_REGISTERED = null; + this.ITEMS_TO_ADD = null; + this.DEPENDENCY_CHAIN = null; + this.UNREGISTERABLE = null; + + // Log + ThELog.endSection("AE Scanables", sectionStartTime); + } } diff --git a/src/main/java/thaumicenergistics/common/registries/EnumCache.java b/src/main/java/thaumicenergistics/common/registries/EnumCache.java index 19046649..119603a0 100644 --- a/src/main/java/thaumicenergistics/common/registries/EnumCache.java +++ b/src/main/java/thaumicenergistics/common/registries/EnumCache.java @@ -12,30 +12,29 @@ import appeng.api.util.AEColor; * @author Nividica * */ -public class EnumCache -{ - /** - * AEColor - */ - public static final AEColor[] AE_COLOR = AEColor.values(); +public class EnumCache { + /** + * AEColor + */ + public static final AEColor[] AE_COLOR = AEColor.values(); - /** - * SortDir - */ - public static final SortDir[] AE_SORT_DIRECTIONS = SortDir.values(); + /** + * SortDir + */ + public static final SortDir[] AE_SORT_DIRECTIONS = SortDir.values(); - /** - * SortOrder - */ - public static final SortOrder[] AE_SORT_ORDERS = SortOrder.values(); + /** + * SortOrder + */ + public static final SortOrder[] AE_SORT_ORDERS = SortOrder.values(); - /** - * ViewItems - */ - public static final ViewItems[] AE_VIEW_ITEMS = ViewItems.values(); + /** + * ViewItems + */ + public static final ViewItems[] AE_VIEW_ITEMS = ViewItems.values(); - /** - * RedstoneMode - */ - public static final RedstoneMode[] AE_REDSTONE_MODES = RedstoneMode.values(); + /** + * RedstoneMode + */ + public static final RedstoneMode[] AE_REDSTONE_MODES = RedstoneMode.values(); } diff --git a/src/main/java/thaumicenergistics/common/registries/FeatureRegistry.java b/src/main/java/thaumicenergistics/common/registries/FeatureRegistry.java index e7d8a06c..615cdc69 100644 --- a/src/main/java/thaumicenergistics/common/registries/FeatureRegistry.java +++ b/src/main/java/thaumicenergistics/common/registries/FeatureRegistry.java @@ -10,210 +10,202 @@ import thaumicenergistics.common.features.*; * @author Nividica * */ -public class FeatureRegistry -{ +public class FeatureRegistry { - /** - * Singleton instance of the FR - */ - private static FeatureRegistry INSTANCE; + /** + * Singleton instance of the FR + */ + private static FeatureRegistry INSTANCE; - /** - * All features. - */ - private final ArrayList featuresList = new ArrayList( 20 ); + /** + * All features. + */ + private final ArrayList featuresList = new ArrayList(20); - /** - * Set to true when registerFeatures() is called. - */ - private boolean hasRegistered = false; + /** + * Set to true when registerFeatures() is called. + */ + private boolean hasRegistered = false; - /** - * Commonly used dependency items. - */ - public final CommonDependantItems cdi; + /** + * Commonly used dependency items. + */ + public final CommonDependantItems cdi; - /** - * Sets up the TC research tab. - */ - public final FeatureThaumicEnergisticsResearch featureThaumicEnergistics; + /** + * Sets up the TC research tab. + */ + public final FeatureThaumicEnergisticsResearch featureThaumicEnergistics; - /** - * Autocrafting. - */ - public final FeatureAutocrafting_Arcane featureAutoCrafting_Arcane; + /** + * Autocrafting. + */ + public final FeatureAutocrafting_Arcane featureAutoCrafting_Arcane; - /** - * Essentia storage cells. - */ - public final FeatureCells featureCells; + /** + * Essentia storage cells. + */ + public final FeatureCells featureCells; - /** - * Arcane Crafting Terminal. - */ - public final FeatureACT featureACT; + /** + * Arcane Crafting Terminal. + */ + public final FeatureACT featureACT; - /** - * Vis Relay Interface. - */ - public final FeatureVisRelayInterface featureVRI; + /** + * Vis Relay Interface. + */ + public final FeatureVisRelayInterface featureVRI; - /** - * Essentia IO buses. - */ - public final FeatureEssentiaIOBuses featureEssentiaIOBuses; + /** + * Essentia IO buses. + */ + public final FeatureEssentiaIOBuses featureEssentiaIOBuses; - /** - * Infusion provider. - */ - public final FeatureInfusionProvider featureInfusionProvider; + /** + * Infusion provider. + */ + public final FeatureInfusionProvider featureInfusionProvider; - /** - * Essentia Provider. - */ - public final FeatureEssentiaProvider featureEssentiaProvider; + /** + * Essentia Provider. + */ + public final FeatureEssentiaProvider featureEssentiaProvider; - /** - * Terminal, wireless terminal, level emitter, and storage monitors. - */ - public final FeatureEssentiaMonitoring featureEssentiaMonitoring; + /** + * Terminal, wireless terminal, level emitter, and storage monitors. + */ + public final FeatureEssentiaMonitoring featureEssentiaMonitoring; - /** - * Conversion cores. - */ - public final FeatureConversionCores featureConversionCores; + /** + * Conversion cores. + */ + public final FeatureConversionCores featureConversionCores; - /** - * Gearboxes. - */ - public final FeatureGearbox featureGearbox; + /** + * Gearboxes. + */ + public final FeatureGearbox featureGearbox; - /** - * Wrench focus. - */ - public final FeatureWrenchFocus featureWrenchFocus; + /** + * Wrench focus. + */ + public final FeatureWrenchFocus featureWrenchFocus; - /** - * Quartz duplication. - */ - public final FeatureQuartzDupe featureQuartzDupe; + /** + * Quartz duplication. + */ + public final FeatureQuartzDupe featureQuartzDupe; - /** - * Essentia Vibration Chamber. - */ - public final FeatureEssentiaVibrationChamber featureEssentiaVibrationChamber; + /** + * Essentia Vibration Chamber. + */ + public final FeatureEssentiaVibrationChamber featureEssentiaVibrationChamber; - /** - * Distillation Pattern Encoder. - */ - public final FeatureAutocrafting_Essentia featureAutocrafting_Essentia; + /** + * Distillation Pattern Encoder. + */ + public final FeatureAutocrafting_Essentia featureAutocrafting_Essentia; - /** - * Thaumcraft facades. - */ - public final FeatureThaumcraftFacades featureTCFacades; + /** + * Thaumcraft facades. + */ + public final FeatureThaumcraftFacades featureTCFacades; - /** - * Golem wifi backpack. - */ - public final FeatureGolemBackpack featureGolemWifiBackpack; + /** + * Golem wifi backpack. + */ + public final FeatureGolemBackpack featureGolemWifiBackpack; - /** - * Private constructor - */ - private FeatureRegistry() - { - // Build common items - this.cdi = new CommonDependantItems(); + /** + * Private constructor + */ + private FeatureRegistry() { + // Build common items + this.cdi = new CommonDependantItems(); - // Build ThE primary node - this.featuresList.add( this.featureThaumicEnergistics = new FeatureThaumicEnergisticsResearch() ); + // Build ThE primary node + this.featuresList.add(this.featureThaumicEnergistics = new FeatureThaumicEnergisticsResearch()); - // Build autocrafting - this.featuresList.add( this.featureAutoCrafting_Arcane = new FeatureAutocrafting_Arcane() ); + // Build autocrafting + this.featuresList.add(this.featureAutoCrafting_Arcane = new FeatureAutocrafting_Arcane()); - // Build cells - this.featuresList.add( this.featureCells = new FeatureCells() ); + // Build cells + this.featuresList.add(this.featureCells = new FeatureCells()); - // Build ACT - this.featuresList.add( this.featureACT = new FeatureACT() ); + // Build ACT + this.featuresList.add(this.featureACT = new FeatureACT()); - // Build VRI - this.featuresList.add( this.featureVRI = new FeatureVisRelayInterface() ); + // Build VRI + this.featuresList.add(this.featureVRI = new FeatureVisRelayInterface()); - // Build IO buses - this.featuresList.add( this.featureEssentiaIOBuses = new FeatureEssentiaIOBuses() ); + // Build IO buses + this.featuresList.add(this.featureEssentiaIOBuses = new FeatureEssentiaIOBuses()); - // Build infusion provider - this.featuresList.add( this.featureInfusionProvider = new FeatureInfusionProvider() ); + // Build infusion provider + this.featuresList.add(this.featureInfusionProvider = new FeatureInfusionProvider()); - // Build essentia provider - this.featuresList.add( this.featureEssentiaProvider = new FeatureEssentiaProvider() ); + // Build essentia provider + this.featuresList.add(this.featureEssentiaProvider = new FeatureEssentiaProvider()); - // Build monitoring - this.featuresList.add( this.featureEssentiaMonitoring = new FeatureEssentiaMonitoring() ); + // Build monitoring + this.featuresList.add(this.featureEssentiaMonitoring = new FeatureEssentiaMonitoring()); - // Build conversion cores - this.featuresList.add( this.featureConversionCores = new FeatureConversionCores() ); + // Build conversion cores + this.featuresList.add(this.featureConversionCores = new FeatureConversionCores()); - // Build gearboxes - this.featuresList.add( this.featureGearbox = new FeatureGearbox() ); + // Build gearboxes + this.featuresList.add(this.featureGearbox = new FeatureGearbox()); - // Build wrench focus - this.featuresList.add( this.featureWrenchFocus = new FeatureWrenchFocus() ); + // Build wrench focus + this.featuresList.add(this.featureWrenchFocus = new FeatureWrenchFocus()); - // Build quartz dupe - this.featuresList.add( this.featureQuartzDupe = new FeatureQuartzDupe() ); + // Build quartz dupe + this.featuresList.add(this.featureQuartzDupe = new FeatureQuartzDupe()); - // Build essentia vibration chamber - this.featuresList.add( this.featureEssentiaVibrationChamber = new FeatureEssentiaVibrationChamber() ); + // Build essentia vibration chamber + this.featuresList.add(this.featureEssentiaVibrationChamber = new FeatureEssentiaVibrationChamber()); - // Build distillation pattern encoder - this.featuresList.add( this.featureAutocrafting_Essentia = new FeatureAutocrafting_Essentia() ); + // Build distillation pattern encoder + this.featuresList.add(this.featureAutocrafting_Essentia = new FeatureAutocrafting_Essentia()); - // Build TC facades - this.featuresList.add( this.featureTCFacades = new FeatureThaumcraftFacades() ); + // Build TC facades + this.featuresList.add(this.featureTCFacades = new FeatureThaumcraftFacades()); - // Build golem wifi backpack - this.featuresList.add( this.featureGolemWifiBackpack = new FeatureGolemBackpack() ); - } + // Build golem wifi backpack + this.featuresList.add(this.featureGolemWifiBackpack = new FeatureGolemBackpack()); + } - /** - * Gets the instance of the FR - * - * @return - */ - public static FeatureRegistry instance() - { - if( FeatureRegistry.INSTANCE == null ) - { - FeatureRegistry.INSTANCE = new FeatureRegistry(); - } + /** + * Gets the instance of the FR + * + * @return + */ + public static FeatureRegistry instance() { + if (FeatureRegistry.INSTANCE == null) { + FeatureRegistry.INSTANCE = new FeatureRegistry(); + } - return FeatureRegistry.INSTANCE; - } + return FeatureRegistry.INSTANCE; + } - /** - * Registers all features of ThE with Minecraft. - */ - public void registerFeatures() - { - // Has registration already occurred? - if( this.hasRegistered ) - { - // Bail - return; - } + /** + * Registers all features of ThE with Minecraft. + */ + public void registerFeatures() { + // Has registration already occurred? + if (this.hasRegistered) { + // Bail + return; + } - // Register each feature - for( ThEFeatureBase feature : this.featuresList ) - { - // Attempt to register the feature - feature.registerFeature( this.cdi ); - } - - // Mark that registration has occurred. - this.hasRegistered = true; - } + // Register each feature + for (ThEFeatureBase feature : this.featuresList) { + // Attempt to register the feature + feature.registerFeature(this.cdi); + } + // Mark that registration has occurred. + this.hasRegistered = true; + } } diff --git a/src/main/java/thaumicenergistics/common/registries/RecipeRegistry.java b/src/main/java/thaumicenergistics/common/registries/RecipeRegistry.java index 841cf2cd..e202618e 100644 --- a/src/main/java/thaumicenergistics/common/registries/RecipeRegistry.java +++ b/src/main/java/thaumicenergistics/common/registries/RecipeRegistry.java @@ -11,54 +11,52 @@ import thaumcraft.api.crafting.InfusionRecipe; * @author Nividica * */ -public class RecipeRegistry -{ - // Arcane recipes - public static IArcaneRecipe ITEM_STORAGE_COMPONENT_1K; - public static IArcaneRecipe ITEM_STORAGE_COMPONENT_4K; - public static IArcaneRecipe ITEM_STORAGE_COMPONENT_16K; - public static IArcaneRecipe ITEM_STORAGE_COMPONENT_64K; - public static IArcaneRecipe ITEM_KNOWLEDGE_CORE; - public static IArcaneRecipe ITEM_WRENCH_FOCUS; - public static IArcaneRecipe ITEM_GOLEM_WIFI_BACKPACK; - public static IArcaneRecipe MATERIAL_DIFFUSION_CORE; - public static IArcaneRecipe MATERIAL_COALESCENCE_CORE; - public static IArcaneRecipe MATERIAL_IRON_GEAR; - public static IArcaneRecipe PART_IMPORT_BUS; - public static IArcaneRecipe PART_EXPORT_BUS; - public static IArcaneRecipe PART_STORAGE_BUS; - public static IArcaneRecipe PART_ESSENTIA_TERMINAL; - public static IArcaneRecipe PART_ARCANE_TERMINAL; - public static IArcaneRecipe PART_ESSENTIA_LEVEL_EMITTER; - public static IArcaneRecipe PART_VIS_INTERFACE; - public static IArcaneRecipe BLOCK_IRONGEARBOX; - public static IArcaneRecipe BLOCK_KNOWLEDGE_INSCRIBER; - public static IArcaneRecipe BLOCK_ESSENTIA_VIBRATION_CHAMBER; - public static IArcaneRecipe BLOCK_DISTILLATION_PATTERN_ENCODER; +public class RecipeRegistry { + // Arcane recipes + public static IArcaneRecipe ITEM_STORAGE_COMPONENT_1K; + public static IArcaneRecipe ITEM_STORAGE_COMPONENT_4K; + public static IArcaneRecipe ITEM_STORAGE_COMPONENT_16K; + public static IArcaneRecipe ITEM_STORAGE_COMPONENT_64K; + public static IArcaneRecipe ITEM_KNOWLEDGE_CORE; + public static IArcaneRecipe ITEM_WRENCH_FOCUS; + public static IArcaneRecipe ITEM_GOLEM_WIFI_BACKPACK; + public static IArcaneRecipe MATERIAL_DIFFUSION_CORE; + public static IArcaneRecipe MATERIAL_COALESCENCE_CORE; + public static IArcaneRecipe MATERIAL_IRON_GEAR; + public static IArcaneRecipe PART_IMPORT_BUS; + public static IArcaneRecipe PART_EXPORT_BUS; + public static IArcaneRecipe PART_STORAGE_BUS; + public static IArcaneRecipe PART_ESSENTIA_TERMINAL; + public static IArcaneRecipe PART_ARCANE_TERMINAL; + public static IArcaneRecipe PART_ESSENTIA_LEVEL_EMITTER; + public static IArcaneRecipe PART_VIS_INTERFACE; + public static IArcaneRecipe BLOCK_IRONGEARBOX; + public static IArcaneRecipe BLOCK_KNOWLEDGE_INSCRIBER; + public static IArcaneRecipe BLOCK_ESSENTIA_VIBRATION_CHAMBER; + public static IArcaneRecipe BLOCK_DISTILLATION_PATTERN_ENCODER; - // Vanilla recipes - public static IRecipe ITEM_STORAGE_HOUSING; - public static IRecipe ITEM_STORAGE_CELL_1K_SHAPED; - public static IRecipe ITEM_STORAGE_CELL_4K_SHAPED; - public static IRecipe ITEM_STORAGE_CELL_16K_SHAPED; - public static IRecipe ITEM_STORAGE_CELL_64K_SHAPED; - public static IRecipe ITEM_STORAGE_CELL_1K_SHAPELESS; - public static IRecipe ITEM_STORAGE_CELL_4K_SHAPELESS; - public static IRecipe ITEM_STORAGE_CELL_16K_SHAPELESS; - public static IRecipe ITEM_STORAGE_CELL_64K_SHAPELESS; - public static IRecipe ITEM_WIRELESS_ESSENTIA_TERMINAL; - public static IRecipe PART_ESSENTIA_STORAGE_MONITOR; - public static IRecipe PART_ESSENTIA_CONVERSION_MONITOR; - public static IRecipe BLOCK_CELL_WORKBENCH; + // Vanilla recipes + public static IRecipe ITEM_STORAGE_HOUSING; + public static IRecipe ITEM_STORAGE_CELL_1K_SHAPED; + public static IRecipe ITEM_STORAGE_CELL_4K_SHAPED; + public static IRecipe ITEM_STORAGE_CELL_16K_SHAPED; + public static IRecipe ITEM_STORAGE_CELL_64K_SHAPED; + public static IRecipe ITEM_STORAGE_CELL_1K_SHAPELESS; + public static IRecipe ITEM_STORAGE_CELL_4K_SHAPELESS; + public static IRecipe ITEM_STORAGE_CELL_16K_SHAPELESS; + public static IRecipe ITEM_STORAGE_CELL_64K_SHAPELESS; + public static IRecipe ITEM_WIRELESS_ESSENTIA_TERMINAL; + public static IRecipe PART_ESSENTIA_STORAGE_MONITOR; + public static IRecipe PART_ESSENTIA_CONVERSION_MONITOR; + public static IRecipe BLOCK_CELL_WORKBENCH; - // Crucible recipes - public static CrucibleRecipe BLOCK_THAUMIUMGEARBOX; - public static CrucibleRecipe DUPE_CERTUS; - public static CrucibleRecipe DUPE_NETHER_QUARTZ; - - // Infusion recipes - public static InfusionRecipe BLOCK_INFUSION_PROVIDER; - public static InfusionRecipe BLOCK_ESSENTIA_PROVIDER; - public static InfusionRecipe BLOCK_ARCANE_ASSEMBLER; + // Crucible recipes + public static CrucibleRecipe BLOCK_THAUMIUMGEARBOX; + public static CrucibleRecipe DUPE_CERTUS; + public static CrucibleRecipe DUPE_NETHER_QUARTZ; + // Infusion recipes + public static InfusionRecipe BLOCK_INFUSION_PROVIDER; + public static InfusionRecipe BLOCK_ESSENTIA_PROVIDER; + public static InfusionRecipe BLOCK_ARCANE_ASSEMBLER; } diff --git a/src/main/java/thaumicenergistics/common/registries/Renderers.java b/src/main/java/thaumicenergistics/common/registries/Renderers.java index afed0795..a58fe360 100644 --- a/src/main/java/thaumicenergistics/common/registries/Renderers.java +++ b/src/main/java/thaumicenergistics/common/registries/Renderers.java @@ -18,52 +18,51 @@ import thaumicenergistics.common.tiles.TileGearBox; * */ @SideOnly(Side.CLIENT) -public class Renderers -{ - public static final int PASS_OPAQUE = 0; - public static final int PASS_ALPHA = 1; +public class Renderers { + public static final int PASS_OPAQUE = 0; + public static final int PASS_ALPHA = 1; - public static int currentRenderPass = 0; + public static int currentRenderPass = 0; - public static int EssentiaProviderRenderID, InfusionProviderRenderID; + public static int EssentiaProviderRenderID, InfusionProviderRenderID; - public static void registerRenderers() - { - // Get the next render ID - Renderers.EssentiaProviderRenderID = RenderingRegistry.getNextAvailableRenderId(); - // Register the essentia provider renderer - RenderingRegistry.registerBlockHandler( new RenderBlockEssentiaProvider() ); + public static void registerRenderers() { + // Get the next render ID + Renderers.EssentiaProviderRenderID = RenderingRegistry.getNextAvailableRenderId(); + // Register the essentia provider renderer + RenderingRegistry.registerBlockHandler(new RenderBlockEssentiaProvider()); - // Get the next render ID - Renderers.InfusionProviderRenderID = RenderingRegistry.getNextAvailableRenderId(); + // Get the next render ID + Renderers.InfusionProviderRenderID = RenderingRegistry.getNextAvailableRenderId(); - // Register the infusion provider renderer - RenderingRegistry.registerBlockHandler( new RenderBlockInfusionProvider() ); + // Register the infusion provider renderer + RenderingRegistry.registerBlockHandler(new RenderBlockInfusionProvider()); - // Are gearbox models enabled? - if( !ThEApi.instance().config().disableGearboxModel() ) - { - // Register the gearbox renderer - ClientRegistry.bindTileEntitySpecialRenderer( TileGearBox.class, new RenderTileGearbox() ); + // Are gearbox models enabled? + if (!ThEApi.instance().config().disableGearboxModel()) { + // Register the gearbox renderer + ClientRegistry.bindTileEntitySpecialRenderer(TileGearBox.class, new RenderTileGearbox()); - // Register thaumium gearbox item renderer - MinecraftForgeClient.registerItemRenderer( ThEApi.instance().blocks().ThaumiumGearBox.getItem(), new TileAsItemRenderer( - new RenderTileGearbox(), new TileGearBox( true ) ) ); + // Register thaumium gearbox item renderer + MinecraftForgeClient.registerItemRenderer( + ThEApi.instance().blocks().ThaumiumGearBox.getItem(), + new TileAsItemRenderer(new RenderTileGearbox(), new TileGearBox(true))); - // Register iron gearbox item renderer - MinecraftForgeClient.registerItemRenderer( ThEApi.instance().blocks().IronGearBox.getItem(), new TileAsItemRenderer( - new RenderTileGearbox(), new TileGearBox( false ) ) ); - } + // Register iron gearbox item renderer + MinecraftForgeClient.registerItemRenderer( + ThEApi.instance().blocks().IronGearBox.getItem(), + new TileAsItemRenderer(new RenderTileGearbox(), new TileGearBox(false))); + } - // Register the arcane assembler renderer - ClientRegistry.bindTileEntitySpecialRenderer( TileArcaneAssembler.class, new RenderTileArcaneAssembler() ); + // Register the arcane assembler renderer + ClientRegistry.bindTileEntitySpecialRenderer(TileArcaneAssembler.class, new RenderTileArcaneAssembler()); - // Register arcane assembler item renderer - MinecraftForgeClient.registerItemRenderer( ThEApi.instance().blocks().ArcaneAssembler.getItem(), new TileAsItemRenderer( - new RenderTileArcaneAssembler(), new TileArcaneAssembler() ) ); + // Register arcane assembler item renderer + MinecraftForgeClient.registerItemRenderer( + ThEApi.instance().blocks().ArcaneAssembler.getItem(), + new TileAsItemRenderer(new RenderTileArcaneAssembler(), new TileArcaneAssembler())); - // Register crafting aspect item renderer - MinecraftForgeClient.registerItemRenderer( ItemEnum.CRAFTING_ASPECT.getItem(), new RendererItemCraftingAspect() ); - - } + // Register crafting aspect item renderer + MinecraftForgeClient.registerItemRenderer(ItemEnum.CRAFTING_ASPECT.getItem(), new RendererItemCraftingAspect()); + } } diff --git a/src/main/java/thaumicenergistics/common/registries/ResearchRegistry.java b/src/main/java/thaumicenergistics/common/registries/ResearchRegistry.java index 8834518b..6ba81251 100644 --- a/src/main/java/thaumicenergistics/common/registries/ResearchRegistry.java +++ b/src/main/java/thaumicenergistics/common/registries/ResearchRegistry.java @@ -13,147 +13,141 @@ import thaumicenergistics.common.integration.tc.PseudoResearchItem; * @author Nividica * */ -public class ResearchRegistry -{ - // Fake research, serves as placeholder for existing research - public static enum PseudoResearchTypes - { - DISTILESSENTIA ("DISTILESSENTIA", "ALCHEMY", -2, 0), - TUBEFILTER ("TUBEFILTER", "ALCHEMY", -3, 0), - MIRROR ("MIRROR", "ARTIFICE", -4, 0), - JAR ("JARLABEL", "ALCHEMY", -4, 0), - INFUSION ("INFUSION", "ARTIFICE", -6, 0), - DUPE ("ALCHEMICALDUPLICATION", "ALCHEMY", -5, -6), - WARDED ("WARDEDARCANA", "ARTIFICE", 1, 2), - FOCUSFIRE ("FOCUSFIRE", "THAUMATURGY", -4, -7), - VISPOWER ("VISPOWER", "THAUMATURGY", 4, 0), - SCEPTRE ("SCEPTRE", "THAUMATURGY", 5, 0), - COREUSE ("COREUSE", "GOLEMANCY", 3, -6), - COREGATHER ("COREGATHER", "GOLEMANCY", 1, -6); +public class ResearchRegistry { + // Fake research, serves as placeholder for existing research + public static enum PseudoResearchTypes { + DISTILESSENTIA("DISTILESSENTIA", "ALCHEMY", -2, 0), + TUBEFILTER("TUBEFILTER", "ALCHEMY", -3, 0), + MIRROR("MIRROR", "ARTIFICE", -4, 0), + JAR("JARLABEL", "ALCHEMY", -4, 0), + INFUSION("INFUSION", "ARTIFICE", -6, 0), + DUPE("ALCHEMICALDUPLICATION", "ALCHEMY", -5, -6), + WARDED("WARDEDARCANA", "ARTIFICE", 1, 2), + FOCUSFIRE("FOCUSFIRE", "THAUMATURGY", -4, -7), + VISPOWER("VISPOWER", "THAUMATURGY", 4, 0), + SCEPTRE("SCEPTRE", "THAUMATURGY", 5, 0), + COREUSE("COREUSE", "GOLEMANCY", 3, -6), + COREGATHER("COREGATHER", "GOLEMANCY", 1, -6); + private String realResearchKey, realResearchCategory; + private int column, row; + private PseudoResearchItem researchItem; + private boolean hasRegistered = false; - private String realResearchKey, realResearchCategory; - private int column, row; - private PseudoResearchItem researchItem; - private boolean hasRegistered = false; + private PseudoResearchTypes(final String key, final String cat, final int column, final int row) { + this.realResearchCategory = cat; + this.realResearchKey = key; + this.column = column; + this.row = row; + } - private PseudoResearchTypes( final String key, final String cat, final int column, final int row ) - { - this.realResearchCategory = cat; - this.realResearchKey = key; - this.column = column; - this.row = row; - } + public String getKey() { + return ThaumicEnergistics.MOD_ID + ".Pseudo." + this.realResearchKey; + } - public String getKey() - { - return ThaumicEnergistics.MOD_ID + ".Pseudo." + this.realResearchKey; - } + public void registerPsudeoResearch() { + if (!this.hasRegistered) { + this.researchItem = PseudoResearchItem.newPseudo( + this.getKey(), + TERESEARCH_TAB, + this.realResearchKey, + this.realResearchCategory, + this.column, + this.row); + this.researchItem.registerResearchItem(); + this.hasRegistered = true; + } + } + } - public void registerPsudeoResearch() - { - if( !this.hasRegistered ) - { - this.researchItem = PseudoResearchItem.newPseudo( this.getKey(), TERESEARCH_TAB, this.realResearchKey, this.realResearchCategory, - this.column, this.row ); - this.researchItem.registerResearchItem(); - this.hasRegistered = true; - } - } - } + // Research types + public static enum ResearchTypes { + BASIC("RESEARCH", 0, 0), + CORES("CORES", 0, -2), + STORAGE("STORAGE", 0, 2), + IO("IO", -2, -2), + ARCANE_TERMINAL("ARCANETERM", 2, -1), + ESSENTIA_TERMINAL("ESSTERM", -1, -4), + ESSENTIA_PROVIDER("ESSPROV", -2, -4), + INFUSION_PROVIDER("INFPROV", -5, -2), + IRON_GEARBOX("IRONGEARBOX", 4, -5), + THAUMIUM_GEARBOX("THAUMGBOX", 4, -6), + CERTUS_DUPE("CERTUSDUPE", -5, -5), + VIS_RELAY_INTERFACE("VISINT", 4, -1), + ARCANE_ASSEMBLER("ARCANEASSEMBLER", 6, -1), + KNOWLEDGE_INSCRIBER("KNOWLEDGEINSCRIBER", 6, 0), + FOCUS_WRENCH("FOCUSWRENCH", -3, -7), + ESSENTIA_VIBRATION_CHAMBER("ESSVIBCMBR", 1, -4), + DISTILLATION_PATTERN_ENCODER("DISTILLATIONPATTERNENCODER", -4, -4), + GOLEM_BACKPACK("GOLEMWIFIBACKPACK", 0, -6); - // Research types - public static enum ResearchTypes - { - BASIC ("RESEARCH", 0, 0), - CORES ("CORES", 0, -2), - STORAGE ("STORAGE", 0, 2), - IO ("IO", -2, -2), - ARCANE_TERMINAL ("ARCANETERM", 2, -1), - ESSENTIA_TERMINAL ("ESSTERM", -1, -4), - ESSENTIA_PROVIDER ("ESSPROV", -2, -4), - INFUSION_PROVIDER ("INFPROV", -5, -2), - IRON_GEARBOX ("IRONGEARBOX", 4, -5), - THAUMIUM_GEARBOX ("THAUMGBOX", 4, -6), - CERTUS_DUPE ("CERTUSDUPE", -5, -5), - VIS_RELAY_INTERFACE ("VISINT", 4, -1), - ARCANE_ASSEMBLER ("ARCANEASSEMBLER", 6, -1), - KNOWLEDGE_INSCRIBER ("KNOWLEDGEINSCRIBER", 6, 0), - FOCUS_WRENCH ("FOCUSWRENCH", -3, -7), - ESSENTIA_VIBRATION_CHAMBER ("ESSVIBCMBR", 1, -4), - DISTILLATION_PATTERN_ENCODER ("DISTILLATIONPATTERNENCODER", -4, -4), - GOLEM_BACKPACK ("GOLEMWIFIBACKPACK", 0, -6); + /** + * Internal name of the research type. + */ + private String internalName; - /** - * Internal name of the research type. - */ - private String internalName; + /** + * Position of the research node in the Thaumonomicon. + */ + private int column, row; - /** - * Position of the research node in the Thaumonomicon. - */ - private int column, row; + /** + * The actual research item. + */ + public ResearchItem researchItem; - /** - * The actual research item. - */ - public ResearchItem researchItem; + private ResearchTypes(final String internalName, final int column, final int row) { + this.internalName = "TE" + internalName; + this.row = row; + this.column = column; + } - private ResearchTypes( final String internalName, final int column, final int row ) - { - this.internalName = "TE" + internalName; - this.row = row; - this.column = column; - } + /** + * Convenience function to aid in research item creation. + * + * @param aspectList + * @param column + * @param row + * @param complexity + * @param icon + * @param pages + */ + public void createResearchItem( + final AspectList aspectList, final int complexity, final ItemStack icon, final ResearchPage[] pages) { + this.researchItem = new ResearchItem( + this.getKey(), TERESEARCH_TAB, aspectList, this.column, this.row, complexity, icon); + this.researchItem.setPages(pages); + } - /** - * Convenience function to aid in research item creation. - * - * @param aspectList - * @param column - * @param row - * @param complexity - * @param icon - * @param pages - */ - public void createResearchItem( final AspectList aspectList, final int complexity, final ItemStack icon, final ResearchPage[] pages ) - { - this.researchItem = new ResearchItem( this.getKey(), TERESEARCH_TAB, aspectList, this.column, this.row, complexity, icon ); - this.researchItem.setPages( pages ); - } + public String getKey() { + return ThaumicEnergistics.MOD_ID + "." + this.internalName; + } - public String getKey() - { - return ThaumicEnergistics.MOD_ID + "." + this.internalName; - } + /** + * Gets the name of a numeric page. + * + * @param index + * @return + */ + public String getPageName(final int index) { + return ThaumicEnergistics.MOD_ID + ".research_page." + this.internalName + "." + index; + } - /** - * Gets the name of a numeric page. - * - * @param index - * @return - */ - public String getPageName( final int index ) - { - return ThaumicEnergistics.MOD_ID + ".research_page." + this.internalName + "." + index; - } + /** + * Gets the name of a named page. + * + * @param subName + * @return + */ + public String getPageName(final String subName) { + return ThaumicEnergistics.MOD_ID + ".research_page." + this.internalName + "." + subName; + } + } - /** - * Gets the name of a named page. - * - * @param subName - * @return - */ - public String getPageName( final String subName ) - { - return ThaumicEnergistics.MOD_ID + ".research_page." + this.internalName + "." + subName; - } - } + // Complexity of research + public static final int COMPLEXITY_SMALL = 1; + public static final int COMPLEXITY_MEDIUM = 2; + public static final int COMPLEXITY_LARGE = 3; - // Complexity of research - public static final int COMPLEXITY_SMALL = 1; - public static final int COMPLEXITY_MEDIUM = 2; - public static final int COMPLEXITY_LARGE = 3; - - // Research Tab name - public static final String TERESEARCH_TAB = ThaumicEnergistics.MOD_ID; + // Research Tab name + public static final String TERESEARCH_TAB = ThaumicEnergistics.MOD_ID; } diff --git a/src/main/java/thaumicenergistics/common/registries/ThEStrings.java b/src/main/java/thaumicenergistics/common/registries/ThEStrings.java index d0984655..7beef7f2 100644 --- a/src/main/java/thaumicenergistics/common/registries/ThEStrings.java +++ b/src/main/java/thaumicenergistics/common/registries/ThEStrings.java @@ -9,115 +9,110 @@ import thaumicenergistics.common.ThaumicEnergistics; * @author Nividica * */ -public enum ThEStrings -{ - // Fluids - Fluid_GaseousEssentia ("fluid.gaseous", false), +public enum ThEStrings { + // Fluids + Fluid_GaseousEssentia("fluid.gaseous", false), - // Blocks - Block_EssentiaProvider ("block.essentia.provider", true), - Block_InfusionProvider ("block.infusion.provider", true), - Block_IronGearbox ("block.gear.box", true), - Block_ThaumiumGearbox ("block.golem.gear.box", true), - Block_EssentiaCellWorkbench ("block.essentia.cell.workbench", true), - Block_ArcaneAssembler ("block.arcane.assembler", true), - Block_KnowledgeInscriber ("block.knowledge.inscriber", true), - Block_EssentiaVibrationChamber ("block.essentia.vibration.chamber", true), - Block_DistillationEncoder ("block.distillation.encoder", true), + // Blocks + Block_EssentiaProvider("block.essentia.provider", true), + Block_InfusionProvider("block.infusion.provider", true), + Block_IronGearbox("block.gear.box", true), + Block_ThaumiumGearbox("block.golem.gear.box", true), + Block_EssentiaCellWorkbench("block.essentia.cell.workbench", true), + Block_ArcaneAssembler("block.arcane.assembler", true), + Block_KnowledgeInscriber("block.knowledge.inscriber", true), + Block_EssentiaVibrationChamber("block.essentia.vibration.chamber", true), + Block_DistillationEncoder("block.distillation.encoder", true), - // Parts - Part_EssentiaImportBus ("aeparts.essentia.ImportBus", true), - Part_EssentiaExportBus ("aeparts.essentia.ExportBus", true), - Part_EssentiaLevelEmitter ("aeparts.essentia.levelemitter", true), - Part_EssentiaStorageBus ("aeparts.essentia.StorageBus", true), - Part_EssentiaTerminal ("aeparts.essentia.terminal", true), - Part_ArcaneCraftingTerminal ("aeparts.arcane.crafting.terminal", true), - Part_VisRelayInterface ("aeparts.vis.interface", true), - Part_EssentiaStorageMonitor ("aeparts.essentia.storage.monitor", true), - Part_EssentiaConversionMonitor ("aeparts.essentia.conversion.monitor", true), + // Parts + Part_EssentiaImportBus("aeparts.essentia.ImportBus", true), + Part_EssentiaExportBus("aeparts.essentia.ExportBus", true), + Part_EssentiaLevelEmitter("aeparts.essentia.levelemitter", true), + Part_EssentiaStorageBus("aeparts.essentia.StorageBus", true), + Part_EssentiaTerminal("aeparts.essentia.terminal", true), + Part_ArcaneCraftingTerminal("aeparts.arcane.crafting.terminal", true), + Part_VisRelayInterface("aeparts.vis.interface", true), + Part_EssentiaStorageMonitor("aeparts.essentia.storage.monitor", true), + Part_EssentiaConversionMonitor("aeparts.essentia.conversion.monitor", true), - // Items - Item_EssentiaCell_1k ("item.essentia.cell.1k", true), - Item_EssentiaCell_4k ("item.essentia.cell.4k", true), - Item_EssentiaCell_16k ("item.essentia.cell.16k", true), - Item_EssentiaCell_64k ("item.essentia.cell.64k", true), - Item_EssentiaCell_Creative ("item.essentia.cell.creative", true), - Item_EssentiaCellHousing ("item.storage.casing", true), - Item_StorageComponent_1k ("item.storage.component.1k", true), - Item_StorageComponent_4k ("item.storage.component.4k", true), - Item_StorageComponent_16k ("item.storage.component.16k", true), - Item_StorageComponent_64k ("item.storage.component.64k", true), - Item_DiffusionCore ("item.material.diffusion.core", true), - Item_CoalescenceCore ("item.material.coalescence.core", true), - Item_IronGear ("item.material.iron.gear", true), - Item_WirelessEssentiaTerminal ("item.wireless.essentia.terminal", true), - Item_KnowledgeCore ("item.knowledge.core", true), - Item_FocusAEWrench ("item.focus.aewrench", true), - Item_FocusAEWrench_Disabled ("item.focus.aewrench.disabled", true), - Item_Golem_Wifi_Backpack ("item.golem.wifi.backpack", true), + // Items + Item_EssentiaCell_1k("item.essentia.cell.1k", true), + Item_EssentiaCell_4k("item.essentia.cell.4k", true), + Item_EssentiaCell_16k("item.essentia.cell.16k", true), + Item_EssentiaCell_64k("item.essentia.cell.64k", true), + Item_EssentiaCell_Creative("item.essentia.cell.creative", true), + Item_EssentiaCellHousing("item.storage.casing", true), + Item_StorageComponent_1k("item.storage.component.1k", true), + Item_StorageComponent_4k("item.storage.component.4k", true), + Item_StorageComponent_16k("item.storage.component.16k", true), + Item_StorageComponent_64k("item.storage.component.64k", true), + Item_DiffusionCore("item.material.diffusion.core", true), + Item_CoalescenceCore("item.material.coalescence.core", true), + Item_IronGear("item.material.iron.gear", true), + Item_WirelessEssentiaTerminal("item.wireless.essentia.terminal", true), + Item_KnowledgeCore("item.knowledge.core", true), + Item_FocusAEWrench("item.focus.aewrench", true), + Item_FocusAEWrench_Disabled("item.focus.aewrench.disabled", true), + Item_Golem_Wifi_Backpack("item.golem.wifi.backpack", true), - // Tooltips - Tooltip_ItemStackDetails ("tooltip.itemstack.details", false), - Tooltip_CellBytes ("tooltip.essentia.cell.bytes", false), - Tooltip_CellTypes ("tooltip.essentia.cell.types", false), - Tooltip_CellContains ("tooltip.essentia.cell.contains", false), - Tooltip_ArcaneAssemblerHasVis ("tooltip.arcane.assembler.hasVis", false), + // Tooltips + Tooltip_ItemStackDetails("tooltip.itemstack.details", false), + Tooltip_CellBytes("tooltip.essentia.cell.bytes", false), + Tooltip_CellTypes("tooltip.essentia.cell.types", false), + Tooltip_CellContains("tooltip.essentia.cell.contains", false), + Tooltip_ArcaneAssemblerHasVis("tooltip.arcane.assembler.hasVis", false), - // Button Tooltips - TooltipButton_VoidHeader ("tooltip.button.void", false), - TooltipButton_VoidAllow ("tooltip.button.void.allowed", false), - TooltipButton_VoidDisable ("tooltip.button.void.disabled", false), - TooltipButton_VoidNote ("tooltip.button.void.note", false), - TooltipButton_InscriberInvalid ("tooltip.button.inscriber.invalid", false), - TooltipButton_InscriberFull ("tooltip.button.inscriber.full", false), - TooltipButton_InscriberDelete ("tooltip.button.inscriber.delete", false), - TooltipButton_InscriberSave ("tooltip.button.inscriber.save", false), - TooltipButton_InscriberMissing ("tooltip.button.inscriber.missing", false), - TooltipButton_SwapArmor ("tooltip.button.swap.armor", false), - TooltipButton_SwapArmor_Title ("tooltip.button.swap.armor.title", false), + // Button Tooltips + TooltipButton_VoidHeader("tooltip.button.void", false), + TooltipButton_VoidAllow("tooltip.button.void.allowed", false), + TooltipButton_VoidDisable("tooltip.button.void.disabled", false), + TooltipButton_VoidNote("tooltip.button.void.note", false), + TooltipButton_InscriberInvalid("tooltip.button.inscriber.invalid", false), + TooltipButton_InscriberFull("tooltip.button.inscriber.full", false), + TooltipButton_InscriberDelete("tooltip.button.inscriber.delete", false), + TooltipButton_InscriberSave("tooltip.button.inscriber.save", false), + TooltipButton_InscriberMissing("tooltip.button.inscriber.missing", false), + TooltipButton_SwapArmor("tooltip.button.swap.armor", false), + TooltipButton_SwapArmor_Title("tooltip.button.swap.armor.title", false), - // GUI - Gui_TitleArcaneCraftingTerminal ("gui.arcane.crafting.terminal.title", false), - Gui_TitleEssentiaCell ("gui.essentia.cell.title", false), - Gui_SelectedAmount ("gui.selected.amount", false), - Gui_SelectedAspect ("gui.selected.aspect", false), - Gui_DigiVisSource ("gui.digivis.source", true), - Gui_TitleEssentiaCellWorkbench ("gui.essentia.cell.workbench.title", false), - Gui_TitleArcaneAssembler ("gui.arcane.assembler.title", false), - GUi_VibrationChamber_Stored ("gui.vibration.chamber.stored", false), - GUi_VibrationChamber_Processing ("gui.vibration.chamber.processing", false); + // GUI + Gui_TitleArcaneCraftingTerminal("gui.arcane.crafting.terminal.title", false), + Gui_TitleEssentiaCell("gui.essentia.cell.title", false), + Gui_SelectedAmount("gui.selected.amount", false), + Gui_SelectedAspect("gui.selected.aspect", false), + Gui_DigiVisSource("gui.digivis.source", true), + Gui_TitleEssentiaCellWorkbench("gui.essentia.cell.workbench.title", false), + Gui_TitleArcaneAssembler("gui.arcane.assembler.title", false), + GUi_VibrationChamber_Stored("gui.vibration.chamber.stored", false), + GUi_VibrationChamber_Processing("gui.vibration.chamber.processing", false); - private String unlocalized; - private boolean isDotName; + private String unlocalized; + private boolean isDotName; - private ThEStrings( final String unloc, final boolean isDotName ) - { - this.unlocalized = ThaumicEnergistics.MOD_ID + "." + unloc; - this.isDotName = isDotName; - } + private ThEStrings(final String unloc, final boolean isDotName) { + this.unlocalized = ThaumicEnergistics.MOD_ID + "." + unloc; + this.isDotName = isDotName; + } - /** - * Gets the localized string. - * - * @return - */ - public String getLocalized() - { - if( this.isDotName ) - { - return StatCollector.translateToLocal( this.unlocalized + ".name" ); - } + /** + * Gets the localized string. + * + * @return + */ + public String getLocalized() { + if (this.isDotName) { + return StatCollector.translateToLocal(this.unlocalized + ".name"); + } - return StatCollector.translateToLocal( this.unlocalized ); - } + return StatCollector.translateToLocal(this.unlocalized); + } - /** - * Gets the unlocalized string. - * - * @return - */ - public String getUnlocalized() - { - return this.unlocalized; - } + /** + * Gets the unlocalized string. + * + * @return + */ + public String getUnlocalized() { + return this.unlocalized; + } } diff --git a/src/main/java/thaumicenergistics/common/storage/AspectStack.java b/src/main/java/thaumicenergistics/common/storage/AspectStack.java index 15e2549b..d63d3364 100644 --- a/src/main/java/thaumicenergistics/common/storage/AspectStack.java +++ b/src/main/java/thaumicenergistics/common/storage/AspectStack.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.storage; -import javax.annotation.Nullable; import io.netty.buffer.ByteBuf; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; @@ -18,343 +18,303 @@ import thaumicenergistics.common.network.ThEBasePacket; * @author Nividica * */ -public class AspectStack - implements IAspectStack -{ - private static final String NBTKEY_ASPECT_TAG = "AspectTag", NBTKEY_ASPECT_AMOUNT = "Amount", NBTKEY_CRAFTABLE = "Craftable"; +public class AspectStack implements IAspectStack { + private static final String NBTKEY_ASPECT_TAG = "AspectTag", + NBTKEY_ASPECT_AMOUNT = "Amount", + NBTKEY_CRAFTABLE = "Craftable"; - /** - * The aspect this stack contains. - */ - @Nullable - protected Aspect aspect; + /** + * The aspect this stack contains. + */ + @Nullable + protected Aspect aspect; - /** - * The amount this stack contains - */ - protected long stackSize; + /** + * The amount this stack contains + */ + protected long stackSize; - /** - * True if the aspect is craftable. - */ - protected boolean isCraftable; + /** + * True if the aspect is craftable. + */ + protected boolean isCraftable; - /** - * Creates an empty stack - */ - public AspectStack() - { - this( null, 0, false ); - } + /** + * Creates an empty stack + */ + public AspectStack() { + this(null, 0, false); + } - /** - * Creates a stack using the specified aspect and amount. - * Defaults to not craftable. - * - * @param aspect - * What aspect this stack will have. - * @param amount - * How much this stack will have. - */ - public AspectStack( final Aspect aspect, final long amount ) - { - this( aspect, amount, false ); - } + /** + * Creates a stack using the specified aspect and amount. + * Defaults to not craftable. + * + * @param aspect + * What aspect this stack will have. + * @param amount + * How much this stack will have. + */ + public AspectStack(final Aspect aspect, final long amount) { + this(aspect, amount, false); + } - /** - * Creates a stack using the specified aspect and amount, and - * sets if it is craftable. - * - * @param aspect - * What aspect this stack will have. - * @param size - * How much this stack will have. - * @param craftable - * Is the stack craftable. - */ - public AspectStack( final Aspect aspect, final long size, final boolean craftable ) - { - this.setAll( aspect, size, craftable ); - } + /** + * Creates a stack using the specified aspect and amount, and + * sets if it is craftable. + * + * @param aspect + * What aspect this stack will have. + * @param size + * How much this stack will have. + * @param craftable + * Is the stack craftable. + */ + public AspectStack(final Aspect aspect, final long size, final boolean craftable) { + this.setAll(aspect, size, craftable); + } - /** - * Creates a new stack from the passed stack. - * If a new stack is not needed you can also use copyFrom(). - * - * @param source - */ - public AspectStack( final AspectStack stack ) - { - this.setAll( stack ); - } + /** + * Creates a new stack from the passed stack. + * If a new stack is not needed you can also use copyFrom(). + * + * @param source + */ + public AspectStack(final AspectStack stack) { + this.setAll(stack); + } - /** - * Creates an aspect stack from a NBT compound tag. - * - * @param data - * Tag to load from - * @return Created stack, or null. - */ - public static AspectStack loadAspectStackFromNBT( final NBTTagCompound data ) - { - Aspect aspect = null; + /** + * Creates an aspect stack from a NBT compound tag. + * + * @param data + * Tag to load from + * @return Created stack, or null. + */ + public static AspectStack loadAspectStackFromNBT(final NBTTagCompound data) { + Aspect aspect = null; - // Does the tag have the tag? - if( data.hasKey( AspectStack.NBTKEY_ASPECT_TAG ) ) - { - // Attempt to get the aspect - aspect = Aspect.aspects.get( data.getString( AspectStack.NBTKEY_ASPECT_TAG ) ); - } + // Does the tag have the tag? + if (data.hasKey(AspectStack.NBTKEY_ASPECT_TAG)) { + // Attempt to get the aspect + aspect = Aspect.aspects.get(data.getString(AspectStack.NBTKEY_ASPECT_TAG)); + } - // Is there an aspect? - if( aspect == null ) - { - return null; - } + // Is there an aspect? + if (aspect == null) { + return null; + } - // Load the amount - long amount = 0; - if( data.hasKey( AspectStack.NBTKEY_ASPECT_AMOUNT ) ) - { - amount = data.getLong( AspectStack.NBTKEY_ASPECT_AMOUNT ); - } + // Load the amount + long amount = 0; + if (data.hasKey(AspectStack.NBTKEY_ASPECT_AMOUNT)) { + amount = data.getLong(AspectStack.NBTKEY_ASPECT_AMOUNT); + } - // Load crafting - boolean craftable = data.hasKey( AspectStack.NBTKEY_CRAFTABLE ); + // Load crafting + boolean craftable = data.hasKey(AspectStack.NBTKEY_CRAFTABLE); - // Return a newly created stack. - return new AspectStack( aspect, amount, craftable ); - } + // Return a newly created stack. + return new AspectStack(aspect, amount, craftable); + } - /** - * Creates an aspect stack from the stream. - * - * @param stream - * @return - */ - public static AspectStack loadAspectStackFromStream( final ByteBuf stream ) - { - // Create the stack - AspectStack stack = new AspectStack(); + /** + * Creates an aspect stack from the stream. + * + * @param stream + * @return + */ + public static AspectStack loadAspectStackFromStream(final ByteBuf stream) { + // Create the stack + AspectStack stack = new AspectStack(); - // Read in the values - stack.readFromStream( stream ); + // Read in the values + stack.readFromStream(stream); - // Return the stack - return stack; - } + // Return the stack + return stack; + } - @Override - public long adjustStackSize( final long delta ) - { - this.stackSize += delta; - return this.stackSize; - } + @Override + public long adjustStackSize(final long delta) { + this.stackSize += delta; + return this.stackSize; + } - @Override - public IAspectStack copy() - { - return new AspectStack( this ); - } + @Override + public IAspectStack copy() { + return new AspectStack(this); + } - @Override - public Aspect getAspect() - { - return this.aspect; - } + @Override + public Aspect getAspect() { + return this.aspect; + } - @Override - public String getAspectDescription() - { - // Is there an aspect? - if( this.aspect != null ) - { - // Return it's description - return this.aspect.getLocalizedDescription(); - } + @Override + public String getAspectDescription() { + // Is there an aspect? + if (this.aspect != null) { + // Return it's description + return this.aspect.getLocalizedDescription(); + } - // Return empty string - return ""; - } + // Return empty string + return ""; + } - @Override - public String getAspectName() - { - // Ensure there is an aspect - if( this.aspect == null ) - { - return ""; - } + @Override + public String getAspectName() { + // Ensure there is an aspect + if (this.aspect == null) { + return ""; + } - // Return the name of the aspect - return this.aspect.getName(); - } + // Return the name of the aspect + return this.aspect.getName(); + } - @Override - public String getAspectName( final EntityPlayer player ) - { - // Has the player discovered the aspect? - if( !this.hasPlayerDiscovered( player ) ) - { - return StatCollector.translateToLocal( "tc.aspect.unknown" ); - } + @Override + public String getAspectName(final EntityPlayer player) { + // Has the player discovered the aspect? + if (!this.hasPlayerDiscovered(player)) { + return StatCollector.translateToLocal("tc.aspect.unknown"); + } - return this.getAspectName(); - } + return this.getAspectName(); + } - @Override - public String getAspectTag() - { - // Do we have an aspect? - if( this.aspect != null ) - { - return this.aspect.getTag(); - } + @Override + public String getAspectTag() { + // Do we have an aspect? + if (this.aspect != null) { + return this.aspect.getTag(); + } - return ""; - } + return ""; + } - @Override - public String getChatColor() - { - // Do we have an aspect? - if( this.aspect != null ) - { - return ThEGuiHelper.INSTANCE.getAspectChatColor( this.aspect ); - } + @Override + public String getChatColor() { + // Do we have an aspect? + if (this.aspect != null) { + return ThEGuiHelper.INSTANCE.getAspectChatColor(this.aspect); + } - return EnumChatFormatting.WHITE.toString(); - } + return EnumChatFormatting.WHITE.toString(); + } - @Override - public boolean getCraftable() - { - return this.isCraftable; - } + @Override + public boolean getCraftable() { + return this.isCraftable; + } - @Override - public long getStackSize() - { - return this.stackSize; - } + @Override + public long getStackSize() { + return this.stackSize; + } - @Override - public boolean hasAspect() - { - return( this.aspect != null ); - } + @Override + public boolean hasAspect() { + return (this.aspect != null); + } - @Override - public boolean hasPlayerDiscovered( final EntityPlayer player ) - { - // Ensure we have a player & aspect - if( ( player != null ) && ( this.aspect != null ) ) - { - // Ask Thaumcraft if the player has discovered the aspect - return Thaumcraft.proxy.getPlayerKnowledge().hasDiscoveredAspect( player.getCommandSenderName(), this.aspect ); - } + @Override + public boolean hasPlayerDiscovered(final EntityPlayer player) { + // Ensure we have a player & aspect + if ((player != null) && (this.aspect != null)) { + // Ask Thaumcraft if the player has discovered the aspect + return Thaumcraft.proxy + .getPlayerKnowledge() + .hasDiscoveredAspect(player.getCommandSenderName(), this.aspect); + } - return false; - } + return false; + } - @Override - public boolean isEmpty() - { - return( this.stackSize <= 0 ); - } + @Override + public boolean isEmpty() { + return (this.stackSize <= 0); + } - @Override - public void readFromStream( final ByteBuf stream ) - { - // Read the aspect - this.aspect = ThEBasePacket.readAspect( stream ); + @Override + public void readFromStream(final ByteBuf stream) { + // Read the aspect + this.aspect = ThEBasePacket.readAspect(stream); - // Read the amount - this.stackSize = stream.readLong(); + // Read the amount + this.stackSize = stream.readLong(); - // Read craftable - this.isCraftable = stream.readBoolean(); - } + // Read craftable + this.isCraftable = stream.readBoolean(); + } - @Override - public void setAll( final Aspect aspect, final long size, final boolean craftable ) - { - this.aspect = aspect; - this.stackSize = size; - this.isCraftable = craftable; - } + @Override + public void setAll(final Aspect aspect, final long size, final boolean craftable) { + this.aspect = aspect; + this.stackSize = size; + this.isCraftable = craftable; + } - @Override - public void setAll( final IAspectStack stack ) - { - if( stack != null ) - { - this.aspect = stack.getAspect(); - this.stackSize = stack.getStackSize(); - this.isCraftable = stack.getCraftable(); - } - else - { - this.aspect = null; - this.stackSize = 0; - this.isCraftable = false; - } - } + @Override + public void setAll(final IAspectStack stack) { + if (stack != null) { + this.aspect = stack.getAspect(); + this.stackSize = stack.getStackSize(); + this.isCraftable = stack.getCraftable(); + } else { + this.aspect = null; + this.stackSize = 0; + this.isCraftable = false; + } + } - @Override - public void setAspect( final Aspect aspect ) - { - this.aspect = aspect; - } + @Override + public void setAspect(final Aspect aspect) { + this.aspect = aspect; + } - @Override - public void setCraftable( final boolean craftable ) - { - this.isCraftable = craftable; - } + @Override + public void setCraftable(final boolean craftable) { + this.isCraftable = craftable; + } - @Override - public void setStackSize( final long size ) - { - this.stackSize = size; - } + @Override + public void setStackSize(final long size) { + this.stackSize = size; + } - @Override - public NBTTagCompound writeToNBT( final NBTTagCompound data ) - { - // Is there an aspect? - if( this.aspect != null ) - { - // Write the tag - data.setString( AspectStack.NBTKEY_ASPECT_TAG, this.aspect.getTag() ); + @Override + public NBTTagCompound writeToNBT(final NBTTagCompound data) { + // Is there an aspect? + if (this.aspect != null) { + // Write the tag + data.setString(AspectStack.NBTKEY_ASPECT_TAG, this.aspect.getTag()); - // Write the amount - if( this.stackSize > 0 ) - { - data.setLong( AspectStack.NBTKEY_ASPECT_AMOUNT, this.stackSize ); - } + // Write the amount + if (this.stackSize > 0) { + data.setLong(AspectStack.NBTKEY_ASPECT_AMOUNT, this.stackSize); + } - // Craftable? - if( this.isCraftable ) - { - // Write craftable - data.setBoolean( AspectStack.NBTKEY_CRAFTABLE, true ); - } - } + // Craftable? + if (this.isCraftable) { + // Write craftable + data.setBoolean(AspectStack.NBTKEY_CRAFTABLE, true); + } + } - return data; - } + return data; + } - @Override - public void writeToStream( final ByteBuf stream ) - { - // Write the aspect - ThEBasePacket.writeAspect( this.aspect, stream ); + @Override + public void writeToStream(final ByteBuf stream) { + // Write the aspect + ThEBasePacket.writeAspect(this.aspect, stream); - // Write the stored amount - stream.writeLong( this.stackSize ); + // Write the stored amount + stream.writeLong(this.stackSize); - // Write if craftable - stream.writeBoolean( this.isCraftable ); - } + // Write if craftable + stream.writeBoolean(this.isCraftable); + } } diff --git a/src/main/java/thaumicenergistics/common/storage/AspectStackComparator.java b/src/main/java/thaumicenergistics/common/storage/AspectStackComparator.java index 0dba7e21..1fc15475 100644 --- a/src/main/java/thaumicenergistics/common/storage/AspectStackComparator.java +++ b/src/main/java/thaumicenergistics/common/storage/AspectStackComparator.java @@ -9,140 +9,126 @@ import thaumicenergistics.api.storage.IAspectStack; * @author Nividica * */ -public class AspectStackComparator - implements Comparator -{ +public class AspectStackComparator implements Comparator { - /** - * Modes of comparison - * - * @author Nividica - * - */ - public enum AspectStackComparatorMode - { - /** - * Compare based on name - */ - MODE_ALPHABETIC, + /** + * Modes of comparison + * + * @author Nividica + * + */ + public enum AspectStackComparatorMode { + /** + * Compare based on name + */ + MODE_ALPHABETIC, - /** - * Compare based on amount - */ - MODE_AMOUNT; + /** + * Compare based on amount + */ + MODE_AMOUNT; - /** - * Cache of the enum values - */ - public static final AspectStackComparatorMode[] VALUES = AspectStackComparatorMode.values(); + /** + * Cache of the enum values + */ + public static final AspectStackComparatorMode[] VALUES = AspectStackComparatorMode.values(); - /** - * Returns the next mode of comparison. - * - * @return - */ - public AspectStackComparatorMode nextMode() - { - return( VALUES[( this.ordinal() + 1 ) % VALUES.length] ); - } + /** + * Returns the next mode of comparison. + * + * @return + */ + public AspectStackComparatorMode nextMode() { + return (VALUES[(this.ordinal() + 1) % VALUES.length]); + } - /** - * Returns the previous mode of comparison. - * - * @return - */ - public AspectStackComparatorMode previousMode() - { - return( VALUES[( this.ordinal() + ( VALUES.length - 1 ) ) % VALUES.length] ); - } - } + /** + * Returns the previous mode of comparison. + * + * @return + */ + public AspectStackComparatorMode previousMode() { + return (VALUES[(this.ordinal() + (VALUES.length - 1)) % VALUES.length]); + } + } - /** - * The set mode of comparison - */ - private AspectStackComparatorMode mode; + /** + * The set mode of comparison + */ + private AspectStackComparatorMode mode; - /** - * Creates the comparator with sorting mode alphabetic. - */ - public AspectStackComparator() - { - this.setMode( AspectStackComparatorMode.MODE_ALPHABETIC ); - } + /** + * Creates the comparator with sorting mode alphabetic. + */ + public AspectStackComparator() { + this.setMode(AspectStackComparatorMode.MODE_ALPHABETIC); + } - /** - * Creates the comparator with specified sorting mode. - * If the mode is unrecognized, the list will not be sorted. - * - * @param mode - * Mode to sort by. - */ - public AspectStackComparator( final AspectStackComparatorMode mode ) - { - this.setMode( mode ); - } + /** + * Creates the comparator with specified sorting mode. + * If the mode is unrecognized, the list will not be sorted. + * + * @param mode + * Mode to sort by. + */ + public AspectStackComparator(final AspectStackComparatorMode mode) { + this.setMode(mode); + } - /** - * Compares the two stacks by amount. - * - * @param left - * @param right - * @return - */ - private int compareByAmount( final IAspectStack left, final IAspectStack right ) - { - return (int)( right.getStackSize() - left.getStackSize() ); - } + /** + * Compares the two stacks by amount. + * + * @param left + * @param right + * @return + */ + private int compareByAmount(final IAspectStack left, final IAspectStack right) { + return (int) (right.getStackSize() - left.getStackSize()); + } - /** - * Compares the two stacks by name - * - * @param left - * @param right - * @return - */ - private int compareByName( final IAspectStack left, final IAspectStack right ) - { - return left.getAspectName().compareTo( right.getAspectName() ); - } + /** + * Compares the two stacks by name + * + * @param left + * @param right + * @return + */ + private int compareByName(final IAspectStack left, final IAspectStack right) { + return left.getAspectName().compareTo(right.getAspectName()); + } - /** - * Compares two aspect stacks by the selected mode. - */ - @Override - public int compare( final IAspectStack left, final IAspectStack right ) - { - switch ( this.mode ) - { - case MODE_ALPHABETIC: - // Compare tags - return this.compareByName( left, right ); + /** + * Compares two aspect stacks by the selected mode. + */ + @Override + public int compare(final IAspectStack left, final IAspectStack right) { + switch (this.mode) { + case MODE_ALPHABETIC: + // Compare tags + return this.compareByName(left, right); - case MODE_AMOUNT: - // Compare amounts - int comparedAmounts = this.compareByAmount( left, right ); + case MODE_AMOUNT: + // Compare amounts + int comparedAmounts = this.compareByAmount(left, right); - // Are the amounts equal? - if( comparedAmounts == 0 ) - { - // Compare tags - comparedAmounts = this.compareByName( left, right ); - } + // Are the amounts equal? + if (comparedAmounts == 0) { + // Compare tags + comparedAmounts = this.compareByName(left, right); + } - return comparedAmounts; - } + return comparedAmounts; + } - return 0; - } - - /** - * Sets the mode of comparison. - * - * @param mode - */ - public void setMode( final AspectStackComparatorMode mode ) - { - this.mode = mode; - } + return 0; + } + /** + * Sets the mode of comparison. + * + * @param mode + */ + public void setMode(final AspectStackComparatorMode mode) { + this.mode = mode; + } } diff --git a/src/main/java/thaumicenergistics/common/storage/EnumEssentiaStorageTypes.java b/src/main/java/thaumicenergistics/common/storage/EnumEssentiaStorageTypes.java index 4ac5b8fb..b27f3c54 100644 --- a/src/main/java/thaumicenergistics/common/storage/EnumEssentiaStorageTypes.java +++ b/src/main/java/thaumicenergistics/common/storage/EnumEssentiaStorageTypes.java @@ -11,112 +11,144 @@ import thaumicenergistics.common.registries.ThEStrings; * @author Nividica * */ -public enum EnumEssentiaStorageTypes -{ - Type_1K (0, 1024, 12, "1k", EnumRarity.common, 0.5, ThEStrings.Item_EssentiaCell_1k, ThEStrings.Item_StorageComponent_1k), - Type_4K (1, 4096, 12, "4k", EnumRarity.uncommon, 1.0, ThEStrings.Item_EssentiaCell_4k, ThEStrings.Item_StorageComponent_4k), - Type_16K (2, 16348, 12, "16k", EnumRarity.uncommon, 1.5, ThEStrings.Item_EssentiaCell_16k, ThEStrings.Item_StorageComponent_16k), - Type_64K (3, 65536, 12, "64k", EnumRarity.rare, 2.0, ThEStrings.Item_EssentiaCell_64k, ThEStrings.Item_StorageComponent_64k), - Type_Creative (4, 0, 63, "creative", EnumRarity.epic, 0.0, ThEStrings.Item_EssentiaCell_Creative, null); +public enum EnumEssentiaStorageTypes { + Type_1K( + 0, + 1024, + 12, + "1k", + EnumRarity.common, + 0.5, + ThEStrings.Item_EssentiaCell_1k, + ThEStrings.Item_StorageComponent_1k), + Type_4K( + 1, + 4096, + 12, + "4k", + EnumRarity.uncommon, + 1.0, + ThEStrings.Item_EssentiaCell_4k, + ThEStrings.Item_StorageComponent_4k), + Type_16K( + 2, + 16348, + 12, + "16k", + EnumRarity.uncommon, + 1.5, + ThEStrings.Item_EssentiaCell_16k, + ThEStrings.Item_StorageComponent_16k), + Type_64K( + 3, + 65536, + 12, + "64k", + EnumRarity.rare, + 2.0, + ThEStrings.Item_EssentiaCell_64k, + ThEStrings.Item_StorageComponent_64k), + Type_Creative(4, 0, 63, "creative", EnumRarity.epic, 0.0, ThEStrings.Item_EssentiaCell_Creative, null); - /** - * Array of values whose index matches the types index. - */ - public static final EnumEssentiaStorageTypes fromIndex[]; + /** + * Array of values whose index matches the types index. + */ + public static final EnumEssentiaStorageTypes fromIndex[]; - /** - * This is to ensure that the index can be independent of the ordinal. - * Since the data is saved based on index, not ordinal. - */ - static - { - // Setup the array - fromIndex = new EnumEssentiaStorageTypes[5]; - fromIndex[Type_1K.index] = Type_1K; - fromIndex[Type_4K.index] = Type_4K; - fromIndex[Type_16K.index] = Type_16K; - fromIndex[Type_64K.index] = Type_64K; - fromIndex[Type_Creative.index] = Type_Creative; - } + /** + * This is to ensure that the index can be independent of the ordinal. + * Since the data is saved based on index, not ordinal. + */ + static { + // Setup the array + fromIndex = new EnumEssentiaStorageTypes[5]; + fromIndex[Type_1K.index] = Type_1K; + fromIndex[Type_4K.index] = Type_4K; + fromIndex[Type_16K.index] = Type_16K; + fromIndex[Type_64K.index] = Type_64K; + fromIndex[Type_Creative.index] = Type_Creative; + } - /** - * Index of the type. - */ - public final int index; + /** + * Index of the type. + */ + public final int index; - /** - * Displayable suffix of the type. - */ - public final String suffix; + /** + * Displayable suffix of the type. + */ + public final String suffix; - /** - * Capacity of the type, in bytes. - */ - public final int capacity; + /** + * Capacity of the type, in bytes. + */ + public final int capacity; - /** - * Rarity class of the type. - */ - public final EnumRarity rarity; + /** + * Rarity class of the type. + */ + public final EnumRarity rarity; - /** - * Maximum number of stored types. - */ - public final int maxStoredTypes; + /** + * Maximum number of stored types. + */ + public final int maxStoredTypes; - /** - * Amount of power drained while the cell is active. - */ - public final double idleAEPowerDrain; + /** + * Amount of power drained while the cell is active. + */ + public final double idleAEPowerDrain; - /** - * Name of the cell for this type. - */ - public final ThEStrings cellName; + /** + * Name of the cell for this type. + */ + public final ThEStrings cellName; - /** - * Name of the component for this type. - * The creative cell does not have a component. - */ - public final ThEStrings componentName; + /** + * Name of the component for this type. + * The creative cell does not have a component. + */ + public final ThEStrings componentName; - private EnumEssentiaStorageTypes( final int index, final int capacity, final int maxStoredTypes, - final String suffix, final EnumRarity rarity, final double aeDrain, - final ThEStrings cellName, final ThEStrings componentName ) - { - this.index = index; - this.capacity = capacity; - this.suffix = suffix; - this.rarity = rarity; - this.maxStoredTypes = maxStoredTypes; - this.idleAEPowerDrain = aeDrain; - this.cellName = cellName; - this.componentName = componentName; - } + private EnumEssentiaStorageTypes( + final int index, + final int capacity, + final int maxStoredTypes, + final String suffix, + final EnumRarity rarity, + final double aeDrain, + final ThEStrings cellName, + final ThEStrings componentName) { + this.index = index; + this.capacity = capacity; + this.suffix = suffix; + this.rarity = rarity; + this.maxStoredTypes = maxStoredTypes; + this.idleAEPowerDrain = aeDrain; + this.cellName = cellName; + this.componentName = componentName; + } - /** - * Returns an empty cell for this type. - * - * @return - */ - public ItemStack getCell() - { - return ItemEnum.ESSENTIA_CELL.getDMGStack( this.index ); - } + /** + * Returns an empty cell for this type. + * + * @return + */ + public ItemStack getCell() { + return ItemEnum.ESSENTIA_CELL.getDMGStack(this.index); + } - /** - * Returns a storage component for this type. - * The creative type has no component, null is returned. - * - * @param stackSize - * @return - */ - public ItemStack getComponent( final int stackSize ) - { - if( this == Type_Creative ) - { - return null; - } - return ItemEnum.STORAGE_COMPONENT.getDMGStack( this.index, stackSize ); - } + /** + * Returns a storage component for this type. + * The creative type has no component, null is returned. + * + * @param stackSize + * @return + */ + public ItemStack getComponent(final int stackSize) { + if (this == Type_Creative) { + return null; + } + return ItemEnum.STORAGE_COMPONENT.getDMGStack(this.index, stackSize); + } } diff --git a/src/main/java/thaumicenergistics/common/storage/EssentiaRepo.java b/src/main/java/thaumicenergistics/common/storage/EssentiaRepo.java index ab203231..e70948a8 100644 --- a/src/main/java/thaumicenergistics/common/storage/EssentiaRepo.java +++ b/src/main/java/thaumicenergistics/common/storage/EssentiaRepo.java @@ -14,205 +14,174 @@ import thaumicenergistics.api.storage.IEssentiaRepo; * @author Nividica * */ -public class EssentiaRepo - implements IEssentiaRepo -{ - /** - * The actual cache of aspects. - */ - private final Map cache; +public class EssentiaRepo implements IEssentiaRepo { + /** + * The actual cache of aspects. + */ + private final Map cache; - /** - * Creates the repository. - */ - public EssentiaRepo() - { - // Create the cache - this.cache = new ConcurrentHashMap(); - } + /** + * Creates the repository. + */ + public EssentiaRepo() { + // Create the cache + this.cache = new ConcurrentHashMap(); + } - @Override - public Set aspectSet() - { - return this.cache.keySet(); - } + @Override + public Set aspectSet() { + return this.cache.keySet(); + } - @Override - public void clear() - { - this.cache.clear(); - } + @Override + public void clear() { + this.cache.clear(); + } - @Override - public boolean containsAspect( final Aspect aspect ) - { - return this.cache.containsKey( aspect ); - } + @Override + public boolean containsAspect(final Aspect aspect) { + return this.cache.containsKey(aspect); + } - @Override - public void copyFrom( final Collection stacks ) - { - // Clear - this.clear(); + @Override + public void copyFrom(final Collection stacks) { + // Clear + this.clear(); - // Null check - if( stacks == null ) - { - return; - } + // Null check + if (stacks == null) { + return; + } - // Add each - for( IAspectStack stack : stacks ) - { - this.cache.put( stack.getAspect(), stack.copy() ); - } - } + // Add each + for (IAspectStack stack : stacks) { + this.cache.put(stack.getAspect(), stack.copy()); + } + } - @Override - public IAspectStack get( final Aspect aspect ) - { - return this.cache.getOrDefault( aspect, null ); - } + @Override + public IAspectStack get(final Aspect aspect) { + return this.cache.getOrDefault(aspect, null); + } - @Override - public Collection getAll() - { - return this.cache.values(); - } + @Override + public Collection getAll() { + return this.cache.values(); + } - @Override - public IAspectStack getOrDefault( final Aspect aspect, final IAspectStack defaultValue ) - { - return this.cache.getOrDefault( aspect, defaultValue ); - } + @Override + public IAspectStack getOrDefault(final Aspect aspect, final IAspectStack defaultValue) { + return this.cache.getOrDefault(aspect, defaultValue); + } - @Override - public boolean isEmpty() - { - return this.cache.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.cache.isEmpty(); + } - @Override - public IAspectStack postChange( final Aspect aspect, final long change, final Boolean isCraftableNullable ) - { - // Is the aspect null? - if( aspect == null ) - { - // No changes - return null; - } + @Override + public IAspectStack postChange(final Aspect aspect, final long change, final Boolean isCraftableNullable) { + // Is the aspect null? + if (aspect == null) { + // No changes + return null; + } - boolean isCraftable; + boolean isCraftable; - // Get the current stack - IAspectStack current = this.cache.get( aspect ); + // Get the current stack + IAspectStack current = this.cache.get(aspect); - // Is their nothing currently stored? - if( current == null ) - { - // Create a new stack - IAspectStack newStack = null; + // Is their nothing currently stored? + if (current == null) { + // Create a new stack + IAspectStack newStack = null; - // Set craftability - isCraftable = ( isCraftableNullable == null ? false : isCraftableNullable ); + // Set craftability + isCraftable = (isCraftableNullable == null ? false : isCraftableNullable); - // Is the change positive? - if( change > 0 ) - { - // Create a new stack - newStack = new AspectStack( aspect, change, isCraftable ); - } - // Is it craftable? - else if( isCraftable ) - { - // Create a new crafting stack - newStack = new AspectStack( aspect, 0, isCraftable ); - } + // Is the change positive? + if (change > 0) { + // Create a new stack + newStack = new AspectStack(aspect, change, isCraftable); + } + // Is it craftable? + else if (isCraftable) { + // Create a new crafting stack + newStack = new AspectStack(aspect, 0, isCraftable); + } - // Is there a new stack? - if( newStack != null ) - { - // Add the stack - this.cache.put( newStack.getAspect(), newStack ); - } + // Is there a new stack? + if (newStack != null) { + // Add the stack + this.cache.put(newStack.getAspect(), newStack); + } - // Done - return null; - } + // Done + return null; + } - // There is something currently stored - IAspectStack previous = current.copy(); + // There is something currently stored + IAspectStack previous = current.copy(); - // Set craftability - isCraftable = ( isCraftableNullable == null ? previous.getCraftable() : isCraftableNullable ); + // Set craftability + isCraftable = (isCraftableNullable == null ? previous.getCraftable() : isCraftableNullable); - // Calculate the new amount - long previousAmount = previous.getStackSize(); - long newAmount = Math.max( 0L, previousAmount + change ); + // Calculate the new amount + long previousAmount = previous.getStackSize(); + long newAmount = Math.max(0L, previousAmount + change); - // Stack drained and is not craftable? - if( ( newAmount == 0 ) && !isCraftable ) - { - // Remove it - this.cache.remove( aspect ); - } - else - { - // Update the amount & craftability - current.setStackSize( newAmount ); - current.setCraftable( isCraftable ); - } + // Stack drained and is not craftable? + if ((newAmount == 0) && !isCraftable) { + // Remove it + this.cache.remove(aspect); + } else { + // Update the amount & craftability + current.setStackSize(newAmount); + current.setCraftable(isCraftable); + } - // Return the previous stack - return previous; - } + // Return the previous stack + return previous; + } - @Override - public IAspectStack postChange( final IAspectStack change ) - { - // Null check - if( change == null ) - { - return null; - } + @Override + public IAspectStack postChange(final IAspectStack change) { + // Null check + if (change == null) { + return null; + } - return this.postChange( change.getAspect(), change.getStackSize(), change.getCraftable() ); - } + return this.postChange(change.getAspect(), change.getStackSize(), change.getCraftable()); + } - @Override - public IAspectStack remove( final Aspect aspect ) - { - return this.cache.remove( aspect ); - } + @Override + public IAspectStack remove(final Aspect aspect) { + return this.cache.remove(aspect); + } - @Override - public IAspectStack setAspect( final Aspect aspect, final long amount, final boolean isCraftable ) - { - if( aspect == null ) - { - return null; - } + @Override + public IAspectStack setAspect(final Aspect aspect, final long amount, final boolean isCraftable) { + if (aspect == null) { + return null; + } - // Set the stack, and return the old one. - return this.cache.put( aspect, new AspectStack( aspect, amount, isCraftable ) ); + // Set the stack, and return the old one. + return this.cache.put(aspect, new AspectStack(aspect, amount, isCraftable)); + } - } + @Override + public IAspectStack setAspect(final IAspectStack stack) { + // Null check + if (stack == null) { + return null; + } - @Override - public IAspectStack setAspect( final IAspectStack stack ) - { - // Null check - if( stack == null ) - { - return null; - } + return this.setAspect(stack.getAspect(), stack.getStackSize(), stack.getCraftable()); + } - return this.setAspect( stack.getAspect(), stack.getStackSize(), stack.getCraftable() ); - } - - @Override - public int size() - { - return this.cache.size(); - } + @Override + public int size() { + return this.cache.size(); + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileArcaneAssembler.java b/src/main/java/thaumicenergistics/common/tiles/TileArcaneAssembler.java index 5be8b25e..62d7716d 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileArcaneAssembler.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileArcaneAssembler.java @@ -1,10 +1,5 @@ package thaumicenergistics.common.tiles; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -40,6 +35,11 @@ import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; @@ -70,1231 +70,1090 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class TileArcaneAssembler - extends AENetworkInvTile - implements ICraftingProvider, IWailaSource -{ - private class AAInv - extends TheInternalInventory - { - - public AAInv() - { - super( "ArcaneAssemblerInventory", TileArcaneAssembler.SLOT_COUNT, 64 ); - } - - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack itemStack ) - { - if( slotIndex == TileArcaneAssembler.KCORE_SLOT_INDEX ) - { - return ( itemStack == null ) || ( itemStack.getItem() instanceof ItemKnowledgeCore ); - } - - return true; - } - - @Override - public void markDirty() - { - TileArcaneAssembler.this.markDirty(); - } - - @Override - public void setInventorySlotContents( final int slotIndex, final ItemStack itemStack ) - { - // Call super - super.setInventorySlotContents( slotIndex, itemStack ); - - // Core changed? - if( slotIndex == TileArcaneAssembler.KCORE_SLOT_INDEX ) - { - TileArcaneAssembler.this.flag_CoreChanged = true; - } - - // Armor changed? - if( slotIndex >= DISCOUNT_ARMOR_INDEX ) - { - TileArcaneAssembler.this.flag_RecalcVis = true; - } - } - - } - - /** - * NBT Keys - */ - private static final String NBTKEY_VIS_INTERFACE = "vis_interface", - NBTKEY_UPGRADES = "upgradeCount", NBTKEY_UPGRADEINV = "upgrades", NBTKEY_CRAFTING = "isCrafting", - NBTKEY_CRAFTING_PATTERN = "pattern"; - - /** - * NBT Key for stored vis. - */ - public static final String NBTKEY_STORED_VIS = "stored_vis"; - - /** - * Used to simulate floating point amounts of vis. - */ - private static final int CVIS_MULTIPLER = 10; - - /** - * The number of ticks required to craft an item without any upgrades. - */ - private static final int BASE_TICKS_PER_CRAFT = 20; - - /** - * Primal aspects. - */ - public static final Aspect[] PRIMALS = new Aspect[] { Aspect.AIR, Aspect.WATER, Aspect.FIRE, Aspect.ORDER, Aspect.ENTROPY, Aspect.EARTH }; - - /** - * Total number of slots. 1 KCore + 21 Patterns + 1 Target + 4 Discount - * Armor - */ - public static final int SLOT_COUNT = 27; - - /** - * Index of the slots. - */ - public static final int KCORE_SLOT_INDEX = 0, PATTERN_SLOT_INDEX = 1, TARGET_SLOT_INDEX = 22, DISCOUNT_ARMOR_INDEX = 23; - - /** - * Maximum amount of stored centi-vis. - */ - public static final int MAX_STORED_CVIS = 150 * TileArcaneAssembler.CVIS_MULTIPLER; - - /** - * Power usage. - */ - public static double IDLE_POWER = 0.0D, ACTIVE_POWER = 1.5D, WARP_POWER_PERCENT = 0.15; - - /** - * Holds the patterns and the kcore. - * Saved and loaded by AEInvTile due to getInternalInventory() call. - */ - private final AAInv internalInventory; - - /** - * Holds the upgrades - */ - private final UpgradeInventory upgradeInventory; - - /** - * Is the assembler busy crafting? - */ - private boolean isCrafting = false; - - /** - * The pattern currently being crafted. - */ - private ArcaneCraftingPattern currentPattern = null; - - /** - * Handles interaction with the knowledge core. - */ - private final HandlerKnowledgeCore kCoreHandler; - - /** - * If true the network should be informed of changes to available patterns. - */ - private boolean stalePatterns = false; - - /** - * Data pertaining to the linked digi-vis source - */ - private final DigiVisSourceData visSourceInfo = new DigiVisSourceData(); - - /** - * Vis stored in the assembler. - */ - private final AspectList storedVis = new AspectList(); - - /** - * Number of elapsed ticks. - */ - private int visTickCounter = 0, craftTickCounter = 0, delayTickCounter = 0; - - /** - * Source of all actions. - */ - private final MachineSource mySource; - - /** - * True when the assembler is online. - */ - private boolean isActive = false; - - /** - * The number of installed upgrades. - */ - private int upgradeCount = 0; - - /** - * How much discount each aspect is receiving. - */ - private final Hashtable visDiscount = new Hashtable<>(); - - /** - * How much additional power is required due to warp. - */ - private float warpPowerMultiplier = 1.0F; - - /** - * When true will send network update periodically. - */ - private boolean delayedUpdate = false; - - /** - * True when the core has changed. - */ - boolean flag_CoreChanged = false; - - /** - * True if the vis discount needs to be re-calculated. - */ - boolean flag_RecalcVis = false; - - /** - * Creates the assembler and it's inventory. - */ - public TileArcaneAssembler() - { - // Create the internal inventory - this.internalInventory = new AAInv(); - - // Create the upgrade inventory - this.upgradeInventory = new BlockUpgradeInventory( ThEApi.instance().blocks().ArcaneAssembler.getBlock(), this, - BlockArcaneAssembler.MAX_SPEED_UPGRADES ); - - // Set the machine source - this.mySource = new MachineSource( this ); - - // Prep the discount table - for( Aspect primal : TileArcaneAssembler.PRIMALS ) - { - this.visDiscount.put( primal, VisCraftingHelper.INSTANCE.getScepterVisModifier( primal ) ); - } - - // Create the handler - this.kCoreHandler = new HandlerKnowledgeCore(); - - // Set idle power usage - this.getProxy().setIdlePowerUsage( TileArcaneAssembler.IDLE_POWER ); - - // Require a channel - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } - - /** - * Get's the NBT tag for the just-crafted assembler. - * - * @return - */ - public static NBTTagCompound getCraftTag() - { - NBTTagCompound data = new NBTTagCompound(); - - // Create the vis list - AspectList vis = new AspectList(); - - // Add each primal - for( Aspect primal : TileArcaneAssembler.PRIMALS ) - { - vis.add( primal, TileArcaneAssembler.MAX_STORED_CVIS ); - } - - // Write into the tag - vis.writeToNBT( data, TileArcaneAssembler.NBTKEY_STORED_VIS ); - - return data; - } - - /** - * Calculates how much vis discount applies to each aspect - */ - private void calculateVisDiscounts() - { - this.flag_RecalcVis = false; - float discount; - - for( Aspect primal : TileArcaneAssembler.PRIMALS ) - { - // Get the discount from the scepter - discount = VisCraftingHelper.INSTANCE.getScepterVisModifier( primal ); - - // Factor in the discount armor - discount -= VisCraftingHelper.INSTANCE.calculateArmorDiscount( this.internalInventory, DISCOUNT_ARMOR_INDEX, 4, - primal ); - - this.visDiscount.put( primal, discount ); - } - - // Reset warp power multiplier - this.warpPowerMultiplier = 1.0F; - - // Calculate warp power multiplier - this.warpPowerMultiplier += VisCraftingHelper.INSTANCE.calculateArmorWarp( this.internalInventory, DISCOUNT_ARMOR_INDEX, 4 ) * - WARP_POWER_PERCENT; - } - - private void craftingTick() - { - // Null check - if( this.currentPattern == null ) - { - this.isCrafting = false; - } - - // Is there enough vis to complete the crafting? - if( !this.hasEnoughVisForCraft() ) - { - return; - } - - // Has the assembler finished crafting? - if( this.craftTickCounter >= this.ticksPerCraft() ) - { - try - { - // Get the storage grid - IStorageGrid storageGrid = this.getProxy().getStorage(); - - // Simulate placing the items - boolean rejected = false; - for( IAEItemStack output : this.currentPattern.getAllResults() ) - { - IAEItemStack rejectedResult = storageGrid.getItemInventory().injectItems( output, Actionable.SIMULATE, - this.mySource ); - if( ( rejectedResult != null ) && ( rejectedResult.getStackSize() > 0 ) ) - { - rejected = true; - break; - } - } - - // Were all items accepted? - if( !rejected ) - { - // Inject into the network - for( IAEItemStack output : this.currentPattern.getAllResults() ) - { - storageGrid.getItemInventory().injectItems( output, Actionable.MODULATE, this.mySource ); - } - - // Mark the assembler as no longer crafting - this.isCrafting = false; - this.internalInventory.setInventorySlotContents( TARGET_SLOT_INDEX, null ); - this.currentPattern = null; - - // Mark for network update - this.markForDelayedUpdate(); - } - } - catch( GridAccessException ignored) - { - } - } - else - { - try - { - // Calculate power required - double powerRequired = ( TileArcaneAssembler.ACTIVE_POWER + ( ( TileArcaneAssembler.ACTIVE_POWER * this.upgradeCount ) / 2.0D ) ) * - this.warpPowerMultiplier; - - // Attempt to take power - IEnergyGrid eGrid = this.getProxy().getEnergy(); - double powerExtracted = eGrid.extractAEPower( powerRequired, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( ( powerExtracted - powerRequired ) <= 0.0D ) - { - // Increment the counter - this.craftTickCounter++ ; - - if( this.craftTickCounter >= this.ticksPerCraft() ) - { - // Take the required vis - Aspect[] requiredAspects = this.currentPattern.getCachedAspects(); - for( Aspect aspect : requiredAspects ) - { - // Calculate the required amount - int requiredAmount = this.getRequiredAmountForAspect( aspect ); - - // Take the vis - this.storedVis.reduce( aspect, requiredAmount ); - } - - this.markForDelayedUpdate(); - } - } - } - catch( GridAccessException ignored) - { - } - } - - } - - /** - * Helper function to calculate how much vis is required for the specified - * aspect for the current recipe. - * - * @param aspect - * @return - */ - private int getRequiredAmountForAspect( final Aspect aspect ) - { - return (int)Math.ceil( - this.visDiscount.get( aspect ) * ( this.currentPattern.getAspectCost( aspect ) * TileArcaneAssembler.CVIS_MULTIPLER ) ); - } - - private boolean hasEnoughVisForCraft() - { - // Null check - if( this.currentPattern == null ) - { - return false; - } - - // Get the required aspects - Aspect[] requiredAspects = this.currentPattern.getCachedAspects(); - - // Check each aspect required by the pattern - for( Aspect aspect : requiredAspects ) - { - // Calculate the required amount - int requiredAmount = this.getRequiredAmountForAspect( aspect ); - - // Is there not enough? - if( this.storedVis.getAmount( aspect ) < requiredAmount ) - { - return false; - } - } - - // Has enough of all aspects - return true; - } - - /** - * Returns true if the tile is connected to the AE network and active. - * - * @return - */ - private boolean isActive() - { - // Are we server side? - if( EffectiveSide.isServerSide() ) - { - // Do we have a proxy and grid node? - if( ( this.getProxy() != null ) && ( this.getProxy().getNode() != null ) ) - { - // Get the grid node activity - this.isActive = this.getProxy().getNode().isActive(); - } - } - - return this.isActive; - } - - /** - * Marks the tile for a delayed update. - */ - private void markForDelayedUpdate() - { - this.delayedUpdate = true; - } - - /** - * Refills the internal vis buffer. - */ - private void replenishVis() - { - IDigiVisSource visSource = null; - - // Ensure the grid is ready - if( !this.getProxy().isReady() ) - { - return; - } - - try - { - // Get the source - visSource = this.visSourceInfo.tryGetSource( this.getProxy().getGrid() ); - } - catch( GridAccessException ignored) - { - } - - // Ensure the source is reachable. - if( visSource == null ) - { - return; - } - - // Calculate how much vis is needed for each primal - for( Aspect primal : TileArcaneAssembler.PRIMALS ) - { - int numNeeded = TileArcaneAssembler.MAX_STORED_CVIS - this.storedVis.getAmount( primal ); - - // Is any needed? - if( numNeeded > 0 ) - { - // Request the vis - int amountDrained = visSource.consumeVis( primal, numNeeded ); - - // Was any drained? - if( amountDrained > 0 ) - { - // Add to the stored amount - this.storedVis.add( primal, amountDrained ); - - // Mark for network sync - this.markForDelayedUpdate(); - } - } - } - - } - - /** - * The number of ticks required to craft an item. - */ - private int ticksPerCraft() - { - return TileArcaneAssembler.BASE_TICKS_PER_CRAFT - ( 4 * this.upgradeCount ); - } - - /** - * Updates the handler to the current core. - */ - private void updateCoreHandler() - { - this.flag_CoreChanged = false; - // Is there a kcore? - ItemStack kCore = this.internalInventory.getStackInSlot( KCORE_SLOT_INDEX ); - if( kCore != null ) - { - // Is it a new core? - if( !TileArcaneAssembler.this.kCoreHandler.isHandlingCore( kCore ) ) - { - // Open the core - TileArcaneAssembler.this.kCoreHandler.open( kCore ); - - // Update the pattern slots - TileArcaneAssembler.this.updatePatternSlots(); - } - } - else - { - // Was there a core? - if( TileArcaneAssembler.this.kCoreHandler.hasCore() ) - { - // No more core - TileArcaneAssembler.this.kCoreHandler.close(); - - // Update the pattern slots - TileArcaneAssembler.this.updatePatternSlots(); - } - } - } - - /** - * Updates the pattern slots to match the kcore patterns. - */ - private void updatePatternSlots() - { - Iterator pIterator = null; - - // Get the list - if( this.kCoreHandler != null ) - { - ArrayList patternOutputs = this.kCoreHandler.getStoredOutputs(); - pIterator = patternOutputs.iterator(); - } - - // Set pattern slots - for( int index = TileArcaneAssembler.PATTERN_SLOT_INDEX; index < ( TileArcaneAssembler.PATTERN_SLOT_INDEX + - HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS ); index++ ) - { - if( ( pIterator != null ) && ( pIterator.hasNext() ) ) - { - // Set to pattern result - this.internalInventory.setInventorySlotContents( index, pIterator.next() ); - } - else - { - // Clear slot - this.internalInventory.setInventorySlotContents( index, null ); - } - } - - this.stalePatterns = true; - } - - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - // Return the itemstack the visually represents this tile - return ThEApi.instance().blocks().ArcaneAssembler.getStack(); - - } - - @Override - public void addWailaInformation( final List tooltip ) - { - // Is it active? - if( this.isActive() ) - { - // Get activity string from AppEng2 - tooltip.add( WailaText.DeviceOnline.getLocal() ); - } - else - { - // Get activity string from AppEng2 - tooltip.add( WailaText.DeviceOffline.getLocal() ); - } - - // Is the assembler crafting anything? - if( ( this.isCrafting ) && this.internalInventory.getHasStack( TARGET_SLOT_INDEX ) ) - { - // Add what is being crafted and the percent it is complete - tooltip.add( String.format( "%s, %.0f%%", this.internalInventory.getStackInSlot( TARGET_SLOT_INDEX ).getDisplayName(), - ( ( this.getPercentComplete() * 100.0F ) ) ) ); - } - - // Build vis amounts - StringBuilder strAspects = new StringBuilder(); - for( int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++ ) - { - // Get the primal - Aspect primal = TileArcaneAssembler.PRIMALS[i]; - - // Change color - strAspects.append( ThEGuiHelper.INSTANCE.getAspectChatColor( primal ) ); - - // Add amount - strAspects.append( ( this.storedVis.getAmount( primal ) / (float)TileArcaneAssembler.CVIS_MULTIPLER ) ); - - // Are there more primals after this one? - if( ( i + 1 ) < TileArcaneAssembler.PRIMALS.length ) - { - // Add a gray pipe - strAspects.append( EnumChatFormatting.WHITE.toString() ); - strAspects.append( " | " ); - } - } - - // Add vis amounts - tooltip.add( strAspects.toString() ); - } - - @MENetworkEventSubscribe - public final void channelEvent( final MENetworkChannelsChanged event ) - { - // Mark for update - this.markForUpdate(); - } - - /** - * Inventory is not world accessible. - */ - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection whichSide ) - { - return new int[0]; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - /** - * Called when the block is broken to get any additional items. - * - * @return - */ - @Override - public void getDrops( final World world, final int x, final int y, final int z, final List drops ) - { - // Add the kCore - ItemStack kCore = this.internalInventory.getStackInSlot( TileArcaneAssembler.KCORE_SLOT_INDEX ); - if( kCore != null ) - { - drops.add( kCore ); - } - - // Add upgrades - for( int i = 0; i < this.upgradeInventory.getSizeInventory(); i++ ) - { - ItemStack upgrade = this.upgradeInventory.getStackInSlot( i ); - - if( upgrade != null ) - { - drops.add( upgrade ); - } - } - - // Add armor - for( int i = 0; i < 4; i++ ) - { - ItemStack armor = this.internalInventory.getStackInSlot( TileArcaneAssembler.DISCOUNT_ARMOR_INDEX + i ); - - if( armor != null ) - { - drops.add( armor ); - } - } - } - - @Override - public IInventory getInternalInventory() - { - return this.internalInventory; - } - - /** - * Get's the current knowledge core handler. - * - * @return - */ - public HandlerKnowledgeCore getKCoreHandler() - { - return this.kCoreHandler; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - /** - * Returns the percent the current crafting job is complete. - * - * @return - */ - public float getPercentComplete() - { - float percent = 0.0F; - - if( this.isCrafting ) - { - percent = Math.min( ( (float)this.craftTickCounter / this.ticksPerCraft() ), 1.0F ); - } - - return percent; - } - - /** - * Get's the stored vis amounts. - * - * @return - */ - public AspectList getStoredVis() - { - return this.storedVis; - } - - public UpgradeInventory getUpgradeInventory() - { - return this.upgradeInventory; - } - - /** - * Returns the discount for the specified aspect. - * - * @param aspect - * @return - */ - public float getVisDiscountForAspect( final Aspect aspect ) - { - return this.visDiscount.get( aspect ); - } - - @Override - public boolean isBusy() - { - return this.isCrafting; - } - - @Override - public boolean isItemValidForSlot( final int slotId, final ItemStack itemStack ) - { - // Is the slot being assigned the knowledge core slot? - if( slotId == KCORE_SLOT_INDEX ) - { - // Ensure the item is a knowledge core. - return( ( itemStack == null ) || ( itemStack.getItem() instanceof ItemKnowledgeCore ) ); - } - - // Assume it is not valid - return false; - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer player ) - { - if( EffectiveSide.isClientSide() ) - { - // Ignored on the client side. - return false; - } - - // Check basic usability - if( !this.internalInventory.isUseableByPlayer( player, this ) ) - { - return false; - } - - // Check the security grid - try - { - // Get the security grid - ISecurityGrid sGrid = this.getProxy().getSecurity(); - - // Return true if the player has inject and extract permissions - return( ( sGrid.hasPermission( player, SecurityPermissions.INJECT ) ) && ( sGrid.hasPermission( player, SecurityPermissions.EXTRACT ) ) ); - } - catch( GridAccessException e ) - { - return false; - } - } - - /** - * Called when the tile entity is about to be destroyed by a block break. - */ - public void onBreak() - { - this.isCrafting = false; - } - - /** - * Called when the upgrade inventory changes - */ - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - // Reset the upgrade count - this.upgradeCount = 0; - - IMaterials aeMaterals = AEApi.instance().definitions().materials(); - - // Look for speed cards - for( int i = 0; i < this.upgradeInventory.getSizeInventory(); i++ ) - { - ItemStack slotStack = this.upgradeInventory.getStackInSlot( i ); - - if( slotStack != null ) - { - if( aeMaterals.cardSpeed().isSameAs( slotStack ) ) - { - this.upgradeCount++ ; - } - } - } - - if( EffectiveSide.isServerSide() ) - { - // Mark for save - this.markDirty(); - - // Mark for network update - this.markForUpdate(); - } - } - - /** - * Called when the player right-clicks the assembler with a memory card in - * hand. - * - * @param memoryCard - */ - public void onMemoryCardActivate( final EntityPlayer player, final IMemoryCard memoryCard, final ItemStack playerHolding ) - { - // Get the stored name - String settingsName = memoryCard.getSettingsName( playerHolding ); - - // Does it contain the data about a vis source? - if( settingsName.equals( DigiVisSourceData.SOURCE_UNLOC_NAME ) ) - { - // Get the data - NBTTagCompound data = memoryCard.getData( playerHolding ); - - // Load the info - this.visSourceInfo.readFromNBT( data ); - - // Ensure there is valid data - if( this.visSourceInfo.hasSourceData() ) - { - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - - // Mark that we need to save - this.markDirty(); - } - // Is the memory card empty? - else if( settingsName.equals( "gui.appliedenergistics2.Blank" ) ) - { - // Clear the source info - this.visSourceInfo.clearData(); - - // Inform the user - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - - // Mark dirty - this.markDirty(); - } - } - - @Override - public void onReady() - { - // Call super - super.onReady(); - - // Setup the kcore handler - this.updateCoreHandler(); - - // Is there a knowledge core? - if( this.internalInventory.getHasStack( KCORE_SLOT_INDEX ) ) - { - // Is there a pattern? - if( this.currentPattern != null ) - { - // Set the patterns core - this.currentPattern.setKnowledgeCore( this.internalInventory.getStackInSlot( KCORE_SLOT_INDEX ) ); - } - } - else if( this.currentPattern != null ) - { - // Clear the pattern - this.isCrafting = false; - this.currentPattern = null; - } - - // Recalculate the vis discounts - this.calculateVisDiscounts(); - } - - @TileEvent(TileEventType.NETWORK_READ) - @SideOnly(Side.CLIENT) - public boolean onReceiveNetworkData( final ByteBuf stream ) - { - // Read the active state - this.isActive = stream.readBoolean(); - - // Read the crafting status - this.isCrafting = stream.readBoolean(); - if( this.isCrafting ) - { - // Read the crafting progress - this.craftTickCounter = stream.readInt(); - - // Add particles - for( int i = 0; i < 2; i++ ) - { - Thaumcraft.proxy.blockRunes( this.worldObj, this.xCoord, this.yCoord, this.zCoord, 0.5F, 0.0F, 0.5F, 10, -0.1F ); - } - } - - // Clear old vis values - this.storedVis.aspects.clear(); - - // Read each stored aspect - for( int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++ ) - { - // Read the stored amount - this.storedVis.add( TileArcaneAssembler.PRIMALS[i], stream.readInt() ); - } - - // Read upgrade count - this.upgradeCount = stream.readInt(); - - return true; - } - - @TileEvent(TileEventType.NETWORK_WRITE) - public void onSendNetworkData( final ByteBuf stream ) throws IOException - { - // Write the active state - stream.writeBoolean( this.isActive() ); - - // Write if the assembler is crafting - stream.writeBoolean( this.isCrafting ); - if( this.isCrafting ) - { - // Write the crafting progress - stream.writeInt( this.craftTickCounter ); - } - - // Write each stored aspect - for( int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++ ) - { - // Write the stored amount - stream.writeInt( this.storedVis.getAmount( TileArcaneAssembler.PRIMALS[i] ) ); - } - - // Write the upgrade count - stream.writeInt( this.upgradeCount ); - } - - @TileEvent(TileEventType.TICK) - public void onTick() - { - // Vis discounts need to be updated? - if( this.flag_RecalcVis ) - { - this.calculateVisDiscounts(); - } - - if( EffectiveSide.isClientSide() ) - { - if( ( this.isCrafting ) && ( this.craftTickCounter < TileArcaneAssembler.BASE_TICKS_PER_CRAFT ) ) - { - this.craftTickCounter++ ; - } - - // Ignore the rest on client side. - return; - } - - // Core changed? - if( this.flag_CoreChanged ) - { - this.updateCoreHandler(); - } - - // Ensure the assembler is active - if( !this.isActive() ) - { - return; - } - - // Are the network patterns stale? - if( this.stalePatterns && this.getProxy().isReady() ) - { - try - { - // Inform the network - this.getProxy().getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.getActionableNode() ) ); - - // Mark they are no longer stale - this.stalePatterns = false; - } - catch( GridAccessException ignored) - { - } - } - - // Is the assembler linked to a vis relay? - if( this.visSourceInfo.hasSourceData() ) - { - // Increment the vis tick counter. - this.visTickCounter++ ; - - // Has five ticks elapsed? - if( this.visTickCounter == 5 ) - { - // Reset the tick counter - this.visTickCounter = 0; - - // Replenish vis stores - this.replenishVis(); - } - } - - // Is there a delayed update queued? - if( this.delayedUpdate ) - { - // Increase the counter - this.delayTickCounter++ ; - - // Have 5 ticks elapsed? - if( this.delayTickCounter >= 5 ) - { - // Mark for an update - this.markForUpdate(); - - // Reset the trackers - this.delayedUpdate = false; - this.delayTickCounter = 0; - } - } - - // Is the assembler crafting? - if( this.isCrafting ) - { - // Tick crafting - this.craftingTick(); - } - } - - @MENetworkEventSubscribe - public final void powerEvent( final MENetworkPowerStatusChange event ) - { - // Mark for update - this.markForUpdate(); - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.kCoreHandler != null ) - { - // Get the list of patterns - ArrayList corePatterns = this.kCoreHandler.getPatterns(); - - // Add each pattern - for( ArcaneCraftingPattern pattern : corePatterns ) - { - if( pattern != null ) - { - craftingTracker.addCraftingOption( this, pattern ); - } - } - } - - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - if( ( !this.isCrafting ) && ( patternDetails instanceof ArcaneCraftingPattern ) ) - { - // Mark that crafting has begun - this.isCrafting = true; - - // Reset the crafting tick counter - this.craftTickCounter = 0; - - // Set the pattern that is being crafted - this.currentPattern = (ArcaneCraftingPattern)patternDetails; - currentPattern.updateInventory(table); - - // Set the target item - this.internalInventory.setInventorySlotContents( TARGET_SLOT_INDEX, this.currentPattern.getResult().getItemStack() ); - - // AE effects - try - { - NetworkRegistry.TargetPoint where = new NetworkRegistry.TargetPoint( this.worldObj.provider.dimensionId, this.xCoord, this.yCoord, - this.zCoord, 32.0D ); - appeng.core.sync.network.NetworkHandler.instance.sendToAllAround( new PacketAssemblerAnimation( this.xCoord, this.yCoord, - this.zCoord, (byte)( 10 + ( 9 * this.upgradeCount ) ), this.currentPattern.getResult() ), - where ); - } - catch( IOException e ) - { - } - - return true; - } - - return false; - } - - @TileEvent(TileEventType.WORLD_NBT_READ) - public void readFromNBT_ArcaneAssembler( final NBTTagCompound data ) - { - // Is there relay info? - if( data.hasKey( TileArcaneAssembler.NBTKEY_VIS_INTERFACE ) ) - { - this.visSourceInfo.readFromNBT( data, TileArcaneAssembler.NBTKEY_VIS_INTERFACE ); - } - - // Read vis levels - this.readVisLevelsFromNBT( data ); - - // Read upgrade count - if( data.hasKey( TileArcaneAssembler.NBTKEY_UPGRADES ) ) - { - this.upgradeCount = data.getInteger( TileArcaneAssembler.NBTKEY_UPGRADES ); - } - - // Read upgrade inventory - this.upgradeInventory.readFromNBT( data, TileArcaneAssembler.NBTKEY_UPGRADEINV ); - - // Read the crafting status - if( data.hasKey( TileArcaneAssembler.NBTKEY_CRAFTING ) ) - { - this.isCrafting = data.getBoolean( TileArcaneAssembler.NBTKEY_CRAFTING ); - } - - // Read the pattern - if( data.hasKey( TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN ) ) - { - this.currentPattern = new ArcaneCraftingPattern( null, data.getCompoundTag( TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN ) ); - } - - } - - /** - * Reads the stored vis levels. - * - * @param data - */ - public void readVisLevelsFromNBT( final NBTTagCompound data ) - { - if( data.hasKey( TileArcaneAssembler.NBTKEY_STORED_VIS ) ) - { - this.storedVis.readFromNBT( data, TileArcaneAssembler.NBTKEY_STORED_VIS ); - } - } - - /** - * Sets the owner of this tile. - * - * @param player - */ - public void setOwner( final EntityPlayer player ) - { - this.getProxy().setOwner( player ); - } - - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void writeToNBT_ArcaneAssembler( final NBTTagCompound data ) - { - // Write the vis interface - this.visSourceInfo.writeToNBT( data, TileArcaneAssembler.NBTKEY_VIS_INTERFACE ); - - // Write the stored vis - this.writeVisLevelsToNBT( data ); - - // Write the number of upgrades - data.setInteger( TileArcaneAssembler.NBTKEY_UPGRADES, this.upgradeCount ); - - // Write the upgrade inventory - this.upgradeInventory.writeToNBT( data, TileArcaneAssembler.NBTKEY_UPGRADEINV ); - - // Write the crafting state - data.setBoolean( TileArcaneAssembler.NBTKEY_CRAFTING, this.isCrafting ); - - // Write the current pattern - if( this.currentPattern != null ) - { - data.setTag( TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN, this.currentPattern.writeToNBT( new NBTTagCompound() ) ); - } - - } - - /** - * Writes the stored vis levels. - * - * @param data - */ - public void writeVisLevelsToNBT( final NBTTagCompound data ) - { - if( this.storedVis.size() > 0 ) - { - this.storedVis.writeToNBT( data, TileArcaneAssembler.NBTKEY_STORED_VIS ); - } - } - +public class TileArcaneAssembler extends AENetworkInvTile implements ICraftingProvider, IWailaSource { + private class AAInv extends TheInternalInventory { + + public AAInv() { + super("ArcaneAssemblerInventory", TileArcaneAssembler.SLOT_COUNT, 64); + } + + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack itemStack) { + if (slotIndex == TileArcaneAssembler.KCORE_SLOT_INDEX) { + return (itemStack == null) || (itemStack.getItem() instanceof ItemKnowledgeCore); + } + + return true; + } + + @Override + public void markDirty() { + TileArcaneAssembler.this.markDirty(); + } + + @Override + public void setInventorySlotContents(final int slotIndex, final ItemStack itemStack) { + // Call super + super.setInventorySlotContents(slotIndex, itemStack); + + // Core changed? + if (slotIndex == TileArcaneAssembler.KCORE_SLOT_INDEX) { + TileArcaneAssembler.this.flag_CoreChanged = true; + } + + // Armor changed? + if (slotIndex >= DISCOUNT_ARMOR_INDEX) { + TileArcaneAssembler.this.flag_RecalcVis = true; + } + } + } + + /** + * NBT Keys + */ + private static final String NBTKEY_VIS_INTERFACE = "vis_interface", + NBTKEY_UPGRADES = "upgradeCount", + NBTKEY_UPGRADEINV = "upgrades", + NBTKEY_CRAFTING = "isCrafting", + NBTKEY_CRAFTING_PATTERN = "pattern"; + + /** + * NBT Key for stored vis. + */ + public static final String NBTKEY_STORED_VIS = "stored_vis"; + + /** + * Used to simulate floating point amounts of vis. + */ + private static final int CVIS_MULTIPLER = 10; + + /** + * The number of ticks required to craft an item without any upgrades. + */ + private static final int BASE_TICKS_PER_CRAFT = 20; + + /** + * Primal aspects. + */ + public static final Aspect[] PRIMALS = + new Aspect[] {Aspect.AIR, Aspect.WATER, Aspect.FIRE, Aspect.ORDER, Aspect.ENTROPY, Aspect.EARTH}; + + /** + * Total number of slots. 1 KCore + 21 Patterns + 1 Target + 4 Discount + * Armor + */ + public static final int SLOT_COUNT = 27; + + /** + * Index of the slots. + */ + public static final int KCORE_SLOT_INDEX = 0, + PATTERN_SLOT_INDEX = 1, + TARGET_SLOT_INDEX = 22, + DISCOUNT_ARMOR_INDEX = 23; + + /** + * Maximum amount of stored centi-vis. + */ + public static final int MAX_STORED_CVIS = 150 * TileArcaneAssembler.CVIS_MULTIPLER; + + /** + * Power usage. + */ + public static double IDLE_POWER = 0.0D, ACTIVE_POWER = 1.5D, WARP_POWER_PERCENT = 0.15; + + /** + * Holds the patterns and the kcore. + * Saved and loaded by AEInvTile due to getInternalInventory() call. + */ + private final AAInv internalInventory; + + /** + * Holds the upgrades + */ + private final UpgradeInventory upgradeInventory; + + /** + * Is the assembler busy crafting? + */ + private boolean isCrafting = false; + + /** + * The pattern currently being crafted. + */ + private ArcaneCraftingPattern currentPattern = null; + + /** + * Handles interaction with the knowledge core. + */ + private final HandlerKnowledgeCore kCoreHandler; + + /** + * If true the network should be informed of changes to available patterns. + */ + private boolean stalePatterns = false; + + /** + * Data pertaining to the linked digi-vis source + */ + private final DigiVisSourceData visSourceInfo = new DigiVisSourceData(); + + /** + * Vis stored in the assembler. + */ + private final AspectList storedVis = new AspectList(); + + /** + * Number of elapsed ticks. + */ + private int visTickCounter = 0, craftTickCounter = 0, delayTickCounter = 0; + + /** + * Source of all actions. + */ + private final MachineSource mySource; + + /** + * True when the assembler is online. + */ + private boolean isActive = false; + + /** + * The number of installed upgrades. + */ + private int upgradeCount = 0; + + /** + * How much discount each aspect is receiving. + */ + private final Hashtable visDiscount = new Hashtable<>(); + + /** + * How much additional power is required due to warp. + */ + private float warpPowerMultiplier = 1.0F; + + /** + * When true will send network update periodically. + */ + private boolean delayedUpdate = false; + + /** + * True when the core has changed. + */ + boolean flag_CoreChanged = false; + + /** + * True if the vis discount needs to be re-calculated. + */ + boolean flag_RecalcVis = false; + + /** + * Creates the assembler and it's inventory. + */ + public TileArcaneAssembler() { + // Create the internal inventory + this.internalInventory = new AAInv(); + + // Create the upgrade inventory + this.upgradeInventory = new BlockUpgradeInventory( + ThEApi.instance().blocks().ArcaneAssembler.getBlock(), this, BlockArcaneAssembler.MAX_SPEED_UPGRADES); + + // Set the machine source + this.mySource = new MachineSource(this); + + // Prep the discount table + for (Aspect primal : TileArcaneAssembler.PRIMALS) { + this.visDiscount.put(primal, VisCraftingHelper.INSTANCE.getScepterVisModifier(primal)); + } + + // Create the handler + this.kCoreHandler = new HandlerKnowledgeCore(); + + // Set idle power usage + this.getProxy().setIdlePowerUsage(TileArcaneAssembler.IDLE_POWER); + + // Require a channel + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } + + /** + * Get's the NBT tag for the just-crafted assembler. + * + * @return + */ + public static NBTTagCompound getCraftTag() { + NBTTagCompound data = new NBTTagCompound(); + + // Create the vis list + AspectList vis = new AspectList(); + + // Add each primal + for (Aspect primal : TileArcaneAssembler.PRIMALS) { + vis.add(primal, TileArcaneAssembler.MAX_STORED_CVIS); + } + + // Write into the tag + vis.writeToNBT(data, TileArcaneAssembler.NBTKEY_STORED_VIS); + + return data; + } + + /** + * Calculates how much vis discount applies to each aspect + */ + private void calculateVisDiscounts() { + this.flag_RecalcVis = false; + float discount; + + for (Aspect primal : TileArcaneAssembler.PRIMALS) { + // Get the discount from the scepter + discount = VisCraftingHelper.INSTANCE.getScepterVisModifier(primal); + + // Factor in the discount armor + discount -= VisCraftingHelper.INSTANCE.calculateArmorDiscount( + this.internalInventory, DISCOUNT_ARMOR_INDEX, 4, primal); + + this.visDiscount.put(primal, discount); + } + + // Reset warp power multiplier + this.warpPowerMultiplier = 1.0F; + + // Calculate warp power multiplier + this.warpPowerMultiplier += + VisCraftingHelper.INSTANCE.calculateArmorWarp(this.internalInventory, DISCOUNT_ARMOR_INDEX, 4) + * WARP_POWER_PERCENT; + } + + private void craftingTick() { + // Null check + if (this.currentPattern == null) { + this.isCrafting = false; + } + + // Is there enough vis to complete the crafting? + if (!this.hasEnoughVisForCraft()) { + return; + } + + // Has the assembler finished crafting? + if (this.craftTickCounter >= this.ticksPerCraft()) { + try { + // Get the storage grid + IStorageGrid storageGrid = this.getProxy().getStorage(); + + // Simulate placing the items + boolean rejected = false; + for (IAEItemStack output : this.currentPattern.getAllResults()) { + IAEItemStack rejectedResult = + storageGrid.getItemInventory().injectItems(output, Actionable.SIMULATE, this.mySource); + if ((rejectedResult != null) && (rejectedResult.getStackSize() > 0)) { + rejected = true; + break; + } + } + + // Were all items accepted? + if (!rejected) { + // Inject into the network + for (IAEItemStack output : this.currentPattern.getAllResults()) { + storageGrid.getItemInventory().injectItems(output, Actionable.MODULATE, this.mySource); + } + + // Mark the assembler as no longer crafting + this.isCrafting = false; + this.internalInventory.setInventorySlotContents(TARGET_SLOT_INDEX, null); + this.currentPattern = null; + + // Mark for network update + this.markForDelayedUpdate(); + } + } catch (GridAccessException ignored) { + } + } else { + try { + // Calculate power required + double powerRequired = (TileArcaneAssembler.ACTIVE_POWER + + ((TileArcaneAssembler.ACTIVE_POWER * this.upgradeCount) / 2.0D)) + * this.warpPowerMultiplier; + + // Attempt to take power + IEnergyGrid eGrid = this.getProxy().getEnergy(); + double powerExtracted = + eGrid.extractAEPower(powerRequired, Actionable.MODULATE, PowerMultiplier.CONFIG); + + if ((powerExtracted - powerRequired) <= 0.0D) { + // Increment the counter + this.craftTickCounter++; + + if (this.craftTickCounter >= this.ticksPerCraft()) { + // Take the required vis + Aspect[] requiredAspects = this.currentPattern.getCachedAspects(); + for (Aspect aspect : requiredAspects) { + // Calculate the required amount + int requiredAmount = this.getRequiredAmountForAspect(aspect); + + // Take the vis + this.storedVis.reduce(aspect, requiredAmount); + } + + this.markForDelayedUpdate(); + } + } + } catch (GridAccessException ignored) { + } + } + } + + /** + * Helper function to calculate how much vis is required for the specified + * aspect for the current recipe. + * + * @param aspect + * @return + */ + private int getRequiredAmountForAspect(final Aspect aspect) { + return (int) Math.ceil(this.visDiscount.get(aspect) + * (this.currentPattern.getAspectCost(aspect) * TileArcaneAssembler.CVIS_MULTIPLER)); + } + + private boolean hasEnoughVisForCraft() { + // Null check + if (this.currentPattern == null) { + return false; + } + + // Get the required aspects + Aspect[] requiredAspects = this.currentPattern.getCachedAspects(); + + // Check each aspect required by the pattern + for (Aspect aspect : requiredAspects) { + // Calculate the required amount + int requiredAmount = this.getRequiredAmountForAspect(aspect); + + // Is there not enough? + if (this.storedVis.getAmount(aspect) < requiredAmount) { + return false; + } + } + + // Has enough of all aspects + return true; + } + + /** + * Returns true if the tile is connected to the AE network and active. + * + * @return + */ + private boolean isActive() { + // Are we server side? + if (EffectiveSide.isServerSide()) { + // Do we have a proxy and grid node? + if ((this.getProxy() != null) && (this.getProxy().getNode() != null)) { + // Get the grid node activity + this.isActive = this.getProxy().getNode().isActive(); + } + } + + return this.isActive; + } + + /** + * Marks the tile for a delayed update. + */ + private void markForDelayedUpdate() { + this.delayedUpdate = true; + } + + /** + * Refills the internal vis buffer. + */ + private void replenishVis() { + IDigiVisSource visSource = null; + + // Ensure the grid is ready + if (!this.getProxy().isReady()) { + return; + } + + try { + // Get the source + visSource = this.visSourceInfo.tryGetSource(this.getProxy().getGrid()); + } catch (GridAccessException ignored) { + } + + // Ensure the source is reachable. + if (visSource == null) { + return; + } + + // Calculate how much vis is needed for each primal + for (Aspect primal : TileArcaneAssembler.PRIMALS) { + int numNeeded = TileArcaneAssembler.MAX_STORED_CVIS - this.storedVis.getAmount(primal); + + // Is any needed? + if (numNeeded > 0) { + // Request the vis + int amountDrained = visSource.consumeVis(primal, numNeeded); + + // Was any drained? + if (amountDrained > 0) { + // Add to the stored amount + this.storedVis.add(primal, amountDrained); + + // Mark for network sync + this.markForDelayedUpdate(); + } + } + } + } + + /** + * The number of ticks required to craft an item. + */ + private int ticksPerCraft() { + return TileArcaneAssembler.BASE_TICKS_PER_CRAFT - (4 * this.upgradeCount); + } + + /** + * Updates the handler to the current core. + */ + private void updateCoreHandler() { + this.flag_CoreChanged = false; + // Is there a kcore? + ItemStack kCore = this.internalInventory.getStackInSlot(KCORE_SLOT_INDEX); + if (kCore != null) { + // Is it a new core? + if (!TileArcaneAssembler.this.kCoreHandler.isHandlingCore(kCore)) { + // Open the core + TileArcaneAssembler.this.kCoreHandler.open(kCore); + + // Update the pattern slots + TileArcaneAssembler.this.updatePatternSlots(); + } + } else { + // Was there a core? + if (TileArcaneAssembler.this.kCoreHandler.hasCore()) { + // No more core + TileArcaneAssembler.this.kCoreHandler.close(); + + // Update the pattern slots + TileArcaneAssembler.this.updatePatternSlots(); + } + } + } + + /** + * Updates the pattern slots to match the kcore patterns. + */ + private void updatePatternSlots() { + Iterator pIterator = null; + + // Get the list + if (this.kCoreHandler != null) { + ArrayList patternOutputs = this.kCoreHandler.getStoredOutputs(); + pIterator = patternOutputs.iterator(); + } + + // Set pattern slots + for (int index = TileArcaneAssembler.PATTERN_SLOT_INDEX; + index < (TileArcaneAssembler.PATTERN_SLOT_INDEX + HandlerKnowledgeCore.MAXIMUM_STORED_PATTERNS); + index++) { + if ((pIterator != null) && (pIterator.hasNext())) { + // Set to pattern result + this.internalInventory.setInventorySlotContents(index, pIterator.next()); + } else { + // Clear slot + this.internalInventory.setInventorySlotContents(index, null); + } + } + + this.stalePatterns = true; + } + + @Override + protected ItemStack getItemFromTile(final Object obj) { + // Return the itemstack the visually represents this tile + return ThEApi.instance().blocks().ArcaneAssembler.getStack(); + } + + @Override + public void addWailaInformation(final List tooltip) { + // Is it active? + if (this.isActive()) { + // Get activity string from AppEng2 + tooltip.add(WailaText.DeviceOnline.getLocal()); + } else { + // Get activity string from AppEng2 + tooltip.add(WailaText.DeviceOffline.getLocal()); + } + + // Is the assembler crafting anything? + if ((this.isCrafting) && this.internalInventory.getHasStack(TARGET_SLOT_INDEX)) { + // Add what is being crafted and the percent it is complete + tooltip.add(String.format( + "%s, %.0f%%", + this.internalInventory.getStackInSlot(TARGET_SLOT_INDEX).getDisplayName(), + ((this.getPercentComplete() * 100.0F)))); + } + + // Build vis amounts + StringBuilder strAspects = new StringBuilder(); + for (int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++) { + // Get the primal + Aspect primal = TileArcaneAssembler.PRIMALS[i]; + + // Change color + strAspects.append(ThEGuiHelper.INSTANCE.getAspectChatColor(primal)); + + // Add amount + strAspects.append((this.storedVis.getAmount(primal) / (float) TileArcaneAssembler.CVIS_MULTIPLER)); + + // Are there more primals after this one? + if ((i + 1) < TileArcaneAssembler.PRIMALS.length) { + // Add a gray pipe + strAspects.append(EnumChatFormatting.WHITE.toString()); + strAspects.append(" | "); + } + } + + // Add vis amounts + tooltip.add(strAspects.toString()); + } + + @MENetworkEventSubscribe + public final void channelEvent(final MENetworkChannelsChanged event) { + // Mark for update + this.markForUpdate(); + } + + /** + * Inventory is not world accessible. + */ + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection whichSide) { + return new int[0]; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + /** + * Called when the block is broken to get any additional items. + * + * @return + */ + @Override + public void getDrops(final World world, final int x, final int y, final int z, final List drops) { + // Add the kCore + ItemStack kCore = this.internalInventory.getStackInSlot(TileArcaneAssembler.KCORE_SLOT_INDEX); + if (kCore != null) { + drops.add(kCore); + } + + // Add upgrades + for (int i = 0; i < this.upgradeInventory.getSizeInventory(); i++) { + ItemStack upgrade = this.upgradeInventory.getStackInSlot(i); + + if (upgrade != null) { + drops.add(upgrade); + } + } + + // Add armor + for (int i = 0; i < 4; i++) { + ItemStack armor = this.internalInventory.getStackInSlot(TileArcaneAssembler.DISCOUNT_ARMOR_INDEX + i); + + if (armor != null) { + drops.add(armor); + } + } + } + + @Override + public IInventory getInternalInventory() { + return this.internalInventory; + } + + /** + * Get's the current knowledge core handler. + * + * @return + */ + public HandlerKnowledgeCore getKCoreHandler() { + return this.kCoreHandler; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + /** + * Returns the percent the current crafting job is complete. + * + * @return + */ + public float getPercentComplete() { + float percent = 0.0F; + + if (this.isCrafting) { + percent = Math.min(((float) this.craftTickCounter / this.ticksPerCraft()), 1.0F); + } + + return percent; + } + + /** + * Get's the stored vis amounts. + * + * @return + */ + public AspectList getStoredVis() { + return this.storedVis; + } + + public UpgradeInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + /** + * Returns the discount for the specified aspect. + * + * @param aspect + * @return + */ + public float getVisDiscountForAspect(final Aspect aspect) { + return this.visDiscount.get(aspect); + } + + @Override + public boolean isBusy() { + return this.isCrafting; + } + + @Override + public boolean isItemValidForSlot(final int slotId, final ItemStack itemStack) { + // Is the slot being assigned the knowledge core slot? + if (slotId == KCORE_SLOT_INDEX) { + // Ensure the item is a knowledge core. + return ((itemStack == null) || (itemStack.getItem() instanceof ItemKnowledgeCore)); + } + + // Assume it is not valid + return false; + } + + @Override + public boolean isUseableByPlayer(final EntityPlayer player) { + if (EffectiveSide.isClientSide()) { + // Ignored on the client side. + return false; + } + + // Check basic usability + if (!this.internalInventory.isUseableByPlayer(player, this)) { + return false; + } + + // Check the security grid + try { + // Get the security grid + ISecurityGrid sGrid = this.getProxy().getSecurity(); + + // Return true if the player has inject and extract permissions + return ((sGrid.hasPermission(player, SecurityPermissions.INJECT)) + && (sGrid.hasPermission(player, SecurityPermissions.EXTRACT))); + } catch (GridAccessException e) { + return false; + } + } + + /** + * Called when the tile entity is about to be destroyed by a block break. + */ + public void onBreak() { + this.isCrafting = false; + } + + /** + * Called when the upgrade inventory changes + */ + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added) { + // Reset the upgrade count + this.upgradeCount = 0; + + IMaterials aeMaterals = AEApi.instance().definitions().materials(); + + // Look for speed cards + for (int i = 0; i < this.upgradeInventory.getSizeInventory(); i++) { + ItemStack slotStack = this.upgradeInventory.getStackInSlot(i); + + if (slotStack != null) { + if (aeMaterals.cardSpeed().isSameAs(slotStack)) { + this.upgradeCount++; + } + } + } + + if (EffectiveSide.isServerSide()) { + // Mark for save + this.markDirty(); + + // Mark for network update + this.markForUpdate(); + } + } + + /** + * Called when the player right-clicks the assembler with a memory card in + * hand. + * + * @param memoryCard + */ + public void onMemoryCardActivate( + final EntityPlayer player, final IMemoryCard memoryCard, final ItemStack playerHolding) { + // Get the stored name + String settingsName = memoryCard.getSettingsName(playerHolding); + + // Does it contain the data about a vis source? + if (settingsName.equals(DigiVisSourceData.SOURCE_UNLOC_NAME)) { + // Get the data + NBTTagCompound data = memoryCard.getData(playerHolding); + + // Load the info + this.visSourceInfo.readFromNBT(data); + + // Ensure there is valid data + if (this.visSourceInfo.hasSourceData()) { + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } + + // Mark that we need to save + this.markDirty(); + } + // Is the memory card empty? + else if (settingsName.equals("gui.appliedenergistics2.Blank")) { + // Clear the source info + this.visSourceInfo.clearData(); + + // Inform the user + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + + // Mark dirty + this.markDirty(); + } + } + + @Override + public void onReady() { + // Call super + super.onReady(); + + // Setup the kcore handler + this.updateCoreHandler(); + + // Is there a knowledge core? + if (this.internalInventory.getHasStack(KCORE_SLOT_INDEX)) { + // Is there a pattern? + if (this.currentPattern != null) { + // Set the patterns core + this.currentPattern.setKnowledgeCore(this.internalInventory.getStackInSlot(KCORE_SLOT_INDEX)); + } + } else if (this.currentPattern != null) { + // Clear the pattern + this.isCrafting = false; + this.currentPattern = null; + } + + // Recalculate the vis discounts + this.calculateVisDiscounts(); + } + + @TileEvent(TileEventType.NETWORK_READ) + @SideOnly(Side.CLIENT) + public boolean onReceiveNetworkData(final ByteBuf stream) { + // Read the active state + this.isActive = stream.readBoolean(); + + // Read the crafting status + this.isCrafting = stream.readBoolean(); + if (this.isCrafting) { + // Read the crafting progress + this.craftTickCounter = stream.readInt(); + + // Add particles + for (int i = 0; i < 2; i++) { + Thaumcraft.proxy.blockRunes( + this.worldObj, this.xCoord, this.yCoord, this.zCoord, 0.5F, 0.0F, 0.5F, 10, -0.1F); + } + } + + // Clear old vis values + this.storedVis.aspects.clear(); + + // Read each stored aspect + for (int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++) { + // Read the stored amount + this.storedVis.add(TileArcaneAssembler.PRIMALS[i], stream.readInt()); + } + + // Read upgrade count + this.upgradeCount = stream.readInt(); + + return true; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void onSendNetworkData(final ByteBuf stream) throws IOException { + // Write the active state + stream.writeBoolean(this.isActive()); + + // Write if the assembler is crafting + stream.writeBoolean(this.isCrafting); + if (this.isCrafting) { + // Write the crafting progress + stream.writeInt(this.craftTickCounter); + } + + // Write each stored aspect + for (int i = 0; i < TileArcaneAssembler.PRIMALS.length; i++) { + // Write the stored amount + stream.writeInt(this.storedVis.getAmount(TileArcaneAssembler.PRIMALS[i])); + } + + // Write the upgrade count + stream.writeInt(this.upgradeCount); + } + + @TileEvent(TileEventType.TICK) + public void onTick() { + // Vis discounts need to be updated? + if (this.flag_RecalcVis) { + this.calculateVisDiscounts(); + } + + if (EffectiveSide.isClientSide()) { + if ((this.isCrafting) && (this.craftTickCounter < TileArcaneAssembler.BASE_TICKS_PER_CRAFT)) { + this.craftTickCounter++; + } + + // Ignore the rest on client side. + return; + } + + // Core changed? + if (this.flag_CoreChanged) { + this.updateCoreHandler(); + } + + // Ensure the assembler is active + if (!this.isActive()) { + return; + } + + // Are the network patterns stale? + if (this.stalePatterns && this.getProxy().isReady()) { + try { + // Inform the network + this.getProxy().getGrid().postEvent(new MENetworkCraftingPatternChange(this, this.getActionableNode())); + + // Mark they are no longer stale + this.stalePatterns = false; + } catch (GridAccessException ignored) { + } + } + + // Is the assembler linked to a vis relay? + if (this.visSourceInfo.hasSourceData()) { + // Increment the vis tick counter. + this.visTickCounter++; + + // Has five ticks elapsed? + if (this.visTickCounter == 5) { + // Reset the tick counter + this.visTickCounter = 0; + + // Replenish vis stores + this.replenishVis(); + } + } + + // Is there a delayed update queued? + if (this.delayedUpdate) { + // Increase the counter + this.delayTickCounter++; + + // Have 5 ticks elapsed? + if (this.delayTickCounter >= 5) { + // Mark for an update + this.markForUpdate(); + + // Reset the trackers + this.delayedUpdate = false; + this.delayTickCounter = 0; + } + } + + // Is the assembler crafting? + if (this.isCrafting) { + // Tick crafting + this.craftingTick(); + } + } + + @MENetworkEventSubscribe + public final void powerEvent(final MENetworkPowerStatusChange event) { + // Mark for update + this.markForUpdate(); + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.kCoreHandler != null) { + // Get the list of patterns + ArrayList corePatterns = this.kCoreHandler.getPatterns(); + + // Add each pattern + for (ArcaneCraftingPattern pattern : corePatterns) { + if (pattern != null) { + craftingTracker.addCraftingOption(this, pattern); + } + } + } + } + + @Override + public boolean pushPattern(final ICraftingPatternDetails patternDetails, final InventoryCrafting table) { + if ((!this.isCrafting) && (patternDetails instanceof ArcaneCraftingPattern)) { + // Mark that crafting has begun + this.isCrafting = true; + + // Reset the crafting tick counter + this.craftTickCounter = 0; + + // Set the pattern that is being crafted + this.currentPattern = (ArcaneCraftingPattern) patternDetails; + currentPattern.updateInventory(table); + + // Set the target item + this.internalInventory.setInventorySlotContents( + TARGET_SLOT_INDEX, this.currentPattern.getResult().getItemStack()); + + // AE effects + try { + NetworkRegistry.TargetPoint where = new NetworkRegistry.TargetPoint( + this.worldObj.provider.dimensionId, this.xCoord, this.yCoord, this.zCoord, 32.0D); + appeng.core.sync.network.NetworkHandler.instance.sendToAllAround( + new PacketAssemblerAnimation( + this.xCoord, + this.yCoord, + this.zCoord, + (byte) (10 + (9 * this.upgradeCount)), + this.currentPattern.getResult()), + where); + } catch (IOException e) { + } + + return true; + } + + return false; + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_ArcaneAssembler(final NBTTagCompound data) { + // Is there relay info? + if (data.hasKey(TileArcaneAssembler.NBTKEY_VIS_INTERFACE)) { + this.visSourceInfo.readFromNBT(data, TileArcaneAssembler.NBTKEY_VIS_INTERFACE); + } + + // Read vis levels + this.readVisLevelsFromNBT(data); + + // Read upgrade count + if (data.hasKey(TileArcaneAssembler.NBTKEY_UPGRADES)) { + this.upgradeCount = data.getInteger(TileArcaneAssembler.NBTKEY_UPGRADES); + } + + // Read upgrade inventory + this.upgradeInventory.readFromNBT(data, TileArcaneAssembler.NBTKEY_UPGRADEINV); + + // Read the crafting status + if (data.hasKey(TileArcaneAssembler.NBTKEY_CRAFTING)) { + this.isCrafting = data.getBoolean(TileArcaneAssembler.NBTKEY_CRAFTING); + } + + // Read the pattern + if (data.hasKey(TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN)) { + this.currentPattern = + new ArcaneCraftingPattern(null, data.getCompoundTag(TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN)); + } + } + + /** + * Reads the stored vis levels. + * + * @param data + */ + public void readVisLevelsFromNBT(final NBTTagCompound data) { + if (data.hasKey(TileArcaneAssembler.NBTKEY_STORED_VIS)) { + this.storedVis.readFromNBT(data, TileArcaneAssembler.NBTKEY_STORED_VIS); + } + } + + /** + * Sets the owner of this tile. + * + * @param player + */ + public void setOwner(final EntityPlayer player) { + this.getProxy().setOwner(player); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_ArcaneAssembler(final NBTTagCompound data) { + // Write the vis interface + this.visSourceInfo.writeToNBT(data, TileArcaneAssembler.NBTKEY_VIS_INTERFACE); + + // Write the stored vis + this.writeVisLevelsToNBT(data); + + // Write the number of upgrades + data.setInteger(TileArcaneAssembler.NBTKEY_UPGRADES, this.upgradeCount); + + // Write the upgrade inventory + this.upgradeInventory.writeToNBT(data, TileArcaneAssembler.NBTKEY_UPGRADEINV); + + // Write the crafting state + data.setBoolean(TileArcaneAssembler.NBTKEY_CRAFTING, this.isCrafting); + + // Write the current pattern + if (this.currentPattern != null) { + data.setTag( + TileArcaneAssembler.NBTKEY_CRAFTING_PATTERN, this.currentPattern.writeToNBT(new NBTTagCompound())); + } + } + + /** + * Writes the stored vis levels. + * + * @param data + */ + public void writeVisLevelsToNBT(final NBTTagCompound data) { + if (this.storedVis.size() > 0) { + this.storedVis.writeToNBT(data, TileArcaneAssembler.NBTKEY_STORED_VIS); + } + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileDistillationPatternEncoder.java b/src/main/java/thaumicenergistics/common/tiles/TileDistillationPatternEncoder.java index a777ec15..68364af9 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileDistillationPatternEncoder.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileDistillationPatternEncoder.java @@ -1,7 +1,7 @@ package thaumicenergistics.common.tiles; -import java.util.ArrayList; import appeng.api.AEApi; +import java.util.ArrayList; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -13,150 +13,128 @@ import thaumicenergistics.common.tiles.abstraction.ThETileInventory; * @author Nividica * */ -public class TileDistillationPatternEncoder - extends ThETileInventory - implements ISidedInventory -{ - /** - * NBT Keys - */ - private static String NBTKEY_INVENTORY = "inventory"; +public class TileDistillationPatternEncoder extends ThETileInventory implements ISidedInventory { + /** + * NBT Keys + */ + private static String NBTKEY_INVENTORY = "inventory"; - /** - * Slot counts - */ - public static int SLOT_PATTERNS_COUNT = 2, - SLOT_SOURCE_ITEM_COUNT = 1, - SLOT_TOTAL_COUNT = TileDistillationPatternEncoder.SLOT_SOURCE_ITEM_COUNT + TileDistillationPatternEncoder.SLOT_PATTERNS_COUNT; - /** - * Slot ID's - */ - public static int SLOT_SOURCE_ITEM = 0, - SLOT_BLANK_PATTERNS = 1, - SLOT_ENCODED_PATTERN = 2; + /** + * Slot counts + */ + public static int SLOT_PATTERNS_COUNT = 2, + SLOT_SOURCE_ITEM_COUNT = 1, + SLOT_TOTAL_COUNT = + TileDistillationPatternEncoder.SLOT_SOURCE_ITEM_COUNT + + TileDistillationPatternEncoder.SLOT_PATTERNS_COUNT; + /** + * Slot ID's + */ + public static int SLOT_SOURCE_ITEM = 0, SLOT_BLANK_PATTERNS = 1, SLOT_ENCODED_PATTERN = 2; - /** - * Default constructor. - */ - public TileDistillationPatternEncoder() - { - super( "distillation.inscriber", TileDistillationPatternEncoder.SLOT_TOTAL_COUNT, 64 ); - } + /** + * Default constructor. + */ + public TileDistillationPatternEncoder() { + super("distillation.inscriber", TileDistillationPatternEncoder.SLOT_TOTAL_COUNT, 64); + } - @Override - public boolean canExtractItem( final int p_102008_1_, final ItemStack p_102008_2_, final int p_102008_3_ ) - { - return false; - } + @Override + public boolean canExtractItem(final int p_102008_1_, final ItemStack p_102008_2_, final int p_102008_3_) { + return false; + } - @Override - public boolean canInsertItem( final int p_102007_1_, final ItemStack p_102007_2_, final int p_102007_3_ ) - { - return false; - } + @Override + public boolean canInsertItem(final int p_102007_1_, final ItemStack p_102007_2_, final int p_102007_3_) { + return false; + } - /** - * Does not need ticks. - */ - @Override - public boolean canUpdate() - { - return false; - } + /** + * Does not need ticks. + */ + @Override + public boolean canUpdate() { + return false; + } - @Override - public int[] getAccessibleSlotsFromSide( final int p_94128_1_ ) - { - return new int[0]; - } + @Override + public int[] getAccessibleSlotsFromSide(final int p_94128_1_) { + return new int[0]; + } - /** - * Returns a list of items to drop when broken. - * - * @return - */ - public ArrayList getDrops( final ArrayList drops ) - { - // Add encoded - if( this.internalInventory.getHasStack( TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN ) ) - { - drops.add( this.internalInventory.getStackInSlot( TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN ) ); - } + /** + * Returns a list of items to drop when broken. + * + * @return + */ + public ArrayList getDrops(final ArrayList drops) { + // Add encoded + if (this.internalInventory.getHasStack(TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN)) { + drops.add(this.internalInventory.getStackInSlot(TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN)); + } - // Add blank - if( this.internalInventory.getHasStack( TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS ) ) - { - drops.add( this.internalInventory.getStackInSlot( TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS ) ); - } + // Add blank + if (this.internalInventory.getHasStack(TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS)) { + drops.add(this.internalInventory.getStackInSlot(TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS)); + } - return drops; - } + return drops; + } - /** - * True if there is a pattern to encode onto. - * - * @return - */ - public boolean hasPatterns() - { - // Is there anything in the pattern slots? - return this.internalInventory.getHasStack( TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN ) || - this.internalInventory.getHasStack( TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS ); + /** + * True if there is a pattern to encode onto. + * + * @return + */ + public boolean hasPatterns() { + // Is there anything in the pattern slots? + return this.internalInventory.getHasStack(TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN) + || this.internalInventory.getHasStack(TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS); + } - } + @Override + public boolean isItemValidForSlot(final int slotId, final ItemStack itemStack) { + // Can always clear a slot + if (itemStack == null) { + return true; + } - @Override - public boolean isItemValidForSlot( final int slotId, final ItemStack itemStack ) - { - // Can always clear a slot - if( itemStack == null ) - { - return true; - } + // Empty pattern slot? + if (slotId == TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS) { + return AEApi.instance().definitions().materials().blankPattern().isSameAs(itemStack); + } - // Empty pattern slot? - if( slotId == TileDistillationPatternEncoder.SLOT_BLANK_PATTERNS ) - { - return AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ); - } + // Encoded pattern slot? + if (slotId == TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN) { + return AEApi.instance().definitions().items().encodedPattern().isSameAs(itemStack); + } - // Encoded pattern slot? - if( slotId == TileDistillationPatternEncoder.SLOT_ENCODED_PATTERN ) - { - return AEApi.instance().definitions().items().encodedPattern().isSameAs( itemStack ); - } + return true; + } - return true; - } + /** + * Read tile state from NBT. + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); - /** - * Read tile state from NBT. - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); + // Has saved inventory? + if (data.hasKey(TileDistillationPatternEncoder.NBTKEY_INVENTORY)) { + this.internalInventory.readFromNBT(data, TileDistillationPatternEncoder.NBTKEY_INVENTORY); + } + } - // Has saved inventory? - if( data.hasKey( TileDistillationPatternEncoder.NBTKEY_INVENTORY ) ) - { - this.internalInventory.readFromNBT( data, TileDistillationPatternEncoder.NBTKEY_INVENTORY ); - } + /** + * Write tile state to NBT. + */ + @Override + public void writeToNBT(final NBTTagCompound data) { + // Call super + super.writeToNBT(data); - } - - /** - * Write tile state to NBT. - */ - @Override - public void writeToNBT( final NBTTagCompound data ) - { - // Call super - super.writeToNBT( data ); - - // Write the inventory - this.internalInventory.writeToNBT( data, TileDistillationPatternEncoder.NBTKEY_INVENTORY ); - - } + // Write the inventory + this.internalInventory.writeToNBT(data, TileDistillationPatternEncoder.NBTKEY_INVENTORY); + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileEnum.java b/src/main/java/thaumicenergistics/common/tiles/TileEnum.java index aa14b875..8d8338ba 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileEnum.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileEnum.java @@ -8,48 +8,44 @@ import thaumicenergistics.common.ThaumicEnergistics; * @author Nividica * */ -public enum TileEnum -{ - EssentiaProvider ("TileEssentiaProvider", TileEssentiaProvider.class), - InfusionProvider ("TileInfusionProvider", TileInfusionProvider.class), - GearBox ("TileGearBox", TileGearBox.class), - CellWorkbench ("TileEssentiaCellWorkbench", TileEssentiaCellWorkbench.class), - ArcaneAssembler ("TileArcaneAssembler", TileArcaneAssembler.class), - KnowledgeInscriber ("TileKnowledgeInscriber", TileKnowledgeInscriber.class), - EssentiaVibrationChamber ("TileEssentiaVibrationChamber", TileEssentiaVibrationChamber.class), - DistillationInscriber ("TileDistillationInscriber", TileDistillationPatternEncoder.class); +public enum TileEnum { + EssentiaProvider("TileEssentiaProvider", TileEssentiaProvider.class), + InfusionProvider("TileInfusionProvider", TileInfusionProvider.class), + GearBox("TileGearBox", TileGearBox.class), + CellWorkbench("TileEssentiaCellWorkbench", TileEssentiaCellWorkbench.class), + ArcaneAssembler("TileArcaneAssembler", TileArcaneAssembler.class), + KnowledgeInscriber("TileKnowledgeInscriber", TileKnowledgeInscriber.class), + EssentiaVibrationChamber("TileEssentiaVibrationChamber", TileEssentiaVibrationChamber.class), + DistillationInscriber("TileDistillationInscriber", TileDistillationPatternEncoder.class); - /** - * Unique ID of the tile entity - */ - private String ID; + /** + * Unique ID of the tile entity + */ + private String ID; - /** - * Tile entity class. - */ - private Class clazz; + /** + * Tile entity class. + */ + private Class clazz; - private TileEnum( final String ID, final Class clazz ) - { - this.ID = ID; - this.clazz = clazz; - } + private TileEnum(final String ID, final Class clazz) { + this.ID = ID; + this.clazz = clazz; + } - /** - * Gets the tile entity's class. - */ - public Class getTileClass() - { - return this.clazz; - } + /** + * Gets the tile entity's class. + */ + public Class getTileClass() { + return this.clazz; + } - /** - * Gets the tile entity's ID. - * - * @return - */ - public String getTileID() - { - return ThaumicEnergistics.MOD_ID + "." + this.ID; - } + /** + * Gets the tile entity's ID. + * + * @return + */ + public String getTileID() { + return ThaumicEnergistics.MOD_ID + "." + this.ID; + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaCellWorkbench.java b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaCellWorkbench.java index 9ae725e0..6a066d59 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaCellWorkbench.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaCellWorkbench.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.tiles; -import java.util.ArrayList; -import java.util.List; import appeng.api.storage.IMEInventory; import appeng.api.storage.ISaveProvider; +import java.util.ArrayList; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -23,377 +23,324 @@ import thaumicenergistics.common.utils.ThEUtils; * @author Nividica * */ -public class TileEssentiaCellWorkbench - extends TileEntity - implements IInventory, ISaveProvider -{ - /** - * NBT Keys - */ - private static String NBT_KEY_CELL = "EssentiaCell"; +public class TileEssentiaCellWorkbench extends TileEntity implements IInventory, ISaveProvider { + /** + * NBT Keys + */ + private static String NBT_KEY_CELL = "EssentiaCell"; - /** - * The stored essentia cell. - */ - private ItemStack eCell = null; + /** + * The stored essentia cell. + */ + private ItemStack eCell = null; - /** - * Cell handler - */ - private HandlerItemEssentiaCell eCellHandler = null; + /** + * Cell handler + */ + private HandlerItemEssentiaCell eCellHandler = null; - /** - * List of containers that are open. - */ - private final List listeners = new ArrayList(); + /** + * List of containers that are open. + */ + private final List listeners = new ArrayList(); - public TileEssentiaCellWorkbench() - { - } + public TileEssentiaCellWorkbench() {} - /** - * Notifies listeners that the partition list has changed. - */ - private void notifyListenersOfPartitionChange() - { - ArrayList partitionList = this.getPartitionList(); + /** + * Notifies listeners that the partition list has changed. + */ + private void notifyListenersOfPartitionChange() { + ArrayList partitionList = this.getPartitionList(); - // Update each listener - for( ContainerEssentiaCellWorkbench container : this.listeners ) - { - container.onPartitionChanged( partitionList ); - } - } + // Update each listener + for (ContainerEssentiaCellWorkbench container : this.listeners) { + container.onPartitionChanged(partitionList); + } + } - /** - * Attempts to add an aspect to the partition. - * - * @param aspect - */ - public boolean addAspectToPartition( final Aspect aspect ) - { - if( ( this.eCellHandler != null ) ) - { - if( this.eCellHandler.addAspectToPartitionList( aspect ) ) - { - // Update listeners - this.notifyListenersOfPartitionChange(); - return true; - } - } + /** + * Attempts to add an aspect to the partition. + * + * @param aspect + */ + public boolean addAspectToPartition(final Aspect aspect) { + if ((this.eCellHandler != null)) { + if (this.eCellHandler.addAspectToPartitionList(aspect)) { + // Update listeners + this.notifyListenersOfPartitionChange(); + return true; + } + } - return false; - } + return false; + } - /** - * Workbench does not need ticks. - */ - @Override - public boolean canUpdate() - { - return false; - } + /** + * Workbench does not need ticks. + */ + @Override + public boolean canUpdate() { + return false; + } - /** - * Clears all partitioning. - * - * @param player - */ - public void clearAllPartitioning() - { - // Ensure there is a handler - if( this.eCellHandler != null ) - { - // Clear the partitioning - this.eCellHandler.clearPartitioning(); + /** + * Clears all partitioning. + * + * @param player + */ + public void clearAllPartitioning() { + // Ensure there is a handler + if (this.eCellHandler != null) { + // Clear the partitioning + this.eCellHandler.clearPartitioning(); - // Update listeners - this.notifyListenersOfPartitionChange(); - } - } + // Update listeners + this.notifyListenersOfPartitionChange(); + } + } - @Override - public void closeInventory() - { - // Ignored - } + @Override + public void closeInventory() { + // Ignored + } - /** - * Gets and removes the cell. - */ - @Override - public ItemStack decrStackSize( final int slotIndex, final int amount ) - { - ItemStack rtn = null; + /** + * Gets and removes the cell. + */ + @Override + public ItemStack decrStackSize(final int slotIndex, final int amount) { + ItemStack rtn = null; - if( this.hasEssentiaCell() ) - { - // Get the cell - rtn = this.eCell; + if (this.hasEssentiaCell()) { + // Get the cell + rtn = this.eCell; - // Null the cell - this.setInventorySlotContents( slotIndex, null ); - } - return rtn; - } + // Null the cell + this.setInventorySlotContents(slotIndex, null); + } + return rtn; + } - @Override - public String getInventoryName() - { - return ThaumicEnergistics.MOD_ID + ".essentia.cell.workbench.inventory"; - } + @Override + public String getInventoryName() { + return ThaumicEnergistics.MOD_ID + ".essentia.cell.workbench.inventory"; + } - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public int getInventoryStackLimit() { + return 1; + } - /** - * Gets the partition list. - * - * @return - */ - public ArrayList getPartitionList() - { - ArrayList partitionList; + /** + * Gets the partition list. + * + * @return + */ + public ArrayList getPartitionList() { + ArrayList partitionList; - // Ensure there is a handler - if( ( this.eCellHandler != null ) ) - { - // Get the partition list - partitionList = this.eCellHandler.getPartitionAspects(); - } - else - { - // Create an empty list - partitionList = new ArrayList(); - } + // Ensure there is a handler + if ((this.eCellHandler != null)) { + // Get the partition list + partitionList = this.eCellHandler.getPartitionAspects(); + } else { + // Create an empty list + partitionList = new ArrayList(); + } - return partitionList; - } + return partitionList; + } - @Override - public int getSizeInventory() - { - return 1; - } + @Override + public int getSizeInventory() { + return 1; + } - /** - * Gets the cell. - */ - @Override - public ItemStack getStackInSlot( final int slotIndex ) - { - return this.eCell; - } + /** + * Gets the cell. + */ + @Override + public ItemStack getStackInSlot(final int slotIndex) { + return this.eCell; + } - /** - * Gets the cell. - */ - @Override - public ItemStack getStackInSlotOnClosing( final int slotIndex ) - { - return this.eCell; - } + /** + * Gets the cell. + */ + @Override + public ItemStack getStackInSlotOnClosing(final int slotIndex) { + return this.eCell; + } - @Override - public boolean hasCustomInventoryName() - { - return true; - } + @Override + public boolean hasCustomInventoryName() { + return true; + } - /** - * Checks if the workbench has a cell. - * - * @return - */ - public boolean hasEssentiaCell() - { - return( this.eCell != null ); - } + /** + * Checks if the workbench has a cell. + * + * @return + */ + public boolean hasEssentiaCell() { + return (this.eCell != null); + } - /** - * Ensures the stack is an essentia cell. - */ - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack stack ) - { - return( ( stack == null ) || ( stack.getItem() instanceof ItemEssentiaCell ) ); - } + /** + * Ensures the stack is an essentia cell. + */ + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack stack) { + return ((stack == null) || (stack.getItem() instanceof ItemEssentiaCell)); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer player ) - { - return ThEUtils.canPlayerInteractWith( player, this ); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer player) { + return ThEUtils.canPlayerInteractWith(player, this); + } - @Override - public void openInventory() - { - // Ignored - } + @Override + public void openInventory() { + // Ignored + } - /** - * Partitions the cell be set to the contents of the cell. - * - * @param player - */ - public void partitionToCellContents() - { - // Ensure there is a handler - if( this.eCellHandler != null ) - { - // Partition the cell - this.eCellHandler.partitionToCellContents(); + /** + * Partitions the cell be set to the contents of the cell. + * + * @param player + */ + public void partitionToCellContents() { + // Ensure there is a handler + if (this.eCellHandler != null) { + // Partition the cell + this.eCellHandler.partitionToCellContents(); - // Update listeners - this.notifyListenersOfPartitionChange(); - } - } + // Update listeners + this.notifyListenersOfPartitionChange(); + } + } - /** - * Loads the workbench. - */ - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); + /** + * Loads the workbench. + */ + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); - // Is there a cell to read? - if( data.hasKey( TileEssentiaCellWorkbench.NBT_KEY_CELL ) ) - { - // Read the cell - this.setInventorySlotContents( 0, ItemStack.loadItemStackFromNBT( data.getCompoundTag( TileEssentiaCellWorkbench.NBT_KEY_CELL ) ) ); - } - } + // Is there a cell to read? + if (data.hasKey(TileEssentiaCellWorkbench.NBT_KEY_CELL)) { + // Read the cell + this.setInventorySlotContents( + 0, ItemStack.loadItemStackFromNBT(data.getCompoundTag(TileEssentiaCellWorkbench.NBT_KEY_CELL))); + } + } - /** - * Registers a container. - * The container will be notified when the cell changes. - * - * @param container - */ - public void registerListener( final ContainerEssentiaCellWorkbench container ) - { - if( !this.listeners.contains( container ) ) - { - this.listeners.add( container ); - } + /** + * Registers a container. + * The container will be notified when the cell changes. + * + * @param container + */ + public void registerListener(final ContainerEssentiaCellWorkbench container) { + if (!this.listeners.contains(container)) { + this.listeners.add(container); + } + } - } + /** + * Removes an aspect from the partition. + * + * @param aspect + */ + public void removeAspectFromPartition(final Aspect aspect) { + // Ensure there is a handler + if ((this.eCellHandler != null)) { + // Remove from the partition list + if (this.eCellHandler.removeAspectFromPartitionList(aspect)) { + // Update listeners + this.notifyListenersOfPartitionChange(); + } + } + } - /** - * Removes an aspect from the partition. - * - * @param aspect - */ - public void removeAspectFromPartition( final Aspect aspect ) - { - // Ensure there is a handler - if( ( this.eCellHandler != null ) ) - { - // Remove from the partition list - if( this.eCellHandler.removeAspectFromPartitionList( aspect ) ) - { - // Update listeners - this.notifyListenersOfPartitionChange(); - } - } - } + /** + * Removes a container. + * It will no longer receive notifications when the cell changes. + * + * @param container + */ + public void removeListener(final ContainerEssentiaCellWorkbench container) { + this.listeners.remove(container); + } - /** - * Removes a container. - * It will no longer receive notifications when the cell changes. - * - * @param container - */ - public void removeListener( final ContainerEssentiaCellWorkbench container ) - { - this.listeners.remove( container ); - } + /** + * Called when the cell changes + */ + @Override + public void saveChanges(final IMEInventory cellInventory) { + // Mark the chunk as needing to be saved. + // Much less invasive than markDirty(), which issues onNeighborChanged events to a 12 block radius... + this.worldObj.markTileEntityChunkModified(this.xCoord, this.yCoord, this.zCoord, this); + } - /** - * Called when the cell changes - */ - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - // Mark the chunk as needing to be saved. - // Much less invasive than markDirty(), which issues onNeighborChanged events to a 12 block radius... - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } + /** + * Sets the stored cell + * + * @param cell + */ + @Override + public void setInventorySlotContents(final int slotIndex, final ItemStack stack) { + if (this.isItemValidForSlot(slotIndex, stack)) { + // Set the cell + this.eCell = stack; - /** - * Sets the stored cell - * - * @param cell - */ - @Override - public void setInventorySlotContents( final int slotIndex, final ItemStack stack ) - { - if( this.isItemValidForSlot( slotIndex, stack ) ) - { - // Set the cell - this.eCell = stack; + if (EffectiveSide.isServerSide()) { + if (stack == null) { + // Null the handler + this.eCellHandler = null; + } else { + // Get the handler + this.eCellHandler = new HandlerItemEssentiaCell(stack, this); + } - if( EffectiveSide.isServerSide() ) - { - if( stack == null ) - { - // Null the handler - this.eCellHandler = null; - } - else - { - // Get the handler - this.eCellHandler = new HandlerItemEssentiaCell( stack, this ); - } + // Update containers + this.notifyListenersOfPartitionChange(); + } + } + } - // Update containers - this.notifyListenersOfPartitionChange(); - } - } - } + /** + * Replaces one aspect with another. + * + * @param aspect + */ + public void swapPartitionedAspect(final Aspect fromAspect, final Aspect toAspect) { + // Ensure there is a handler + if (this.eCellHandler != null) { + // Replace the aspect + if (this.eCellHandler.replaceAspectInPartitionList(fromAspect, toAspect)) { + // Update listeners + this.notifyListenersOfPartitionChange(); + } + } + } - /** - * Replaces one aspect with another. - * - * @param aspect - */ - public void swapPartitionedAspect( final Aspect fromAspect, final Aspect toAspect ) - { - // Ensure there is a handler - if( this.eCellHandler != null ) - { - // Replace the aspect - if( this.eCellHandler.replaceAspectInPartitionList( fromAspect, toAspect ) ) - { - // Update listeners - this.notifyListenersOfPartitionChange(); - } - } - } + /** + * Saves the workbench. + */ + @Override + public void writeToNBT(final NBTTagCompound data) { + // Call super + super.writeToNBT(data); - /** - * Saves the workbench. - */ - @Override - public void writeToNBT( final NBTTagCompound data ) - { - // Call super - super.writeToNBT( data ); - - // Is there a cell? - if( this.hasEssentiaCell() ) - { - // Write the cell data - NBTTagCompound cellData = this.eCell.writeToNBT( new NBTTagCompound() ); - - // Add the cell data - data.setTag( TileEssentiaCellWorkbench.NBT_KEY_CELL, cellData ); - } - } + // Is there a cell? + if (this.hasEssentiaCell()) { + // Write the cell data + NBTTagCompound cellData = this.eCell.writeToNBT(new NBTTagCompound()); + // Add the cell data + data.setTag(TileEssentiaCellWorkbench.NBT_KEY_CELL, cellData); + } + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaProvider.java b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaProvider.java index b187e1d3..f313c948 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaProvider.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaProvider.java @@ -1,11 +1,11 @@ package thaumicenergistics.common.tiles; -import java.lang.ref.WeakReference; -import java.util.HashSet; -import java.util.Set; import appeng.api.config.Actionable; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; +import java.lang.ref.WeakReference; +import java.util.HashSet; +import java.util.Set; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; @@ -23,261 +23,224 @@ import thaumicenergistics.common.tiles.abstraction.TileProviderBase; * @author Nividica * */ -public class TileEssentiaProvider - extends TileProviderBase - implements IEssentiaTransportWithSimulate -{ - /** - * How often should the tile tick. - */ - private static final int TICK_RATE_IDLE = 15, TICK_RATE_URGENT = 5; +public class TileEssentiaProvider extends TileProviderBase implements IEssentiaTransportWithSimulate { + /** + * How often should the tile tick. + */ + private static final int TICK_RATE_IDLE = 15, TICK_RATE_URGENT = 5; - /** - * Tracks the number of ticks that have occurred. - */ - private int tickCount = 0; + /** + * Tracks the number of ticks that have occurred. + */ + private int tickCount = 0; - /** - * How often should the tile tick. - */ - private int tickRate = TileEssentiaProvider.TICK_RATE_IDLE; + /** + * How often should the tile tick. + */ + private int tickRate = TileEssentiaProvider.TICK_RATE_IDLE; - /** - * Set of watchers that would like to be notified of events. - */ - private Set> blockWatchers; + /** + * Set of watchers that would like to be notified of events. + */ + private Set> blockWatchers; - /** - * How much power does this require just to be active? - */ - @Override - protected double getIdlePowerusage() - { - return 3.0; - } + /** + * How much power does this require just to be active? + */ + @Override + protected double getIdlePowerusage() { + return 3.0; + } - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - // Return the itemstack the visually represents this tile - return ThEApi.instance().blocks().EssentiaProvider.getStack(); + @Override + protected ItemStack getItemFromTile(final Object obj) { + // Return the itemstack the visually represents this tile + return ThEApi.instance().blocks().EssentiaProvider.getStack(); + } - } + protected Aspect getNeighborWantedAspect(final ForgeDirection side) { + // Get the tile entity next to this side + TileEntity neighbor = this.worldObj.getTileEntity( + this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ); - protected Aspect getNeighborWantedAspect( final ForgeDirection side ) - { - // Get the tile entity next to this side - TileEntity neighbor = this.worldObj.getTileEntity( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); + // Do we have essentia transport neighbor? + if ((neighbor != null) && (neighbor instanceof IEssentiaTransport)) { + // Get the aspect they want + Aspect wantedAspect = ((IEssentiaTransport) neighbor).getSuctionType(side.getOpposite()); - // Do we have essentia transport neighbor? - if( ( neighbor != null ) && ( neighbor instanceof IEssentiaTransport ) ) - { - // Get the aspect they want - Aspect wantedAspect = ( (IEssentiaTransport)neighbor ).getSuctionType( side.getOpposite() ); + // Return the aspect they want + return wantedAspect; + } - // Return the aspect they want - return wantedAspect; - } + return null; + } - return null; - } + @Override + protected void onPowerChange(final boolean isPowered) { + // Any watchers? + if (this.blockWatchers != null) { + // Inform each watcher that the provider is about to be broken. + for (WeakReference watcherRef : this.blockWatchers) { + IEssentiaProviderWatcher watcher = watcherRef.get(); + if (watcher != null) { + watcher.onProviderPowerChange(isPowered); + } + } + } + } - @Override - protected void onPowerChange( final boolean isPowered ) - { - // Any watchers? - if( this.blockWatchers != null ) - { - // Inform each watcher that the provider is about to be broken. - for( WeakReference watcherRef : this.blockWatchers ) - { - IEssentiaProviderWatcher watcher = watcherRef.get(); - if( watcher != null ) - { - watcher.onProviderPowerChange( isPowered ); - } - } - } - } + @Override + public int addEssentia(final Aspect aspect, final int amount, final ForgeDirection side) { + return this.addEssentia(aspect, amount, side, Actionable.MODULATE); + } - @Override - public int addEssentia( final Aspect aspect, final int amount, final ForgeDirection side ) - { - return this.addEssentia( aspect, amount, side, Actionable.MODULATE ); - } + @Override + public int addEssentia(final Aspect aspect, final int amount, final ForgeDirection side, final Actionable mode) { + // Assume its all rejected + long rejectedAmount = amount; - @Override - public int addEssentia( final Aspect aspect, final int amount, final ForgeDirection side, final Actionable mode ) - { - // Assume its all rejected - long rejectedAmount = amount; + // Ensure we have a monitor + if (this.getEssentiaMonitor()) { + // Inject essentia + rejectedAmount = this.monitor.injectEssentia(aspect, amount, mode, this.getMachineSource(), true); + } - // Ensure we have a monitor - if( this.getEssentiaMonitor() ) - { - // Inject essentia - rejectedAmount = this.monitor.injectEssentia( aspect, amount, mode, this.getMachineSource(), true ); - } + // Calculate the accepted amount + long acceptedAmount = amount - rejectedAmount; - // Calculate the accepted amount - long acceptedAmount = amount - rejectedAmount; + if ((mode == Actionable.MODULATE) && (acceptedAmount > 0)) { + this.tickRate = TileEssentiaProvider.TICK_RATE_URGENT; + } - if( ( mode == Actionable.MODULATE ) && ( acceptedAmount > 0 ) ) - { - this.tickRate = TileEssentiaProvider.TICK_RATE_URGENT; - } + return (int) acceptedAmount; + } - return (int)acceptedAmount; - } + @Override + public boolean canInputFrom(final ForgeDirection side) { + // Can input from any side + return true; + } - @Override - public boolean canInputFrom( final ForgeDirection side ) - { - // Can input from any side - return true; - } + @Override + public boolean canOutputTo(final ForgeDirection side) { + // Can output to any side + return true; + } - @Override - public boolean canOutputTo( final ForgeDirection side ) - { - // Can output to any side - return true; - } + @Override + public int getEssentiaAmount(final ForgeDirection side) { + // Get the aspect this neighbor wants + Aspect wantedAspect = this.getNeighborWantedAspect(side); - @Override - public int getEssentiaAmount( final ForgeDirection side ) - { - // Get the aspect this neighbor wants - Aspect wantedAspect = this.getNeighborWantedAspect( side ); + // Does the neighbor want anything? + if (wantedAspect != null) { + return (int) Math.min(this.getAspectAmountInNetwork(wantedAspect), Integer.MAX_VALUE); + } - // Does the neighbor want anything? - if( wantedAspect != null ) - { - return (int)Math.min( this.getAspectAmountInNetwork( wantedAspect ), Integer.MAX_VALUE ); - } + // No match or no request + return 0; + } - // No match or no request - return 0; - } + @Override + public Aspect getEssentiaType(final ForgeDirection side) { + // Get the aspect this neighbor wants + Aspect wantedAspect = this.getNeighborWantedAspect(side); - @Override - public Aspect getEssentiaType( final ForgeDirection side ) - { - // Get the aspect this neighbor wants - Aspect wantedAspect = this.getNeighborWantedAspect( side ); + // Does the neighbor want anything? + if (wantedAspect != null) { + // Does the network have that aspect? + if (this.getAspectAmountInNetwork(wantedAspect) > 0) { + // Return the aspect they want + return wantedAspect; + } + } - // Does the neighbor want anything? - if( wantedAspect != null ) - { - // Does the network have that aspect? - if( this.getAspectAmountInNetwork( wantedAspect ) > 0 ) - { - // Return the aspect they want - return wantedAspect; - } - } + // No match or no request + return null; + } - // No match or no request - return null; - } + @Override + public int getMinimumSuction() { + // Any amount of suction is good enough + return 1; + } - @Override - public int getMinimumSuction() - { - // Any amount of suction is good enough - return 1; - } + @Override + public int getSuctionAmount(final ForgeDirection side) { + // Just a wee bit of suction. + return 8; + } - @Override - public int getSuctionAmount( final ForgeDirection side ) - { - // Just a wee bit of suction. - return 8; - } + @Override + public Aspect getSuctionType(final ForgeDirection side) { + // All types + return null; + } - @Override - public Aspect getSuctionType( final ForgeDirection side ) - { - // All types - return null; - } + @Override + public boolean isConnectable(final ForgeDirection side) { + // Can connect on any side + return true; + } - @Override - public boolean isConnectable( final ForgeDirection side ) - { - // Can connect on any side - return true; - } + @Override + public void onBreakBlock() { + // Any watchers? + if (this.blockWatchers != null) { + // Inform each watcher that the provider is about to be broken. + for (WeakReference watcherRef : this.blockWatchers) { + IEssentiaProviderWatcher watcher = watcherRef.get(); + if (watcher != null) { + watcher.onProviderBroken(); + } + } + this.blockWatchers.clear(); + } + } - @Override - public void onBreakBlock() - { - // Any watchers? - if( this.blockWatchers != null ) - { - // Inform each watcher that the provider is about to be broken. - for( WeakReference watcherRef : this.blockWatchers ) - { - IEssentiaProviderWatcher watcher = watcherRef.get(); - if( watcher != null ) - { - watcher.onProviderBroken(); - } - } - this.blockWatchers.clear(); - } - } + /** + * Called during the tileentity update phase. + */ + @TileEvent(TileEventType.TICK) + public void onTick() { + // Ensure this is server side, and that 5 ticks have elapsed + if ((!this.worldObj.isRemote) && (++this.tickCount >= this.tickRate)) { + // Reset the tick count + this.tickCount = 0; - /** - * Called during the tileentity update phase. - */ - @TileEvent(TileEventType.TICK) - public void onTick() - { - // Ensure this is server side, and that 5 ticks have elapsed - if( ( !this.worldObj.isRemote ) && ( ++this.tickCount >= this.tickRate ) ) - { - // Reset the tick count - this.tickCount = 0; + // Assume idle + this.tickRate = TileEssentiaProvider.TICK_RATE_IDLE; - // Assume idle - this.tickRate = TileEssentiaProvider.TICK_RATE_IDLE; + // Take essentia from the neighbors + EssentiaTransportHelper.INSTANCE.takeEssentiaFromTransportNeighbors( + this, this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + } - // Take essentia from the neighbors - EssentiaTransportHelper.INSTANCE.takeEssentiaFromTransportNeighbors( this, this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } + public void registerBlockWatcher(final IEssentiaProviderWatcher watcher) { + // Create the set if needed + if (this.blockWatchers == null) { + this.blockWatchers = new HashSet>(); + } - public void registerBlockWatcher( final IEssentiaProviderWatcher watcher ) - { - // Create the set if needed - if( this.blockWatchers == null ) - { - this.blockWatchers = new HashSet>(); - } + // Add the watcher + this.blockWatchers.add(new WeakReference(watcher)); + } - // Add the watcher - this.blockWatchers.add( new WeakReference( watcher ) ); - } + @Override + public boolean renderExtendedTube() { + // We take up a full block + return false; + } - @Override - public boolean renderExtendedTube() - { - // We take up a full block - return false; - } - - @Override - public void setSuction( final Aspect aspect, final int amount ) - { - // Ignored - } - - @Override - public int takeEssentia( final Aspect aspect, final int amount, final ForgeDirection side ) - { - // Extract essentia from the network, and return the amount extracted - return this.extractEssentiaFromNetwork( aspect, amount, false ); - } + @Override + public void setSuction(final Aspect aspect, final int amount) { + // Ignored + } + @Override + public int takeEssentia(final Aspect aspect, final int amount, final ForgeDirection side) { + // Extract essentia from the network, and return the amount extracted + return this.extractEssentiaFromNetwork(aspect, amount, false); + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaVibrationChamber.java b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaVibrationChamber.java index 4c62a0f1..101b84f9 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileEssentiaVibrationChamber.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileEssentiaVibrationChamber.java @@ -1,8 +1,5 @@ package thaumicenergistics.common.tiles; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; @@ -11,6 +8,9 @@ import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; import appeng.me.GridAccessException; import io.netty.buffer.ByteBuf; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -30,616 +30,555 @@ import thaumicenergistics.common.tiles.abstraction.TileEVCBase; * @author Nividica * */ -public class TileEssentiaVibrationChamber - extends TileEVCBase - implements IGridTickable, IWailaSource -{ - private static String NBTKEY_TIME_REMAINING = "TRemain", NBTKEY_PROCESSING_SPEED = "ProcSpeed", NBTKEY_POWER_PER_TICK = "PwrPerTick", - NBTKEY_PROCESSING_ASPECT = "ProcAspect"; - - /** - * How much power is produced per tick - */ - private static final double BASE_POWER_PER_TICK = 5.0; - - /** - * Half second. - */ - private static final int TICKRATE_MIN = 10; - - /** - * Two seconds. - */ - private static final int TICKRATE_MAX = 40; - - /** - * Min and Max processing speed - */ - private static final int PROCESS_SPEED_MAX = 200, PROCESS_SPEED_MIN = 20; - - /** - * Adjusts processing speed. - */ - private static final double DILATATION_DIVISOR = 100; - - /** - * How long it takes coal to burn - */ - private static int coalBurnTime = 0; - - /** - * Time dilation amount - */ - private double dilation = 1.0F; - - /** - * How much longer the essentia will be processed, in ticks. - */ - private int processingTicksRemaining = 0; - - /** - * How fast processing is occurring. - */ - private int processingSpeed = 0; - - /** - * How much power is produced per processing tick. - * Note: This is not the same as a minecraft tick. Processing ticks are dilated by processing speed. - */ - private double powerProducedPerProcessingTick = 0; - - /** - * What aspect is currently being processed. - */ - private Aspect processingAspect = null; - - /** - * Set true when the aspect changed. - */ - private boolean processingChanged = false; - - /** - * The total amount of processing ticks for the current aspect. - * Used for GUI. - */ - private int sync_totalProcessingTicks = 0; - - /** - * How much power is being produced per tick. - * Used for GUI. - */ - private double sync_powerPerTick = 0; - - /** - * Players who have the GUI open. - */ - private final Set listeners = new HashSet(); - - /** - * Adjusts processing time and power production based on essentia type. - * - * @return - */ - private int adjustProcessingValues() - { - int pTime = 0; - - // Has the burn time of coal been retrieved? - if( TileEssentiaVibrationChamber.coalBurnTime == 0 ) - { - // Get the base processing time of coal - TileEssentiaVibrationChamber.coalBurnTime = TileEntityFurnace.getItemBurnTime( new ItemStack( Items.coal ) ); - } - - // What kind of essentia is stored? - if( this.storedEssentia.getAspect() == Aspect.FIRE ) - { - pTime = TileEssentiaVibrationChamber.coalBurnTime / 2; - this.powerProducedPerProcessingTick = TileEssentiaVibrationChamber.BASE_POWER_PER_TICK * 1.0D; - } - else if( this.storedEssentia.getAspect() == Aspect.ENERGY ) - { - pTime = (int)( TileEssentiaVibrationChamber.coalBurnTime / 1.6F ); - this.powerProducedPerProcessingTick = TileEssentiaVibrationChamber.BASE_POWER_PER_TICK * 1.6D; - } - - // Set the total - this.sync_totalProcessingTicks = pTime; - - return pTime; - } - - /** - * Clamps the processing speed to the min-max constants. - */ - private void clampProcessingSpeed() - { - this.processingSpeed = Math.max( TileEssentiaVibrationChamber.PROCESS_SPEED_MIN, - Math.min( TileEssentiaVibrationChamber.PROCESS_SPEED_MAX, this.processingSpeed ) ); - } - - /** - * Converts an essentia to processing time. - * - * @return True if essentia was consumed, false otherwise. - */ - private boolean consumeEssentia() - { - // Is there anything stored? - if( this.hasStoredEssentia() ) - { - // Get the processing time - int pTime = this.adjustProcessingValues(); - if( pTime > 0 ) - { - // Set the type - this.processingAspect = this.storedEssentia.getAspect(); - this.processingChanged = true; - - // Take one - this.storedEssentia.adjustStackSize( -1 ); - - // Mark dirty - this.markDirty(); - this.markForUpdate(); - - // Add to processing time - this.processingTicksRemaining += pTime; - - return true; - } - } - - return false; - } - - /** - * Adds power to the network. - * - * @param ticksSinceLastCall - * @return - */ - private TickRateModulation doProcessingTick( final int ticksSinceLastCall ) - { - // Is there any processing time remaining? - if( this.processingTicksRemaining == 0 ) - { - return TickRateModulation.IDLE; - } - - // Clap the processing speed - this.clampProcessingSpeed(); - - // Calculate dilation - this.dilation = this.processingSpeed / TileEssentiaVibrationChamber.DILATATION_DIVISOR; - - // Calculate number of processing ticks - double processingTicks = ticksSinceLastCall * this.dilation; - - // Adjust time remaining - this.processingTicksRemaining -= processingTicks; - - // Calculate the goal produced power - this.sync_powerPerTick = ( processingTicks * this.powerProducedPerProcessingTick ) / ticksSinceLastCall; - - // Finished? - if( this.processingTicksRemaining <= 0 ) - { - // Adjust processing time - processingTicks += this.processingTicksRemaining; - - // Reset time - this.processingTicksRemaining = 0; - - // Clear the aspect - this.processingAspect = null; - - // Mark dirty - this.processingChanged = true; - this.markForUpdate(); - this.markDirty(); - } - - // Calculate the actual produced power - double producedPower = processingTicks * this.powerProducedPerProcessingTick; - - // Assume slower - TickRateModulation rate = TickRateModulation.SLOWER; - - try - { - // Get the energy grid - IEnergyGrid eGrid = this.getProxy().getEnergy(); - - // Get rejected amount, note that any rejected amount is simply lost. - double rejectedPower = eGrid.injectPower( producedPower, Actionable.SIMULATE ); - - // Was any rejected? - if( rejectedPower > 0 ) - { - // Adjust the power - producedPower = Math.max( 0, producedPower - rejectedPower ); - - // Adjust speed - this.processingSpeed -= ticksSinceLastCall; - } - else - { - // Increase tickrate - rate = TickRateModulation.FASTER; - - // Adjust speed - this.processingSpeed += ticksSinceLastCall; - } - - // Inject the power - if( producedPower > 0 ) - { - eGrid.injectPower( producedPower, Actionable.MODULATE ); - } - } - catch( GridAccessException g ) - { - // Silently ignore. - } - - return rate; - - } - - /** - * Updates all listening containers. - */ - private void updateListeners() - { - // Fast exit check - if( this.listeners.isEmpty() ) - { - return; - } - - // Cast power per tick - float powerPerTick = (float)this.sync_powerPerTick; - - // Calculate the maximum power per tick - float maxPowerPerTick = (float)( this.powerProducedPerProcessingTick * - ( TileEssentiaVibrationChamber.PROCESS_SPEED_MAX / TileEssentiaVibrationChamber.DILATATION_DIVISOR ) ); - - // Clamp the processing speed - this.clampProcessingSpeed(); - - // Calculate ticks remaining - int ticksRemaining = (int)( this.processingTicksRemaining / this.dilation ); - - // Calculate total ticks - int totalTicks = (int)( this.sync_totalProcessingTicks / this.dilation ); - - // Update listeners - for( ContainerEssentiaVibrationChamber listener : this.listeners ) - { - listener.onChamberUpdate( powerPerTick, maxPowerPerTick, ticksRemaining, totalTicks ); - } - } - - /** - * Adds essentia to the buffer. - * - * @param aspect - * @param amount - * @param mode - * @return - */ - @Override - protected int addEssentia( final Aspect aspect, final int amount, final Actionable mode ) - { - // Validate essentia type - if( ( this.hasStoredEssentia() ) && ( this.storedEssentia.getAspect() != aspect ) ) - { - // Essentia type does not match - return 0; - } - - // Get how much is stored, and the aspect - int storedAmount = ( this.storedEssentia == null ? 0 : (int)this.storedEssentia.getStackSize() ); - Aspect storedAspect = ( this.storedEssentia == null ? null : this.storedEssentia.getAspect() ); - - // Calculate how much to be stored - int addedAmount = Math.min( amount, TileEVCBase.MAX_ESSENTIA_STORED - storedAmount ); - - if( ( addedAmount > 0 ) && ( mode == Actionable.MODULATE ) ) - { - // Create the stack if needed - if( storedAspect == null ) - { - this.storedEssentia = new AspectStack( aspect, 0 ); - } - else - { - this.storedEssentia.setAspect( aspect ); - } - - // Add to the amount - this.storedEssentia.adjustStackSize( addedAmount ); - - // Mark for update - this.markForUpdate(); - - // Mark for save - this.markDirty(); - } - - return addedAmount; - } - - /** - * Reads saved data. - * - * @param data - */ - @Override - protected void NBTRead( final NBTTagCompound data ) - { - // Read time remaining - if( data.hasKey( TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING ) ) - { - this.processingTicksRemaining = data.getInteger( TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING ); - } - - if( this.processingTicksRemaining > 0 ) - { - // Read processing speed - if( data.hasKey( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED ) ) - { - this.processingSpeed = data.getInteger( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED ); - } - - // Read power per tick - if( data.hasKey( TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK ) ) - { - this.powerProducedPerProcessingTick = data.getDouble( TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK ); - } - - // Read aspect - if( data.hasKey( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT ) ) - { - String aspectTag = data.getString( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT ); - this.processingAspect = Aspect.aspects.get( aspectTag ); - this.processingChanged = true; - } - - // Mark to sync with client - this.markForUpdate(); - } - } - - /** - * Saves the data. - * - * @param data - */ - @Override - protected void NBTWrite( final NBTTagCompound data ) - { - if( this.processingTicksRemaining > 0 ) - { - // Write time remaining - data.setInteger( TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING, this.processingTicksRemaining ); - - // Write processing speed - data.setInteger( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED, this.processingSpeed ); - - // Write power per processing tick - data.setDouble( TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK, this.powerProducedPerProcessingTick ); - - // Is there an aspect? - if( this.processingAspect != null ) - { - // Write processing aspect - data.setString( TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT, this.processingAspect.getTag() ); - } - } - } - - /** - * Reads info from the network. - * - * @param stream - */ - @Override - protected void networkRead( final ByteBuf stream ) - { - // Change? - if( stream.readBoolean() ) - { - // Read aspect - this.processingAspect = ThEBasePacket.readAspect( stream ); - } - - } - - /** - * Writes data to the network. - * - * @param stream - */ - @Override - protected void networkWrite( final ByteBuf stream ) - { - // Write change flag - stream.writeBoolean( this.processingChanged ); - - if( this.processingChanged ) - { - // Write aspect - ThEBasePacket.writeAspect( this.processingAspect, stream ); - } - - this.processingChanged = false; - } - - /** - * Adds WAILA tooltip strings. - * - * @param tooltip - */ - @Override - public void addWailaInformation( final List tooltip ) - { - // Write stored - if( this.hasStoredEssentia() ) - { - tooltip.add( String.format( ThEStrings.GUi_VibrationChamber_Stored.getLocalized(), this.storedEssentia.getStackSize(), - this.storedEssentia.getAspectName() ) ); - } - - // Write processing - if( this.processingAspect != null ) - { - tooltip.add( String.format( ThEStrings.GUi_VibrationChamber_Processing.getLocalized(), this.processingAspect.getName() ) ); - } - } - - /** - * Returns what aspect is currently being processed. - * - * @return - */ - public Aspect getProcessingAspect() - { - return this.processingAspect; - } - - /** - * How often to tick? - * - * @param node - * @return - */ - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - // Half second, to 2 seconds. - return new TickingRequest( TileEssentiaVibrationChamber.TICKRATE_MIN, TileEssentiaVibrationChamber.TICKRATE_MAX, false, false ); - - } - - /** - * Returns true if there is data that should be saved during a dismantle. - * - * @return - */ - public boolean hasSaveDataForDismanle() - { - // Anything stored? - if( ( this.storedEssentia != null ) && !this.storedEssentia.isEmpty() ) - { - return true; - } - - // Anything being processed? - if( this.processingTicksRemaining > 0 ) - { - return true; - } - - return false; - } - - /** - * Registers a listener with the EVC - * - * @param listener - */ - public void registerListener( final ContainerEssentiaVibrationChamber listener ) - { - this.listeners.add( listener ); - } - - /** - * Un-registers a listener with the EVC. - * - * @param listener - */ - public void removeListener( final ContainerEssentiaVibrationChamber listener ) - { - this.listeners.remove( listener ); - } - - /** - * This should only be called when the EVC is being dismantled. - */ - public void resetForDismantle() - { - this.processingSpeed = TileEssentiaVibrationChamber.PROCESS_SPEED_MIN; - this.processingTicksRemaining = 0; - } - - /** - * Called when the network ticks. - * - * @param node - * @param ticksSinceLastCall - * @return - */ - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - boolean replenish = false; - - TickRateModulation rate = TickRateModulation.IDLE; - - // Is there any processing time remaining? - if( this.processingTicksRemaining > 0 ) - { - // Process the essentia - rate = this.doProcessingTick( ticksSinceLastCall ); - } - else - { - // No longer producing power - this.sync_powerPerTick = 0; - - // Reset speed - this.processingSpeed = TileEssentiaVibrationChamber.PROCESS_SPEED_MIN; - } - - // Is there anything stored? - if( this.hasStoredEssentia() ) - { - // Is the chamber idle? - if( this.processingTicksRemaining == 0 ) - { - // Can essentia be consumed? - if( this.consumeEssentia() ) - { - rate = TickRateModulation.URGENT; - } - } - - // Is the buffer not full? - if( this.storedEssentia.getStackSize() < TileEVCBase.MAX_ESSENTIA_STORED ) - { - // Replenish if possible - replenish = true; - } - } - else - { - // Replenish if possible - replenish = true; - } - - // Does the essentia need to be replenished? - if( replenish ) - { - // Replenish essentia - EssentiaTransportHelper.INSTANCE.takeEssentiaFromTransportNeighbors( this, this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - - // Update listeners - this.updateListeners(); - - return rate; - } - +public class TileEssentiaVibrationChamber extends TileEVCBase implements IGridTickable, IWailaSource { + private static String NBTKEY_TIME_REMAINING = "TRemain", + NBTKEY_PROCESSING_SPEED = "ProcSpeed", + NBTKEY_POWER_PER_TICK = "PwrPerTick", + NBTKEY_PROCESSING_ASPECT = "ProcAspect"; + + /** + * How much power is produced per tick + */ + private static final double BASE_POWER_PER_TICK = 5.0; + + /** + * Half second. + */ + private static final int TICKRATE_MIN = 10; + + /** + * Two seconds. + */ + private static final int TICKRATE_MAX = 40; + + /** + * Min and Max processing speed + */ + private static final int PROCESS_SPEED_MAX = 200, PROCESS_SPEED_MIN = 20; + + /** + * Adjusts processing speed. + */ + private static final double DILATATION_DIVISOR = 100; + + /** + * How long it takes coal to burn + */ + private static int coalBurnTime = 0; + + /** + * Time dilation amount + */ + private double dilation = 1.0F; + + /** + * How much longer the essentia will be processed, in ticks. + */ + private int processingTicksRemaining = 0; + + /** + * How fast processing is occurring. + */ + private int processingSpeed = 0; + + /** + * How much power is produced per processing tick. + * Note: This is not the same as a minecraft tick. Processing ticks are dilated by processing speed. + */ + private double powerProducedPerProcessingTick = 0; + + /** + * What aspect is currently being processed. + */ + private Aspect processingAspect = null; + + /** + * Set true when the aspect changed. + */ + private boolean processingChanged = false; + + /** + * The total amount of processing ticks for the current aspect. + * Used for GUI. + */ + private int sync_totalProcessingTicks = 0; + + /** + * How much power is being produced per tick. + * Used for GUI. + */ + private double sync_powerPerTick = 0; + + /** + * Players who have the GUI open. + */ + private final Set listeners = new HashSet(); + + /** + * Adjusts processing time and power production based on essentia type. + * + * @return + */ + private int adjustProcessingValues() { + int pTime = 0; + + // Has the burn time of coal been retrieved? + if (TileEssentiaVibrationChamber.coalBurnTime == 0) { + // Get the base processing time of coal + TileEssentiaVibrationChamber.coalBurnTime = TileEntityFurnace.getItemBurnTime(new ItemStack(Items.coal)); + } + + // What kind of essentia is stored? + if (this.storedEssentia.getAspect() == Aspect.FIRE) { + pTime = TileEssentiaVibrationChamber.coalBurnTime / 2; + this.powerProducedPerProcessingTick = TileEssentiaVibrationChamber.BASE_POWER_PER_TICK * 1.0D; + } else if (this.storedEssentia.getAspect() == Aspect.ENERGY) { + pTime = (int) (TileEssentiaVibrationChamber.coalBurnTime / 1.6F); + this.powerProducedPerProcessingTick = TileEssentiaVibrationChamber.BASE_POWER_PER_TICK * 1.6D; + } + + // Set the total + this.sync_totalProcessingTicks = pTime; + + return pTime; + } + + /** + * Clamps the processing speed to the min-max constants. + */ + private void clampProcessingSpeed() { + this.processingSpeed = Math.max( + TileEssentiaVibrationChamber.PROCESS_SPEED_MIN, + Math.min(TileEssentiaVibrationChamber.PROCESS_SPEED_MAX, this.processingSpeed)); + } + + /** + * Converts an essentia to processing time. + * + * @return True if essentia was consumed, false otherwise. + */ + private boolean consumeEssentia() { + // Is there anything stored? + if (this.hasStoredEssentia()) { + // Get the processing time + int pTime = this.adjustProcessingValues(); + if (pTime > 0) { + // Set the type + this.processingAspect = this.storedEssentia.getAspect(); + this.processingChanged = true; + + // Take one + this.storedEssentia.adjustStackSize(-1); + + // Mark dirty + this.markDirty(); + this.markForUpdate(); + + // Add to processing time + this.processingTicksRemaining += pTime; + + return true; + } + } + + return false; + } + + /** + * Adds power to the network. + * + * @param ticksSinceLastCall + * @return + */ + private TickRateModulation doProcessingTick(final int ticksSinceLastCall) { + // Is there any processing time remaining? + if (this.processingTicksRemaining == 0) { + return TickRateModulation.IDLE; + } + + // Clap the processing speed + this.clampProcessingSpeed(); + + // Calculate dilation + this.dilation = this.processingSpeed / TileEssentiaVibrationChamber.DILATATION_DIVISOR; + + // Calculate number of processing ticks + double processingTicks = ticksSinceLastCall * this.dilation; + + // Adjust time remaining + this.processingTicksRemaining -= processingTicks; + + // Calculate the goal produced power + this.sync_powerPerTick = (processingTicks * this.powerProducedPerProcessingTick) / ticksSinceLastCall; + + // Finished? + if (this.processingTicksRemaining <= 0) { + // Adjust processing time + processingTicks += this.processingTicksRemaining; + + // Reset time + this.processingTicksRemaining = 0; + + // Clear the aspect + this.processingAspect = null; + + // Mark dirty + this.processingChanged = true; + this.markForUpdate(); + this.markDirty(); + } + + // Calculate the actual produced power + double producedPower = processingTicks * this.powerProducedPerProcessingTick; + + // Assume slower + TickRateModulation rate = TickRateModulation.SLOWER; + + try { + // Get the energy grid + IEnergyGrid eGrid = this.getProxy().getEnergy(); + + // Get rejected amount, note that any rejected amount is simply lost. + double rejectedPower = eGrid.injectPower(producedPower, Actionable.SIMULATE); + + // Was any rejected? + if (rejectedPower > 0) { + // Adjust the power + producedPower = Math.max(0, producedPower - rejectedPower); + + // Adjust speed + this.processingSpeed -= ticksSinceLastCall; + } else { + // Increase tickrate + rate = TickRateModulation.FASTER; + + // Adjust speed + this.processingSpeed += ticksSinceLastCall; + } + + // Inject the power + if (producedPower > 0) { + eGrid.injectPower(producedPower, Actionable.MODULATE); + } + } catch (GridAccessException g) { + // Silently ignore. + } + + return rate; + } + + /** + * Updates all listening containers. + */ + private void updateListeners() { + // Fast exit check + if (this.listeners.isEmpty()) { + return; + } + + // Cast power per tick + float powerPerTick = (float) this.sync_powerPerTick; + + // Calculate the maximum power per tick + float maxPowerPerTick = (float) (this.powerProducedPerProcessingTick + * (TileEssentiaVibrationChamber.PROCESS_SPEED_MAX / TileEssentiaVibrationChamber.DILATATION_DIVISOR)); + + // Clamp the processing speed + this.clampProcessingSpeed(); + + // Calculate ticks remaining + int ticksRemaining = (int) (this.processingTicksRemaining / this.dilation); + + // Calculate total ticks + int totalTicks = (int) (this.sync_totalProcessingTicks / this.dilation); + + // Update listeners + for (ContainerEssentiaVibrationChamber listener : this.listeners) { + listener.onChamberUpdate(powerPerTick, maxPowerPerTick, ticksRemaining, totalTicks); + } + } + + /** + * Adds essentia to the buffer. + * + * @param aspect + * @param amount + * @param mode + * @return + */ + @Override + protected int addEssentia(final Aspect aspect, final int amount, final Actionable mode) { + // Validate essentia type + if ((this.hasStoredEssentia()) && (this.storedEssentia.getAspect() != aspect)) { + // Essentia type does not match + return 0; + } + + // Get how much is stored, and the aspect + int storedAmount = (this.storedEssentia == null ? 0 : (int) this.storedEssentia.getStackSize()); + Aspect storedAspect = (this.storedEssentia == null ? null : this.storedEssentia.getAspect()); + + // Calculate how much to be stored + int addedAmount = Math.min(amount, TileEVCBase.MAX_ESSENTIA_STORED - storedAmount); + + if ((addedAmount > 0) && (mode == Actionable.MODULATE)) { + // Create the stack if needed + if (storedAspect == null) { + this.storedEssentia = new AspectStack(aspect, 0); + } else { + this.storedEssentia.setAspect(aspect); + } + + // Add to the amount + this.storedEssentia.adjustStackSize(addedAmount); + + // Mark for update + this.markForUpdate(); + + // Mark for save + this.markDirty(); + } + + return addedAmount; + } + + /** + * Reads saved data. + * + * @param data + */ + @Override + protected void NBTRead(final NBTTagCompound data) { + // Read time remaining + if (data.hasKey(TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING)) { + this.processingTicksRemaining = data.getInteger(TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING); + } + + if (this.processingTicksRemaining > 0) { + // Read processing speed + if (data.hasKey(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED)) { + this.processingSpeed = data.getInteger(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED); + } + + // Read power per tick + if (data.hasKey(TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK)) { + this.powerProducedPerProcessingTick = + data.getDouble(TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK); + } + + // Read aspect + if (data.hasKey(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT)) { + String aspectTag = data.getString(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT); + this.processingAspect = Aspect.aspects.get(aspectTag); + this.processingChanged = true; + } + + // Mark to sync with client + this.markForUpdate(); + } + } + + /** + * Saves the data. + * + * @param data + */ + @Override + protected void NBTWrite(final NBTTagCompound data) { + if (this.processingTicksRemaining > 0) { + // Write time remaining + data.setInteger(TileEssentiaVibrationChamber.NBTKEY_TIME_REMAINING, this.processingTicksRemaining); + + // Write processing speed + data.setInteger(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_SPEED, this.processingSpeed); + + // Write power per processing tick + data.setDouble(TileEssentiaVibrationChamber.NBTKEY_POWER_PER_TICK, this.powerProducedPerProcessingTick); + + // Is there an aspect? + if (this.processingAspect != null) { + // Write processing aspect + data.setString(TileEssentiaVibrationChamber.NBTKEY_PROCESSING_ASPECT, this.processingAspect.getTag()); + } + } + } + + /** + * Reads info from the network. + * + * @param stream + */ + @Override + protected void networkRead(final ByteBuf stream) { + // Change? + if (stream.readBoolean()) { + // Read aspect + this.processingAspect = ThEBasePacket.readAspect(stream); + } + } + + /** + * Writes data to the network. + * + * @param stream + */ + @Override + protected void networkWrite(final ByteBuf stream) { + // Write change flag + stream.writeBoolean(this.processingChanged); + + if (this.processingChanged) { + // Write aspect + ThEBasePacket.writeAspect(this.processingAspect, stream); + } + + this.processingChanged = false; + } + + /** + * Adds WAILA tooltip strings. + * + * @param tooltip + */ + @Override + public void addWailaInformation(final List tooltip) { + // Write stored + if (this.hasStoredEssentia()) { + tooltip.add(String.format( + ThEStrings.GUi_VibrationChamber_Stored.getLocalized(), + this.storedEssentia.getStackSize(), + this.storedEssentia.getAspectName())); + } + + // Write processing + if (this.processingAspect != null) { + tooltip.add(String.format( + ThEStrings.GUi_VibrationChamber_Processing.getLocalized(), this.processingAspect.getName())); + } + } + + /** + * Returns what aspect is currently being processed. + * + * @return + */ + public Aspect getProcessingAspect() { + return this.processingAspect; + } + + /** + * How often to tick? + * + * @param node + * @return + */ + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + // Half second, to 2 seconds. + return new TickingRequest( + TileEssentiaVibrationChamber.TICKRATE_MIN, TileEssentiaVibrationChamber.TICKRATE_MAX, false, false); + } + + /** + * Returns true if there is data that should be saved during a dismantle. + * + * @return + */ + public boolean hasSaveDataForDismanle() { + // Anything stored? + if ((this.storedEssentia != null) && !this.storedEssentia.isEmpty()) { + return true; + } + + // Anything being processed? + if (this.processingTicksRemaining > 0) { + return true; + } + + return false; + } + + /** + * Registers a listener with the EVC + * + * @param listener + */ + public void registerListener(final ContainerEssentiaVibrationChamber listener) { + this.listeners.add(listener); + } + + /** + * Un-registers a listener with the EVC. + * + * @param listener + */ + public void removeListener(final ContainerEssentiaVibrationChamber listener) { + this.listeners.remove(listener); + } + + /** + * This should only be called when the EVC is being dismantled. + */ + public void resetForDismantle() { + this.processingSpeed = TileEssentiaVibrationChamber.PROCESS_SPEED_MIN; + this.processingTicksRemaining = 0; + } + + /** + * Called when the network ticks. + * + * @param node + * @param ticksSinceLastCall + * @return + */ + @Override + public TickRateModulation tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + boolean replenish = false; + + TickRateModulation rate = TickRateModulation.IDLE; + + // Is there any processing time remaining? + if (this.processingTicksRemaining > 0) { + // Process the essentia + rate = this.doProcessingTick(ticksSinceLastCall); + } else { + // No longer producing power + this.sync_powerPerTick = 0; + + // Reset speed + this.processingSpeed = TileEssentiaVibrationChamber.PROCESS_SPEED_MIN; + } + + // Is there anything stored? + if (this.hasStoredEssentia()) { + // Is the chamber idle? + if (this.processingTicksRemaining == 0) { + // Can essentia be consumed? + if (this.consumeEssentia()) { + rate = TickRateModulation.URGENT; + } + } + + // Is the buffer not full? + if (this.storedEssentia.getStackSize() < TileEVCBase.MAX_ESSENTIA_STORED) { + // Replenish if possible + replenish = true; + } + } else { + // Replenish if possible + replenish = true; + } + + // Does the essentia need to be replenished? + if (replenish) { + // Replenish essentia + EssentiaTransportHelper.INSTANCE.takeEssentiaFromTransportNeighbors( + this, this.worldObj, this.xCoord, this.yCoord, this.zCoord); + } + + // Update listeners + this.updateListeners(); + + return rate; + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileGearBox.java b/src/main/java/thaumicenergistics/common/tiles/TileGearBox.java index 4c32cb9d..77ad8aa0 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileGearBox.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileGearBox.java @@ -18,465 +18,422 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public class TileGearBox - extends TileEntity -{ - /** - * Amount of power generated each time the gearbox is cranked. - * This power is divided among the connected shafts. - */ - private static final int BASE_POWER = 6; - - /** - * How much shaft power is required to apply a turn? - */ - private static final int REQUIRED_POWER = 18; - - /** - * Number of valid sides. - */ - private static final int SIDE_COUNT = ForgeDirection.VALID_DIRECTIONS.length; - - /** - * The number of ticks required to pass before a sync packet can be sent. - */ - private static final int MIN_TICKS_PER_SYNC = 6; - - /** - * One full rotation(PI) - */ - private static final float FULL_ROTATION = (float)Math.PI; - - /** - * NBT Keys - */ - private static final String NBT_KEY_CRANKABLES = "crankables", NBT_KEY_ROTATION = "shaftrotation", NBT_KEY_ISTHAUMBOX = "isthaumbox"; - - /** - * Tracks the amount of power being sent per side - */ - private int[] shafts = new int[SIDE_COUNT]; - - /** - * Stores the located crankables. - */ - private ICrankable[] crankables = new ICrankable[SIDE_COUNT]; - - /** - * Tracks if the crankable can be turned. - */ - private boolean[] canTurn = new boolean[TileGearBox.SIDE_COUNT]; - - /** - * The number of crankable tiles attached to the gearbox. - */ - private int crankableCount = -1; - - /** - * Is this tile a thaumium gearbox? - */ - private boolean isThaumiumGearbox = false; - - /** - * Set to true when the tile entity is ready. - */ - private boolean isReady = false; - - /** - * Tracks if there have been new cranks since the last tick. - */ - private boolean hasNewCranks = false; - - /** - * Counts the number of ticks since the last(potential) sync. - */ - private int syncTickCount = 0; - - /** - * True if the side is facing a crankable. - */ - public boolean[] sideIsFacingCrankable = new boolean[TileGearBox.SIDE_COUNT]; - - /** - * The current amount of shaft rotation. - */ - public float shaftRotation = 0.0F; - - /** - * Default constructor. - */ - public TileGearBox() - { - // Intentionally Empty - } - - /** - * Constructor used for item rendering. - * - * @param isThaumium - */ - public TileGearBox( final boolean isThaumium ) - { - this.isThaumiumGearbox = isThaumium; - } - - /** - * Calculates the amount of power to send to each crank. - * - * @return - */ - private int calculateTransferPower() - { - // Number of crankables that can turn. - int powerDivisor = 0; - - // Calculate how many can accept a turn - for( int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++ ) - { - ICrankable c = this.crankables[sideIndex]; - if( ( c != null ) && ( c.canTurn() ) ) - { - this.canTurn[sideIndex] = true; - powerDivisor++ ; - } - } - - // Can any turn? - if( powerDivisor == 0 ) - { - // None can turn - return 0; - } - - // Calculate the amount of power to send to each - return TileGearBox.BASE_POWER / powerDivisor; - } - - /** - * Called when the tile entity is made, placed, and ready to use! - */ - private void onReady() - { - // Update the crankables - this.updateCrankables(); - - // Is the tile a thaumium gearbox? - this.isThaumiumGearbox = ( this.worldObj.getBlock( this.xCoord, this.yCoord, this.zCoord ) instanceof BlockGolemGearBox ); - - // Mark the tile as ready - this.isReady = true; - } - - /** - * Reads Server->Client sync data from the specified NBT tag. - * - * @param data - */ - private void readSyncData( final NBTTagCompound data ) - { - // Does that data have the crankables tag? - if( data.hasKey( TileGearBox.NBT_KEY_CRANKABLES ) ) - { - // Read the flags byte - byte crankableFlags = data.getByte( TileGearBox.NBT_KEY_CRANKABLES ); - - // Set the array - for( int i = 0; i < TileGearBox.SIDE_COUNT; i++ ) - { - this.sideIsFacingCrankable[i] = ( ( crankableFlags & ( (int)Math.pow( 2, i ) ) ) != 0 ); - } - } - - // Does the data have the rotation tag? - if( data.hasKey( TileGearBox.NBT_KEY_ROTATION ) ) - { - // Should rotation be added? - if( this.shaftRotation < 1.0F ) - { - // Add rotation. - this.shaftRotation += TileGearBox.FULL_ROTATION * 2; - } - } - - // Does the data have the thaum box tag? - if( data.hasKey( TileGearBox.NBT_KEY_ISTHAUMBOX ) ) - { - this.isThaumiumGearbox = data.getBoolean( TileGearBox.NBT_KEY_ISTHAUMBOX ); - } - } - - /** - * Applies the specified power to each shaft. - * Once a shaft has enough stored power, it applies a turn to - * its crankable. - * - * @param powerTransfered - */ - private void updateShafts( final int powerTransfered ) - { - for( int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++ ) - { - // Can this side turn? - if( this.canTurn[sideIndex] && ( this.crankables[sideIndex] != null ) ) - { - // Does it have enough power to turn the grinder? - if( ( this.shafts[sideIndex] += powerTransfered ) >= TileGearBox.REQUIRED_POWER ) - { - // Reset the power - this.shafts[sideIndex] = 0; - - // Turn it - this.crankables[sideIndex].applyTurn(); - } - } - else - { - // No power is going to this side. - this.shafts[sideIndex] = 0; - } - } - } - - /** - * Writes Server->Client sync data to the specified NBT tag. - * - * @param data - */ - private void writeSyncDataToNBT( final NBTTagCompound data ) - { - // Call on ready? - if( !this.isReady ) - { - this.onReady(); - } - - // Create a byte of flags marking if each side has a crankable next to it - byte crankableFlags = 0; - for( int i = 0; i < TileGearBox.SIDE_COUNT; i++ ) - { - if( this.sideIsFacingCrankable[i] ) - { - crankableFlags |= (int)Math.pow( 2, i ); - } - } - - // Write the flags - data.setByte( TileGearBox.NBT_KEY_CRANKABLES, crankableFlags ); - - // Write has new cranks - if( this.hasNewCranks ) - { - data.setBoolean( TileGearBox.NBT_KEY_ROTATION, true ); - - // Clear the flag - this.hasNewCranks = false; - } - - // Write is thaumium gearbox - data.setBoolean( TileGearBox.NBT_KEY_ISTHAUMBOX, this.isThaumiumGearbox ); - } - - /** - * Gearbox would like ticks; - */ - @Override - public boolean canUpdate() - { - return true; - } - - /** - * Cranks the gearbox. - * - * @return - */ - public boolean crankGearbox() - { - // Don't do work on client side - if( EffectiveSide.isClientSide() ) - { - return true; - } - - // Are there any crankables? - if( this.crankableCount <= 0 ) - { - // Nothing to crank. - return false; - } - - // Get the power transfer amount - int powerTransfered = this.calculateTransferPower(); - - // Ensure there is some power to transfer - if( powerTransfered == 0 ) - { - // Nothing to crank - return false; - } - - // Update the shafts - this.updateShafts( powerTransfered ); - - // Mark there are new cranks - this.hasNewCranks = true; - - // Did work - return true; - - } - - /** - * Creates the Server->Client sync data packet. - */ - @Override - public Packet getDescriptionPacket() - { - // Create the tag - NBTTagCompound data = new NBTTagCompound(); - - // Write the sync data - this.writeSyncDataToNBT( data ); - - // Send the packet - return new S35PacketUpdateTileEntity( this.xCoord, this.yCoord, this.zCoord, 1, data ); - } - - /** - * Returns true if this is a thaumium gearbox, false if iron gearbox. - * - * @return - */ - public boolean isThaumiumGearbox() - { - return this.isThaumiumGearbox; - } - - /** - * Called when a Server->Client sync data packet arrives. - */ - @Override - @SideOnly(Side.CLIENT) - public void onDataPacket( final NetworkManager net, final S35PacketUpdateTileEntity packet ) - { - // Read the sync data - this.readSyncData( packet.func_148857_g() ); - } - - /* - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); - - // Read crankables - this.readSyncData( data ); - }*/ - - /** - * Locates attached crankables. - * - * @return Number of attached crankables found. - */ - public void updateCrankables() - { - // Reset attached to zero - this.crankableCount = 0; - - // Check all sides - for( int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++ ) - { - // Get the side - ForgeDirection side = ForgeDirection.VALID_DIRECTIONS[sideIndex]; - - // Assume there is not a crankable - this.crankables[sideIndex] = null; - this.sideIsFacingCrankable[sideIndex] = false; - - // Get the tile - TileEntity tile = this.worldObj.getTileEntity( side.offsetX + this.xCoord, side.offsetY + this.yCoord, side.offsetZ + this.zCoord ); - - // Is there a crankable? - if( !( tile instanceof ICrankable ) ) - { - continue; - } - - // Get the crankable - ICrankable crank = (ICrankable)tile; - - // Is it facing the correct direction? - if( crank.canCrankAttach( side.getOpposite() ) ) - { - // Increment the crankable count - this.crankableCount++ ; - - // Mark there is a crankable. - this.crankables[sideIndex] = crank; - this.sideIsFacingCrankable[sideIndex] = true; - } - - } - } - - /** - * Called during each tick. - */ - @Override - public void updateEntity() - { - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Increment the tick count - this.syncTickCount++ ; - - // Have enough ticks elapsed? - if( this.syncTickCount >= TileGearBox.MIN_TICKS_PER_SYNC ) - { - // Decrement the tick count - this.syncTickCount-- ; - - // Is there rotation to send? - if( this.hasNewCranks ) - { - // Mark for update - this.worldObj.markBlockForUpdate( this.xCoord, this.yCoord, this.zCoord ); - - // Reset the counter - this.syncTickCount = 0; - } - } - } - // Client side - else - { - // Is there rotation? - if( this.shaftRotation != 0 ) - { - // Adjust rotation - this.shaftRotation -= 0.20F; - - // Has the rotation exceeded epsilon? - if( this.shaftRotation < 0.001F ) - { - // Stop rotation. - this.shaftRotation = 0; - } - } - } - } - - /* - @Override - public void writeToNBT( final NBTTagCompound data ) - { - // Call super - super.writeToNBT( data ); - - // Write sync data - this.writeSyncDataToNBT( data ); - } - */ +public class TileGearBox extends TileEntity { + /** + * Amount of power generated each time the gearbox is cranked. + * This power is divided among the connected shafts. + */ + private static final int BASE_POWER = 6; + + /** + * How much shaft power is required to apply a turn? + */ + private static final int REQUIRED_POWER = 18; + + /** + * Number of valid sides. + */ + private static final int SIDE_COUNT = ForgeDirection.VALID_DIRECTIONS.length; + + /** + * The number of ticks required to pass before a sync packet can be sent. + */ + private static final int MIN_TICKS_PER_SYNC = 6; + + /** + * One full rotation(PI) + */ + private static final float FULL_ROTATION = (float) Math.PI; + + /** + * NBT Keys + */ + private static final String NBT_KEY_CRANKABLES = "crankables", + NBT_KEY_ROTATION = "shaftrotation", + NBT_KEY_ISTHAUMBOX = "isthaumbox"; + + /** + * Tracks the amount of power being sent per side + */ + private int[] shafts = new int[SIDE_COUNT]; + + /** + * Stores the located crankables. + */ + private ICrankable[] crankables = new ICrankable[SIDE_COUNT]; + + /** + * Tracks if the crankable can be turned. + */ + private boolean[] canTurn = new boolean[TileGearBox.SIDE_COUNT]; + + /** + * The number of crankable tiles attached to the gearbox. + */ + private int crankableCount = -1; + + /** + * Is this tile a thaumium gearbox? + */ + private boolean isThaumiumGearbox = false; + + /** + * Set to true when the tile entity is ready. + */ + private boolean isReady = false; + + /** + * Tracks if there have been new cranks since the last tick. + */ + private boolean hasNewCranks = false; + + /** + * Counts the number of ticks since the last(potential) sync. + */ + private int syncTickCount = 0; + + /** + * True if the side is facing a crankable. + */ + public boolean[] sideIsFacingCrankable = new boolean[TileGearBox.SIDE_COUNT]; + + /** + * The current amount of shaft rotation. + */ + public float shaftRotation = 0.0F; + + /** + * Default constructor. + */ + public TileGearBox() { + // Intentionally Empty + } + + /** + * Constructor used for item rendering. + * + * @param isThaumium + */ + public TileGearBox(final boolean isThaumium) { + this.isThaumiumGearbox = isThaumium; + } + + /** + * Calculates the amount of power to send to each crank. + * + * @return + */ + private int calculateTransferPower() { + // Number of crankables that can turn. + int powerDivisor = 0; + + // Calculate how many can accept a turn + for (int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++) { + ICrankable c = this.crankables[sideIndex]; + if ((c != null) && (c.canTurn())) { + this.canTurn[sideIndex] = true; + powerDivisor++; + } + } + + // Can any turn? + if (powerDivisor == 0) { + // None can turn + return 0; + } + + // Calculate the amount of power to send to each + return TileGearBox.BASE_POWER / powerDivisor; + } + + /** + * Called when the tile entity is made, placed, and ready to use! + */ + private void onReady() { + // Update the crankables + this.updateCrankables(); + + // Is the tile a thaumium gearbox? + this.isThaumiumGearbox = + (this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord) instanceof BlockGolemGearBox); + + // Mark the tile as ready + this.isReady = true; + } + + /** + * Reads Server->Client sync data from the specified NBT tag. + * + * @param data + */ + private void readSyncData(final NBTTagCompound data) { + // Does that data have the crankables tag? + if (data.hasKey(TileGearBox.NBT_KEY_CRANKABLES)) { + // Read the flags byte + byte crankableFlags = data.getByte(TileGearBox.NBT_KEY_CRANKABLES); + + // Set the array + for (int i = 0; i < TileGearBox.SIDE_COUNT; i++) { + this.sideIsFacingCrankable[i] = ((crankableFlags & ((int) Math.pow(2, i))) != 0); + } + } + + // Does the data have the rotation tag? + if (data.hasKey(TileGearBox.NBT_KEY_ROTATION)) { + // Should rotation be added? + if (this.shaftRotation < 1.0F) { + // Add rotation. + this.shaftRotation += TileGearBox.FULL_ROTATION * 2; + } + } + + // Does the data have the thaum box tag? + if (data.hasKey(TileGearBox.NBT_KEY_ISTHAUMBOX)) { + this.isThaumiumGearbox = data.getBoolean(TileGearBox.NBT_KEY_ISTHAUMBOX); + } + } + + /** + * Applies the specified power to each shaft. + * Once a shaft has enough stored power, it applies a turn to + * its crankable. + * + * @param powerTransfered + */ + private void updateShafts(final int powerTransfered) { + for (int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++) { + // Can this side turn? + if (this.canTurn[sideIndex] && (this.crankables[sideIndex] != null)) { + // Does it have enough power to turn the grinder? + if ((this.shafts[sideIndex] += powerTransfered) >= TileGearBox.REQUIRED_POWER) { + // Reset the power + this.shafts[sideIndex] = 0; + + // Turn it + this.crankables[sideIndex].applyTurn(); + } + } else { + // No power is going to this side. + this.shafts[sideIndex] = 0; + } + } + } + + /** + * Writes Server->Client sync data to the specified NBT tag. + * + * @param data + */ + private void writeSyncDataToNBT(final NBTTagCompound data) { + // Call on ready? + if (!this.isReady) { + this.onReady(); + } + + // Create a byte of flags marking if each side has a crankable next to it + byte crankableFlags = 0; + for (int i = 0; i < TileGearBox.SIDE_COUNT; i++) { + if (this.sideIsFacingCrankable[i]) { + crankableFlags |= (int) Math.pow(2, i); + } + } + + // Write the flags + data.setByte(TileGearBox.NBT_KEY_CRANKABLES, crankableFlags); + + // Write has new cranks + if (this.hasNewCranks) { + data.setBoolean(TileGearBox.NBT_KEY_ROTATION, true); + + // Clear the flag + this.hasNewCranks = false; + } + + // Write is thaumium gearbox + data.setBoolean(TileGearBox.NBT_KEY_ISTHAUMBOX, this.isThaumiumGearbox); + } + + /** + * Gearbox would like ticks; + */ + @Override + public boolean canUpdate() { + return true; + } + + /** + * Cranks the gearbox. + * + * @return + */ + public boolean crankGearbox() { + // Don't do work on client side + if (EffectiveSide.isClientSide()) { + return true; + } + + // Are there any crankables? + if (this.crankableCount <= 0) { + // Nothing to crank. + return false; + } + + // Get the power transfer amount + int powerTransfered = this.calculateTransferPower(); + + // Ensure there is some power to transfer + if (powerTransfered == 0) { + // Nothing to crank + return false; + } + + // Update the shafts + this.updateShafts(powerTransfered); + + // Mark there are new cranks + this.hasNewCranks = true; + + // Did work + return true; + } + + /** + * Creates the Server->Client sync data packet. + */ + @Override + public Packet getDescriptionPacket() { + // Create the tag + NBTTagCompound data = new NBTTagCompound(); + + // Write the sync data + this.writeSyncDataToNBT(data); + + // Send the packet + return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, data); + } + + /** + * Returns true if this is a thaumium gearbox, false if iron gearbox. + * + * @return + */ + public boolean isThaumiumGearbox() { + return this.isThaumiumGearbox; + } + + /** + * Called when a Server->Client sync data packet arrives. + */ + @Override + @SideOnly(Side.CLIENT) + public void onDataPacket(final NetworkManager net, final S35PacketUpdateTileEntity packet) { + // Read the sync data + this.readSyncData(packet.func_148857_g()); + } + + /* + @Override + public void readFromNBT( final NBTTagCompound data ) + { + // Call super + super.readFromNBT( data ); + + // Read crankables + this.readSyncData( data ); + }*/ + + /** + * Locates attached crankables. + * + * @return Number of attached crankables found. + */ + public void updateCrankables() { + // Reset attached to zero + this.crankableCount = 0; + + // Check all sides + for (int sideIndex = 0; sideIndex < TileGearBox.SIDE_COUNT; sideIndex++) { + // Get the side + ForgeDirection side = ForgeDirection.VALID_DIRECTIONS[sideIndex]; + + // Assume there is not a crankable + this.crankables[sideIndex] = null; + this.sideIsFacingCrankable[sideIndex] = false; + + // Get the tile + TileEntity tile = this.worldObj.getTileEntity( + side.offsetX + this.xCoord, side.offsetY + this.yCoord, side.offsetZ + this.zCoord); + + // Is there a crankable? + if (!(tile instanceof ICrankable)) { + continue; + } + + // Get the crankable + ICrankable crank = (ICrankable) tile; + + // Is it facing the correct direction? + if (crank.canCrankAttach(side.getOpposite())) { + // Increment the crankable count + this.crankableCount++; + + // Mark there is a crankable. + this.crankables[sideIndex] = crank; + this.sideIsFacingCrankable[sideIndex] = true; + } + } + } + + /** + * Called during each tick. + */ + @Override + public void updateEntity() { + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Increment the tick count + this.syncTickCount++; + + // Have enough ticks elapsed? + if (this.syncTickCount >= TileGearBox.MIN_TICKS_PER_SYNC) { + // Decrement the tick count + this.syncTickCount--; + + // Is there rotation to send? + if (this.hasNewCranks) { + // Mark for update + this.worldObj.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); + + // Reset the counter + this.syncTickCount = 0; + } + } + } + // Client side + else { + // Is there rotation? + if (this.shaftRotation != 0) { + // Adjust rotation + this.shaftRotation -= 0.20F; + + // Has the rotation exceeded epsilon? + if (this.shaftRotation < 0.001F) { + // Stop rotation. + this.shaftRotation = 0; + } + } + } + } + + /* + @Override + public void writeToNBT( final NBTTagCompound data ) + { + // Call super + super.writeToNBT( data ); + + // Write sync data + this.writeSyncDataToNBT( data ); + } + */ } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileInfusionProvider.java b/src/main/java/thaumicenergistics/common/tiles/TileInfusionProvider.java index e48915e5..9f1f5140 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileInfusionProvider.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileInfusionProvider.java @@ -14,120 +14,102 @@ import thaumicenergistics.common.tiles.abstraction.TileProviderBase; * @author Nividica * */ -public class TileInfusionProvider - extends TileProviderBase - implements IAspectSource -{ - /** - * Shows runes on the infusion provider. - * - * @param aspectColor - */ - private void doParticalFX( final int aspectColor ) - { - // Convert each color to percentage - float red = ( aspectColor & 0xFF0000 ) / (float)0xFF0000; - float green = ( aspectColor & 0x00FF00 ) / (float)0x00FF00; - float blue = ( aspectColor & 0x0000FF ) / (float)0x0000FF; +public class TileInfusionProvider extends TileProviderBase implements IAspectSource { + /** + * Shows runes on the infusion provider. + * + * @param aspectColor + */ + private void doParticalFX(final int aspectColor) { + // Convert each color to percentage + float red = (aspectColor & 0xFF0000) / (float) 0xFF0000; + float green = (aspectColor & 0x00FF00) / (float) 0x00FF00; + float blue = (aspectColor & 0x0000FF) / (float) 0x0000FF; - // Add particles - for( int i = 0; i < 5; i++ ) - { - Thaumcraft.proxy.blockRunes( this.worldObj, this.xCoord, this.yCoord, this.zCoord, red, green, blue, 15, -0.1F ); - } - for( int i = 0; i < 5; i++ ) - { - Thaumcraft.proxy.blockRunes( this.worldObj, this.xCoord, this.yCoord, this.zCoord, red, green, blue, 15, 0.1F ); - } - } + // Add particles + for (int i = 0; i < 5; i++) { + Thaumcraft.proxy.blockRunes( + this.worldObj, this.xCoord, this.yCoord, this.zCoord, red, green, blue, 15, -0.1F); + } + for (int i = 0; i < 5; i++) { + Thaumcraft.proxy.blockRunes( + this.worldObj, this.xCoord, this.yCoord, this.zCoord, red, green, blue, 15, 0.1F); + } + } - /** - * How much power does this require just to be active? - */ - @Override - protected double getIdlePowerusage() - { - return 5.0; - } + /** + * How much power does this require just to be active? + */ + @Override + protected double getIdlePowerusage() { + return 5.0; + } - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - // Return the itemstack the visually represents this tile - return ThEApi.instance().blocks().InfusionProvider.getStack(); + @Override + protected ItemStack getItemFromTile(final Object obj) { + // Return the itemstack the visually represents this tile + return ThEApi.instance().blocks().InfusionProvider.getStack(); + } - } + @Override + public int addToContainer(final Aspect tag, final int amount) { + // Ignored + return 0; + } - @Override - public int addToContainer( final Aspect tag, final int amount ) - { - // Ignored - return 0; - } + @Override + public int containerContains(final Aspect tag) { + // Ignored + return 0; + } - @Override - public int containerContains( final Aspect tag ) - { - // Ignored - return 0; - } + @Override + public boolean doesContainerAccept(final Aspect tag) { + // Ignored + return false; + } - @Override - public boolean doesContainerAccept( final Aspect tag ) - { - // Ignored - return false; - } + @Deprecated + @Override + public boolean doesContainerContain(final AspectList ot) { + // Ignored + return false; + } - @Deprecated - @Override - public boolean doesContainerContain( final AspectList ot ) - { - // Ignored - return false; - } + @Override + public boolean doesContainerContainAmount(final Aspect tag, final int amount) { + // Ignored + return false; + } - @Override - public boolean doesContainerContainAmount( final Aspect tag, final int amount ) - { - // Ignored - return false; - } + @Override + public AspectList getAspects() { + // Ignored + return null; + } - @Override - public AspectList getAspects() - { - // Ignored - return null; - } + @Override + public void setAspects(final AspectList aspects) { + // Ignored + } - @Override - public void setAspects( final AspectList aspects ) - { - // Ignored - } + @Override + public boolean takeFromContainer(final Aspect tag, final int amount) { + // Can we extract the essentia from the network? + if (this.extractEssentiaFromNetwork(tag, amount, true) == amount) { + // Show partical FX + this.doParticalFX(tag.getColor()); - @Override - public boolean takeFromContainer( final Aspect tag, final int amount ) - { - // Can we extract the essentia from the network? - if( this.extractEssentiaFromNetwork( tag, amount, true ) == amount ) - { - // Show partical FX - this.doParticalFX( tag.getColor() ); + return true; + } - return true; - } - - return false; - } - - @Deprecated - @Override - public boolean takeFromContainer( final AspectList ot ) - { - // Ignored - return false; - } + return false; + } + @Deprecated + @Override + public boolean takeFromContainer(final AspectList ot) { + // Ignored + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/TileKnowledgeInscriber.java b/src/main/java/thaumicenergistics/common/tiles/TileKnowledgeInscriber.java index 7b6857f8..b010c9d7 100644 --- a/src/main/java/thaumicenergistics/common/tiles/TileKnowledgeInscriber.java +++ b/src/main/java/thaumicenergistics/common/tiles/TileKnowledgeInscriber.java @@ -11,74 +11,63 @@ import thaumicenergistics.common.tiles.abstraction.ThETileInventory; * @author Nividica * */ -public class TileKnowledgeInscriber - extends ThETileInventory -{ - public static final int KCORE_SLOT = 0; +public class TileKnowledgeInscriber extends ThETileInventory { + public static final int KCORE_SLOT = 0; - private static final String NBTKEY_KCORE = "kcore"; + private static final String NBTKEY_KCORE = "kcore"; - public TileKnowledgeInscriber() - { - super( "knowledge.inscriber", 1, 64 ); - } + public TileKnowledgeInscriber() { + super("knowledge.inscriber", 1, 64); + } - /** - * Returns true if there is a stored KCore. - * - * @return - */ - public boolean hasKCore() - { - return this.internalInventory.getHasStack( KCORE_SLOT ); - } + /** + * Returns true if there is a stored KCore. + * + * @return + */ + public boolean hasKCore() { + return this.internalInventory.getHasStack(KCORE_SLOT); + } - @Override - public boolean isItemValidForSlot( final int slotIndex, final ItemStack itemStack ) - { - // Null is always allowed - if( itemStack == null ) - { - return true; - } + @Override + public boolean isItemValidForSlot(final int slotIndex, final ItemStack itemStack) { + // Null is always allowed + if (itemStack == null) { + return true; + } - // KCORE slot? - if( slotIndex == KCORE_SLOT ) - { - // Ensure the item is a KCORE - return( itemStack.getItem() instanceof ItemKnowledgeCore ); - } + // KCORE slot? + if (slotIndex == KCORE_SLOT) { + // Ensure the item is a KCORE + return (itemStack.getItem() instanceof ItemKnowledgeCore); + } - return true; - } + return true; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - // Call super - super.readFromNBT( data ); + @Override + public void readFromNBT(final NBTTagCompound data) { + // Call super + super.readFromNBT(data); - // Is there a saved core? - if( data.hasKey( NBTKEY_KCORE ) ) - { - // Load the saved core - this.internalInventory.setInventorySlotContents( KCORE_SLOT, - ItemStack.loadItemStackFromNBT( data.getCompoundTag( NBTKEY_KCORE ) ) ); - } - } + // Is there a saved core? + if (data.hasKey(NBTKEY_KCORE)) { + // Load the saved core + this.internalInventory.setInventorySlotContents( + KCORE_SLOT, ItemStack.loadItemStackFromNBT(data.getCompoundTag(NBTKEY_KCORE))); + } + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - // Call super - super.writeToNBT( data ); + @Override + public void writeToNBT(final NBTTagCompound data) { + // Call super + super.writeToNBT(data); - // Get the kcore - ItemStack kCore = this.internalInventory.getStackInSlot( KCORE_SLOT ); - if( kCore != null ) - { - // Write the kcore - data.setTag( NBTKEY_KCORE, kCore.writeToNBT( new NBTTagCompound() ) ); - } - } + // Get the kcore + ItemStack kCore = this.internalInventory.getStackInSlot(KCORE_SLOT); + if (kCore != null) { + // Write the kcore + data.setTag(NBTKEY_KCORE, kCore.writeToNBT(new NBTTagCompound())); + } + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/abstraction/ThETileInventory.java b/src/main/java/thaumicenergistics/common/tiles/abstraction/ThETileInventory.java index 56057ffa..923130e5 100644 --- a/src/main/java/thaumicenergistics/common/tiles/abstraction/ThETileInventory.java +++ b/src/main/java/thaumicenergistics/common/tiles/abstraction/ThETileInventory.java @@ -13,89 +13,70 @@ import thaumicenergistics.common.inventory.TheInternalInventory; * @author Nividica * */ -public abstract class ThETileInventory - extends TileEntity - implements IInventory -{ - /** - * The internal inventory of the tile. - */ - protected final TheInternalInventory internalInventory; +public abstract class ThETileInventory extends TileEntity implements IInventory { + /** + * The internal inventory of the tile. + */ + protected final TheInternalInventory internalInventory; - public ThETileInventory( final String invName, final int invSize, final int invStackLimit ) - { - // Create the internal inventory - this.internalInventory = new TheInternalInventory( invName, invSize, invStackLimit ); - } + public ThETileInventory(final String invName, final int invSize, final int invStackLimit) { + // Create the internal inventory + this.internalInventory = new TheInternalInventory(invName, invSize, invStackLimit); + } - @Override - public void closeInventory() - { - } + @Override + public void closeInventory() {} - @Override - public ItemStack decrStackSize( final int slotIndex, final int amount ) - { - return this.internalInventory.decrStackSize( slotIndex, amount ); - } + @Override + public ItemStack decrStackSize(final int slotIndex, final int amount) { + return this.internalInventory.decrStackSize(slotIndex, amount); + } - @Override - public String getInventoryName() - { - return this.internalInventory.getInventoryName(); - } + @Override + public String getInventoryName() { + return this.internalInventory.getInventoryName(); + } - @Override - public int getInventoryStackLimit() - { - return this.internalInventory.getInventoryStackLimit(); - } + @Override + public int getInventoryStackLimit() { + return this.internalInventory.getInventoryStackLimit(); + } - @Override - public int getSizeInventory() - { - return this.internalInventory.getSizeInventory(); - } + @Override + public int getSizeInventory() { + return this.internalInventory.getSizeInventory(); + } - @Override - public ItemStack getStackInSlot( final int slotIndex ) - { - return this.internalInventory.getStackInSlot( slotIndex ); - } + @Override + public ItemStack getStackInSlot(final int slotIndex) { + return this.internalInventory.getStackInSlot(slotIndex); + } - @Override - public ItemStack getStackInSlotOnClosing( final int slotIndex ) - { - return this.internalInventory.getStackInSlotOnClosing( slotIndex ); - } + @Override + public ItemStack getStackInSlotOnClosing(final int slotIndex) { + return this.internalInventory.getStackInSlotOnClosing(slotIndex); + } - @Override - public boolean hasCustomInventoryName() - { - return this.internalInventory.hasCustomInventoryName(); - } + @Override + public boolean hasCustomInventoryName() { + return this.internalInventory.hasCustomInventoryName(); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer player ) - { - return this.internalInventory.isUseableByPlayer( player, this ); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer player) { + return this.internalInventory.isUseableByPlayer(player, this); + } - @Override - public void markDirty() - { - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } + @Override + public void markDirty() { + this.worldObj.markTileEntityChunkModified(this.xCoord, this.yCoord, this.zCoord, this); + } - @Override - public void openInventory() - { - } - - @Override - public void setInventorySlotContents( final int slotIndex, final ItemStack itemStack ) - { - this.internalInventory.setInventorySlotContents( slotIndex, itemStack ); - } + @Override + public void openInventory() {} + @Override + public void setInventorySlotContents(final int slotIndex, final ItemStack itemStack) { + this.internalInventory.setInventorySlotContents(slotIndex, itemStack); + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/abstraction/TileEVCBase.java b/src/main/java/thaumicenergistics/common/tiles/abstraction/TileEVCBase.java index cddd4b16..d024acd1 100644 --- a/src/main/java/thaumicenergistics/common/tiles/abstraction/TileEVCBase.java +++ b/src/main/java/thaumicenergistics/common/tiles/abstraction/TileEVCBase.java @@ -1,6 +1,5 @@ package thaumicenergistics.common.tiles.abstraction; -import java.io.IOException; import appeng.api.config.Actionable; import appeng.api.util.AECableType; import appeng.api.util.DimensionalCoord; @@ -10,6 +9,7 @@ import appeng.tile.grid.AENetworkTile; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -31,412 +31,358 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public abstract class TileEVCBase - extends AENetworkTile - implements IEssentiaTransportWithSimulate, IAspectSource -{ - /** - * NBT Key for the stored aspect stack. - */ - public static final String NBTKEY_STORED = "StoredEssentia"; +public abstract class TileEVCBase extends AENetworkTile implements IEssentiaTransportWithSimulate, IAspectSource { + /** + * NBT Key for the stored aspect stack. + */ + public static final String NBTKEY_STORED = "StoredEssentia"; - /** - * The maximum amount of stored essentia. - */ - public static final int MAX_ESSENTIA_STORED = 64; + /** + * The maximum amount of stored essentia. + */ + public static final int MAX_ESSENTIA_STORED = 64; - /** - * Maximum reciprocal - */ - public static final float MAX_ESSENTIA_STORED_RECIPROCAL = 1.0f / MAX_ESSENTIA_STORED; + /** + * Maximum reciprocal + */ + public static final float MAX_ESSENTIA_STORED_RECIPROCAL = 1.0f / MAX_ESSENTIA_STORED; - /** - * Stored Essentia - */ - protected IAspectStack storedEssentia = null; + /** + * Stored Essentia + */ + protected IAspectStack storedEssentia = null; - /** - * Returns true if the EVC accepts the specified aspect. - * - * @param aspect - * @return - */ - public static boolean acceptsAspect( final Aspect aspect ) - { - return( ( aspect == Aspect.FIRE ) || ( aspect == Aspect.ENERGY ) ); - } + /** + * Returns true if the EVC accepts the specified aspect. + * + * @param aspect + * @return + */ + public static boolean acceptsAspect(final Aspect aspect) { + return ((aspect == Aspect.FIRE) || (aspect == Aspect.ENERGY)); + } - /** - * Add essentia to the EVC. - * - * @param aspect - * @param amount - * @param mode - * @return - */ - protected abstract int addEssentia( final Aspect aspect, final int amount, final Actionable mode ); + /** + * Add essentia to the EVC. + * + * @param aspect + * @param amount + * @param mode + * @return + */ + protected abstract int addEssentia(final Aspect aspect, final int amount, final Actionable mode); - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - // Return the itemstack that visually represents this tile - return ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); - } + @Override + protected ItemStack getItemFromTile(final Object obj) { + // Return the itemstack that visually represents this tile + return ThEApi.instance().blocks().EssentiaVibrationChamber.getStack(); + } - /** - * Returns true if there is any stored essentia. - * - * @return - */ - protected boolean hasStoredEssentia() - { - return ( this.storedEssentia != null ) && ( !this.storedEssentia.isEmpty() ); - } + /** + * Returns true if there is any stored essentia. + * + * @return + */ + protected boolean hasStoredEssentia() { + return (this.storedEssentia != null) && (!this.storedEssentia.isEmpty()); + } - protected abstract void NBTRead( NBTTagCompound data ); + protected abstract void NBTRead(NBTTagCompound data); - protected abstract void NBTWrite( NBTTagCompound data ); + protected abstract void NBTWrite(NBTTagCompound data); - @SideOnly(Side.CLIENT) - protected abstract void networkRead( ByteBuf stream ); + @SideOnly(Side.CLIENT) + protected abstract void networkRead(ByteBuf stream); - protected abstract void networkWrite( ByteBuf stream ); + protected abstract void networkWrite(ByteBuf stream); - @Override - public int addEssentia( final Aspect aspect, final int amount, final ForgeDirection side ) - { - return this.addEssentia( aspect, amount, Actionable.MODULATE ); - } + @Override + public int addEssentia(final Aspect aspect, final int amount, final ForgeDirection side) { + return this.addEssentia(aspect, amount, Actionable.MODULATE); + } - @Override - public int addEssentia( final Aspect aspect, final int amount, final ForgeDirection side, final Actionable mode ) - { - return this.addEssentia( aspect, amount, mode ); - } + @Override + public int addEssentia(final Aspect aspect, final int amount, final ForgeDirection side, final Actionable mode) { + return this.addEssentia(aspect, amount, mode); + } - @Override - public int addToContainer( final Aspect aspect, final int amount ) - { - return this.addEssentia( aspect, amount, Actionable.MODULATE ); - } + @Override + public int addToContainer(final Aspect aspect, final int amount) { + return this.addEssentia(aspect, amount, Actionable.MODULATE); + } - @Override - public boolean canInputFrom( final ForgeDirection side ) - { - return( side != this.getForward() ); - } + @Override + public boolean canInputFrom(final ForgeDirection side) { + return (side != this.getForward()); + } - /** - * Can not output. - */ - @Override - public boolean canOutputTo( final ForgeDirection side ) - { - return false; - } + /** + * Can not output. + */ + @Override + public boolean canOutputTo(final ForgeDirection side) { + return false; + } - @Override - public int containerContains( final Aspect aspect ) - { - int storedAmount = 0; + @Override + public int containerContains(final Aspect aspect) { + int storedAmount = 0; - // Is the aspect stored? - if( ( this.hasStoredEssentia() ) && ( this.storedEssentia.getAspect() == aspect ) ) - { - storedAmount = (int)this.storedEssentia.getStackSize(); - } + // Is the aspect stored? + if ((this.hasStoredEssentia()) && (this.storedEssentia.getAspect() == aspect)) { + storedAmount = (int) this.storedEssentia.getStackSize(); + } - return storedAmount; - } + return storedAmount; + } - @Override - public boolean doesContainerAccept( final Aspect aspect ) - { - // Is there stored essentia? - if( this.hasStoredEssentia() ) - { - // Match to stored essentia - return aspect == this.storedEssentia.getAspect(); - } + @Override + public boolean doesContainerAccept(final Aspect aspect) { + // Is there stored essentia? + if (this.hasStoredEssentia()) { + // Match to stored essentia + return aspect == this.storedEssentia.getAspect(); + } - // Nothing is stored, accepts ignis or potentia - return TileEVCBase.acceptsAspect( aspect ); - } + // Nothing is stored, accepts ignis or potentia + return TileEVCBase.acceptsAspect(aspect); + } - @Deprecated - @Override - public boolean doesContainerContain( final AspectList aspectList ) - { - // Is there not stored essentia? - if( !this.hasStoredEssentia() ) - { - return false; - } + @Deprecated + @Override + public boolean doesContainerContain(final AspectList aspectList) { + // Is there not stored essentia? + if (!this.hasStoredEssentia()) { + return false; + } - return aspectList.aspects.containsKey( this.storedEssentia.getAspect() ); - } + return aspectList.aspects.containsKey(this.storedEssentia.getAspect()); + } - @Override - public boolean doesContainerContainAmount( final Aspect aspect, final int amount ) - { - // Does the stored essentia match the aspect? - if( ( this.storedEssentia == null ) || ( this.storedEssentia.getAspect() != aspect ) ) - { - // Does not match - return false; - } + @Override + public boolean doesContainerContainAmount(final Aspect aspect, final int amount) { + // Does the stored essentia match the aspect? + if ((this.storedEssentia == null) || (this.storedEssentia.getAspect() != aspect)) { + // Does not match + return false; + } - return( this.storedEssentia.getStackSize() >= amount ); - } + return (this.storedEssentia.getStackSize() >= amount); + } - @Override - public AspectList getAspects() - { - // Create a new list - AspectList aspectList = new AspectList(); + @Override + public AspectList getAspects() { + // Create a new list + AspectList aspectList = new AspectList(); - // Is there stored essentia? - if( this.hasStoredEssentia() ) - { - // Add the essentia aspect and amount - aspectList.add( this.storedEssentia.getAspect(), (int)this.storedEssentia.getStackSize() ); - } + // Is there stored essentia? + if (this.hasStoredEssentia()) { + // Add the essentia aspect and amount + aspectList.add(this.storedEssentia.getAspect(), (int) this.storedEssentia.getStackSize()); + } - return aspectList; - } + return aspectList; + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - @Override - public int getEssentiaAmount( final ForgeDirection side ) - { - return( this.hasStoredEssentia() ? (int)this.storedEssentia.getStackSize() : 0 ); - } + @Override + public int getEssentiaAmount(final ForgeDirection side) { + return (this.hasStoredEssentia() ? (int) this.storedEssentia.getStackSize() : 0); + } - @Override - public Aspect getEssentiaType( final ForgeDirection side ) - { - return( this.hasStoredEssentia() ? this.storedEssentia.getAspect() : null ); - } + @Override + public Aspect getEssentiaType(final ForgeDirection side) { + return (this.hasStoredEssentia() ? this.storedEssentia.getAspect() : null); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - /** - * Can not output. - */ - @Override - public int getMinimumSuction() - { - return 0; - } + /** + * Can not output. + */ + @Override + public int getMinimumSuction() { + return 0; + } - @Override - public int getSuctionAmount( final ForgeDirection side ) - { - // Suction is based on how full the chamber is, as it fills up suction drops + @Override + public int getSuctionAmount(final ForgeDirection side) { + // Suction is based on how full the chamber is, as it fills up suction drops - // Get how much is stored - float stored = ( this.storedEssentia == null ? 0.0f : this.storedEssentia.getStackSize() ); - if( stored == MAX_ESSENTIA_STORED ) - { - return 0; - } + // Get how much is stored + float stored = (this.storedEssentia == null ? 0.0f : this.storedEssentia.getStackSize()); + if (stored == MAX_ESSENTIA_STORED) { + return 0; + } - // Calculate the ratio, minimum of 25%, and multiply against maximum suction - return (int)( 128 * ( 1.0f - ( ( stored * 0.75f ) * MAX_ESSENTIA_STORED_RECIPROCAL ) ) ); - } + // Calculate the ratio, minimum of 25%, and multiply against maximum suction + return (int) (128 * (1.0f - ((stored * 0.75f) * MAX_ESSENTIA_STORED_RECIPROCAL))); + } - @Override - public Aspect getSuctionType( final ForgeDirection side ) - { - // Is there anything stored? - if( this.hasStoredEssentia() ) - { - // Suction type must match what is stored - return this.storedEssentia.getAspect(); - } + @Override + public Aspect getSuctionType(final ForgeDirection side) { + // Is there anything stored? + if (this.hasStoredEssentia()) { + // Suction type must match what is stored + return this.storedEssentia.getAspect(); + } - // Rotate into Potentia? - if( ( MinecraftServer.getServer().getTickCounter() % 200 ) > 100 ) - { - // Set to Potentia - return Aspect.ENERGY; - } + // Rotate into Potentia? + if ((MinecraftServer.getServer().getTickCounter() % 200) > 100) { + // Set to Potentia + return Aspect.ENERGY; + } - // Default to Ignis - return Aspect.FIRE; - } + // Default to Ignis + return Aspect.FIRE; + } - @Override - public boolean isConnectable( final ForgeDirection side ) - { - return( side != this.getForward() ); - } + @Override + public boolean isConnectable(final ForgeDirection side) { + return (side != this.getForward()); + } - @TileEvent(TileEventType.WORLD_NBT_READ) - public final void onNBTLoad( final NBTTagCompound data ) - { - // Is there essentia stored? - if( data.hasKey( TileEVCBase.NBTKEY_STORED ) ) - { - // Load the stack - this.storedEssentia = AspectStack.loadAspectStackFromNBT( data.getCompoundTag( TileEVCBase.NBTKEY_STORED ) ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public final void onNBTLoad(final NBTTagCompound data) { + // Is there essentia stored? + if (data.hasKey(TileEVCBase.NBTKEY_STORED)) { + // Load the stack + this.storedEssentia = AspectStack.loadAspectStackFromNBT(data.getCompoundTag(TileEVCBase.NBTKEY_STORED)); + } - // Call sub - this.NBTRead( data ); - } + // Call sub + this.NBTRead(data); + } - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public final void onNBTSave( final NBTTagCompound data ) - { - // Save storage - if( this.hasStoredEssentia() ) - { - // Save stack - NBTTagCompound stack = new NBTTagCompound(); - this.storedEssentia.writeToNBT( stack ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public final void onNBTSave(final NBTTagCompound data) { + // Save storage + if (this.hasStoredEssentia()) { + // Save stack + NBTTagCompound stack = new NBTTagCompound(); + this.storedEssentia.writeToNBT(stack); - // Write into data - data.setTag( TileEVCBase.NBTKEY_STORED, stack ); - } + // Write into data + data.setTag(TileEVCBase.NBTKEY_STORED, stack); + } - // Call sub - this.NBTWrite( data ); - } + // Call sub + this.NBTWrite(data); + } - @TileEvent(TileEventType.NETWORK_READ) - @SideOnly(Side.CLIENT) - public final boolean onNetworkRead( final ByteBuf stream ) - { - // Anything stored? - if( stream.readBoolean() ) - { - // Is the local copy null? - if( this.storedEssentia == null ) - { - // Create the stack from the stream - this.storedEssentia = AspectStack.loadAspectStackFromStream( stream ); - } - else - { - // Update the stack from the stream - this.storedEssentia.readFromStream( stream ); - } - } - else - { - // Null out the stack - this.storedEssentia = null; - } + @TileEvent(TileEventType.NETWORK_READ) + @SideOnly(Side.CLIENT) + public final boolean onNetworkRead(final ByteBuf stream) { + // Anything stored? + if (stream.readBoolean()) { + // Is the local copy null? + if (this.storedEssentia == null) { + // Create the stack from the stream + this.storedEssentia = AspectStack.loadAspectStackFromStream(stream); + } else { + // Update the stack from the stream + this.storedEssentia.readFromStream(stream); + } + } else { + // Null out the stack + this.storedEssentia = null; + } - // Call sub - this.networkRead( stream ); + // Call sub + this.networkRead(stream); - return true; - } + return true; + } - @TileEvent(TileEventType.NETWORK_WRITE) - public final void onNetworkWrite( final ByteBuf stream ) throws IOException - { - // Is there anything stored? - boolean hasStored = this.storedEssentia != null; + @TileEvent(TileEventType.NETWORK_WRITE) + public final void onNetworkWrite(final ByteBuf stream) throws IOException { + // Is there anything stored? + boolean hasStored = this.storedEssentia != null; - // Write stored - stream.writeBoolean( hasStored ); - if( hasStored ) - { - // Write the stack - this.storedEssentia.writeToStream( stream ); - } + // Write stored + stream.writeBoolean(hasStored); + if (hasStored) { + // Write the stack + this.storedEssentia.writeToStream(stream); + } - // Call sub - this.networkWrite( stream ); - } + // Call sub + this.networkWrite(stream); + } - /** - * Sets up the chamber - * - * @return - */ - @Override - public void onReady() - { - // Call super - super.onReady(); + /** + * Sets up the chamber + * + * @return + */ + @Override + public void onReady() { + // Call super + super.onReady(); - // Ignored on client side - if( EffectiveSide.isServerSide() ) - { - // Set idle power usage to zero - this.getProxy().setIdlePowerUsage( 0.0D ); - } - } + // Ignored on client side + if (EffectiveSide.isServerSide()) { + // Set idle power usage to zero + this.getProxy().setIdlePowerUsage(0.0D); + } + } - /** - * Full block, not extension needed. - */ - @Override - public boolean renderExtendedTube() - { - return false; - } + /** + * Full block, not extension needed. + */ + @Override + public boolean renderExtendedTube() { + return false; + } - @Override - public void setAspects( final AspectList aspectList ) - { - // Ignored - } + @Override + public void setAspects(final AspectList aspectList) { + // Ignored + } - /** - * Sets the owner of this tile. - * - * @param player - */ - public void setOwner( final EntityPlayer player ) - { - this.getProxy().setOwner( player ); - } + /** + * Sets the owner of this tile. + * + * @param player + */ + public void setOwner(final EntityPlayer player) { + this.getProxy().setOwner(player); + } - @Override - public void setSuction( final Aspect aspect, final int amount ) - { - // Ignored - } + @Override + public void setSuction(final Aspect aspect, final int amount) { + // Ignored + } - /** - * Can not output. - */ - @Override - public int takeEssentia( final Aspect aspect, final int amount, final ForgeDirection side ) - { - return 0; - } + /** + * Can not output. + */ + @Override + public int takeEssentia(final Aspect aspect, final int amount, final ForgeDirection side) { + return 0; + } - /** - * Can not output. - */ - @Override - public boolean takeFromContainer( final Aspect aspect, final int amount ) - { - return false; - } + /** + * Can not output. + */ + @Override + public boolean takeFromContainer(final Aspect aspect, final int amount) { + return false; + } - /** - * Can not output. - */ - @Deprecated - @Override - public boolean takeFromContainer( final AspectList arg0 ) - { - return false; - } + /** + * Can not output. + */ + @Deprecated + @Override + public boolean takeFromContainer(final AspectList arg0) { + return false; + } } diff --git a/src/main/java/thaumicenergistics/common/tiles/abstraction/TileProviderBase.java b/src/main/java/thaumicenergistics/common/tiles/abstraction/TileProviderBase.java index fac002cf..7ba9665e 100644 --- a/src/main/java/thaumicenergistics/common/tiles/abstraction/TileProviderBase.java +++ b/src/main/java/thaumicenergistics/common/tiles/abstraction/TileProviderBase.java @@ -1,7 +1,5 @@ package thaumicenergistics.common.tiles.abstraction; -import java.io.IOException; -import java.util.List; import appeng.api.config.Actionable; import appeng.api.implementations.tiles.IColorableTile; import appeng.api.networking.GridFlags; @@ -22,6 +20,8 @@ import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; +import java.io.IOException; +import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -42,533 +42,473 @@ import thaumicenergistics.common.utils.EffectiveSide; * @author Nividica * */ -public abstract class TileProviderBase - extends AENetworkTile - implements IColorableTile, IWailaSource -{ - /** - * NBT keys - */ - protected static final String NBT_KEY_COLOR = "TEColor", NBT_KEY_ATTACHMENT = "TEAttachSide", NBT_KEY_ISCOLORFORCED = "ColorForced"; - - /** - * Network source representing the provider. - */ - private MachineSource asMachineSource; - - /** - * ForgeDirection ordinal of our attachment side. - */ - protected int attachmentSide; - - /** - * ME monitor that watches for changes in essentia. - */ - protected IMEEssentiaMonitor monitor = null; - - /** - * True if the provider is connected and powered. - */ - protected boolean isActive; - - /** - * True when the color applicator has been used on the provider. - */ - protected boolean isColorForced = false; - - public TileProviderBase() - { - // Create the source - this.asMachineSource = new MachineSource( this ); - } - - /** - * Returns an array with the AE colors of any neighbor tiles. - * Index is side. - * - * @return - */ - private AEColor[] getNeighborCableColors() - { - AEColor[] sideColors = new AEColor[6]; - - for( ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - // Get the tile entity on the current side - TileEntity tileEntity = this.worldObj.getTileEntity( this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ ); - - // Did we get an entity? - if( tileEntity == null ) - { - continue; - } - - // Is that entity a cable? - if( tileEntity instanceof TileCableBus ) - { - // Set the color - sideColors[side.ordinal()] = ( (TileCableBus)tileEntity ).getColor(); - } - - } - - return sideColors; - } - - /** - * Returns how much was extracted from the network. - * - * @param wantedAspect - * @param wantedAmount - * @param mustMatch - * @return - */ - protected int extractEssentiaFromNetwork( final Aspect wantedAspect, final int wantedAmount, final boolean mustMatch ) - { - // Ensure we have a monitor - if( this.getEssentiaMonitor() ) - { - // Request the essentia - long amountExtracted = this.monitor.extractEssentia( wantedAspect, wantedAmount, Actionable.SIMULATE, this.asMachineSource, true ); - - // Was any essentia extracted? - if( amountExtracted == 0 ) - { - // Nothing extracted. - return 0; - } - - // Are we in match mode? - else if( mustMatch ) - { - // Does the amount match how much we want? - if( amountExtracted != wantedAmount ) - { - // Could not provide enough essentia - return 0; - } - } - - // Extract the essentia - this.monitor.extractEssentia( wantedAspect, wantedAmount, Actionable.MODULATE, this.asMachineSource, true ); - - // Return how much was extracted - return (int)amountExtracted; - } - - // No monitor - return 0; - - } - - /** - * Gets the essentia monitor from the network. - * Returns true if a monitor was retrieved. - * - * @return - */ - protected boolean getEssentiaMonitor() - { - IMEEssentiaMonitor essentiaMonitor = null; - IGrid grid = null; - - // Get the grid node - IGridNode node = this.getProxy().getNode(); - - // Ensure we have the node - if( node != null ) - { - // Get the grid that node is connected to - grid = node.getGrid(); - - // Is there a grid? - if( grid != null ) - { - // Get the monitor - essentiaMonitor = (IMEEssentiaMonitor)grid.getCache( IEssentiaGrid.class ); - } - } - - // Set the monitor - this.monitor = essentiaMonitor; - - // Return true if the monitor is not null - return( this.monitor != null ); - } - - protected abstract double getIdlePowerusage(); - - @Override - protected abstract ItemStack getItemFromTile( Object obj ); - - /** - * Called when the power goes on or off. - * - * @param isPowered - */ - protected void onPowerChange( final boolean isPowered ) - { - } - - /** - * Sets the color of the provider. - * This does not set the isColorForced flag to true. - * - * @param gridColor - */ - protected void setProviderColor( final AEColor gridColor ) - { - // Set our color to match - this.getProxy().setColor( gridColor ); - - // Are we server side? - if( EffectiveSide.isServerSide() ) - { - /* - // Get the grid node - IGridNode gridNode = this.getProxy().getNode(); - - // Do we have a grid node? - if( gridNode != null ) - { - // Update the grid node - this.getProxy().getNode().updateState(); - } - */ - - // Mark the tile as needing updates and to be saved - this.markForUpdate(); - this.saveChanges(); - } - } - - /** - * Adds the power state and color to a Waila tooltip - */ - @Override - public void addWailaInformation( final List tooltip ) - { - // Is it active? - if( this.isActive() ) - { - // Get activity string from AppEng2 - tooltip.add( WailaText.DeviceOnline.getLocal() ); - } - else - { - // Get activity string from AppEng2 - tooltip.add( WailaText.DeviceOffline.getLocal() ); - } - - // Add the color - tooltip.add( "Color: " + this.getColor().toString() ); - } - - @MENetworkEventSubscribe - public final void channelEvent( final MENetworkChannelsChanged event ) - { - // Check that our color is still valid - this.checkGridConnectionColor(); - - // Is this server side? - if( EffectiveSide.isServerSide() ) - { - // Update the monitor - this.getEssentiaMonitor(); - } - - // Mark for update - this.markForUpdate(); - } - - public void checkGridConnectionColor() - { - // Are we server side and with a world? - if( FMLCommonHandler.instance().getEffectiveSide().isClient() || ( this.worldObj == null ) ) - { - // Nothing to do - return; - } - - // Is our color forced? - if( this.isColorForced ) - { - // Do not change colors. - return; - } - - // Get the colors of our neighbors - AEColor[] sideColors = this.getNeighborCableColors(); - - // Get our current color - AEColor currentColor = this.getProxy().getColor(); - - // Are we attached to a side? - if( this.attachmentSide != ForgeDirection.UNKNOWN.ordinal() ) - { - // Does our attached side still exist - if( sideColors[this.attachmentSide] != null ) - { - // Do we match it's color? - if( sideColors[this.attachmentSide] == currentColor ) - { - // Nothing to change - return; - } - - // Set our color to match - this.setProviderColor( sideColors[this.attachmentSide] ); - - return; - } - } - - // Are any of the other sides the same color? - for( int index = 0; index < 6; index++ ) - { - if( sideColors[index] != null ) - { - // Does the current side match our color? - if( sideColors[index] == currentColor ) - { - // Found another cable with the same color, lets attach to it - this.attachmentSide = index; - - // Mark for a save - this.saveChanges(); - - return; - } - // Are we transparent? - else if( currentColor == AEColor.Transparent ) - { - // Attach to this cable - this.attachmentSide = index; - - // Take on its color - this.setProviderColor( sideColors[index] ); - - return; - } - } - } - - // No cables match our color, set attachment to unknown - this.attachmentSide = ForgeDirection.UNKNOWN.ordinal(); - - // Set color to transparent - this.setProviderColor( AEColor.Transparent ); - - } - - /** - * Returns how much of the specified aspect is in the network. - * - * @param searchAspect - * @return - */ - public long getAspectAmountInNetwork( final Aspect searchAspect ) - { - // Ensure there is a monitor - if( this.getEssentiaMonitor() ) - { - // Return the amount in the network - return this.monitor.getEssentiaAmount( searchAspect ); - } - - // No monitor. - return 0; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection direction ) - { - return AECableType.SMART; - } - - /** - * Get's the color of the provider - */ - @Override - public AEColor getColor() - { - return this.getProxy().getColor(); - } - - public AEColor getGridColor() - { - return this.getProxy().getGridColor(); - } - - /** - * Gets the machine source for the provider. - * - * @return - */ - public MachineSource getMachineSource() - { - return this.asMachineSource; - } - - public boolean isActive() - { - // Are we server side? - if( EffectiveSide.isServerSide() ) - { - boolean prevActive = this.isActive; - - // Do we have a proxy and grid node? - if( ( this.getProxy() != null ) && ( this.getProxy().getNode() != null ) ) - { - // Get the grid node activity - this.isActive = this.getProxy().getNode().isActive(); - - // Did the power state change? - if( prevActive != this.isActive ) - { - // Send event - this.onPowerChange( this.isActive ); - } - } - } - - return this.isActive; - } - - /** - * Called when our parent block is about to be destroyed. - */ - public void onBreakBlock() - { - } - - @TileEvent(TileEventType.WORLD_NBT_READ) - public void onLoadNBT( final NBTTagCompound data ) - { - int attachmentSideFromNBT = ForgeDirection.UNKNOWN.ordinal(); - - // Do we have the forced key? - if( data.hasKey( TileProviderBase.NBT_KEY_ISCOLORFORCED ) ) - { - this.isColorForced = data.getBoolean( TileProviderBase.NBT_KEY_ISCOLORFORCED ); - } - - // Do we have the color key? - if( data.hasKey( TileProviderBase.NBT_KEY_COLOR ) ) - { - // Read the color from the tag - this.setProviderColor( EnumCache.AE_COLOR[data.getInteger( TileProviderBase.NBT_KEY_COLOR )] ); - } - - // Do we have the attachment key? - if( data.hasKey( TileProviderBase.NBT_KEY_ATTACHMENT ) ) - { - // Read the attachment side - attachmentSideFromNBT = data.getInteger( TileProviderBase.NBT_KEY_ATTACHMENT ); - } - - // Setup the tile - this.setupProvider( attachmentSideFromNBT ); - } - - @Override - public void onReady() - { - // Call super - super.onReady(); - - // Check grid color - this.checkGridConnectionColor(); - } - - @TileEvent(TileEventType.NETWORK_READ) - @SideOnly(Side.CLIENT) - public boolean onReceiveNetworkData( final ByteBuf data ) - { - // Read the color from the stream - this.setProviderColor( EnumCache.AE_COLOR[data.readInt()] ); - - // Read the activity - this.isActive = data.readBoolean(); - - return true; - } - - @TileEvent(TileEventType.WORLD_NBT_WRITE) - public void onSaveNBT( final NBTTagCompound data ) - { - // Write our color to the tag - data.setInteger( TileProviderBase.NBT_KEY_COLOR, this.getGridColor().ordinal() ); - - // Write the attachment side to the tag - data.setInteger( TileProviderBase.NBT_KEY_ATTACHMENT, this.attachmentSide ); - - // Write the forced color flag - data.setBoolean( TileProviderBase.NBT_KEY_ISCOLORFORCED, this.isColorForced ); - } - - @TileEvent(TileEventType.NETWORK_WRITE) - public void onSendNetworkData( final ByteBuf data ) throws IOException - { - // Write the color data to the stream - data.writeInt( this.getGridColor().ordinal() ); - - // Write the activity to the stream - data.writeBoolean( this.isActive() ); - } - - @MENetworkEventSubscribe - public final void powerEvent( final MENetworkPowerStatusChange event ) - { - this.markForUpdate(); - } - - /** - * Forces a color change for the provider. - * Called when the provider's color is changed via the ColorApplicator item. - */ - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor color, final EntityPlayer player ) - { - // Mark our color as forced - this.isColorForced = true; - - // Set our color - this.setProviderColor( color ); - - return true; - } - - /** - * Sets the owner of this tile. - * - * @param player - */ - public void setOwner( final EntityPlayer player ) - { - this.getProxy().setOwner( player ); - } - - /** - * Configures the provider based on the specified - * attachment side. - * - * @param attachmentSide - */ - public void setupProvider( final int attachmentSide ) - { - // Ignored on client side - if( FMLCommonHandler.instance().getEffectiveSide().isServer() ) - { - // Set which side we are attached to - this.attachmentSide = attachmentSide; - - // Set that we require a channel - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - - // Set the idle power usage - this.getProxy().setIdlePowerUsage( this.getIdlePowerusage() ); - } - } - +public abstract class TileProviderBase extends AENetworkTile implements IColorableTile, IWailaSource { + /** + * NBT keys + */ + protected static final String NBT_KEY_COLOR = "TEColor", + NBT_KEY_ATTACHMENT = "TEAttachSide", + NBT_KEY_ISCOLORFORCED = "ColorForced"; + + /** + * Network source representing the provider. + */ + private MachineSource asMachineSource; + + /** + * ForgeDirection ordinal of our attachment side. + */ + protected int attachmentSide; + + /** + * ME monitor that watches for changes in essentia. + */ + protected IMEEssentiaMonitor monitor = null; + + /** + * True if the provider is connected and powered. + */ + protected boolean isActive; + + /** + * True when the color applicator has been used on the provider. + */ + protected boolean isColorForced = false; + + public TileProviderBase() { + // Create the source + this.asMachineSource = new MachineSource(this); + } + + /** + * Returns an array with the AE colors of any neighbor tiles. + * Index is side. + * + * @return + */ + private AEColor[] getNeighborCableColors() { + AEColor[] sideColors = new AEColor[6]; + + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + // Get the tile entity on the current side + TileEntity tileEntity = this.worldObj.getTileEntity( + this.xCoord + side.offsetX, this.yCoord + side.offsetY, this.zCoord + side.offsetZ); + + // Did we get an entity? + if (tileEntity == null) { + continue; + } + + // Is that entity a cable? + if (tileEntity instanceof TileCableBus) { + // Set the color + sideColors[side.ordinal()] = ((TileCableBus) tileEntity).getColor(); + } + } + + return sideColors; + } + + /** + * Returns how much was extracted from the network. + * + * @param wantedAspect + * @param wantedAmount + * @param mustMatch + * @return + */ + protected int extractEssentiaFromNetwork( + final Aspect wantedAspect, final int wantedAmount, final boolean mustMatch) { + // Ensure we have a monitor + if (this.getEssentiaMonitor()) { + // Request the essentia + long amountExtracted = this.monitor.extractEssentia( + wantedAspect, wantedAmount, Actionable.SIMULATE, this.asMachineSource, true); + + // Was any essentia extracted? + if (amountExtracted == 0) { + // Nothing extracted. + return 0; + } + + // Are we in match mode? + else if (mustMatch) { + // Does the amount match how much we want? + if (amountExtracted != wantedAmount) { + // Could not provide enough essentia + return 0; + } + } + + // Extract the essentia + this.monitor.extractEssentia(wantedAspect, wantedAmount, Actionable.MODULATE, this.asMachineSource, true); + + // Return how much was extracted + return (int) amountExtracted; + } + + // No monitor + return 0; + } + + /** + * Gets the essentia monitor from the network. + * Returns true if a monitor was retrieved. + * + * @return + */ + protected boolean getEssentiaMonitor() { + IMEEssentiaMonitor essentiaMonitor = null; + IGrid grid = null; + + // Get the grid node + IGridNode node = this.getProxy().getNode(); + + // Ensure we have the node + if (node != null) { + // Get the grid that node is connected to + grid = node.getGrid(); + + // Is there a grid? + if (grid != null) { + // Get the monitor + essentiaMonitor = (IMEEssentiaMonitor) grid.getCache(IEssentiaGrid.class); + } + } + + // Set the monitor + this.monitor = essentiaMonitor; + + // Return true if the monitor is not null + return (this.monitor != null); + } + + protected abstract double getIdlePowerusage(); + + @Override + protected abstract ItemStack getItemFromTile(Object obj); + + /** + * Called when the power goes on or off. + * + * @param isPowered + */ + protected void onPowerChange(final boolean isPowered) {} + + /** + * Sets the color of the provider. + * This does not set the isColorForced flag to true. + * + * @param gridColor + */ + protected void setProviderColor(final AEColor gridColor) { + // Set our color to match + this.getProxy().setColor(gridColor); + + // Are we server side? + if (EffectiveSide.isServerSide()) { + /* + // Get the grid node + IGridNode gridNode = this.getProxy().getNode(); + + // Do we have a grid node? + if( gridNode != null ) + { + // Update the grid node + this.getProxy().getNode().updateState(); + } + */ + + // Mark the tile as needing updates and to be saved + this.markForUpdate(); + this.saveChanges(); + } + } + + /** + * Adds the power state and color to a Waila tooltip + */ + @Override + public void addWailaInformation(final List tooltip) { + // Is it active? + if (this.isActive()) { + // Get activity string from AppEng2 + tooltip.add(WailaText.DeviceOnline.getLocal()); + } else { + // Get activity string from AppEng2 + tooltip.add(WailaText.DeviceOffline.getLocal()); + } + + // Add the color + tooltip.add("Color: " + this.getColor().toString()); + } + + @MENetworkEventSubscribe + public final void channelEvent(final MENetworkChannelsChanged event) { + // Check that our color is still valid + this.checkGridConnectionColor(); + + // Is this server side? + if (EffectiveSide.isServerSide()) { + // Update the monitor + this.getEssentiaMonitor(); + } + + // Mark for update + this.markForUpdate(); + } + + public void checkGridConnectionColor() { + // Are we server side and with a world? + if (FMLCommonHandler.instance().getEffectiveSide().isClient() || (this.worldObj == null)) { + // Nothing to do + return; + } + + // Is our color forced? + if (this.isColorForced) { + // Do not change colors. + return; + } + + // Get the colors of our neighbors + AEColor[] sideColors = this.getNeighborCableColors(); + + // Get our current color + AEColor currentColor = this.getProxy().getColor(); + + // Are we attached to a side? + if (this.attachmentSide != ForgeDirection.UNKNOWN.ordinal()) { + // Does our attached side still exist + if (sideColors[this.attachmentSide] != null) { + // Do we match it's color? + if (sideColors[this.attachmentSide] == currentColor) { + // Nothing to change + return; + } + + // Set our color to match + this.setProviderColor(sideColors[this.attachmentSide]); + + return; + } + } + + // Are any of the other sides the same color? + for (int index = 0; index < 6; index++) { + if (sideColors[index] != null) { + // Does the current side match our color? + if (sideColors[index] == currentColor) { + // Found another cable with the same color, lets attach to it + this.attachmentSide = index; + + // Mark for a save + this.saveChanges(); + + return; + } + // Are we transparent? + else if (currentColor == AEColor.Transparent) { + // Attach to this cable + this.attachmentSide = index; + + // Take on its color + this.setProviderColor(sideColors[index]); + + return; + } + } + } + + // No cables match our color, set attachment to unknown + this.attachmentSide = ForgeDirection.UNKNOWN.ordinal(); + + // Set color to transparent + this.setProviderColor(AEColor.Transparent); + } + + /** + * Returns how much of the specified aspect is in the network. + * + * @param searchAspect + * @return + */ + public long getAspectAmountInNetwork(final Aspect searchAspect) { + // Ensure there is a monitor + if (this.getEssentiaMonitor()) { + // Return the amount in the network + return this.monitor.getEssentiaAmount(searchAspect); + } + + // No monitor. + return 0; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection direction) { + return AECableType.SMART; + } + + /** + * Get's the color of the provider + */ + @Override + public AEColor getColor() { + return this.getProxy().getColor(); + } + + public AEColor getGridColor() { + return this.getProxy().getGridColor(); + } + + /** + * Gets the machine source for the provider. + * + * @return + */ + public MachineSource getMachineSource() { + return this.asMachineSource; + } + + public boolean isActive() { + // Are we server side? + if (EffectiveSide.isServerSide()) { + boolean prevActive = this.isActive; + + // Do we have a proxy and grid node? + if ((this.getProxy() != null) && (this.getProxy().getNode() != null)) { + // Get the grid node activity + this.isActive = this.getProxy().getNode().isActive(); + + // Did the power state change? + if (prevActive != this.isActive) { + // Send event + this.onPowerChange(this.isActive); + } + } + } + + return this.isActive; + } + + /** + * Called when our parent block is about to be destroyed. + */ + public void onBreakBlock() {} + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void onLoadNBT(final NBTTagCompound data) { + int attachmentSideFromNBT = ForgeDirection.UNKNOWN.ordinal(); + + // Do we have the forced key? + if (data.hasKey(TileProviderBase.NBT_KEY_ISCOLORFORCED)) { + this.isColorForced = data.getBoolean(TileProviderBase.NBT_KEY_ISCOLORFORCED); + } + + // Do we have the color key? + if (data.hasKey(TileProviderBase.NBT_KEY_COLOR)) { + // Read the color from the tag + this.setProviderColor(EnumCache.AE_COLOR[data.getInteger(TileProviderBase.NBT_KEY_COLOR)]); + } + + // Do we have the attachment key? + if (data.hasKey(TileProviderBase.NBT_KEY_ATTACHMENT)) { + // Read the attachment side + attachmentSideFromNBT = data.getInteger(TileProviderBase.NBT_KEY_ATTACHMENT); + } + + // Setup the tile + this.setupProvider(attachmentSideFromNBT); + } + + @Override + public void onReady() { + // Call super + super.onReady(); + + // Check grid color + this.checkGridConnectionColor(); + } + + @TileEvent(TileEventType.NETWORK_READ) + @SideOnly(Side.CLIENT) + public boolean onReceiveNetworkData(final ByteBuf data) { + // Read the color from the stream + this.setProviderColor(EnumCache.AE_COLOR[data.readInt()]); + + // Read the activity + this.isActive = data.readBoolean(); + + return true; + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void onSaveNBT(final NBTTagCompound data) { + // Write our color to the tag + data.setInteger(TileProviderBase.NBT_KEY_COLOR, this.getGridColor().ordinal()); + + // Write the attachment side to the tag + data.setInteger(TileProviderBase.NBT_KEY_ATTACHMENT, this.attachmentSide); + + // Write the forced color flag + data.setBoolean(TileProviderBase.NBT_KEY_ISCOLORFORCED, this.isColorForced); + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void onSendNetworkData(final ByteBuf data) throws IOException { + // Write the color data to the stream + data.writeInt(this.getGridColor().ordinal()); + + // Write the activity to the stream + data.writeBoolean(this.isActive()); + } + + @MENetworkEventSubscribe + public final void powerEvent(final MENetworkPowerStatusChange event) { + this.markForUpdate(); + } + + /** + * Forces a color change for the provider. + * Called when the provider's color is changed via the ColorApplicator item. + */ + @Override + public boolean recolourBlock(final ForgeDirection side, final AEColor color, final EntityPlayer player) { + // Mark our color as forced + this.isColorForced = true; + + // Set our color + this.setProviderColor(color); + + return true; + } + + /** + * Sets the owner of this tile. + * + * @param player + */ + public void setOwner(final EntityPlayer player) { + this.getProxy().setOwner(player); + } + + /** + * Configures the provider based on the specified + * attachment side. + * + * @param attachmentSide + */ + public void setupProvider(final int attachmentSide) { + // Ignored on client side + if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { + // Set which side we are attached to + this.attachmentSide = attachmentSide; + + // Set that we require a channel + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + + // Set the idle power usage + this.getProxy().setIdlePowerUsage(this.getIdlePowerusage()); + } + } } diff --git a/src/main/java/thaumicenergistics/common/utils/EffectiveSide.java b/src/main/java/thaumicenergistics/common/utils/EffectiveSide.java index eedb32ef..0e994b47 100644 --- a/src/main/java/thaumicenergistics/common/utils/EffectiveSide.java +++ b/src/main/java/thaumicenergistics/common/utils/EffectiveSide.java @@ -9,40 +9,36 @@ import cpw.mods.fml.relauncher.Side; * @author Nividica * */ -public final class EffectiveSide -{ - /** - * Cache the handler - */ - private static FMLCommonHandler FCH = FMLCommonHandler.instance(); +public final class EffectiveSide { + /** + * Cache the handler + */ + private static FMLCommonHandler FCH = FMLCommonHandler.instance(); - /** - * True if the thread executing this code is client side. - * - * @return - */ - public static final boolean isClientSide() - { - return FCH.getEffectiveSide().isClient(); - } + /** + * True if the thread executing this code is client side. + * + * @return + */ + public static final boolean isClientSide() { + return FCH.getEffectiveSide().isClient(); + } - /** - * True if the thread executing this code is server side. - * - * @return - */ - public static final boolean isServerSide() - { - return FCH.getEffectiveSide().isServer(); - } + /** + * True if the thread executing this code is server side. + * + * @return + */ + public static final boolean isServerSide() { + return FCH.getEffectiveSide().isServer(); + } - /** - * Returns the effective side for the context in the game. - * - * @return - */ - public static final Side side() - { - return FCH.getEffectiveSide(); - } + /** + * Returns the effective side for the context in the game. + * + * @return + */ + public static final Side side() { + return FCH.getEffectiveSide(); + } } diff --git a/src/main/java/thaumicenergistics/common/utils/ThELog.java b/src/main/java/thaumicenergistics/common/utils/ThELog.java index 1cb72f73..aac6f020 100644 --- a/src/main/java/thaumicenergistics/common/utils/ThELog.java +++ b/src/main/java/thaumicenergistics/common/utils/ThELog.java @@ -9,82 +9,73 @@ import org.apache.logging.log4j.Logger; * @author Nividica * */ -public class ThELog -{ - public static final Logger log = LogManager.getLogger( "Thaumic Energistics" ); +public class ThELog { + public static final Logger log = LogManager.getLogger("Thaumic Energistics"); - /** - * Displays the section header. - */ - public static long beginSection( final String section ) - { - log.info( String.format( "Starting (%s)", section ) ); - return System.currentTimeMillis(); - } + /** + * Displays the section header. + */ + public static long beginSection(final String section) { + log.info(String.format("Starting (%s)", section)); + return System.currentTimeMillis(); + } - /** - * Logs a debug statement. - * - * @param format - * @param data - */ - public static void debug( final String format, final Object ... data ) - { - log.debug( String.format( format, data ) ); - } + /** + * Logs a debug statement. + * + * @param format + * @param data + */ + public static void debug(final String format, final Object... data) { + log.debug(String.format(format, data)); + } - /** - * Displays the section footer. - */ - public static void endSection( final String section, final long sectionStartTime ) - { - log.info( String.format( "Finished (%s in %dms)", section, ( System.currentTimeMillis() - sectionStartTime ) ) ); - } + /** + * Displays the section footer. + */ + public static void endSection(final String section, final long sectionStartTime) { + log.info(String.format("Finished (%s in %dms)", section, (System.currentTimeMillis() - sectionStartTime))); + } - /** - * Logs an exception. - * - * @param e - * @param format - * @param data - */ - public static void error( final Throwable e, final String format, final Object ... data ) - { - log.error( String.format( format, data ), e ); - } + /** + * Logs an exception. + * + * @param e + * @param format + * @param data + */ + public static void error(final Throwable e, final String format, final Object... data) { + log.error(String.format(format, data), e); + } - /** - * Logs basic info. - * - * @param format - * @param data - */ - public static void info( final String format, final Object ... data ) - { - log.info( String.format( format, data ) ); - } + /** + * Logs basic info. + * + * @param format + * @param data + */ + public static void info(final String format, final Object... data) { + log.info(String.format(format, data)); + } - /** - * Logs an error.
- * If there is an exception available, use {@code error}. - * - * @param format - * @param data - */ - public static void severe( final String format, final Object ... data ) - { - log.error( String.format( format, data ) ); - } - - /** - * Logs a warning. - * - * @param format - * @param data - */ - public static void warning( final String format, final Object ... data ) - { - log.warn( String.format( format, data ) ); - } + /** + * Logs an error.
+ * If there is an exception available, use {@code error}. + * + * @param format + * @param data + */ + public static void severe(final String format, final Object... data) { + log.error(String.format(format, data)); + } + /** + * Logs a warning. + * + * @param format + * @param data + */ + public static void warning(final String format, final Object... data) { + log.warn(String.format(format, data)); + } } diff --git a/src/main/java/thaumicenergistics/common/utils/ThEUtils.java b/src/main/java/thaumicenergistics/common/utils/ThEUtils.java index bae70929..79d4fb56 100644 --- a/src/main/java/thaumicenergistics/common/utils/ThEUtils.java +++ b/src/main/java/thaumicenergistics/common/utils/ThEUtils.java @@ -1,9 +1,9 @@ package thaumicenergistics.common.utils; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.entity.player.EntityPlayer; @@ -21,218 +21,191 @@ import thaumicenergistics.common.network.packet.client.Packet_C_Sync; * @author Nividica * */ -public final class ThEUtils -{ - /** - * The squared reach distance. - */ - private static final double SQUARED_REACH = 64.0D; +public final class ThEUtils { + /** + * The squared reach distance. + */ + private static final double SQUARED_REACH = 64.0D; - /** - * Plays a sound for this player. - */ - @SideOnly(Side.CLIENT) - private static final void playLocalSound( final ResourceLocation sound ) - { - Minecraft.getMinecraft().getSoundHandler() - .playSound( PositionedSoundRecord.func_147674_a( sound, 1.0F ) ); - } + /** + * Plays a sound for this player. + */ + @SideOnly(Side.CLIENT) + private static final void playLocalSound(final ResourceLocation sound) { + Minecraft.getMinecraft().getSoundHandler().playSound(PositionedSoundRecord.func_147674_a(sound, 1.0F)); + } - /** - * Determines if the specified stacks are equal, ignoring their stack size.
- * If either stack is null, returns false. - * - * @param stack1 - * @param stack2 - * @return - */ - public static boolean areStacksEqualIgnoreAmount( final ItemStack stack1, final ItemStack stack2 ) - { - // Nulls never match - if( ( stack1 == null ) || ( stack2 == null ) || ( stack1.getItem() == null ) || ( stack2.getItem() == null ) ) - { - return false; - } + /** + * Determines if the specified stacks are equal, ignoring their stack size.
+ * If either stack is null, returns false. + * + * @param stack1 + * @param stack2 + * @return + */ + public static boolean areStacksEqualIgnoreAmount(final ItemStack stack1, final ItemStack stack2) { + // Nulls never match + if ((stack1 == null) || (stack2 == null) || (stack1.getItem() == null) || (stack2.getItem() == null)) { + return false; + } - // NBT state must match - if( stack1.hasTagCompound() != stack2.hasTagCompound() ) - { - return false; - } + // NBT state must match + if (stack1.hasTagCompound() != stack2.hasTagCompound()) { + return false; + } - // Item mismatch? - if( !( stack1.getItem().equals( stack2.getItem() ) ) ) - { - return false; - } + // Item mismatch? + if (!(stack1.getItem().equals(stack2.getItem()))) { + return false; + } - // Check damage - // Are either NOT wildcard? - if( ( stack1.getItemDamage() != OreDictionary.WILDCARD_VALUE ) && ( stack2.getItemDamage() != OreDictionary.WILDCARD_VALUE ) ) - { - // Does damage match? - if( stack1.getItemDamage() != stack2.getItemDamage() ) - { - return false; - } - } + // Check damage + // Are either NOT wildcard? + if ((stack1.getItemDamage() != OreDictionary.WILDCARD_VALUE) + && (stack2.getItemDamage() != OreDictionary.WILDCARD_VALUE)) { + // Does damage match? + if (stack1.getItemDamage() != stack2.getItemDamage()) { + return false; + } + } - // NBT mismatch? - if( stack1.hasTagCompound() ) - { - if( !( stack1.getTagCompound().equals( stack2.getTagCompound() ) ) ) - { - return false; - } - } + // NBT mismatch? + if (stack1.hasTagCompound()) { + if (!(stack1.getTagCompound().equals(stack2.getTagCompound()))) { + return false; + } + } - // All tests passed - return true; - } + // All tests passed + return true; + } - /** - * Returns true if the tile still exists and the player is within reach range. - * - * @param player - * @param tile - * @return - */ - public static final boolean canPlayerInteractWith( @Nonnull final EntityPlayer player, @Nonnull final TileEntity tile ) - { - TileEntity tileAtCoords = tile.getWorldObj().getTileEntity( tile.xCoord, tile.yCoord, tile.zCoord ); + /** + * Returns true if the tile still exists and the player is within reach range. + * + * @param player + * @param tile + * @return + */ + public static final boolean canPlayerInteractWith( + @Nonnull final EntityPlayer player, @Nonnull final TileEntity tile) { + TileEntity tileAtCoords = tile.getWorldObj().getTileEntity(tile.xCoord, tile.yCoord, tile.zCoord); - // Null check - if( tileAtCoords == null ) - { - return false; - } + // Null check + if (tileAtCoords == null) { + return false; + } - // Range check - return( player.getDistanceSq( tile.xCoord + 0.5D, tile.yCoord + 0.5D, tile.zCoord + 0.5D ) <= ThEUtils.SQUARED_REACH ); + // Range check + return (player.getDistanceSq(tile.xCoord + 0.5D, tile.yCoord + 0.5D, tile.zCoord + 0.5D) + <= ThEUtils.SQUARED_REACH); + } - } + /** + * Returns true if the item stack is a wand, scepter, or staff if they are + * allowed. + * + * @param stack + * @param allowStaves + * @return + */ + public static final boolean isItemValidWand(final ItemStack stack, final boolean allowStaves) { + Item potentialWand; - /** - * Returns true if the item stack is a wand, scepter, or staff if they are - * allowed. - * - * @param stack - * @param allowStaves - * @return - */ - public static final boolean isItemValidWand( final ItemStack stack, final boolean allowStaves ) - { - Item potentialWand; + // Ensure it is not null + if ((stack == null) || ((potentialWand = stack.getItem()) == null)) { + return false; + } - // Ensure it is not null - if( ( stack == null ) || ( ( potentialWand = stack.getItem() ) == null ) ) - { - return false; - } + // Ensure it is a casting wand + if (!(potentialWand instanceof ItemWandCasting)) { + return false; + } - // Ensure it is a casting wand - if( !( potentialWand instanceof ItemWandCasting ) ) - { - return false; - } + // Ensure it is not a staff + if ((!allowStaves) && (((ItemWandCasting) potentialWand).isStaff(stack))) { + return false; + } - // Ensure it is not a staff - if( ( !allowStaves ) && ( ( (ItemWandCasting)potentialWand ).isStaff( stack ) ) ) - { - return false; - } + // Get the wand + ItemWandCasting wand = (ItemWandCasting) stack.getItem(); - // Get the wand - ItemWandCasting wand = (ItemWandCasting)stack.getItem(); + // Validate internals + try { + wand.getAspectsWithRoom(stack); + } catch (Exception e) { + // Internal failure + return false; + } - // Validate internals - try - { - wand.getAspectsWithRoom( stack ); - } - catch( Exception e ) - { - // Internal failure - return false; - } + // Valid wand + return true; + } - // Valid wand - return true; - } + /** + * Ping pongs a value back and forth from min -> max -> min. + * The base speed of this effect is 1 second per transition, 2 seconds + * total. + * + * @param speedReduction + * The higher this value, the slower the effect. The smaller this value, the + * faster the effect. + * PingPong time (1) = 2 Seconds; (0.5) = 1 Second; (2) = 4 Seconds; + * @param minValue + * @param maxValue + * @return + */ + public static final float pingPongFromTime(double speedReduction, final float minValue, final float maxValue) { + // Sanity check for situations like pingPongFromTime( ?, 1.0F, 1.0F ) + if (minValue == maxValue) { + return minValue; + } - /** - * Ping pongs a value back and forth from min -> max -> min. - * The base speed of this effect is 1 second per transition, 2 seconds - * total. - * - * @param speedReduction - * The higher this value, the slower the effect. The smaller this value, the - * faster the effect. - * PingPong time (1) = 2 Seconds; (0.5) = 1 Second; (2) = 4 Seconds; - * @param minValue - * @param maxValue - * @return - */ - public static final float pingPongFromTime( double speedReduction, final float minValue, final float maxValue ) - { - // Sanity check for situations like pingPongFromTime( ?, 1.0F, 1.0F ) - if( minValue == maxValue ) - { - return minValue; - } + // Bounds check speed reduction + if (speedReduction <= 0) { + speedReduction = Float.MIN_VALUE; + } - // Bounds check speed reduction - if( speedReduction <= 0 ) - { - speedReduction = Float.MIN_VALUE; - } + // Get the time modulated to 2000, then reduced + float time = (float) ((System.currentTimeMillis() / speedReduction) % 2000.F); - // Get the time modulated to 2000, then reduced - float time = (float)( ( System.currentTimeMillis() / speedReduction ) % 2000.F ); + // Offset by -1000 and take the abs + time = Math.abs(time - 1000.0F); - // Offset by -1000 and take the abs - time = Math.abs( time - 1000.0F ); + // Convert time to a percentage + float timePercentage = time / 1000.0F; - // Convert time to a percentage - float timePercentage = time / 1000.0F; + // Get the position in the range we are now at + float rangePercentage = (maxValue - minValue) * timePercentage; - // Get the position in the range we are now at - float rangePercentage = ( maxValue - minValue ) * timePercentage; + // Add the range position back to min + return minValue + rangePercentage; + } - // Add the range position back to min - return minValue + rangePercentage; - } + /** + * Plays a sound only the specified player can hear. + * + * @param player + * Can be null on client side. + * @param soundLocation + */ + public static final void playClientSound(@Nullable final EntityPlayer player, final String soundLocation) { + // Ensure there is a sound + if ((soundLocation == null) || (soundLocation == "")) { + return; + } - /** - * Plays a sound only the specified player can hear. - * - * @param player - * Can be null on client side. - * @param soundLocation - */ - public static final void playClientSound( @Nullable final EntityPlayer player, final String soundLocation ) - { - // Ensure there is a sound - if( ( soundLocation == null ) || ( soundLocation == "" ) ) - { - return; - } + if (EffectiveSide.isClientSide()) { + // Create the resource + ResourceLocation sound = new ResourceLocation(soundLocation); - if( EffectiveSide.isClientSide() ) - { - // Create the resource - ResourceLocation sound = new ResourceLocation( soundLocation ); - - // Play the sound - ThEUtils.playLocalSound( sound ); - } - else - { - // Send to the player - if( player != null ) - { - Packet_C_Sync.sendPlaySound( player, soundLocation ); - } - } - } + // Play the sound + ThEUtils.playLocalSound(sound); + } else { + // Send to the player + if (player != null) { + Packet_C_Sync.sendPlaySound(player, soundLocation); + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/AClassTransformer.java b/src/main/java/thaumicenergistics/fml/AClassTransformer.java index 3e723978..86972505 100644 --- a/src/main/java/thaumicenergistics/fml/AClassTransformer.java +++ b/src/main/java/thaumicenergistics/fml/AClassTransformer.java @@ -1,5 +1,6 @@ package thaumicenergistics.fml; +import cpw.mods.fml.relauncher.FMLRelaunchLog; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.logging.log4j.Level; @@ -11,232 +12,201 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.util.Printer; import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceMethodVisitor; -import cpw.mods.fml.relauncher.FMLRelaunchLog; -public abstract class AClassTransformer -{ - protected static final String InstanceConstructorName = ""; +public abstract class AClassTransformer { + protected static final String InstanceConstructorName = ""; - private static Printer asmPrinter = new Textifier(); + private static Printer asmPrinter = new Textifier(); - private static TraceMethodVisitor asmVisitor = new TraceMethodVisitor( AClassTransformer.asmPrinter ); + private static TraceMethodVisitor asmVisitor = new TraceMethodVisitor(AClassTransformer.asmPrinter); - /** - * Canonical name of the class to be transformed. - */ - public final String classCanonicalName; + /** + * Canonical name of the class to be transformed. + */ + public final String classCanonicalName; - protected AClassTransformer( final String classCanonicalName ) - { - this.classCanonicalName = classCanonicalName; - } + protected AClassTransformer(final String classCanonicalName) { + this.classCanonicalName = classCanonicalName; + } - /** - * Locates the first occurrence of the specified opcode. - * - * @param instructions - * @param opcode - * @return - */ - protected AbstractInsnNode findFirstOpCode( final InsnList instructions, final int opcode ) - { - for( int index = 0; index < instructions.size(); ++index ) - { - if( instructions.get( index ).getOpcode() == opcode ) - { - return instructions.get( index ); - } - } - return null; - } + /** + * Locates the first occurrence of the specified opcode. + * + * @param instructions + * @param opcode + * @return + */ + protected AbstractInsnNode findFirstOpCode(final InsnList instructions, final int opcode) { + for (int index = 0; index < instructions.size(); ++index) { + if (instructions.get(index).getOpcode() == opcode) { + return instructions.get(index); + } + } + return null; + } - /** - * Locates the last occurrence of the specified opcode. - * - * @param instructions - * @param opcode - * @return - */ - protected AbstractInsnNode findLastOpCode( final InsnList instructions, final int opcode ) - { - for( int index = instructions.size() - 1; index > 0; --index ) - { - if( instructions.get( index ).getOpcode() == opcode ) - { - return instructions.get( index ); - } - } - return null; - } + /** + * Locates the last occurrence of the specified opcode. + * + * @param instructions + * @param opcode + * @return + */ + protected AbstractInsnNode findLastOpCode(final InsnList instructions, final int opcode) { + for (int index = instructions.size() - 1; index > 0; --index) { + if (instructions.get(index).getOpcode() == opcode) { + return instructions.get(index); + } + } + return null; + } - /** - * Locates the last occurrence of the specified type. - * - * @param instructions - * @param type - * @param number - * of occurrences to skip - * @return - */ - protected AbstractInsnNode findLastType( final InsnList instructions, final int type, int skip ) - { - for( int index = instructions.size() - 1; index > 0; --index ) - { - if( instructions.get( index ).getType() == type ) - { - if( --skip < 0 ) - { - return instructions.get( index ); - } - } - } - return null; - } + /** + * Locates the last occurrence of the specified type. + * + * @param instructions + * @param type + * @param number + * of occurrences to skip + * @return + */ + protected AbstractInsnNode findLastType(final InsnList instructions, final int type, int skip) { + for (int index = instructions.size() - 1; index > 0; --index) { + if (instructions.get(index).getType() == type) { + if (--skip < 0) { + return instructions.get(index); + } + } + } + return null; + } - /** - * Finds the next occurrence of the opcode after the specified instruction. - * - * @param fromInstruction - * @param opcode - * @return - */ - protected AbstractInsnNode findNextOpCode( final AbstractInsnNode fromInstruction, final int opcode ) - { - AbstractInsnNode nextInsn = fromInstruction; - do - { - if( nextInsn.getOpcode() == opcode ) - { - return nextInsn; - } - } - while( ( nextInsn = nextInsn.getNext() ) != null ); + /** + * Finds the next occurrence of the opcode after the specified instruction. + * + * @param fromInstruction + * @param opcode + * @return + */ + protected AbstractInsnNode findNextOpCode(final AbstractInsnNode fromInstruction, final int opcode) { + AbstractInsnNode nextInsn = fromInstruction; + do { + if (nextInsn.getOpcode() == opcode) { + return nextInsn; + } + } while ((nextInsn = nextInsn.getNext()) != null); - return null; - } + return null; + } - /** - * Locates a sequence of instructions. - * - * @param instructions - * @param opSequence - * @param skipNons - * If true all -1 instructions will be skipped - * @return The last instruction in the sequence. - */ - protected AbstractInsnNode findSequence( final InsnList instructions, final int opSequence[], final boolean skipNons ) - { - int seqIndex = 0; - AbstractInsnNode insertionPoint = null; - for( int index = 0; index < instructions.size(); ++index ) - { - // Get the instruction - AbstractInsnNode ins = instructions.get( index ); + /** + * Locates a sequence of instructions. + * + * @param instructions + * @param opSequence + * @param skipNons + * If true all -1 instructions will be skipped + * @return The last instruction in the sequence. + */ + protected AbstractInsnNode findSequence( + final InsnList instructions, final int opSequence[], final boolean skipNons) { + int seqIndex = 0; + AbstractInsnNode insertionPoint = null; + for (int index = 0; index < instructions.size(); ++index) { + // Get the instruction + AbstractInsnNode ins = instructions.get(index); - if( skipNons && ( ins.getOpcode() == -1 ) ) - { - continue; - } + if (skipNons && (ins.getOpcode() == -1)) { + continue; + } - // Does it match the sequence? - if( ins.getOpcode() == opSequence[seqIndex] ) - { - // Has the full sequence been found? - if( ++seqIndex == opSequence.length ) - { - // Found the full sequence - insertionPoint = ins; - break; - } - } - else if( ins.getOpcode() == opSequence[0] ) - { - // Restart sequence - seqIndex = 1; - } - else - { - // Reset sequence - seqIndex = 0; - } - } + // Does it match the sequence? + if (ins.getOpcode() == opSequence[seqIndex]) { + // Has the full sequence been found? + if (++seqIndex == opSequence.length) { + // Found the full sequence + insertionPoint = ins; + break; + } + } else if (ins.getOpcode() == opSequence[0]) { + // Restart sequence + seqIndex = 1; + } else { + // Reset sequence + seqIndex = 0; + } + } - return insertionPoint; - } + return insertionPoint; + } - /** - * Adds an entry to the log. - * - * @param text - */ - protected void log( final String text ) - { - FMLRelaunchLog.log( "ThE-Core", Level.INFO, text ); - } + /** + * Adds an entry to the log. + * + * @param text + */ + protected void log(final String text) { + FMLRelaunchLog.log("ThE-Core", Level.INFO, text); + } - protected void logInstructionDetails( final AbstractInsnNode insn ) - { - // Visit the instruction - insn.accept( AClassTransformer.asmVisitor ); + protected void logInstructionDetails(final AbstractInsnNode insn) { + // Visit the instruction + insn.accept(AClassTransformer.asmVisitor); - // Create the string writer - StringWriter sw = new StringWriter(); + // Create the string writer + StringWriter sw = new StringWriter(); - // Print the details into the writer - AClassTransformer.asmPrinter.print( new PrintWriter( sw ) ); + // Print the details into the writer + AClassTransformer.asmPrinter.print(new PrintWriter(sw)); - // Clear the printer - AClassTransformer.asmPrinter.getText().clear(); + // Clear the printer + AClassTransformer.asmPrinter.getText().clear(); - // Log the details - this.log( sw.toString() ); - } + // Log the details + this.log(sw.toString()); + } - /** - * Action to take if the transform fails. - */ - protected abstract void onTransformFailure(); + /** + * Action to take if the transform fails. + */ + protected abstract void onTransformFailure(); - /** - * Internal call to transform the class. - * - * @param classBytes - * @return - */ - protected abstract void transform( ClassNode classNode ); + /** + * Internal call to transform the class. + * + * @param classBytes + * @return + */ + protected abstract void transform(ClassNode classNode); - /** - * Transforms the class. - * - * @param classBytes - * @return - */ - public final byte[] transformClass( final byte[] classBytes ) - { - try - { - this.log( String.format( "Transforming Class (%s)", this.classCanonicalName ) ); + /** + * Transforms the class. + * + * @param classBytes + * @return + */ + public final byte[] transformClass(final byte[] classBytes) { + try { + this.log(String.format("Transforming Class (%s)", this.classCanonicalName)); - // Create the class node and read in the class - ClassNode classNode = new ClassNode(); - ClassReader classReader = new ClassReader( classBytes ); - classReader.accept( classNode, 0 ); + // Create the class node and read in the class + ClassNode classNode = new ClassNode(); + ClassReader classReader = new ClassReader(classBytes); + classReader.accept(classNode, 0); - // Transform - this.transform( classNode ); + // Transform + this.transform(classNode); - // Create the writer - ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - classNode.accept( writer ); + // Create the writer + ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); - // Return the modified class - return writer.toByteArray(); - } - catch( Exception e ) - { - this.log( String.format( "Unable to transform (%s)", this.classCanonicalName ) ); - this.onTransformFailure(); - } - return classBytes; - } + // Return the modified class + return writer.toByteArray(); + } catch (Exception e) { + this.log(String.format("Unable to transform (%s)", this.classCanonicalName)); + this.onTransformFailure(); + } + return classBytes; + } } diff --git a/src/main/java/thaumicenergistics/fml/ASMTransformer.java b/src/main/java/thaumicenergistics/fml/ASMTransformer.java index fb9bcf95..f37e370d 100644 --- a/src/main/java/thaumicenergistics/fml/ASMTransformer.java +++ b/src/main/java/thaumicenergistics/fml/ASMTransformer.java @@ -6,53 +6,45 @@ import thaumicenergistics.fml.classtransformers.ae.ClassTransformer_CraftingTree import thaumicenergistics.fml.classtransformers.ae.ClassTransformer_GuiMEMonitorable; import thaumicenergistics.fml.classtransformers.tc.*; -public class ASMTransformer - implements IClassTransformer -{ - /** - * Map of all transformers
- * Class name -> Transformer - */ - private final HashMap tranformers; +public class ASMTransformer implements IClassTransformer { + /** + * Map of all transformers
+ * Class name -> Transformer + */ + private final HashMap tranformers; - public ASMTransformer() - { - // Create the transformers map - this.tranformers = new HashMap(); + public ASMTransformer() { + // Create the transformers map + this.tranformers = new HashMap(); - // Add Thaumcraft transformers - this.addTransformer( new ClassTransformer_Aspect() ); - this.addTransformer( new ClassTransformer_RenderGolemBase() ); - this.addTransformer( new ClassTransformer_ItemGolemPlacer() ); - this.addTransformer( new ClassTransformer_ItemGolemBell() ); - this.addTransformer( new ClassTransformer_EntityGolemBase() ); + // Add Thaumcraft transformers + this.addTransformer(new ClassTransformer_Aspect()); + this.addTransformer(new ClassTransformer_RenderGolemBase()); + this.addTransformer(new ClassTransformer_ItemGolemPlacer()); + this.addTransformer(new ClassTransformer_ItemGolemBell()); + this.addTransformer(new ClassTransformer_EntityGolemBase()); - // Add AE transformers - this.addTransformer( new ClassTransformer_CraftingTreeProcess() ); - this.addTransformer( new ClassTransformer_GuiMEMonitorable() ); - } + // Add AE transformers + this.addTransformer(new ClassTransformer_CraftingTreeProcess()); + this.addTransformer(new ClassTransformer_GuiMEMonitorable()); + } - /** - * Adds a transformer to the map. - * - * @param transformer - */ - private void addTransformer( final AClassTransformer transformer ) - { - this.tranformers.put( transformer.classCanonicalName, transformer ); - } + /** + * Adds a transformer to the map. + * + * @param transformer + */ + private void addTransformer(final AClassTransformer transformer) { + this.tranformers.put(transformer.classCanonicalName, transformer); + } - @Override - public byte[] transform( final String name, final String transformedName, final byte[] basicClass ) - { - AClassTransformer transformer; - if( ( transformer = this.tranformers.getOrDefault( transformedName, null ) ) != null ) - { - return transformer.transformClass( basicClass ); - } - - return basicClass; - - } + @Override + public byte[] transform(final String name, final String transformedName, final byte[] basicClass) { + AClassTransformer transformer; + if ((transformer = this.tranformers.getOrDefault(transformedName, null)) != null) { + return transformer.transformClass(basicClass); + } + return basicClass; + } } diff --git a/src/main/java/thaumicenergistics/fml/ThECore.java b/src/main/java/thaumicenergistics/fml/ThECore.java index 74908548..a5152274 100644 --- a/src/main/java/thaumicenergistics/fml/ThECore.java +++ b/src/main/java/thaumicenergistics/fml/ThECore.java @@ -1,12 +1,12 @@ package thaumicenergistics.fml; -import java.util.Map; import com.google.common.eventbus.EventBus; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.LoadController; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; +import java.util.Map; /** * Thaumic Energistics Core Mod. @@ -15,92 +15,76 @@ import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; * */ @MCVersion("1.7.10") -public class ThECore - extends DummyModContainer - implements IFMLLoadingPlugin -{ - /** - * Set to true if any classes required for golem hooks can not be transformed. - */ - public static boolean golemHooksTransformFailed = false; +public class ThECore extends DummyModContainer implements IFMLLoadingPlugin { + /** + * Set to true if any classes required for golem hooks can not be transformed. + */ + public static boolean golemHooksTransformFailed = false; - private final ModMetadata metadata = new ModMetadata(); + private final ModMetadata metadata = new ModMetadata(); - public ThECore() - { - this.metadata.autogenerated = false; - this.metadata.authorList.add( "Nividica" ); - this.metadata.credits = "Nividica"; - this.metadata.modId = this.getModId(); - this.metadata.version = this.getVersion(); - this.metadata.name = this.getName(); - this.metadata.url = "http://minecraft.curseforge.com/projects/thaumic-energistics"; - this.metadata.logoFile = "assets/thaumicenergistics/meta/logo.png"; - this.metadata.description = "Embedded Coremod for Thaumic Energistics"; - } + public ThECore() { + this.metadata.autogenerated = false; + this.metadata.authorList.add("Nividica"); + this.metadata.credits = "Nividica"; + this.metadata.modId = this.getModId(); + this.metadata.version = this.getVersion(); + this.metadata.name = this.getName(); + this.metadata.url = "http://minecraft.curseforge.com/projects/thaumic-energistics"; + this.metadata.logoFile = "assets/thaumicenergistics/meta/logo.png"; + this.metadata.description = "Embedded Coremod for Thaumic Energistics"; + } - @Override - public String getAccessTransformerClass() - { - return null; - } + @Override + public String getAccessTransformerClass() { + return null; + } - @Override - public String[] getASMTransformerClass() - { - return new String[] { "thaumicenergistics.fml.ASMTransformer" }; - } + @Override + public String[] getASMTransformerClass() { + return new String[] {"thaumicenergistics.fml.ASMTransformer"}; + } - @Override - public String getDisplayVersion() - { - return this.getVersion(); - } + @Override + public String getDisplayVersion() { + return this.getVersion(); + } - @Override - public ModMetadata getMetadata() - { - return this.metadata; - } + @Override + public ModMetadata getMetadata() { + return this.metadata; + } - @Override - public String getModContainerClass() - { - return "thaumicenergistics.fml.ThECore"; - } + @Override + public String getModContainerClass() { + return "thaumicenergistics.fml.ThECore"; + } - @Override - public String getModId() - { - return "ThE-core"; - } + @Override + public String getModId() { + return "ThE-core"; + } - @Override - public String getName() - { - return "Thaumic Energistics Core"; - } + @Override + public String getName() { + return "Thaumic Energistics Core"; + } - @Override - public String getSetupClass() - { - return null; - } + @Override + public String getSetupClass() { + return null; + } - @Override - public String getVersion() - { - return "1.0.0.1"; - } + @Override + public String getVersion() { + return "1.0.0.1"; + } - @Override - public void injectData( final Map data ) - { - } + @Override + public void injectData(final Map data) {} - @Override - public boolean registerBus( final EventBus bus, final LoadController controller ) - { - return true; - } + @Override + public boolean registerBus(final EventBus bus, final LoadController controller) { + return true; + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_CraftingTreeProcess.java b/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_CraftingTreeProcess.java index ce8c3c96..26f0d500 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_CraftingTreeProcess.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_CraftingTreeProcess.java @@ -10,57 +10,48 @@ import thaumicenergistics.fml.AClassTransformer; *
  • Adds this.world = world to constructor.
  • * */ -public class ClassTransformer_CraftingTreeProcess - extends AClassTransformer -{ +public class ClassTransformer_CraftingTreeProcess extends AClassTransformer { - public ClassTransformer_CraftingTreeProcess() - { - super( "appeng.crafting.CraftingTreeProcess" ); - } + public ClassTransformer_CraftingTreeProcess() { + super("appeng.crafting.CraftingTreeProcess"); + } - private void transformConstructor( final MethodNode method ) - { - int opSequence[] = new int[] { Opcodes.ILOAD, Opcodes.PUTFIELD, Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.ASTORE }; - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, true ); + private void transformConstructor(final MethodNode method) { + int opSequence[] = + new int[] {Opcodes.ILOAD, Opcodes.PUTFIELD, Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.ASTORE}; + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, true); - // Insert this.world = world - InsnList instructionList = new InsnList(); + // Insert this.world = world + InsnList instructionList = new InsnList(); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // world - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 6 ) ); + // world + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 6)); - // this.world = world - instructionList.add( new FieldInsnNode( Opcodes.PUTFIELD, - "appeng/crafting/CraftingTreeProcess", "world", "Lnet/minecraft/world/World;" ) ); + // this.world = world + instructionList.add(new FieldInsnNode( + Opcodes.PUTFIELD, "appeng/crafting/CraftingTreeProcess", "world", "Lnet/minecraft/world/World;")); - // Insert the new code - method.instructions.insert( insertionPoint, instructionList ); + // Insert the new code + method.instructions.insert(insertionPoint, instructionList); + } - } - - @Override - protected void onTransformFailure() - { - this.log( "Recipes containing Thaumcraft's primordial pearl will not function with AE2's crafting system." ); - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Constructor - if( method.name.equals( AClassTransformer.InstanceConstructorName ) ) - { - this.transformConstructor( method ); - break; // Stop searching. - } - } - } + @Override + protected void onTransformFailure() { + this.log("Recipes containing Thaumcraft's primordial pearl will not function with AE2's crafting system."); + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + // Constructor + if (method.name.equals(AClassTransformer.InstanceConstructorName)) { + this.transformConstructor(method); + break; // Stop searching. + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_GuiMEMonitorable.java b/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_GuiMEMonitorable.java index 315e2158..d907e776 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_GuiMEMonitorable.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/ae/ClassTransformer_GuiMEMonitorable.java @@ -4,63 +4,58 @@ import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import thaumicenergistics.fml.AClassTransformer; -public class ClassTransformer_GuiMEMonitorable - extends AClassTransformer -{ +public class ClassTransformer_GuiMEMonitorable extends AClassTransformer { - public ClassTransformer_GuiMEMonitorable() - { - super( "appeng.client.gui.implementations.GuiMEMonitorable" ); - } + public ClassTransformer_GuiMEMonitorable() { + super("appeng.client.gui.implementations.GuiMEMonitorable"); + } - private void transformPostUpdate( final MethodNode method ) - { - // Search for: - // for( final IAEItemStack is : list ) - int opSequence[] = new int[] { Opcodes.IFEQ, Opcodes.ALOAD, Opcodes.INVOKEINTERFACE, Opcodes.CHECKCAST, Opcodes.ASTORE }; - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, true ); + private void transformPostUpdate(final MethodNode method) { + // Search for: + // for( final IAEItemStack is : list ) + int opSequence[] = + new int[] {Opcodes.IFEQ, Opcodes.ALOAD, Opcodes.INVOKEINTERFACE, Opcodes.CHECKCAST, Opcodes.ASTORE}; + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, true); - // Get the end of loop jump - JumpInsnNode EOL_Jump = (JumpInsnNode)this.findNextOpCode( insertionPoint, Opcodes.GOTO ); + // Get the end of loop jump + JumpInsnNode EOL_Jump = (JumpInsnNode) this.findNextOpCode(insertionPoint, Opcodes.GOTO); - // Insert hook: - // if( AEHooks.isItemGUIBlacklisted( is ) ) continue; - InsnList instructionList = new InsnList(); + // Insert hook: + // if( AEHooks.isItemGUIBlacklisted( is ) ) continue; + InsnList instructionList = new InsnList(); - // is - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 3 ) ); + // is + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 3)); - // Static call: isItemGUIBlacklisted( IAEItemStack ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, "thaumicenergistics/common/integration/AEHooks", - "isItemGUIBlacklisted", "(Lappeng/api/storage/data/IAEItemStack;)Z", - false ) ); + // Static call: isItemGUIBlacklisted( IAEItemStack ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + "thaumicenergistics/common/integration/AEHooks", + "isItemGUIBlacklisted", + "(Lappeng/api/storage/data/IAEItemStack;)Z", + false)); - // continue - instructionList.add( new JumpInsnNode( Opcodes.IFNE, EOL_Jump.label ) ); + // continue + instructionList.add(new JumpInsnNode(Opcodes.IFNE, EOL_Jump.label)); - // Insert into method - method.instructions.insert( insertionPoint, instructionList ); - } + // Insert into method + method.instructions.insert(insertionPoint, instructionList); + } - @Override - protected void onTransformFailure() - { - // No action required - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Constructor - if( method.name.equals( "postUpdate" ) ) - { - this.transformPostUpdate( method ); - return; // Stop searching. - } - } - } + @Override + protected void onTransformFailure() { + // No action required + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + // Constructor + if (method.name.equals("postUpdate")) { + this.transformPostUpdate(method); + return; // Stop searching. + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_Aspect.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_Aspect.java index 0496e63d..dc8921e5 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_Aspect.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_Aspect.java @@ -10,68 +10,62 @@ import thaumicenergistics.fml.AClassTransformer; *
  • Adds hook to constructor
  • * */ -public class ClassTransformer_Aspect - extends AClassTransformer -{ - private static final String CLASS_Aspect = "thaumcraft/api/aspects/Aspect"; - private static final String CLASS_AspectHooks = "thaumicenergistics/common/integration/tc/AspectHooks"; +public class ClassTransformer_Aspect extends AClassTransformer { + private static final String CLASS_Aspect = "thaumcraft/api/aspects/Aspect"; + private static final String CLASS_AspectHooks = "thaumicenergistics/common/integration/tc/AspectHooks"; - public ClassTransformer_Aspect() - { - super( "thaumcraft.api.aspects.Aspect" ); - } + public ClassTransformer_Aspect() { + super("thaumcraft.api.aspects.Aspect"); + } - private boolean transformConstructor( final MethodNode method ) - { - // Is this the full constructor? - // Check description - if( !"(Ljava/lang/String;I[Lthaumcraft/api/aspects/Aspect;Lnet/minecraft/util/ResourceLocation;I)V".equals( method.desc ) ) - { - return false; - } + private boolean transformConstructor(final MethodNode method) { + // Is this the full constructor? + // Check description + if (!"(Ljava/lang/String;I[Lthaumcraft/api/aspects/Aspect;Lnet/minecraft/util/ResourceLocation;I)V" + .equals(method.desc)) { + return false; + } - int opSequence[] = new int[] { Opcodes.GETSTATIC, Opcodes.ALOAD, Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.POP }; - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, false ); + int opSequence[] = + new int[] {Opcodes.GETSTATIC, Opcodes.ALOAD, Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.POP}; + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, false); - // Insert the hook - // AspectHooks.hook_AspectInit( this ) - InsnList instructionList = new InsnList(); + // Insert the hook + // AspectHooks.hook_AspectInit( this ) + InsnList instructionList = new InsnList(); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // AspectHooks.hook_AspectInit( Aspect ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - ClassTransformer_Aspect.CLASS_AspectHooks, "hook_AspectInit", - "(L" + ClassTransformer_Aspect.CLASS_Aspect + ";)V", false ) ); + // AspectHooks.hook_AspectInit( Aspect ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + ClassTransformer_Aspect.CLASS_AspectHooks, + "hook_AspectInit", + "(L" + ClassTransformer_Aspect.CLASS_Aspect + ";)V", + false)); - // Insert the static call - method.instructions.insert( insertionPoint, instructionList ); + // Insert the static call + method.instructions.insert(insertionPoint, instructionList); - return true; - } + return true; + } - @Override - protected void onTransformFailure() - { - // No action required. - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Constructor - if( method.name.equals( AClassTransformer.InstanceConstructorName ) ) - { - if( this.transformConstructor( method ) ) - { - return; // Stop searching. - } - } - } - } + @Override + protected void onTransformFailure() { + // No action required. + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + // Constructor + if (method.name.equals(AClassTransformer.InstanceConstructorName)) { + if (this.transformConstructor(method)) { + return; // Stop searching. + } + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_EntityGolemBase.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_EntityGolemBase.java index 1f137bd6..41052392 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_EntityGolemBase.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_EntityGolemBase.java @@ -20,281 +20,279 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class ClassTransformer_EntityGolemBase - extends AClassTransformer -{ +public class ClassTransformer_EntityGolemBase extends AClassTransformer { - public ClassTransformer_EntityGolemBase() - { - super( "thaumcraft.common.entities.golems.EntityGolemBase" ); - } + public ClassTransformer_EntityGolemBase() { + super("thaumcraft.common.entities.golems.EntityGolemBase"); + } - private void insertMethod_GolemBase_onEntityUpdate( final ClassNode classNode, final boolean isObf ) - { - // Create the onEntityUpdate() method - String oEU_Name = ( isObf ? "func_70030_z" : "onEntityUpdate" ); - MethodNode onEntityUpdate = new MethodNode( Opcodes.ACC_PUBLIC, - oEU_Name, "()V", null, null ); + private void insertMethod_GolemBase_onEntityUpdate(final ClassNode classNode, final boolean isObf) { + // Create the onEntityUpdate() method + String oEU_Name = (isObf ? "func_70030_z" : "onEntityUpdate"); + MethodNode onEntityUpdate = new MethodNode(Opcodes.ACC_PUBLIC, oEU_Name, "()V", null, null); - // super.onEntityUpdate() - onEntityUpdate.instructions.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); - onEntityUpdate.instructions.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, - "net/minecraft/entity/monster/EntityGolem", oEU_Name, "()V", false ) ); + // super.onEntityUpdate() + onEntityUpdate.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + onEntityUpdate.instructions.add(new MethodInsnNode( + Opcodes.INVOKESPECIAL, "net/minecraft/entity/monster/EntityGolem", oEU_Name, "()V", false)); - // GolemHooks.hook_onEntityUpdate( this, this.hookHandlers ) - // this - onEntityUpdate.instructions.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( onEntityUpdate.instructions, 0, false ); - // GolemHooks.hook_onEntityUpdate( EntityGolemBase, Hashmap ) - onEntityUpdate.instructions.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_onEntityUpdate", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", - false ) ); + // GolemHooks.hook_onEntityUpdate( this, this.hookHandlers ) + // this + onEntityUpdate.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(onEntityUpdate.instructions, 0, false); + // GolemHooks.hook_onEntityUpdate( EntityGolemBase, Hashmap ) + onEntityUpdate.instructions.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_onEntityUpdate", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", + false)); - // return - onEntityUpdate.instructions.add( new InsnNode( Opcodes.RETURN ) ); + // return + onEntityUpdate.instructions.add(new InsnNode(Opcodes.RETURN)); - // Add the method to the class - classNode.methods.add( onEntityUpdate ); - } + // Add the method to the class + classNode.methods.add(onEntityUpdate); + } - private void transformMethod_CustomInteraction( final MethodNode method ) - { - int opSequence[] = new int[] { Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.ICONST_M1 }; - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, false ); + private void transformMethod_CustomInteraction(final MethodNode method) { + int opSequence[] = new int[] {Opcodes.ALOAD, Opcodes.INVOKEVIRTUAL, Opcodes.ICONST_M1}; + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, false); - // Go two back - insertionPoint = insertionPoint.getPrevious().getPrevious(); + // Go two back + insertionPoint = insertionPoint.getPrevious().getPrevious(); - // Find the last label - LabelNode lastLabel = (LabelNode)this.findLastType( method.instructions, AbstractInsnNode.LABEL, 1 ); + // Find the last label + LabelNode lastLabel = (LabelNode) this.findLastType(method.instructions, AbstractInsnNode.LABEL, 1); - // Insert the hook - // GolemHooks.hook_CustomInteraction( this, player, this.hookHandlers ); - InsnList instructionList = new InsnList(); + // Insert the hook + // GolemHooks.hook_CustomInteraction( this, player, this.hookHandlers ); + InsnList instructionList = new InsnList(); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // player - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); + // player + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 1)); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 0, false ); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 0, false); - // GolemHooks.setupGolemHook( EntityGolemBase, Hashmap ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_CustomInteraction", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";Lnet/minecraft/entity/player/EntityPlayer;L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + - ";)Z", - false ) ); + // GolemHooks.setupGolemHook( EntityGolemBase, Hashmap ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_CustomInteraction", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";Lnet/minecraft/entity/player/EntityPlayer;L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + + ";)Z", + false)); - // Insert the return check - instructionList.add( new JumpInsnNode( Opcodes.IFNE, lastLabel ) ); + // Insert the return check + instructionList.add(new JumpInsnNode(Opcodes.IFNE, lastLabel)); - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); - } + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - private void transformMethod_EntityInit( final MethodNode method ) - { - // Locate the return statement - AbstractInsnNode insertionPoint = this.findLastOpCode( method.instructions, Opcodes.RETURN ); + private void transformMethod_EntityInit(final MethodNode method) { + // Locate the return statement + AbstractInsnNode insertionPoint = this.findLastOpCode(method.instructions, Opcodes.RETURN); - // Insert the hookHandlers initializer - // hookHandlers = new HashMap(); - InsnList instructionList = new InsnList(); + // Insert the hookHandlers initializer + // hookHandlers = new HashMap(); + InsnList instructionList = new InsnList(); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // new HashMap - instructionList.add( new TypeInsnNode( Opcodes.NEW, GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers ) ); - instructionList.add( new InsnNode( Opcodes.DUP ) ); + // new HashMap + instructionList.add( + new TypeInsnNode(Opcodes.NEW, GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers)); + instructionList.add(new InsnNode(Opcodes.DUP)); - // Hashmap. - instructionList.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers, "", "()V", false ) ); + // Hashmap. + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESPECIAL, + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers, + "", + "()V", + false)); - // .hookHandlers = - instructionList.add( new FieldInsnNode( Opcodes.PUTFIELD, GolemHookTransformHelper.CLASS_EntityGolemBase, - GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, - "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";" ) ); + // .hookHandlers = + instructionList.add(new FieldInsnNode( + Opcodes.PUTFIELD, + GolemHookTransformHelper.CLASS_EntityGolemBase, + GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, + "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";")); - // Insert the hook - // GolemHooks.hook_EntityInit( this, this.hookHandlers ); + // Insert the hook + // GolemHooks.hook_EntityInit( this, this.hookHandlers ); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 0, false ); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 0, false); - // GolemHooks.hook_EntityInit( EntityGolemBase, Hashmap ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_EntityInit", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", - false ) ); + // GolemHooks.hook_EntityInit( EntityGolemBase, Hashmap ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_EntityInit", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", + false)); - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - } + private void transformMethod_ReadEntityFromNBT(final MethodNode method) { + // Locate the super call + AbstractInsnNode insertionPoint = this.findFirstOpCode(method.instructions, Opcodes.INVOKESPECIAL); - private void transformMethod_ReadEntityFromNBT( final MethodNode method ) - { - // Locate the super call - AbstractInsnNode insertionPoint = this.findFirstOpCode( method.instructions, Opcodes.INVOKESPECIAL ); + // Insert the hook + // GolemHooks.hook_ReadEntityFromNBT( this, this.hookHandlers, nbt); + InsnList instructionList = new InsnList(); - // Insert the hook - // GolemHooks.hook_ReadEntityFromNBT( this, this.hookHandlers, nbt); - InsnList instructionList = new InsnList(); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 0, false); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 0, false ); + // nbt + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 1)); - // nbt - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); + // GolemHooks.hook_ReadEntityFromNBT( EntityGolemBase, Hashmap, NBTTagCompound ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_ReadEntityFromNBT", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + + ";" + "Lnet/minecraft/nbt/NBTTagCompound;" + + ")V", + false)); - // GolemHooks.hook_ReadEntityFromNBT( EntityGolemBase, Hashmap, NBTTagCompound ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_ReadEntityFromNBT", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";" + - "Lnet/minecraft/nbt/NBTTagCompound;" + - ")V", - false ) ); + // Insert the static call + method.instructions.insert(insertionPoint, instructionList); + } - // Insert the static call - method.instructions.insert( insertionPoint, instructionList ); - } + private void transformMethod_SetupGolem(final MethodNode method) { + // Set the insertion point to the instruction before return + // Previous node is important, since the method returns a value, the previous + // instruction is what sets that return value. + AbstractInsnNode insertionPoint = this.findLastOpCode(method.instructions, Opcodes.IRETURN); + insertionPoint = insertionPoint.getPrevious(); - private void transformMethod_SetupGolem( final MethodNode method ) - { - // Set the insertion point to the instruction before return - // Previous node is important, since the method returns a value, the previous - // instruction is what sets that return value. - AbstractInsnNode insertionPoint = this.findLastOpCode( method.instructions, Opcodes.IRETURN ); - insertionPoint = insertionPoint.getPrevious(); + // Insert the hook + // GolemHooks.setupGolemHook( this, this.hookHandlers ); + InsnList instructionList = new InsnList(); - // Insert the hook - // GolemHooks.setupGolemHook( this, this.hookHandlers ); - InsnList instructionList = new InsnList(); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 0, false); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 0, false ); + // GolemHooks.setupGolemHook( EntityGolemBase, Hashmap ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_SetupGolem", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", + false)); - // GolemHooks.setupGolemHook( EntityGolemBase, Hashmap ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_SetupGolem", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", - false ) ); + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); + private void transformMethod_WriteEntityToNBT(final MethodNode method) { + // Locate the return statement + AbstractInsnNode insertionPoint = this.findLastOpCode(method.instructions, Opcodes.RETURN); - } + // Insert the hook + // GolemHooks.hook_WriteEntityToNBT( this, this.hookHandlers, nbt); + InsnList instructionList = new InsnList(); - private void transformMethod_WriteEntityToNBT( final MethodNode method ) - { - // Locate the return statement - AbstractInsnNode insertionPoint = this.findLastOpCode( method.instructions, Opcodes.RETURN ); + // this + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 0)); - // Insert the hook - // GolemHooks.hook_WriteEntityToNBT( this, this.hookHandlers, nbt); - InsnList instructionList = new InsnList(); + // this.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 0, false); - // this - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); + // nbt + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 1)); - // this.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 0, false ); + // GolemHooks.hook_WriteEntityToNBT( EntityGolemBase, Hashmap, NBTTagCompound ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_WriteEntityToNBT", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + + ";" + "Lnet/minecraft/nbt/NBTTagCompound;" + + ")V", + false)); - // nbt - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - // GolemHooks.hook_WriteEntityToNBT( EntityGolemBase, Hashmap, NBTTagCompound ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_WriteEntityToNBT", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";" + - "Lnet/minecraft/nbt/NBTTagCompound;" + - ")V", - false ) ); + @Override + protected void onTransformFailure() { + ThECore.golemHooksTransformFailed = true; + } - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); - } + @Override + protected void transform(final ClassNode classNode) { + // Add the handlers field + // public HashMap hookHandlers; + classNode.fields.add(new FieldNode( + Opcodes.ACC_PUBLIC, + GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, + "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";", + "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";", + null)); - @Override - protected void onTransformFailure() - { - ThECore.golemHooksTransformFailed = true; - } + boolean isObf = false; - @Override - protected void transform( final ClassNode classNode ) - { - // Add the handlers field - // public HashMap hookHandlers; - classNode.fields.add( new FieldNode( Opcodes.ACC_PUBLIC, - GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, - "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";", - "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";", - null ) ); - - boolean isObf = false; - - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Look for an obfuscated method - if( method.name.equals( "func_70014_b" ) ) - { - isObf = true; - } - // Setup golem - if( method.name.equals( "setupGolem" ) ) - { - this.transformMethod_SetupGolem( method ); - } - // Custom interaction - else if( method.name.equals( "customInteraction" ) ) - { - this.transformMethod_CustomInteraction( method ); - } - // Write entity NBT - else if( method.name.equals( "func_70014_b" ) || method.name.equals( "writeEntityToNBT" ) ) - { - this.transformMethod_WriteEntityToNBT( method ); - } - // Read entity from NBT - else if( method.name.equals( "func_70037_a" ) || method.name.equals( "readEntityFromNBT" ) ) - { - this.transformMethod_ReadEntityFromNBT( method ); - } - // Entity Init - else if( method.name.equals( "func_70088_a" ) || method.name.equals( "entityInit" ) ) - { - this.transformMethod_EntityInit( method ); - } - } - - // Add the onEntityUpdate method. - this.insertMethod_GolemBase_onEntityUpdate( classNode, isObf ); - } + // Transform methods + for (MethodNode method : classNode.methods) { + // Look for an obfuscated method + if (method.name.equals("func_70014_b")) { + isObf = true; + } + // Setup golem + if (method.name.equals("setupGolem")) { + this.transformMethod_SetupGolem(method); + } + // Custom interaction + else if (method.name.equals("customInteraction")) { + this.transformMethod_CustomInteraction(method); + } + // Write entity NBT + else if (method.name.equals("func_70014_b") || method.name.equals("writeEntityToNBT")) { + this.transformMethod_WriteEntityToNBT(method); + } + // Read entity from NBT + else if (method.name.equals("func_70037_a") || method.name.equals("readEntityFromNBT")) { + this.transformMethod_ReadEntityFromNBT(method); + } + // Entity Init + else if (method.name.equals("func_70088_a") || method.name.equals("entityInit")) { + this.transformMethod_EntityInit(method); + } + } + // Add the onEntityUpdate method. + this.insertMethod_GolemBase_onEntityUpdate(classNode, isObf); + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemBell.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemBell.java index c1377f6c..6a4352a4 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemBell.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemBell.java @@ -14,70 +14,65 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class ClassTransformer_ItemGolemBell - extends AClassTransformer -{ +public class ClassTransformer_ItemGolemBell extends AClassTransformer { - public ClassTransformer_ItemGolemBell() - { - super( "thaumcraft.common.entities.golems.ItemGolemBell" ); - } + public ClassTransformer_ItemGolemBell() { + super("thaumcraft.common.entities.golems.ItemGolemBell"); + } - private void transformMethod_OnLeftClickEntity( final MethodNode method ) - { - int opSequence[] = new int[] { Opcodes.GETSTATIC, Opcodes.ICONST_1, Opcodes.ILOAD, Opcodes.INVOKESPECIAL, Opcodes.ASTORE }; + private void transformMethod_OnLeftClickEntity(final MethodNode method) { + int opSequence[] = + new int[] {Opcodes.GETSTATIC, Opcodes.ICONST_1, Opcodes.ILOAD, Opcodes.INVOKESPECIAL, Opcodes.ASTORE}; - // Locate the sequence - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, true ); + // Locate the sequence + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, true); - // Insert the hook - // GolemHooks.hook_Bell_OnLeftClickGolem( entity, dropped, player, ((EntityGolemBase)entity).hookHandlers ) - InsnList instructionList = new InsnList(); + // Insert the hook + // GolemHooks.hook_Bell_OnLeftClickGolem( entity, dropped, player, ((EntityGolemBase)entity).hookHandlers ) + InsnList instructionList = new InsnList(); - // ((EntityGolemBase)entity) - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 3 ) ); - instructionList.add( new TypeInsnNode( Opcodes.CHECKCAST, GolemHookTransformHelper.CLASS_EntityGolemBase ) ); + // ((EntityGolemBase)entity) + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 3)); + instructionList.add(new TypeInsnNode(Opcodes.CHECKCAST, GolemHookTransformHelper.CLASS_EntityGolemBase)); - // dropped - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 9 ) ); + // dropped + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 9)); - // player - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 2 ) ); + // player + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 2)); - // ((EntityGolemBase)entity).hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 3, true ); + // ((EntityGolemBase)entity).hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 3, true); - // GolemHooks.hook_Bell_OnLeftClickGolem( EntityGolemBase, ItemStack, EntityPlayer, Hashmap ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_Bell_OnLeftClickGolem", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + - ";Lnet/minecraft/item/ItemStack;Lnet/minecraft/entity/player/EntityPlayer;L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", - false ) ); + // GolemHooks.hook_Bell_OnLeftClickGolem( EntityGolemBase, ItemStack, EntityPlayer, Hashmap ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_Bell_OnLeftClickGolem", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + + ";Lnet/minecraft/item/ItemStack;Lnet/minecraft/entity/player/EntityPlayer;L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + + ";)V", + false)); - // Insert the static call - method.instructions.insert( insertionPoint, instructionList ); - } + // Insert the static call + method.instructions.insert(insertionPoint, instructionList); + } - @Override - protected void onTransformFailure() - { - ThECore.golemHooksTransformFailed = true; - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Left click entity - if( method.name.equals( "onLeftClickEntity" ) ) - { - this.transformMethod_OnLeftClickEntity( method ); - return; // Stop searching. - } - } - } + @Override + protected void onTransformFailure() { + ThECore.golemHooksTransformFailed = true; + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + // Left click entity + if (method.name.equals("onLeftClickEntity")) { + this.transformMethod_OnLeftClickEntity(method); + return; // Stop searching. + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemPlacer.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemPlacer.java index 4b59e54b..9b571f2f 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemPlacer.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_ItemGolemPlacer.java @@ -14,68 +14,60 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class ClassTransformer_ItemGolemPlacer - extends AClassTransformer -{ +public class ClassTransformer_ItemGolemPlacer extends AClassTransformer { - public ClassTransformer_ItemGolemPlacer() - { - super( "thaumcraft.common.entities.golems.ItemGolemPlacer" ); - } + public ClassTransformer_ItemGolemPlacer() { + super("thaumcraft.common.entities.golems.ItemGolemPlacer"); + } - private void transformMethod_SpawnCreature( final MethodNode method ) - { - // Locate "golem.setup(side);" - int opSequence[] = new int[] { Opcodes.PUTFIELD, Opcodes.ALOAD, Opcodes.ILOAD, Opcodes.INVOKEVIRTUAL }; - AbstractInsnNode insertionPoint = this.findSequence( method.instructions, opSequence, true ); + private void transformMethod_SpawnCreature(final MethodNode method) { + // Locate "golem.setup(side);" + int opSequence[] = new int[] {Opcodes.PUTFIELD, Opcodes.ALOAD, Opcodes.ILOAD, Opcodes.INVOKEVIRTUAL}; + AbstractInsnNode insertionPoint = this.findSequence(method.instructions, opSequence, true); - // Move back to the aload - insertionPoint = insertionPoint.getPrevious().getPrevious(); + // Move back to the aload + insertionPoint = insertionPoint.getPrevious().getPrevious(); - // Insert the hook - // GolemHooks.hook_Placer_SpawnGolem( golem, stack, golem.hookHandlers ) - InsnList instructionList = new InsnList(); + // Insert the hook + // GolemHooks.hook_Placer_SpawnGolem( golem, stack, golem.hookHandlers ) + InsnList instructionList = new InsnList(); - // golem - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 12 ) ); + // golem + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 12)); - // stack - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 9 ) ); + // stack + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 9)); - // golem.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 12, false ); + // golem.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 12, false); - // GolemHooks.hook_Placer_SpawnGolem( EntityGolemBase, ItemStack, Hashmap ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_Placer_SpawnGolem", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";Lnet/minecraft/item/ItemStack;L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", - false ) ); + // GolemHooks.hook_Placer_SpawnGolem( EntityGolemBase, ItemStack, Hashmap ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_Placer_SpawnGolem", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";Lnet/minecraft/item/ItemStack;L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";)V", + false)); - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - } - - @Override - protected void onTransformFailure() - { - ThECore.golemHooksTransformFailed = true; - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - // Spawn creature - if( method.name.equals( "spawnCreature" ) ) - { - this.transformMethod_SpawnCreature( method ); - break; // Stop searching. - } - } - } + @Override + protected void onTransformFailure() { + ThECore.golemHooksTransformFailed = true; + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + // Spawn creature + if (method.name.equals("spawnCreature")) { + this.transformMethod_SpawnCreature(method); + break; // Stop searching. + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_RenderGolemBase.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_RenderGolemBase.java index 8570b714..d29eecfc 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_RenderGolemBase.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/ClassTransformer_RenderGolemBase.java @@ -14,72 +14,65 @@ import thaumicenergistics.fml.ThECore; * @author Nividica * */ -public class ClassTransformer_RenderGolemBase - extends AClassTransformer -{ +public class ClassTransformer_RenderGolemBase extends AClassTransformer { - public ClassTransformer_RenderGolemBase() - { - super( "thaumcraft.client.renderers.entity.RenderGolemBase" ); - } + public ClassTransformer_RenderGolemBase() { + super("thaumcraft.client.renderers.entity.RenderGolemBase"); + } - private void transformMethod_Render( final MethodNode method ) - { - // Find the return - AbstractInsnNode insertionPoint = this.findLastOpCode( method.instructions, Opcodes.RETURN ); + private void transformMethod_Render(final MethodNode method) { + // Find the return + AbstractInsnNode insertionPoint = this.findLastOpCode(method.instructions, Opcodes.RETURN); - // Insert the hook - // GolemHooks.hook_RenderGolem( e, e.hookHandlers, par2, par4, par6, par9 ) - InsnList instructionList = new InsnList(); + // Insert the hook + // GolemHooks.hook_RenderGolem( e, e.hookHandlers, par2, par4, par6, par9 ) + InsnList instructionList = new InsnList(); - // e - instructionList.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); + // e + instructionList.add(new VarInsnNode(Opcodes.ALOAD, 1)); - // e.hookHandlers - GolemHookTransformHelper.addGetField_hookHandlers( instructionList, 1, false ); + // e.hookHandlers + GolemHookTransformHelper.addGetField_hookHandlers(instructionList, 1, false); - // par2 - instructionList.add( new VarInsnNode( Opcodes.DLOAD, 2 ) ); + // par2 + instructionList.add(new VarInsnNode(Opcodes.DLOAD, 2)); - // par4 - instructionList.add( new VarInsnNode( Opcodes.DLOAD, 4 ) ); + // par4 + instructionList.add(new VarInsnNode(Opcodes.DLOAD, 4)); - // par6 - instructionList.add( new VarInsnNode( Opcodes.DLOAD, 6 ) ); + // par6 + instructionList.add(new VarInsnNode(Opcodes.DLOAD, 6)); - // par9 - instructionList.add( new VarInsnNode( Opcodes.FLOAD, 9 ) ); + // par9 + instructionList.add(new VarInsnNode(Opcodes.FLOAD, 9)); - // GolemHooks.hook_RenderGolem( EntityGolemBase, Hashmap, double, double, double, float ) - instructionList.add( new MethodInsnNode( Opcodes.INVOKESTATIC, - GolemHookTransformHelper.CLASS_GolemHooks, "hook_RenderGolem", - "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + - GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";DDDF)V", - false ) ); + // GolemHooks.hook_RenderGolem( EntityGolemBase, Hashmap, double, double, double, float ) + instructionList.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + GolemHookTransformHelper.CLASS_GolemHooks, + "hook_RenderGolem", + "(L" + GolemHookTransformHelper.CLASS_EntityGolemBase + ";L" + + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";DDDF)V", + false)); - // Insert the static call - method.instructions.insertBefore( insertionPoint, instructionList ); - } + // Insert the static call + method.instructions.insertBefore(insertionPoint, instructionList); + } - @Override - protected void onTransformFailure() - { - ThECore.golemHooksTransformFailed = true; - } - - @Override - protected void transform( final ClassNode classNode ) - { - // Transform methods - for( MethodNode method : classNode.methods ) - { - if( method.name.equals( "render" ) ) - { - // Render - this.transformMethod_Render( method ); - break; // Stop searching. - } - } - } + @Override + protected void onTransformFailure() { + ThECore.golemHooksTransformFailed = true; + } + @Override + protected void transform(final ClassNode classNode) { + // Transform methods + for (MethodNode method : classNode.methods) { + if (method.name.equals("render")) { + // Render + this.transformMethod_Render(method); + break; // Stop searching. + } + } + } } diff --git a/src/main/java/thaumicenergistics/fml/classtransformers/tc/GolemHookTransformHelper.java b/src/main/java/thaumicenergistics/fml/classtransformers/tc/GolemHookTransformHelper.java index f44a203c..21fec3d6 100644 --- a/src/main/java/thaumicenergistics/fml/classtransformers/tc/GolemHookTransformHelper.java +++ b/src/main/java/thaumicenergistics/fml/classtransformers/tc/GolemHookTransformHelper.java @@ -6,34 +6,32 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; -class GolemHookTransformHelper -{ +class GolemHookTransformHelper { - public static final String CLASS_EntityGolemBase = "thaumcraft/common/entities/golems/EntityGolemBase"; - public static final String CLASS_GolemHooks = "thaumicenergistics/common/integration/tc/GolemHooks"; - public static final String INTERFACE_IGolemHookHandler = "thaumicenergistics/api/entities/IGolemHookHandler"; - public static final String FIELD_EntityGolemBase_hookHandlers = "hookHandlers"; - public static final String FIELDTYPE_EntityGolemBase_hookHandlers = "java/util/HashMap"; - - /** - * Adds a reference to a golems hookHandlers field to the stack. - * - * @param instructionList - * @param golemVar - * @param checkCast - * If the var specified is not type EntityGolemBase(such as just Entity or EntityLiving) a cast check must be performed. - */ - public static void addGetField_hookHandlers( final InsnList instructionList, final int golemVar, final boolean checkCast ) - { - instructionList.add( new VarInsnNode( Opcodes.ALOAD, golemVar ) ); - if( checkCast ) - { - instructionList.add( new TypeInsnNode( Opcodes.CHECKCAST, GolemHookTransformHelper.CLASS_EntityGolemBase ) ); - } - instructionList.add( new FieldInsnNode( Opcodes.GETFIELD, - GolemHookTransformHelper.CLASS_EntityGolemBase, - GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, - "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";" ) ); - } + public static final String CLASS_EntityGolemBase = "thaumcraft/common/entities/golems/EntityGolemBase"; + public static final String CLASS_GolemHooks = "thaumicenergistics/common/integration/tc/GolemHooks"; + public static final String INTERFACE_IGolemHookHandler = "thaumicenergistics/api/entities/IGolemHookHandler"; + public static final String FIELD_EntityGolemBase_hookHandlers = "hookHandlers"; + public static final String FIELDTYPE_EntityGolemBase_hookHandlers = "java/util/HashMap"; + /** + * Adds a reference to a golems hookHandlers field to the stack. + * + * @param instructionList + * @param golemVar + * @param checkCast + * If the var specified is not type EntityGolemBase(such as just Entity or EntityLiving) a cast check must be performed. + */ + public static void addGetField_hookHandlers( + final InsnList instructionList, final int golemVar, final boolean checkCast) { + instructionList.add(new VarInsnNode(Opcodes.ALOAD, golemVar)); + if (checkCast) { + instructionList.add(new TypeInsnNode(Opcodes.CHECKCAST, GolemHookTransformHelper.CLASS_EntityGolemBase)); + } + instructionList.add(new FieldInsnNode( + Opcodes.GETFIELD, + GolemHookTransformHelper.CLASS_EntityGolemBase, + GolemHookTransformHelper.FIELD_EntityGolemBase_hookHandlers, + "L" + GolemHookTransformHelper.FIELDTYPE_EntityGolemBase_hookHandlers + ";")); + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEAPIImplementation.java b/src/main/java/thaumicenergistics/implementaion/ThEAPIImplementation.java index a084506d..91ba87da 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEAPIImplementation.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEAPIImplementation.java @@ -1,11 +1,11 @@ package thaumicenergistics.implementaion; +import com.google.common.collect.ImmutableList; +import cpw.mods.fml.common.LoaderState; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; -import com.google.common.collect.ImmutableList; -import cpw.mods.fml.common.LoaderState; import thaumcraft.api.aspects.Aspect; import thaumicenergistics.api.*; import thaumicenergistics.common.ThaumicEnergistics; @@ -18,130 +18,114 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -public class ThEAPIImplementation - extends ThEApi -{ - /** - * Create the API instance. - */ - private static ThEAPIImplementation INSTANCE = null; - private final ThEBlocks blocks; - private final ThEItems items; - private final ThEParts parts; - private final List essentiaGases; - private final ThETransportPermissions transportPermissions; +public class ThEAPIImplementation extends ThEApi { + /** + * Create the API instance. + */ + private static ThEAPIImplementation INSTANCE = null; - private final ThEInteractionHelper interactionHelper; + private final ThEBlocks blocks; + private final ThEItems items; + private final ThEParts parts; + private final List essentiaGases; + private final ThETransportPermissions transportPermissions; - /** - * Private constructor - */ - private ThEAPIImplementation() - { - this.blocks = new ThEBlocks(); - this.items = new ThEItems(); - this.parts = new ThEParts(); - this.essentiaGases = new ArrayList(); - this.transportPermissions = new ThETransportPermissions(); - this.interactionHelper = new ThEInteractionHelper(); - } + private final ThEInteractionHelper interactionHelper; - /** - * Checks if ThE has finished the preinit phase. - * - * @return - */ - protected static boolean hasFinishedPreInit() - { - // Ensure that ThE has finished the PreInit phase - if( ThaumicEnergistics.getLoaderState() == LoaderState.NOINIT ) - { - // Invalid state, API can not yet load. - ThELog.warning( "API is not available until ThE finishes the PreInit phase." ); - return false; - } + /** + * Private constructor + */ + private ThEAPIImplementation() { + this.blocks = new ThEBlocks(); + this.items = new ThEItems(); + this.parts = new ThEParts(); + this.essentiaGases = new ArrayList(); + this.transportPermissions = new ThETransportPermissions(); + this.interactionHelper = new ThEInteractionHelper(); + } - return true; - } + /** + * Checks if ThE has finished the preinit phase. + * + * @return + */ + protected static boolean hasFinishedPreInit() { + // Ensure that ThE has finished the PreInit phase + if (ThaumicEnergistics.getLoaderState() == LoaderState.NOINIT) { + // Invalid state, API can not yet load. + ThELog.warning("API is not available until ThE finishes the PreInit phase."); + return false; + } - /** - * Gets the Thaumic Energistics API. - * Note: Only available after the PREINIT event. - */ - public static ThEAPIImplementation instance() - { - // Has the singleton been created? - if( ThEAPIImplementation.INSTANCE == null ) - { - // Ensure that preinit has finished. - if( !ThEAPIImplementation.hasFinishedPreInit() ) - { - return null; - } + return true; + } - // Create the singleton. - ThEAPIImplementation.INSTANCE = new ThEAPIImplementation(); - } + /** + * Gets the Thaumic Energistics API. + * Note: Only available after the PREINIT event. + */ + public static ThEAPIImplementation instance() { + // Has the singleton been created? + if (ThEAPIImplementation.INSTANCE == null) { + // Ensure that preinit has finished. + if (!ThEAPIImplementation.hasFinishedPreInit()) { + return null; + } - return ThEAPIImplementation.INSTANCE; - } + // Create the singleton. + ThEAPIImplementation.INSTANCE = new ThEAPIImplementation(); + } - @Override - public IThEBlocks blocks() - { - return this.blocks; - } + return ThEAPIImplementation.INSTANCE; + } - @Override - public IThEConfig config() - { - return ThaumicEnergistics.config; - } + @Override + public IThEBlocks blocks() { + return this.blocks; + } - @Override - public ImmutableList> essentiaGases() - { - // Do we need to update? - if( this.essentiaGases.size() != GaseousEssentia.gasList.size() ) - { - // Clear the list - this.essentiaGases.clear(); + @Override + public IThEConfig config() { + return ThaumicEnergistics.config; + } - // Get the iterator - Iterator> iterator = GaseousEssentia.gasList.entrySet().iterator(); + @Override + public ImmutableList> essentiaGases() { + // Do we need to update? + if (this.essentiaGases.size() != GaseousEssentia.gasList.size()) { + // Clear the list + this.essentiaGases.clear(); - // Add all gasses - while( iterator.hasNext() ) - { - this.essentiaGases.add( iterator.next().getValue() ); - } - } + // Get the iterator + Iterator> iterator = + GaseousEssentia.gasList.entrySet().iterator(); - return ImmutableList.of( this.essentiaGases ); - } + // Add all gasses + while (iterator.hasNext()) { + this.essentiaGases.add(iterator.next().getValue()); + } + } - @Override - public IThEInteractionHelper interact() - { - return this.interactionHelper; - } + return ImmutableList.of(this.essentiaGases); + } - @Override - public IThEItems items() - { - return this.items; - } + @Override + public IThEInteractionHelper interact() { + return this.interactionHelper; + } - @Override - public IThEParts parts() - { - return this.parts; - } + @Override + public IThEItems items() { + return this.items; + } - @Override - public IThETransportPermissions transportPermissions() - { - return this.transportPermissions; - } + @Override + public IThEParts parts() { + return this.parts; + } + @Override + public IThETransportPermissions transportPermissions() { + return this.transportPermissions; + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEBlocks.java b/src/main/java/thaumicenergistics/implementaion/ThEBlocks.java index 4e76a5ae..b5833df8 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEBlocks.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEBlocks.java @@ -9,19 +9,16 @@ import thaumicenergistics.common.blocks.BlockEnum; * @author Nividica * */ -class ThEBlocks - extends IThEBlocks -{ - ThEBlocks() - { - this.EssentiaProvider = new ThEItemDescription( BlockEnum.ESSENTIA_PROVIDER.getBlock() ); - this.InfusionProvider = new ThEItemDescription( BlockEnum.INFUSION_PROVIDER.getBlock() ); - this.IronGearBox = new ThEItemDescription( BlockEnum.IRON_GEAR_BOX.getBlock() ); - this.ThaumiumGearBox = new ThEItemDescription( BlockEnum.THAUMIUM_GEAR_BOX.getBlock() ); - this.EssentiaCellWorkbench = new ThEItemDescription( BlockEnum.ESSENTIA_CELL_WORKBENCH.getBlock() ); - this.ArcaneAssembler = new ThEItemDescription( BlockEnum.ARCANE_ASSEMBLER.getBlock() ); - this.KnowledgeInscriber = new ThEItemDescription( BlockEnum.KNOWLEDGE_INSCRIBER.getBlock() ); - this.EssentiaVibrationChamber = new ThEItemDescription( BlockEnum.ESSENTIA_VIBRATION_CHAMBER.getBlock() ); - this.DistillationPatternEncoder = new ThEItemDescription( BlockEnum.DISTILLATION_ENCODER.getBlock() ); - } +class ThEBlocks extends IThEBlocks { + ThEBlocks() { + this.EssentiaProvider = new ThEItemDescription(BlockEnum.ESSENTIA_PROVIDER.getBlock()); + this.InfusionProvider = new ThEItemDescription(BlockEnum.INFUSION_PROVIDER.getBlock()); + this.IronGearBox = new ThEItemDescription(BlockEnum.IRON_GEAR_BOX.getBlock()); + this.ThaumiumGearBox = new ThEItemDescription(BlockEnum.THAUMIUM_GEAR_BOX.getBlock()); + this.EssentiaCellWorkbench = new ThEItemDescription(BlockEnum.ESSENTIA_CELL_WORKBENCH.getBlock()); + this.ArcaneAssembler = new ThEItemDescription(BlockEnum.ARCANE_ASSEMBLER.getBlock()); + this.KnowledgeInscriber = new ThEItemDescription(BlockEnum.KNOWLEDGE_INSCRIBER.getBlock()); + this.EssentiaVibrationChamber = new ThEItemDescription(BlockEnum.ESSENTIA_VIBRATION_CHAMBER.getBlock()); + this.DistillationPatternEncoder = new ThEItemDescription(BlockEnum.DISTILLATION_ENCODER.getBlock()); + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEInteractionHelper.java b/src/main/java/thaumicenergistics/implementaion/ThEInteractionHelper.java index bc59f8d7..805b6563 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEInteractionHelper.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEInteractionHelper.java @@ -1,12 +1,12 @@ package thaumicenergistics.implementaion; -import java.util.ArrayList; import appeng.api.AEApi; import appeng.api.implementations.tiles.IWirelessAccessPoint; import appeng.api.storage.data.IAEItemStack; import appeng.core.localization.PlayerMessages; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; @@ -30,183 +30,158 @@ import thaumicenergistics.common.utils.ThELog; /** * Implements {@link IThEInteractionHelper} */ -public class ThEInteractionHelper - implements IThEInteractionHelper -{ +public class ThEInteractionHelper implements IThEInteractionHelper { - @Override - public long convertEssentiaAmountToFluidAmount( final long essentiaAmount ) - { - return EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount( essentiaAmount ); - } + @Override + public long convertEssentiaAmountToFluidAmount(final long essentiaAmount) { + return EssentiaConversionHelper.INSTANCE.convertEssentiaAmountToFluidAmount(essentiaAmount); + } - @Override - public long convertFluidAmountToEssentiaAmount( final long milibuckets ) - { - return EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount( milibuckets ); - } + @Override + public long convertFluidAmountToEssentiaAmount(final long milibuckets) { + return EssentiaConversionHelper.INSTANCE.convertFluidAmountToEssentiaAmount(milibuckets); + } - @Override - public IAspectStack createAspectStack( final Aspect aspect, final long stackSize ) - { - return new AspectStack( aspect, stackSize ); - } + @Override + public IAspectStack createAspectStack(final Aspect aspect, final long stackSize) { + return new AspectStack(aspect, stackSize); + } - @Override - @SideOnly(Side.CLIENT) - public Class getArcaneCraftingTerminalGUIClass() - { - return GuiArcaneCraftingTerminal.class; - } + @Override + @SideOnly(Side.CLIENT) + public Class getArcaneCraftingTerminalGUIClass() { + return GuiArcaneCraftingTerminal.class; + } - @Override - public void openWirelessTerminalGui( final EntityPlayer player ) - { - // Valid player? - if( ( player == null ) || ( player instanceof FakePlayer ) ) - { - return; - } + @Override + public void openWirelessTerminalGui(final EntityPlayer player) { + // Valid player? + if ((player == null) || (player instanceof FakePlayer)) { + return; + } - // Ignored client side - if( player.worldObj.isRemote ) - { - return; - } + // Ignored client side + if (player.worldObj.isRemote) { + return; + } - // Get the item the player is holding. - ItemStack wirelessTerminal = player.getHeldItem(); + // Get the item the player is holding. + ItemStack wirelessTerminal = player.getHeldItem(); - // Ensure the stack is valid - if( ( wirelessTerminal == null ) ) - { - // Invalid terminal - return; - } + // Ensure the stack is valid + if ((wirelessTerminal == null)) { + // Invalid terminal + return; + } - // Ensure the stack's item implements the wireless interface - if( !( wirelessTerminal.getItem() instanceof IThEWirelessEssentiaTerminal ) ) - { - // Invalid item. - return; - } + // Ensure the stack's item implements the wireless interface + if (!(wirelessTerminal.getItem() instanceof IThEWirelessEssentiaTerminal)) { + // Invalid item. + return; + } - // Get the interface - IThEWirelessEssentiaTerminal terminalInterface = (IThEWirelessEssentiaTerminal)wirelessTerminal.getItem(); + // Get the interface + IThEWirelessEssentiaTerminal terminalInterface = (IThEWirelessEssentiaTerminal) wirelessTerminal.getItem(); - // Ensure the terminal has power - if( terminalInterface.getAECurrentPower( wirelessTerminal ) == 0 ) - { - // Terminal is dead - player.addChatMessage( PlayerMessages.DeviceNotPowered.get() ); - return; - } + // Ensure the terminal has power + if (terminalInterface.getAECurrentPower(wirelessTerminal) == 0) { + // Terminal is dead + player.addChatMessage(PlayerMessages.DeviceNotPowered.get()); + return; + } - // Ensure the terminal is linked - if( !HandlerWirelessEssentiaTerminal.isTerminalLinked( terminalInterface, wirelessTerminal ) ) - { - // Unlinked terminal - player.addChatMessage( PlayerMessages.CommunicationError.get() ); - return; - } + // Ensure the terminal is linked + if (!HandlerWirelessEssentiaTerminal.isTerminalLinked(terminalInterface, wirelessTerminal)) { + // Unlinked terminal + player.addChatMessage(PlayerMessages.CommunicationError.get()); + return; + } - // Get the encryption key - String encKey = terminalInterface.getEncryptionKey( wirelessTerminal ); + // Get the encryption key + String encKey = terminalInterface.getEncryptionKey(wirelessTerminal); - // Are any AP's in range? - ArrayList accessPoints = WirelessAELink.locateAPsInRangeOfPlayer( player, encKey ); + // Are any AP's in range? + ArrayList accessPoints = WirelessAELink.locateAPsInRangeOfPlayer(player, encKey); - // Error occured - if( accessPoints == null ) - { - player.addChatMessage( PlayerMessages.CommunicationError.get() ); - } - // None in range - else if( accessPoints.isEmpty() ) - { - player.addChatMessage( PlayerMessages.OutOfRange.get() ); - } - // Launch the gui - else - { - ThEGuiHandler.launchGui( ThEGuiHandler.WIRELESS_TERMINAL_ID, player, player.worldObj, (int)player.posX, (int)player.posY, - (int)player.posZ, new Object[] { new HandlerWirelessEssentiaTerminal( player, encKey, terminalInterface, wirelessTerminal ) } ); - } + // Error occured + if (accessPoints == null) { + player.addChatMessage(PlayerMessages.CommunicationError.get()); + } + // None in range + else if (accessPoints.isEmpty()) { + player.addChatMessage(PlayerMessages.OutOfRange.get()); + } + // Launch the gui + else { + ThEGuiHandler.launchGui( + ThEGuiHandler.WIRELESS_TERMINAL_ID, + player, + player.worldObj, + (int) player.posX, + (int) player.posY, + (int) player.posZ, + new Object[] { + new HandlerWirelessEssentiaTerminal(player, encKey, terminalInterface, wirelessTerminal) + }); + } + } - } + @Deprecated + @Override + public void openWirelessTerminalGui( + final EntityPlayer player, final IThEWirelessEssentiaTerminal terminalInterface) { + this.openWirelessTerminalGui(player); + } - @Deprecated - @Override - public void openWirelessTerminalGui( final EntityPlayer player, final IThEWirelessEssentiaTerminal terminalInterface ) - { - this.openWirelessTerminalGui( player ); + @Override + public void registerGolemHookHandler(final IGolemHookHandler handler) { + try { + GolemHooks.registerHandler(handler); + } catch (Exception e) { + ThELog.warning("Caught Exception During API call to registerGolemHookHandler"); + ThELog.warning(e.toString()); + e.printStackTrace(); + } + } - } + @Override + @SideOnly(Side.CLIENT) + public void setArcaneCraftingTerminalRecipe(final ItemStack[] itemsVanilla) { + try { + // Get the player + EntityPlayer player = Minecraft.getMinecraft().thePlayer; - @Override - public void registerGolemHookHandler( final IGolemHookHandler handler ) - { - try - { - GolemHooks.registerHandler( handler ); - } - catch( Exception e ) - { - ThELog.warning( "Caught Exception During API call to registerGolemHookHandler" ); - ThELog.warning( e.toString() ); - e.printStackTrace(); - } - } + // Is the player looking at an ACT? + if (!(player.openContainer instanceof ContainerPartArcaneCraftingTerminal)) { + return; + } - @Override - @SideOnly(Side.CLIENT) - public void setArcaneCraftingTerminalRecipe( final ItemStack[] itemsVanilla ) - { - try - { - // Get the player - EntityPlayer player = Minecraft.getMinecraft().thePlayer; + boolean hasItems = false; - // Is the player looking at an ACT? - if( !( player.openContainer instanceof ContainerPartArcaneCraftingTerminal ) ) - { - return; - } + // Ensure the input items array is the correct size + if ((itemsVanilla == null) || (itemsVanilla.length != 9)) { + return; + } - boolean hasItems = false; + // Create the AE items array + IAEItemStack[] items = new IAEItemStack[9]; - // Ensure the input items array is the correct size - if( ( itemsVanilla == null ) || ( itemsVanilla.length != 9 ) ) - { - return; - } - - // Create the AE items array - IAEItemStack[] items = new IAEItemStack[9]; - - // Get the items and convert them to their AE counterparts. - for( int slotIndex = 0; slotIndex < 9; ++slotIndex ) - { - if( itemsVanilla[slotIndex] != null ) - { - items[slotIndex] = AEApi.instance().storage().createItemStack( itemsVanilla[slotIndex] ); - hasItems = true; - } - } - - // Send the list to the server - if( hasItems ) - { - Packet_S_ArcaneCraftingTerminal.sendSetCrafting_NEI( player, items ); - } - } - catch( Exception e ) - { - ThELog.warning( "Caught Exception During API call to setArcaneCraftingTerminalRecipe" ); - ThELog.warning( e.toString() ); - e.printStackTrace(); - } - - } + // Get the items and convert them to their AE counterparts. + for (int slotIndex = 0; slotIndex < 9; ++slotIndex) { + if (itemsVanilla[slotIndex] != null) { + items[slotIndex] = AEApi.instance().storage().createItemStack(itemsVanilla[slotIndex]); + hasItems = true; + } + } + // Send the list to the server + if (hasItems) { + Packet_S_ArcaneCraftingTerminal.sendSetCrafting_NEI(player, items); + } + } catch (Exception e) { + ThELog.warning("Caught Exception During API call to setArcaneCraftingTerminalRecipe"); + ThELog.warning(e.toString()); + e.printStackTrace(); + } + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEItemDescription.java b/src/main/java/thaumicenergistics/implementaion/ThEItemDescription.java index b514aa2e..90b855f7 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEItemDescription.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEItemDescription.java @@ -11,58 +11,47 @@ import thaumicenergistics.api.IThEItemDescription; * @author Nividica * */ -public class ThEItemDescription - implements IThEItemDescription -{ - private Block myBlock = null; - private Item myItem = null; - private int itemMeta = 0; +public class ThEItemDescription implements IThEItemDescription { + private Block myBlock = null; + private Item myItem = null; + private int itemMeta = 0; - ThEItemDescription( final Block block ) - { - this( Item.getItemFromBlock( block ), 0 ); - this.myBlock = block; - } + ThEItemDescription(final Block block) { + this(Item.getItemFromBlock(block), 0); + this.myBlock = block; + } - ThEItemDescription( final Item item, final int meta ) - { - this.myItem = item; - this.itemMeta = meta; - } + ThEItemDescription(final Item item, final int meta) { + this.myItem = item; + this.itemMeta = meta; + } - ThEItemDescription( final ItemStack stack ) - { - this( stack.getItem(), stack.getItemDamage() ); - } + ThEItemDescription(final ItemStack stack) { + this(stack.getItem(), stack.getItemDamage()); + } - @Override - public Block getBlock() - { - return this.myBlock; - } + @Override + public Block getBlock() { + return this.myBlock; + } - @Override - public int getDamage() - { - return this.itemMeta; - } + @Override + public int getDamage() { + return this.itemMeta; + } - @Override - public Item getItem() - { - return this.myItem; - } + @Override + public Item getItem() { + return this.myItem; + } - @Override - public ItemStack getStack() - { - return this.getStacks( 1 ); - } - - @Override - public ItemStack getStacks( final int amount ) - { - return new ItemStack( this.myItem, amount, this.itemMeta ); - } + @Override + public ItemStack getStack() { + return this.getStacks(1); + } + @Override + public ItemStack getStacks(final int amount) { + return new ItemStack(this.myItem, amount, this.itemMeta); + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEItems.java b/src/main/java/thaumicenergistics/implementaion/ThEItems.java index ec7a9300..1d70c94f 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEItems.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEItems.java @@ -11,34 +11,31 @@ import thaumicenergistics.common.storage.EnumEssentiaStorageTypes; * @author Nividica * */ -class ThEItems - extends IThEItems -{ - ThEItems() - { - // Cores - this.CoalescenceCore = new ThEItemDescription( MaterialTypes.COALESCENCE_CORE.getStack() ); - this.DiffusionCore = new ThEItemDescription( MaterialTypes.DIFFUSION_CORE.getStack() ); +class ThEItems extends IThEItems { + ThEItems() { + // Cores + this.CoalescenceCore = new ThEItemDescription(MaterialTypes.COALESCENCE_CORE.getStack()); + this.DiffusionCore = new ThEItemDescription(MaterialTypes.DIFFUSION_CORE.getStack()); - // Cells - this.EssentiaCell_1k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_1K.getCell() ); - this.EssentiaCell_4k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_4K.getCell() ); - this.EssentiaCell_16k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_16K.getCell() ); - this.EssentiaCell_64k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_64K.getCell() ); - this.EssentiaCell_Creative = new ThEItemDescription( EnumEssentiaStorageTypes.Type_Creative.getCell() ); - this.EssentiaCell_Casing = new ThEItemDescription( ItemEnum.STORAGE_CASING.getStack() ); + // Cells + this.EssentiaCell_1k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_1K.getCell()); + this.EssentiaCell_4k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_4K.getCell()); + this.EssentiaCell_16k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_16K.getCell()); + this.EssentiaCell_64k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_64K.getCell()); + this.EssentiaCell_Creative = new ThEItemDescription(EnumEssentiaStorageTypes.Type_Creative.getCell()); + this.EssentiaCell_Casing = new ThEItemDescription(ItemEnum.STORAGE_CASING.getStack()); - // Components - this.EssentiaStorageComponent_1k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_1K.getComponent( 1 ) ); - this.EssentiaStorageComponent_4k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_4K.getComponent( 1 ) ); - this.EssentiaStorageComponent_16k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_16K.getComponent( 1 ) ); - this.EssentiaStorageComponent_64k = new ThEItemDescription( EnumEssentiaStorageTypes.Type_64K.getComponent( 1 ) ); + // Components + this.EssentiaStorageComponent_1k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_1K.getComponent(1)); + this.EssentiaStorageComponent_4k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_4K.getComponent(1)); + this.EssentiaStorageComponent_16k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_16K.getComponent(1)); + this.EssentiaStorageComponent_64k = new ThEItemDescription(EnumEssentiaStorageTypes.Type_64K.getComponent(1)); - // Misc - this.IronGear = new ThEItemDescription( MaterialTypes.IRON_GEAR.getStack() ); - this.WirelessEssentiaTerminal = new ThEItemDescription( ItemEnum.WIRELESS_TERMINAL.getStack() ); - this.KnowledgeCore = new ThEItemDescription( ItemEnum.KNOWLEDGE_CORE.getStack() ); - this.WandFocusAEWrench = new ThEItemDescription( ItemEnum.FOCUS_AEWRENCH.getStack() ); - this.GolemWifiBackpack = new ThEItemDescription( ItemEnum.GOLEM_WIFI_BACKPACK.getStack() ); - } + // Misc + this.IronGear = new ThEItemDescription(MaterialTypes.IRON_GEAR.getStack()); + this.WirelessEssentiaTerminal = new ThEItemDescription(ItemEnum.WIRELESS_TERMINAL.getStack()); + this.KnowledgeCore = new ThEItemDescription(ItemEnum.KNOWLEDGE_CORE.getStack()); + this.WandFocusAEWrench = new ThEItemDescription(ItemEnum.FOCUS_AEWRENCH.getStack()); + this.GolemWifiBackpack = new ThEItemDescription(ItemEnum.GOLEM_WIFI_BACKPACK.getStack()); + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEMultiCraftingTracker.java b/src/main/java/thaumicenergistics/implementaion/ThEMultiCraftingTracker.java index 54af984a..e4eda52c 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEMultiCraftingTracker.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEMultiCraftingTracker.java @@ -9,12 +9,11 @@ import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.data.IAEItemStack; import com.google.common.collect.ImmutableSet; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class ThEMultiCraftingTracker { @@ -24,128 +23,101 @@ public class ThEMultiCraftingTracker { private Future[] jobs = null; private ICraftingLink[] links = null; - public ThEMultiCraftingTracker( final ICraftingRequester o, final int size ) - { + public ThEMultiCraftingTracker(final ICraftingRequester o, final int size) { this.owner = o; this.size = size; } - public void readFromNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final NBTTagCompound link = extra.getCompoundTag( "links-" + x ); + public void readFromNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final NBTTagCompound link = extra.getCompoundTag("links-" + x); - if( link != null && !link.hasNoTags() ) - { - this.setLink( x, AEApi.instance().storage().loadCraftingLink( link, this.owner ) ); + if (link != null && !link.hasNoTags()) { + this.setLink(x, AEApi.instance().storage().loadCraftingLink(link, this.owner)); } } } - public void writeToNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final ICraftingLink link = this.getLink( x ); + public void writeToNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final ICraftingLink link = this.getLink(x); - if( link != null ) - { + if (link != null) { final NBTTagCompound ln = new NBTTagCompound(); - link.writeToNBT( ln ); - extra.setTag( "links-" + x, ln ); + link.writeToNBT(ln); + extra.setTag("links-" + x, ln); } } } - public boolean handleCrafting(final int x, final long itemToCraft, final IAEItemStack ais, final World w, final IGrid g, final ICraftingGrid cg, final BaseActionSource mySrc ) - { - final Future craftingJob = this.getJob( x ); + public boolean handleCrafting( + final int x, + final long itemToCraft, + final IAEItemStack ais, + final World w, + final IGrid g, + final ICraftingGrid cg, + final BaseActionSource mySrc) { + final Future craftingJob = this.getJob(x); - if( this.getLink( x ) != null ) - { - return false; - } - else if( craftingJob != null ) - { - try - { - ICraftingJob job = null; - if( craftingJob.isDone() ) - { - job = craftingJob.get(); - } + if (this.getLink(x) != null) { + return false; + } else if (craftingJob != null) { + try { + ICraftingJob job = null; + if (craftingJob.isDone()) { + job = craftingJob.get(); + } - if( job != null ) - { - final ICraftingLink link = cg.submitJob( job, this.owner, null, false, mySrc ); + if (job != null) { + final ICraftingLink link = cg.submitJob(job, this.owner, null, false, mySrc); - this.setJob( x, null ); + this.setJob(x, null); - if( link != null ) - { - this.setLink( x, link ); + if (link != null) { + this.setLink(x, link); - return true; - } + return true; } } - catch( final InterruptedException e ) - { - // :P - } - catch( final ExecutionException e ) - { - // :P - } + } catch (final InterruptedException e) { + // :P + } catch (final ExecutionException e) { + // :P } - else - { - if( this.getLink( x ) == null ) - { - final IAEItemStack aisC = ais.copy(); - aisC.setStackSize( itemToCraft ); + } else { + if (this.getLink(x) == null) { + final IAEItemStack aisC = ais.copy(); + aisC.setStackSize(itemToCraft); - this.setJob( x, cg.beginCraftingJob( w, g, mySrc, aisC, null ) ); - } + this.setJob(x, cg.beginCraftingJob(w, g, mySrc, aisC, null)); } + } return false; } - public ImmutableSet getRequestedJobs() - { - if( this.links == null ) - return ImmutableSet.of(); + public ImmutableSet getRequestedJobs() { + if (this.links == null) return ImmutableSet.of(); ArrayList result = new ArrayList(); - for (ICraftingLink l : links) - if (l != null) - result.add(l); + for (ICraftingLink l : links) if (l != null) result.add(l); return ImmutableSet.copyOf(result); } - public void jobStateChange( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - this.setLink( x, null ); + public void jobStateChange(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + this.setLink(x, null); return; } } } } - int getSlot( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { + int getSlot(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { return x; } } @@ -154,14 +126,10 @@ public class ThEMultiCraftingTracker { return -1; } - void cancel() - { - if( this.links != null ) - { - for( final ICraftingLink l : this.links ) - { - if( l != null ) - { + void cancel() { + if (this.links != null) { + for (final ICraftingLink l : this.links) { + if (l != null) { l.cancel(); } } @@ -169,13 +137,10 @@ public class ThEMultiCraftingTracker { this.links = null; } - if( this.jobs != null ) - { - for( final Future l : this.jobs ) - { - if( l != null ) - { - l.cancel( true ); + if (this.jobs != null) { + for (final Future l : this.jobs) { + if (l != null) { + l.cancel(true); } } @@ -183,65 +148,51 @@ public class ThEMultiCraftingTracker { } } - boolean isBusy( final int slot ) - { - return this.getLink( slot ) != null || this.getJob( slot ) != null; + boolean isBusy(final int slot) { + return this.getLink(slot) != null || this.getJob(slot) != null; } - private ICraftingLink getLink( final int slot ) - { - if( this.links == null ) - { + private ICraftingLink getLink(final int slot) { + if (this.links == null) { return null; } return this.links[slot]; } - private void setLink( final int slot, final ICraftingLink l ) - { - if( this.links == null ) - { + private void setLink(final int slot, final ICraftingLink l) { + if (this.links == null) { this.links = new ICraftingLink[this.size]; } this.links[slot] = l; boolean hasStuff = false; - for( int x = 0; x < this.links.length; x++ ) - { + for (int x = 0; x < this.links.length; x++) { final ICraftingLink g = this.links[x]; - if( g == null || g.isCanceled() || g.isDone() ) - { + if (g == null || g.isCanceled() || g.isDone()) { this.links[x] = null; - } - else - { + } else { hasStuff = true; } } - if( !hasStuff ) - { + if (!hasStuff) { this.links = null; } } - private Future getJob( final int slot ) - { - if( this.jobs == null ) - { + private Future getJob(final int slot) { + if (this.jobs == null) { return null; } return this.jobs[slot]; } - private void setJob( final int slot, final Future l ) - { - if( this.jobs == null ) - { + private void setJob(final int slot, final Future l) { + if (this.jobs == null) { this.jobs = new Future[this.size]; } @@ -249,16 +200,13 @@ public class ThEMultiCraftingTracker { boolean hasStuff = false; - for( final Future job : this.jobs ) - { - if( job != null ) - { + for (final Future job : this.jobs) { + if (job != null) { hasStuff = true; } } - if( !hasStuff ) - { + if (!hasStuff) { this.jobs = null; } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThEParts.java b/src/main/java/thaumicenergistics/implementaion/ThEParts.java index 21088646..670660c2 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThEParts.java +++ b/src/main/java/thaumicenergistics/implementaion/ThEParts.java @@ -9,21 +9,17 @@ import thaumicenergistics.common.parts.AEPartsEnum; * @author Nividica * */ -class ThEParts - extends IThEParts -{ - - ThEParts() - { - this.ArcaneCrafting_Terminal = new ThEItemDescription( AEPartsEnum.ArcaneCraftingTerminal.getStack() ); - this.Essentia_ExportBus = new ThEItemDescription( AEPartsEnum.EssentiaExportBus.getStack() ); - this.Essentia_ImportBus = new ThEItemDescription( AEPartsEnum.EssentiaImportBus.getStack() ); - this.Essentia_LevelEmitter = new ThEItemDescription( AEPartsEnum.EssentiaLevelEmitter.getStack() ); - this.Essentia_StorageBus = new ThEItemDescription( AEPartsEnum.EssentiaStorageBus.getStack() ); - this.Essentia_Terminal = new ThEItemDescription( AEPartsEnum.EssentiaTerminal.getStack() ); - this.VisRelay_Interface = new ThEItemDescription( AEPartsEnum.VisInterface.getStack() ); - this.Essentia_StorageMonitor = new ThEItemDescription( AEPartsEnum.EssentiaStorageMonitor.getStack() ); - this.Essentia_ConversionMonitor = new ThEItemDescription( AEPartsEnum.EssentiaConversionMonitor.getStack() ); - } +class ThEParts extends IThEParts { + ThEParts() { + this.ArcaneCrafting_Terminal = new ThEItemDescription(AEPartsEnum.ArcaneCraftingTerminal.getStack()); + this.Essentia_ExportBus = new ThEItemDescription(AEPartsEnum.EssentiaExportBus.getStack()); + this.Essentia_ImportBus = new ThEItemDescription(AEPartsEnum.EssentiaImportBus.getStack()); + this.Essentia_LevelEmitter = new ThEItemDescription(AEPartsEnum.EssentiaLevelEmitter.getStack()); + this.Essentia_StorageBus = new ThEItemDescription(AEPartsEnum.EssentiaStorageBus.getStack()); + this.Essentia_Terminal = new ThEItemDescription(AEPartsEnum.EssentiaTerminal.getStack()); + this.VisRelay_Interface = new ThEItemDescription(AEPartsEnum.VisInterface.getStack()); + this.Essentia_StorageMonitor = new ThEItemDescription(AEPartsEnum.EssentiaStorageMonitor.getStack()); + this.Essentia_ConversionMonitor = new ThEItemDescription(AEPartsEnum.EssentiaConversionMonitor.getStack()); + } } diff --git a/src/main/java/thaumicenergistics/implementaion/ThETransportPermissions.java b/src/main/java/thaumicenergistics/implementaion/ThETransportPermissions.java index 14644785..40735120 100644 --- a/src/main/java/thaumicenergistics/implementaion/ThETransportPermissions.java +++ b/src/main/java/thaumicenergistics/implementaion/ThETransportPermissions.java @@ -20,260 +20,238 @@ import thaumicenergistics.common.utils.ThELog; * @author Nividica * */ -class ThETransportPermissions - implements IThETransportPermissions -{ - /** - * Collection of ContainerInfo indexed by damage value. - * - * @author Nividica - * - */ - private class ContainerCollection - { - /** - * DamageValue -> Info map - */ - private HashMap containers = new HashMap(); +class ThETransportPermissions implements IThETransportPermissions { + /** + * Collection of ContainerInfo indexed by damage value. + * + * @author Nividica + * + */ + private class ContainerCollection { + /** + * DamageValue -> Info map + */ + private HashMap containers = new HashMap(); - /** - * Constructor adding the specified info the the collection - * - * @param capacity - * @param canHoldPartialAmount - * @param damageValue - */ - public ContainerCollection( final int capacity, final boolean canHoldPartialAmount, final int damageValue ) - { - this.addContainer( capacity, canHoldPartialAmount, damageValue ); - } + /** + * Constructor adding the specified info the the collection + * + * @param capacity + * @param canHoldPartialAmount + * @param damageValue + */ + public ContainerCollection(final int capacity, final boolean canHoldPartialAmount, final int damageValue) { + this.addContainer(capacity, canHoldPartialAmount, damageValue); + } - /** - * Adds the specified info to the collection - * - * @param capacity - * @param canHoldPartialAmount - * @param damageValue - * @return - */ - public ContainerCollection addContainer( final int capacity, final boolean canHoldPartialAmount, final int damageValue ) - { - // Create the container info - ContainerInfo info = new ContainerInfo( capacity, canHoldPartialAmount ); + /** + * Adds the specified info to the collection + * + * @param capacity + * @param canHoldPartialAmount + * @param damageValue + * @return + */ + public ContainerCollection addContainer( + final int capacity, final boolean canHoldPartialAmount, final int damageValue) { + // Create the container info + ContainerInfo info = new ContainerInfo(capacity, canHoldPartialAmount); - // Add to the map - this.containers.put( damageValue, info ); + // Add to the map + this.containers.put(damageValue, info); - return this; - } + return this; + } - /** - * Gets the info about the item using the specified metadata. - * - * @param damageValue - * @return {@link ContainerInfo} if a match is found, null otherwise. - */ - public ContainerInfo getInfo( final int damageValue ) - { - return this.containers.get( damageValue ); - } - } + /** + * Gets the info about the item using the specified metadata. + * + * @param damageValue + * @return {@link ContainerInfo} if a match is found, null otherwise. + */ + public ContainerInfo getInfo(final int damageValue) { + return this.containers.get(damageValue); + } + } - /** - * Basic information about a thaumcraft container. - * - * @author Nividica - * - */ - private class ContainerInfo - implements IThEEssentiaContainerPermission - { - private int capacity; - private boolean canHoldPartialAmount; + /** + * Basic information about a thaumcraft container. + * + * @author Nividica + * + */ + private class ContainerInfo implements IThEEssentiaContainerPermission { + private int capacity; + private boolean canHoldPartialAmount; - public ContainerInfo( final int capacity, final boolean canHoldPartialAmount ) - { - this.capacity = capacity; - this.canHoldPartialAmount = canHoldPartialAmount; - } + public ContainerInfo(final int capacity, final boolean canHoldPartialAmount) { + this.capacity = capacity; + this.canHoldPartialAmount = canHoldPartialAmount; + } - @Override - public boolean canHoldPartialAmount() - { - return this.canHoldPartialAmount; - } + @Override + public boolean canHoldPartialAmount() { + return this.canHoldPartialAmount; + } - @Override - public int maximumCapacity() - { - return this.capacity; - } - } + @Override + public int maximumCapacity() { + return this.capacity; + } + } - /** - * List of items allowed to work with. - * Indexed by item class. - */ - private final HashMap, ContainerCollection> itemWhitelist = new HashMap, ContainerCollection>(); + /** + * List of items allowed to work with. + * Indexed by item class. + */ + private final HashMap, ContainerCollection> itemWhitelist = + new HashMap, ContainerCollection>(); - /** - * Holds a list of tiles that we are allowed to extract from. - */ - private final Set> tileExtractWhiteList = new HashSet>(); + /** + * Holds a list of tiles that we are allowed to extract from. + */ + private final Set> tileExtractWhiteList = + new HashSet>(); - /** - * Holds a list of tiles that we are allowed to inject into. - */ - private final Set> tileInjectWhiteList = new HashSet>(); + /** + * Holds a list of tiles that we are allowed to inject into. + */ + private final Set> tileInjectWhiteList = + new HashSet>(); - /** - * Holds the capacities for each registered tile. - */ - private final HashMap, Integer> tileCapacities = new HashMap, Integer>(); + /** + * Holds the capacities for each registered tile. + */ + private final HashMap, Integer> tileCapacities = + new HashMap, Integer>(); - @Override - public boolean addAspectContainerTileToBothPermissions( final Class tileClass, final int capacity ) - { - // Add to both - return( this.addAspectContainerTileToInjectPermissions( tileClass, capacity ) | this.addAspectContainerTileToExtractPermissions( tileClass, - capacity ) ); - } + @Override + public boolean addAspectContainerTileToBothPermissions( + final Class tileClass, final int capacity) { + // Add to both + return (this.addAspectContainerTileToInjectPermissions(tileClass, capacity) + | this.addAspectContainerTileToExtractPermissions(tileClass, capacity)); + } - @Override - public boolean addAspectContainerTileToExtractPermissions( final Class tileClass, - final int capacity ) - { - // Ensure we have a tile - if( tileClass != null ) - { - // Set capacity - this.tileCapacities.put( tileClass, capacity ); + @Override + public boolean addAspectContainerTileToExtractPermissions( + final Class tileClass, final int capacity) { + // Ensure we have a tile + if (tileClass != null) { + // Set capacity + this.tileCapacities.put(tileClass, capacity); - // Is it not already registered? - if( this.tileExtractWhiteList.add( tileClass ) ) - { - // Log the addition - ThELog.info( "Added \"%s\" with capacity (%d) to extraction whitelist.", tileClass.toString(), capacity ); - } + // Is it not already registered? + if (this.tileExtractWhiteList.add(tileClass)) { + // Log the addition + ThELog.info("Added \"%s\" with capacity (%d) to extraction whitelist.", tileClass.toString(), capacity); + } - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public boolean addAspectContainerTileToInjectPermissions( final Class tileClass, final int capacity ) - { - // Ensure we have a tile - if( tileClass != null ) - { - // Set capacity - this.tileCapacities.put( tileClass, capacity ); + @Override + public boolean addAspectContainerTileToInjectPermissions( + final Class tileClass, final int capacity) { + // Ensure we have a tile + if (tileClass != null) { + // Set capacity + this.tileCapacities.put(tileClass, capacity); - // Is it not already registered? - if( this.tileInjectWhiteList.add( tileClass ) ) - { - // Log the addition - ThELog.info( "Added \"%s\" with capacity (%d) to injection whitelist.", tileClass.toString(), capacity ); - } + // Is it not already registered? + if (this.tileInjectWhiteList.add(tileClass)) { + // Log the addition + ThELog.info("Added \"%s\" with capacity (%d) to injection whitelist.", tileClass.toString(), capacity); + } - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public void addEssentiaContainerItemToTransportPermissions( final Class itemClass, final int capacity, - final int damageValue, final boolean canHoldPartialAmount ) - { - // Do we have an item? - if( itemClass != null ) - { - // Is it already registered? - if( this.itemWhitelist.containsKey( itemClass ) ) - { - // Add to the existing registry - this.itemWhitelist.get( itemClass ).addContainer( capacity, canHoldPartialAmount, damageValue ); - } - else - { - // Create a new registry - this.itemWhitelist.put( itemClass, new ContainerCollection( capacity, canHoldPartialAmount, damageValue ) ); - } + @Override + public void addEssentiaContainerItemToTransportPermissions( + final Class itemClass, + final int capacity, + final int damageValue, + final boolean canHoldPartialAmount) { + // Do we have an item? + if (itemClass != null) { + // Is it already registered? + if (this.itemWhitelist.containsKey(itemClass)) { + // Add to the existing registry + this.itemWhitelist.get(itemClass).addContainer(capacity, canHoldPartialAmount, damageValue); + } else { + // Create a new registry + this.itemWhitelist.put(itemClass, new ContainerCollection(capacity, canHoldPartialAmount, damageValue)); + } - // Log the addition - ThELog.info( "Added \"%s\"[%d] to item whitelist.", itemClass.toString(), damageValue ); - } - } + // Log the addition + ThELog.info("Added \"%s\"[%d] to item whitelist.", itemClass.toString(), damageValue); + } + } - @Override - public void addEssentiaContainerItemToTransportPermissions( final ItemStack containerItem, final int capacity, - final boolean canHoldPartialAmount ) - { - // Ensure the item is a valid container - if( ( containerItem == null ) || !( containerItem.getItem() instanceof IEssentiaContainerItem ) ) - { - return; - } + @Override + public void addEssentiaContainerItemToTransportPermissions( + final ItemStack containerItem, final int capacity, final boolean canHoldPartialAmount) { + // Ensure the item is a valid container + if ((containerItem == null) || !(containerItem.getItem() instanceof IEssentiaContainerItem)) { + return; + } - try - { - this.addEssentiaContainerItemToTransportPermissions( (Class)containerItem.getItem().getClass(), - capacity, containerItem.getItemDamage(), canHoldPartialAmount ); - } - catch( Throwable t ) - { - } + try { + this.addEssentiaContainerItemToTransportPermissions( + (Class) + containerItem.getItem().getClass(), + capacity, + containerItem.getItemDamage(), + canHoldPartialAmount); + } catch (Throwable t) { + } + } - } + @Override + public boolean canExtractFromAspectContainerTile(final IAspectContainer container) { + // Return if it is whitelisted or not + return (this.tileExtractWhiteList.contains(container.getClass())); + } - @Override - public boolean canExtractFromAspectContainerTile( final IAspectContainer container ) - { - // Return if it is whitelisted or not - return( this.tileExtractWhiteList.contains( container.getClass() ) ); - } + @Override + public boolean canInjectToAspectContainerTile(final IAspectContainer container) { + // Return if it is whitelisted or not + return (this.tileInjectWhiteList.contains(container.getClass())); + } - @Override - public boolean canInjectToAspectContainerTile( final IAspectContainer container ) - { - // Return if it is whitelisted or not - return( this.tileInjectWhiteList.contains( container.getClass() ) ); - } + @Override + public int getAspectContainerTileCapacity(final IAspectContainer container) { + // Is the capacity registered? + if (this.tileCapacities.containsKey(container.getClass())) { + return this.tileCapacities.get(container.getClass()); + } - @Override - public int getAspectContainerTileCapacity( final IAspectContainer container ) - { - // Is the capacity registered? - if( this.tileCapacities.containsKey( container.getClass() ) ) - { - return this.tileCapacities.get( container.getClass() ); - } + return -1; + } - return -1; - } + @Override + public IThEEssentiaContainerPermission getEssentiaContainerInfo( + final Class itemClass, final int damageValue) { + // Is the item registered? + if (this.itemWhitelist.containsKey(itemClass)) { + // Return the info + return this.itemWhitelist.get(itemClass).getInfo(damageValue); + } - @Override - public IThEEssentiaContainerPermission getEssentiaContainerInfo( final Class itemClass, final int damageValue ) - { - // Is the item registered? - if( this.itemWhitelist.containsKey( itemClass ) ) - { - // Return the info - return this.itemWhitelist.get( itemClass ).getInfo( damageValue ); - } - - // Special check for empty jars - if( itemClass == BlockJarItem.class ) - { - // Return the info for filled jars - return this.itemWhitelist.get( ItemJarFilled.class ).getInfo( damageValue ); - } - - // Not registered return null - return null; - } + // Special check for empty jars + if (itemClass == BlockJarItem.class) { + // Return the info for filled jars + return this.itemWhitelist.get(ItemJarFilled.class).getInfo(damageValue); + } + // Not registered return null + return null; + } }