diff --git a/build.gradle b/build.gradle index 6a5522352..8b7e2e274 100755 --- a/build.gradle +++ b/build.gradle @@ -63,7 +63,7 @@ dependencies { deobfCompile "net.darkhax.tesla:Tesla:${tesla_version}" deobfCompile "mezz.jei:jei_${mcversion}:${jei_version}:api" runtime "mezz.jei:jei_${mcversion}:${jei_version}" - deobfCompile "net.industrial-craft:industrialcraft-2:${ic2_version}:api" +// deobfCompile "net.industrial-craft:industrialcraft-2:${ic2_version}:api" } configurations { diff --git a/gradle.properties b/gradle.properties index 264f4f482..bce354c30 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,11 +1,11 @@ -mcversion=1.10.2 -forgeversion=12.18.2.2125 -mcp_mappings=snapshot_20161111 +mcversion=1.11 +forgeversion=13.19.1.2198 +mcp_mappings=snapshot_20161220 -tesla_version=1.10.2-1.2.1.49 -jei_version=3.13.2.349 -ic2_version=2.6.76-ex110 +tesla_version=1.11-1.3.0.51 +jei_version=4.1.1.207 +#ic2_version=2.6.76-ex110 version_major=5 -version_minor=2 -version_patch=16 +version_minor=3 +version_patch=0 diff --git a/src/api/java/cofh/LICENSE - LGPLv3.txt b/src/api/java/cofh/LICENSE - LGPLv3.txt deleted file mode 100644 index 65c5ca88a..000000000 --- a/src/api/java/cofh/LICENSE - LGPLv3.txt +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/src/api/java/cofh/README.md b/src/api/java/cofh/README.md deleted file mode 100644 index 3f855b753..000000000 --- a/src/api/java/cofh/README.md +++ /dev/null @@ -1,11 +0,0 @@ -Redstone Flux API -==================================== -This is the standalone CoFH Energy API - also known as the "Redstone Flux" API. - -Make great use of it. - -You are of course free to modify any/all of this code and even repackage it, but then it wouldn't be an awesome crossmod API anymore, now would it? - -Don't be a jerk. - -~Team CoFH \ No newline at end of file diff --git a/src/api/java/cofh/api/CoFHAPIProps.java b/src/api/java/cofh/api/CoFHAPIProps.java deleted file mode 100644 index eb2e05ade..000000000 --- a/src/api/java/cofh/api/CoFHAPIProps.java +++ /dev/null @@ -1,11 +0,0 @@ -package cofh.api; - -public class CoFHAPIProps { - - private CoFHAPIProps() { - - } - - public static final String VERSION = "1.8.9R1.2.0B1"; - -} diff --git a/src/api/java/cofh/api/energy/EnergyStorage.java b/src/api/java/cofh/api/energy/EnergyStorage.java deleted file mode 100644 index dd7dd3e02..000000000 --- a/src/api/java/cofh/api/energy/EnergyStorage.java +++ /dev/null @@ -1,162 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * Reference implementation of {@link IEnergyStorage}. Use/extend this or implement your own. - * - * @author King Lemming - * - */ -public class EnergyStorage implements IEnergyStorage { - - protected int energy; - protected int capacity; - protected int maxReceive; - protected int maxExtract; - - public EnergyStorage(int capacity) { - - this(capacity, capacity, capacity); - } - - public EnergyStorage(int capacity, int maxTransfer) { - - this(capacity, maxTransfer, maxTransfer); - } - - public EnergyStorage(int capacity, int maxReceive, int maxExtract) { - - this.capacity = capacity; - this.maxReceive = maxReceive; - this.maxExtract = maxExtract; - } - - public EnergyStorage readFromNBT(NBTTagCompound nbt) { - - this.energy = nbt.getInteger("Energy"); - - if (energy > capacity) { - energy = capacity; - } - return this; - } - - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - - if (energy < 0) { - energy = 0; - } - nbt.setInteger("Energy", energy); - return nbt; - } - - public EnergyStorage setCapacity(int capacity) { - - this.capacity = capacity; - - if (energy > capacity) { - energy = capacity; - } - return this; - } - - public EnergyStorage setMaxTransfer(int maxTransfer) { - - setMaxReceive(maxTransfer); - setMaxExtract(maxTransfer); - return this; - } - - public EnergyStorage setMaxReceive(int maxReceive) { - - this.maxReceive = maxReceive; - return this; - } - - public EnergyStorage setMaxExtract(int maxExtract) { - - this.maxExtract = maxExtract; - return this; - } - - public int getMaxReceive() { - - return maxReceive; - } - - public int getMaxExtract() { - - return maxExtract; - } - - /** - * This function is included to allow for server to client sync. Do not call this externally to the containing Tile Entity, as not all IEnergyHandlers - * are guaranteed to have it. - * - * @param energy - */ - public void setEnergyStored(int energy) { - - this.energy = energy; - - if (this.energy > capacity) { - this.energy = capacity; - } else if (this.energy < 0) { - this.energy = 0; - } - } - - /** - * This function is included to allow the containing tile to directly and efficiently modify the energy contained in the EnergyStorage. Do not rely on this - * externally, as not all IEnergyHandlers are guaranteed to have it. - * - * @param energy - */ - public void modifyEnergyStored(int energy) { - - this.energy += energy; - - if (this.energy > capacity) { - this.energy = capacity; - } else if (this.energy < 0) { - this.energy = 0; - } - } - - /* IEnergyStorage */ - @Override - public int receiveEnergy(int maxReceive, boolean simulate) { - - int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive)); - - if (!simulate) { - energy += energyReceived; - } - return energyReceived; - } - - @Override - public int extractEnergy(int maxExtract, boolean simulate) { - - int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract)); - - if (!simulate) { - energy -= energyExtracted; - } - return energyExtracted; - } - - @Override - public int getEnergyStored() { - - return energy; - } - - @Override - public int getMaxEnergyStored() { - - return capacity; - } - -} diff --git a/src/api/java/cofh/api/energy/IEnergyConnection.java b/src/api/java/cofh/api/energy/IEnergyConnection.java deleted file mode 100644 index 29ef0a1ce..000000000 --- a/src/api/java/cofh/api/energy/IEnergyConnection.java +++ /dev/null @@ -1,22 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.util.EnumFacing; - - -/** - * Implement this interface on TileEntities which should connect to energy transportation blocks. This is intended for blocks which generate energy but do not - * accept it; otherwise just use IEnergyHandler. - *

- * Note that {@link IEnergyHandler} is an extension of this. - * - * @author King Lemming - * - */ -public interface IEnergyConnection { - - /** - * Returns TRUE if the TileEntity can connect on a given side. - */ - boolean canConnectEnergy(EnumFacing from); - -} diff --git a/src/api/java/cofh/api/energy/IEnergyContainerItem.java b/src/api/java/cofh/api/energy/IEnergyContainerItem.java deleted file mode 100644 index 3ef725765..000000000 --- a/src/api/java/cofh/api/energy/IEnergyContainerItem.java +++ /dev/null @@ -1,52 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.item.ItemStack; - -/** - * Implement this interface on Item classes that support external manipulation of their internal energy storages. - *

- * A reference implementation is provided {@link ItemEnergyContainer}. - * - * @author King Lemming - * - */ -public interface IEnergyContainerItem { - - /** - * Adds energy to a container item. Returns the quantity of energy that was accepted. This should always return 0 if the item cannot be externally charged. - * - * @param container - * ItemStack to be charged. - * @param maxReceive - * Maximum amount of energy to be sent into the item. - * @param simulate - * If TRUE, the charge will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) received by the item. - */ - int receiveEnergy(ItemStack container, int maxReceive, boolean simulate); - - /** - * Removes energy from a container item. Returns the quantity of energy that was removed. This should always return 0 if the item cannot be externally - * discharged. - * - * @param container - * ItemStack to be discharged. - * @param maxExtract - * Maximum amount of energy to be extracted from the item. - * @param simulate - * If TRUE, the discharge will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) extracted from the item. - */ - int extractEnergy(ItemStack container, int maxExtract, boolean simulate); - - /** - * Get the amount of energy currently stored in the container item. - */ - int getEnergyStored(ItemStack container); - - /** - * Get the max amount of energy that can be stored in the container item. - */ - int getMaxEnergyStored(ItemStack container); - -} diff --git a/src/api/java/cofh/api/energy/IEnergyHandler.java b/src/api/java/cofh/api/energy/IEnergyHandler.java deleted file mode 100644 index 16b236e7a..000000000 --- a/src/api/java/cofh/api/energy/IEnergyHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.util.EnumFacing; - -/** - * Implement this interface on Tile Entities which should handle energy, generally storing it in one or more internal {@link IEnergyStorage} objects. - *

- * A reference implementation is provided {@link TileEnergyHandler}. - *

- * Note that {@link IEnergyReceiver} and {@link IEnergyProvider} are extensions of this. - * - * @author King Lemming - * - */ -public interface IEnergyHandler extends IEnergyConnection { - - /** - * Returns the amount of energy currently stored. - */ - int getEnergyStored(EnumFacing from); - - /** - * Returns the maximum amount of energy that can be stored. - */ - int getMaxEnergyStored(EnumFacing from); - -} diff --git a/src/api/java/cofh/api/energy/IEnergyProvider.java b/src/api/java/cofh/api/energy/IEnergyProvider.java deleted file mode 100644 index ef0e09d06..000000000 --- a/src/api/java/cofh/api/energy/IEnergyProvider.java +++ /dev/null @@ -1,29 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.util.EnumFacing; - - -/** - * Implement this interface on Tile Entities which should provide energy, generally storing it in one or more internal {@link IEnergyStorage} objects. - *

- * A reference implementation is provided {@link TileEnergyHandler}. - * - * @author King Lemming - * - */ -public interface IEnergyProvider extends IEnergyHandler { - - /** - * Remove energy from an IEnergyProvider, internal distribution is left entirely to the IEnergyProvider. - * - * @param from - * Orientation the energy is extracted from. - * @param maxExtract - * Maximum amount of energy to extract. - * @param simulate - * If TRUE, the extraction will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) extracted. - */ - int extractEnergy(EnumFacing from, int maxExtract, boolean simulate); - -} diff --git a/src/api/java/cofh/api/energy/IEnergyReceiver.java b/src/api/java/cofh/api/energy/IEnergyReceiver.java deleted file mode 100644 index 989e9baa5..000000000 --- a/src/api/java/cofh/api/energy/IEnergyReceiver.java +++ /dev/null @@ -1,29 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.util.EnumFacing; - - -/** - * Implement this interface on Tile Entities which should receive energy, generally storing it in one or more internal {@link IEnergyStorage} objects. - *

- * A reference implementation is provided {@link TileEnergyHandler}. - * - * @author King Lemming - * - */ -public interface IEnergyReceiver extends IEnergyHandler { - - /** - * Add energy to an IEnergyReceiver, internal distribution is left entirely to the IEnergyReceiver. - * - * @param from - * Orientation the energy is received from. - * @param maxReceive - * Maximum amount of energy to receive. - * @param simulate - * If TRUE, the charge will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) received. - */ - int receiveEnergy(EnumFacing from, int maxReceive, boolean simulate); - -} diff --git a/src/api/java/cofh/api/energy/IEnergyStorage.java b/src/api/java/cofh/api/energy/IEnergyStorage.java deleted file mode 100644 index 414b26566..000000000 --- a/src/api/java/cofh/api/energy/IEnergyStorage.java +++ /dev/null @@ -1,46 +0,0 @@ -package cofh.api.energy; - -/** - * An energy storage is the unit of interaction with Energy inventories.
- * This is not to be implemented on TileEntities. This is for internal use only. - *

- * A reference implementation can be found at {@link EnergyStorage}. - * - * @author King Lemming - * - */ -public interface IEnergyStorage { - - /** - * Adds energy to the storage. Returns quantity of energy that was accepted. - * - * @param maxReceive - * Maximum amount of energy to be inserted. - * @param simulate - * If TRUE, the insertion will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) accepted by the storage. - */ - int receiveEnergy(int maxReceive, boolean simulate); - - /** - * Removes energy from the storage. Returns quantity of energy that was removed. - * - * @param maxExtract - * Maximum amount of energy to be extracted. - * @param simulate - * If TRUE, the extraction will only be simulated. - * @return Amount of energy that was (or would have been, if simulated) extracted from the storage. - */ - int extractEnergy(int maxExtract, boolean simulate); - - /** - * Returns the amount of energy currently stored. - */ - int getEnergyStored(); - - /** - * Returns the maximum amount of energy that can be stored. - */ - int getMaxEnergyStored(); - -} diff --git a/src/api/java/cofh/api/energy/ItemEnergyContainer.java b/src/api/java/cofh/api/energy/ItemEnergyContainer.java deleted file mode 100644 index 0fb36dab6..000000000 --- a/src/api/java/cofh/api/energy/ItemEnergyContainer.java +++ /dev/null @@ -1,113 +0,0 @@ -package cofh.api.energy; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -/** - * Reference implementation of {@link IEnergyContainerItem}. Use/extend this or implement your own. - * - * @author King Lemming - * - */ -public class ItemEnergyContainer extends Item implements IEnergyContainerItem { - - protected int capacity; - protected int maxReceive; - protected int maxExtract; - - public ItemEnergyContainer() { - - } - - public ItemEnergyContainer(int capacity) { - - this(capacity, capacity, capacity); - } - - public ItemEnergyContainer(int capacity, int maxTransfer) { - - this(capacity, maxTransfer, maxTransfer); - } - - public ItemEnergyContainer(int capacity, int maxReceive, int maxExtract) { - - this.capacity = capacity; - this.maxReceive = maxReceive; - this.maxExtract = maxExtract; - } - - public ItemEnergyContainer setCapacity(int capacity) { - - this.capacity = capacity; - return this; - } - - public ItemEnergyContainer setMaxTransfer(int maxTransfer) { - - setMaxReceive(maxTransfer); - setMaxExtract(maxTransfer); - return this; - } - - public ItemEnergyContainer setMaxReceive(int maxReceive) { - - this.maxReceive = maxReceive; - return this; - } - - public ItemEnergyContainer setMaxExtract(int maxExtract) { - - this.maxExtract = maxExtract; - return this; - } - - /* IEnergyContainerItem */ - @Override - public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { - - if (!container.hasTagCompound()) { - container.setTagCompound(new NBTTagCompound()); - } - int energy = container.getTagCompound().getInteger("Energy"); - int energyReceived = Math.min(capacity - energy, Math.min(this.maxReceive, maxReceive)); - - if (!simulate) { - energy += energyReceived; - container.getTagCompound().setInteger("Energy", energy); - } - return energyReceived; - } - - @Override - public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { - - if (container.getTagCompound() == null || !container.getTagCompound().hasKey("Energy")) { - return 0; - } - int energy = container.getTagCompound().getInteger("Energy"); - int energyExtracted = Math.min(energy, Math.min(this.maxExtract, maxExtract)); - - if (!simulate) { - energy -= energyExtracted; - container.getTagCompound().setInteger("Energy", energy); - } - return energyExtracted; - } - - @Override - public int getEnergyStored(ItemStack container) { - - if (container.getTagCompound() == null || !container.getTagCompound().hasKey("Energy")) { - return 0; - } - return container.getTagCompound().getInteger("Energy"); - } - - @Override - public int getMaxEnergyStored(ItemStack container) { - - return capacity; - } - -} diff --git a/src/api/java/cofh/api/energy/TileEnergyHandler.java b/src/api/java/cofh/api/energy/TileEnergyHandler.java deleted file mode 100644 index 6d2726c89..000000000 --- a/src/api/java/cofh/api/energy/TileEnergyHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -package cofh.api.energy; - -import javax.annotation.Nonnull; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - -/** - * Reference implementation of {@link IEnergyReceiver} and {@link IEnergyProvider}. Use/extend this or implement your own. - * - * This class is really meant to summarize how each interface is properly used. - * - * @author King Lemming - * - */ -public class TileEnergyHandler extends TileEntity implements IEnergyReceiver, IEnergyProvider { - - protected EnergyStorage storage = new EnergyStorage(32000); - - @Override - public void readFromNBT(NBTTagCompound nbt) { - - super.readFromNBT(nbt); - storage.readFromNBT(nbt); - } - - @Nonnull - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - nbt = super.writeToNBT(nbt); - storage.writeToNBT(nbt); - return nbt; - } - - /* IEnergyConnection */ - @Override - public boolean canConnectEnergy(EnumFacing from) { - - return true; - } - - /* IEnergyReceiver */ - @Override - public int receiveEnergy(EnumFacing from, int maxReceive, boolean simulate) { - - return storage.receiveEnergy(maxReceive, simulate); - } - - /* IEnergyProvider */ - @Override - public int extractEnergy(EnumFacing from, int maxExtract, boolean simulate) { - - return storage.extractEnergy(maxExtract, simulate); - } - - /* IEnergyHandler */ - @Override - public int getEnergyStored(EnumFacing from) { - - return storage.getEnergyStored(); - } - - @Override - public int getMaxEnergyStored(EnumFacing from) { - - return storage.getMaxEnergyStored(); - } - -} diff --git a/src/api/java/cofh/api/energy/package-info.java b/src/api/java/cofh/api/energy/package-info.java deleted file mode 100644 index da8566735..000000000 --- a/src/api/java/cofh/api/energy/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * (C) 2014-2016 Team CoFH / CoFH / Cult of the Full Hub - * http://www.teamcofh.com - */ -@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHAPI", provides = "CoFHAPI|energy") -package cofh.api.energy; - -import net.minecraftforge.fml.common.API; -import cofh.api.CoFHAPIProps; - diff --git a/src/api/java/cofh/api/package-info.java b/src/api/java/cofh/api/package-info.java deleted file mode 100644 index e2847daad..000000000 --- a/src/api/java/cofh/api/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * (C) 2014-2016 Team CoFH / CoFH / Cult of the Full Hub - * http://www.teamcofh.com - */ -@API(apiVersion = CoFHAPIProps.VERSION, owner = "CoFHLib", provides = "CoFHAPI") -package cofh.api; - -import net.minecraftforge.fml.common.API; - diff --git a/src/main/java/forestry/Forestry.java b/src/main/java/forestry/Forestry.java index 61f0a27cd..b1f5d09d7 100644 --- a/src/main/java/forestry/Forestry.java +++ b/src/main/java/forestry/Forestry.java @@ -10,8 +10,10 @@ ******************************************************************************/ package forestry; +import javax.annotation.Nullable; import java.io.File; +import com.google.common.base.Preconditions; import forestry.api.core.ForestryAPI; import forestry.core.EventHandlerCore; import forestry.core.climate.ClimateEventHandler; @@ -26,7 +28,6 @@ import forestry.core.network.PacketHandler; import forestry.core.proxy.Proxies; import forestry.core.worldgen.WorldGenerator; import forestry.plugins.PluginManager; -import forestry.plugins.compat.PluginIC2; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fml.common.Mod; @@ -50,14 +51,16 @@ import net.minecraftforge.fml.common.registry.GameRegistry; name = "Forestry", version = Constants.VERSION, guiFactory = "forestry.core.config.ForestryGuiConfigFactory", - acceptedMinecraftVersions = "[1.10]", - dependencies = "required-after:Forge@[12.18.1.2080,);" - + "after:JEI@[3.11.2.278,);" - + "after:" + PluginIC2.modId + ";") + acceptedMinecraftVersions = "[1.11]", + dependencies = "required-after:forge@[13.19.1.2189,);" + + "after:JEI@[4.1.1,);") +// + "after:" + PluginIC2.modId + ";") public class Forestry { + @SuppressWarnings("NullableProblems") @Mod.Instance(Constants.MOD_ID) public static Forestry instance; + @Nullable private File configFolder; public Forestry() { @@ -68,6 +71,7 @@ public class Forestry { FluidRegistry.enableUniversalBucket(); } + @Nullable public static PacketHandler packetHandler; @EventHandler @@ -85,10 +89,12 @@ public class Forestry { PluginManager.runSetup(event); - ForestryAPI.activeMode = new GameMode(Config.gameMode); + String gameMode = Config.gameMode; + Preconditions.checkState(gameMode != null); + ForestryAPI.activeMode = new GameMode(gameMode); PluginManager.runPreInit(); - + Proxies.render.registerModels(); } @@ -122,6 +128,7 @@ public class Forestry { PluginManager.serverStarting(event.getServer()); } + @Nullable public File getConfigFolder() { return configFolder; } diff --git a/src/main/java/forestry/api/apiculture/EnumBeeType.java b/src/main/java/forestry/api/apiculture/EnumBeeType.java index 87ea5af71..0acd66d3a 100644 --- a/src/main/java/forestry/api/apiculture/EnumBeeType.java +++ b/src/main/java/forestry/api/apiculture/EnumBeeType.java @@ -14,7 +14,7 @@ public enum EnumBeeType implements ISpeciesType { public static final EnumBeeType[] VALUES = values(); - String name; + private final String name; EnumBeeType() { this.name = this.toString().toLowerCase(Locale.ENGLISH); diff --git a/src/main/java/forestry/api/apiculture/IBee.java b/src/main/java/forestry/api/apiculture/IBee.java index bb28b2d07..803671196 100644 --- a/src/main/java/forestry/api/apiculture/IBee.java +++ b/src/main/java/forestry/api/apiculture/IBee.java @@ -5,18 +5,16 @@ ******************************************************************************/ package forestry.api.apiculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Set; -import net.minecraft.item.ItemStack; -import net.minecraft.world.biome.Biome; - import forestry.api.core.IErrorState; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IIndividualLiving; +import net.minecraft.item.ItemStack; +import net.minecraft.world.biome.Biome; /** * Other implementations than Forestry's default one are not supported. @@ -28,7 +26,6 @@ public interface IBee extends IIndividualLiving { /** * @return Bee's genetic information. */ - @Nonnull @Override IBeeGenome getGenome(); @@ -51,6 +48,7 @@ public interface IBee extends IIndividualLiving { /** * Set the natural flag on this bee. + * * @param flag */ void setIsNatural(boolean flag); @@ -66,6 +64,7 @@ public interface IBee extends IIndividualLiving { /** * Determines whether the queen can work. + * * @param housing the {@link IBeeHousing} the bee currently resides in. * @return an empty set if the queen can work, a set of error states if the queen can not work */ @@ -77,14 +76,16 @@ public interface IBee extends IIndividualLiving { ItemStack[] getSpecialtyList(); - ItemStack[] produceStacks(IBeeHousing housing); + List produceStacks(IBeeHousing housing); + @Nullable IBee spawnPrincess(IBeeHousing housing); IBee[] spawnDrones(IBeeHousing housing); void plantFlowerRandom(IBeeHousing housing); + @Nullable IIndividual retrievePollen(IBeeHousing housing); boolean pollinateRandom(IBeeHousing housing, IIndividual pollen); diff --git a/src/main/java/forestry/api/apiculture/IBeeGenome.java b/src/main/java/forestry/api/apiculture/IBeeGenome.java index 03140c71e..05a0dc97f 100644 --- a/src/main/java/forestry/api/apiculture/IBeeGenome.java +++ b/src/main/java/forestry/api/apiculture/IBeeGenome.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.apiculture; -import javax.annotation.Nonnull; - import net.minecraft.util.math.Vec3i; import forestry.api.genetics.EnumTolerance; @@ -22,11 +20,9 @@ import forestry.api.genetics.IGenome; public interface IBeeGenome extends IGenome { @Override - @Nonnull IAlleleBeeSpecies getPrimary(); @Override - @Nonnull IAlleleBeeSpecies getSecondary(); float getSpeed(); diff --git a/src/main/java/forestry/api/apiculture/IBeeHousing.java b/src/main/java/forestry/api/apiculture/IBeeHousing.java index 5a9658834..fc3bc6a1c 100644 --- a/src/main/java/forestry/api/apiculture/IBeeHousing.java +++ b/src/main/java/forestry/api/apiculture/IBeeHousing.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.apiculture; +import javax.annotation.Nullable; + import com.mojang.authlib.GameProfile; import forestry.api.climate.IClimateProvider; import forestry.api.core.IErrorLogicSource; @@ -38,6 +40,7 @@ public interface IBeeHousing extends IHousing, IErrorLogicSource, IClimateProvid boolean isRaining(); + @Nullable GameProfile getOwner(); /** diff --git a/src/main/java/forestry/api/apiculture/IBeeRoot.java b/src/main/java/forestry/api/apiculture/IBeeRoot.java index 1323eb600..a09cee641 100644 --- a/src/main/java/forestry/api/apiculture/IBeeRoot.java +++ b/src/main/java/forestry/api/apiculture/IBeeRoot.java @@ -6,7 +6,6 @@ package forestry.api.apiculture; import javax.annotation.Nullable; -import java.util.ArrayList; import java.util.List; import com.mojang.authlib.GameProfile; @@ -53,7 +52,7 @@ public interface IBeeRoot extends ISpeciesRoot { * @return {@link IApiaristTracker} associated with the passed world. */ @Override - IApiaristTracker getBreedingTracker(World world, GameProfile player); + IApiaristTracker getBreedingTracker(World world, @Nullable GameProfile player); /* BEE SPECIFIC */ @@ -75,8 +74,7 @@ public interface IBeeRoot extends ISpeciesRoot { boolean isMated(ItemStack stack); /** - * @param genome - * Valid {@link IBeeGenome} + * @param genome Valid {@link IBeeGenome} * @return {@link IBee} from the passed genome */ IBee getBee(IBeeGenome genome); @@ -84,17 +82,16 @@ public interface IBeeRoot extends ISpeciesRoot { /** * Creates an IBee suitable for a queen containing the necessary second genome for the mate. * - * @param genome - * Valid {@link IBeeGenome} - * @param mate - * Valid {@link IBee} representing the mate. + * @param genome Valid {@link IBeeGenome} + * @param mate Valid {@link IBee} representing the mate. * @return Mated {@link IBee} from the passed genomes. */ IBee getBee(World world, IBeeGenome genome, IBee mate); /* TEMPLATES */ + @Override - ArrayList getIndividualTemplates(); + List getIndividualTemplates(); /* MUTATIONS */ @Override @@ -103,10 +100,11 @@ public interface IBeeRoot extends ISpeciesRoot { /* GAME MODE */ void resetBeekeepingMode(); - ArrayList getBeekeepingModes(); + List getBeekeepingModes(); IBeekeepingMode getBeekeepingMode(World world); + @Nullable IBeekeepingMode getBeekeepingMode(String name); void registerBeekeepingMode(IBeekeepingMode mode); diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java index c18aac502..4f2584f91 100644 --- a/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java +++ b/src/main/java/forestry/api/apiculture/IBeekeepingLogic.java @@ -5,17 +5,15 @@ ******************************************************************************/ package forestry.api.apiculture; -import javax.annotation.Nonnull; import java.util.List; +import forestry.api.core.INbtReadable; +import forestry.api.core.INbtWritable; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; -import forestry.api.core.INbtReadable; -import forestry.api.core.INbtWritable; - /** * Stores beekeeping logic for bee housings. * Get one with BeeManager.beeRoot.createBeekeepingLogic(IBeeHousing housing) @@ -27,6 +25,7 @@ public interface IBeekeepingLogic extends INbtWritable, INbtReadable { /** * Checks that the bees can work, setting error conditions on the housing where needed + * * @return true if no errors are present and doWork should be called */ boolean canWork(); @@ -75,6 +74,5 @@ public interface IBeekeepingLogic extends INbtWritable, INbtReadable { * Used by bee fx to direct bees to nearby flowers. * These positions are synced to the client from the server. */ - @Nonnull List getFlowerPositions(); } diff --git a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java b/src/main/java/forestry/api/apiculture/IBeekeepingMode.java index 4bfb4787e..602db3557 100644 --- a/src/main/java/forestry/api/apiculture/IBeekeepingMode.java +++ b/src/main/java/forestry/api/apiculture/IBeekeepingMode.java @@ -5,7 +5,7 @@ ******************************************************************************/ package forestry.api.apiculture; -import java.util.ArrayList; +import java.util.List; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -20,7 +20,7 @@ public interface IBeekeepingMode { /** * @return Localized list of strings outlining the behaviour of this beekeeping mode. */ - ArrayList getDescription(); + List getDescription(); /** * @return Float used to modify the wear on comb frames. @@ -47,7 +47,6 @@ public interface IBeekeepingMode { boolean isOverworked(IBee queen, IBeeHousing housing); /** - * * @param queen * @param offspring * @param housing diff --git a/src/main/java/forestry/api/apiculture/IHiveFrame.java b/src/main/java/forestry/api/apiculture/IHiveFrame.java index 008c95b6c..b9919b4ae 100644 --- a/src/main/java/forestry/api/apiculture/IHiveFrame.java +++ b/src/main/java/forestry/api/apiculture/IHiveFrame.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.apiculture; +import javax.annotation.Nullable; + import net.minecraft.item.ItemStack; public interface IHiveFrame { @@ -18,6 +20,7 @@ public interface IHiveFrame { * @param wear Integer denoting the amount worn out. The wear modifier of the current beekeeping mode has already been taken into account. * @return ItemStack containing the actual frame with adjusted damage, or null if it has been broken. */ + @Nullable ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear); IBeeModifier getBeeModifier(); diff --git a/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java b/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java index 79b239332..708ab9b8d 100644 --- a/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java +++ b/src/main/java/forestry/api/apiculture/hives/IHiveRegistry.java @@ -5,13 +5,11 @@ ******************************************************************************/ package forestry.api.apiculture.hives; -import javax.annotation.Nonnull; import java.util.List; import java.util.Locale; -import net.minecraft.util.IStringSerializable; - import forestry.api.apiculture.IHiveDrop; +import net.minecraft.util.IStringSerializable; public interface IHiveRegistry { @@ -25,25 +23,23 @@ public interface IHiveRegistry { SNOW("forestry:snow", "forestry.speciesWintry"), SWAMP("forestry:swamp", "forestry.speciesMarshy"), SWARM("forestry:swarm", "forestry.speciesForest"); - + public static final HiveType[] VALUES = values(); - @Nonnull private final String hiveUid; - @Nonnull private final String speciesUid; - HiveType(@Nonnull String hiveUid, @Nonnull String speciesUid) { + HiveType(String hiveUid, String speciesUid) { this.hiveUid = hiveUid; this.speciesUid = speciesUid; } - @Nonnull + public String getHiveUid() { return hiveUid; } - @Nonnull + public String getSpeciesUid() { return speciesUid; } @@ -56,7 +52,6 @@ public interface IHiveRegistry { public int getMeta() { return ordinal(); } - } /** diff --git a/src/main/java/forestry/api/apiculture/hives/package-info.java b/src/main/java/forestry/api/apiculture/hives/package-info.java index 18fb3c8b4..1e54c8c35 100644 --- a/src/main/java/forestry/api/apiculture/hives/package-info.java +++ b/src/main/java/forestry/api/apiculture/hives/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "4.1.0", owner = "ForestryAPI|apiculture", provides = "ForestryAPI|hives") package forestry.api.apiculture.hives; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/apiculture/package-info.java b/src/main/java/forestry/api/apiculture/package-info.java index b149566c2..9bb5568a3 100644 --- a/src/main/java/forestry/api/apiculture/package-info.java +++ b/src/main/java/forestry/api/apiculture/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "5.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|apiculture") package forestry.api.apiculture; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/arboriculture/EnumForestryWoodType.java b/src/main/java/forestry/api/arboriculture/EnumForestryWoodType.java index d3cf229f2..4aae500c2 100644 --- a/src/main/java/forestry/api/arboriculture/EnumForestryWoodType.java +++ b/src/main/java/forestry/api/arboriculture/EnumForestryWoodType.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import java.util.Locale; import java.util.Random; @@ -62,7 +61,7 @@ public enum EnumForestryWoodType implements IWoodType { public float getHardness() { return hardness; } - + public static EnumForestryWoodType getRandom(Random random) { return VALUES[random.nextInt(VALUES.length)]; } @@ -71,7 +70,7 @@ public enum EnumForestryWoodType implements IWoodType { public String toString() { return super.toString().toLowerCase(Locale.ENGLISH); } - + @Override public String getName() { return toString(); @@ -82,7 +81,6 @@ public enum EnumForestryWoodType implements IWoodType { return ordinal(); } - @Nonnull public static EnumForestryWoodType byMetadata(int meta) { if (meta < 0 || meta >= VALUES.length) { meta = 0; @@ -94,14 +92,14 @@ public enum EnumForestryWoodType implements IWoodType { public int getCarbonization() { return carbonization; } - + @Override public float getCharcoalChance(int numberOfCharcoal) { - if(numberOfCharcoal == 3){ + if (numberOfCharcoal == 3) { return 0.75F; - }else if(numberOfCharcoal == 4){ + } else if (numberOfCharcoal == 4) { return 0.5F; - }else if(numberOfCharcoal == 5){ + } else if (numberOfCharcoal == 5) { return 0.25F; } return 0.15F; diff --git a/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java b/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java index b57a1910e..b4741a2a7 100644 --- a/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java +++ b/src/main/java/forestry/api/arboriculture/EnumFruitFamily.java @@ -14,7 +14,8 @@ public enum EnumFruitFamily implements IFruitFamily { PRUNES("prunes", "Prunus domestica"), POMES("pomes", "Pomum"), JUNGLE("jungle", "Tropicus"), - NUX("nuts", "Nux"); + NUX("nuts", "Nux"), + NONE("none", "None"); private final String uid; private final String scientific; diff --git a/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java b/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java index 80d55f94d..61c075409 100644 --- a/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java +++ b/src/main/java/forestry/api/arboriculture/EnumTreeChromosome.java @@ -8,11 +8,9 @@ package forestry.api.arboriculture; import java.util.Locale; import forestry.api.genetics.IAllele; -import forestry.api.genetics.IAlleleArea; import forestry.api.genetics.IAlleleBoolean; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleInteger; -import forestry.api.genetics.IAllelePlantType; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.ISpeciesRoot; @@ -25,12 +23,6 @@ public enum EnumTreeChromosome implements IChromosomeType { * will actually yield fruit with this species. - Native {@link EnumPlantType} for this tree. Combines with the PLANT chromosome. */ SPECIES(IAlleleTreeSpecies.class), - /** - * {@link IGrowthProvider}, determines conditions required by the tree to grow. - * @deprecated unused - */ - @Deprecated - GROWTH(IAlleleGrowth.class), /** * A float modifying the height of the tree. Taken into account at worldgen. */ @@ -47,22 +39,10 @@ public enum EnumTreeChromosome implements IChromosomeType { * Chance for fruit leaves and/or drops. */ YIELD(IAlleleFloat.class), - /** - * May add additional tolerances for {@link EnumPlantType}. - * @deprecated this is tied to species directly - */ - @Deprecated - PLANT(IAllelePlantType.class), /** * Determines the speed at which fruit will ripen on this tree. */ SAPPINESS(IAlleleFloat.class), - /** - * Territory for leaf effects. - * @deprecated unused - */ - @Deprecated - TERRITORY(IAlleleArea.class), /** * Leaf effect. Unused. */ @@ -73,24 +53,12 @@ public enum EnumTreeChromosome implements IChromosomeType { MATURATION(IAlleleInteger.class), GIRTH(IAlleleInteger.class), - /** - * The combustibility of the wood, when it burn to charcoal and the combustibility of the charcoal. - * @deprecated this is tied to species directly - */ - @Deprecated - COMBUSTIBILITY(IAlleleInteger.class), - /** - * The amount of charcoal that a wood pile ash drop; - * @deprecated this is tied to species directly - */ - @Deprecated - CARBONIZATION(IAlleleInteger.class), /** * Determines if the tree can burn. */ FIREPROOF(IAlleleBoolean.class),; - Class alleleClass; + private final Class alleleClass; EnumTreeChromosome(Class alleleClass) { this.alleleClass = alleleClass; diff --git a/src/main/java/forestry/api/arboriculture/EnumVanillaWoodType.java b/src/main/java/forestry/api/arboriculture/EnumVanillaWoodType.java index e397e37b3..c126fedbe 100644 --- a/src/main/java/forestry/api/arboriculture/EnumVanillaWoodType.java +++ b/src/main/java/forestry/api/arboriculture/EnumVanillaWoodType.java @@ -1,6 +1,5 @@ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import java.util.Locale; import java.util.Random; @@ -47,7 +46,6 @@ public enum EnumVanillaWoodType implements IWoodType { return ordinal(); } - @Nonnull public static EnumVanillaWoodType byMetadata(int meta) { if (meta < 0 || meta >= VALUES.length) { meta = 0; @@ -64,14 +62,14 @@ public enum EnumVanillaWoodType implements IWoodType { public int getCarbonization() { return carbonization; } - + @Override public float getCharcoalChance(int numberOfCharcoal) { - if(numberOfCharcoal == 3){ + if (numberOfCharcoal == 3) { return 0.75F; - }else if(numberOfCharcoal == 4){ + } else if (numberOfCharcoal == 4) { return 0.5F; - }else if(numberOfCharcoal == 5){ + } else if (numberOfCharcoal == 5) { return 0.25F; } return 0.15F; @@ -79,7 +77,7 @@ public enum EnumVanillaWoodType implements IWoodType { @Override public String getPlankTexture() { - if(this == DARK_OAK){ + if (this == DARK_OAK) { return "blocks/planks_big_oak"; } return "blocks/planks_" + getName(); @@ -87,7 +85,7 @@ public enum EnumVanillaWoodType implements IWoodType { @Override public String getDoorLowerTexture() { - if(this == OAK){ + if (this == OAK) { return "blocks/door_wood_lower"; } return "blocks/door_wood_lower"; @@ -95,7 +93,7 @@ public enum EnumVanillaWoodType implements IWoodType { @Override public String getDoorUpperTexture() { - if(this == OAK){ + if (this == OAK) { return "blocks/door_wood_upper"; } return "blocks/door_" + getName() + "_upper"; @@ -103,7 +101,7 @@ public enum EnumVanillaWoodType implements IWoodType { @Override public String getBarkTexture() { - if(this == DARK_OAK){ + if (this == DARK_OAK) { return "blocks/log_big_oak"; } return "blocks/log_" + getName(); @@ -111,7 +109,7 @@ public enum EnumVanillaWoodType implements IWoodType { @Override public String getHeartTexture() { - if(this == DARK_OAK){ + if (this == DARK_OAK) { return "blocks/log_big_oak_top"; } return "blocks/log_" + getName() + "_top"; diff --git a/src/main/java/forestry/api/arboriculture/IAlleleFruit.java b/src/main/java/forestry/api/arboriculture/IAlleleFruit.java index 3a6d47cd0..2272250fb 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleFruit.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleFruit.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.api.genetics.IAlleleProperty; @@ -15,13 +14,11 @@ import forestry.api.genetics.IAlleleProperty; */ public interface IAlleleFruit extends IAlleleProperty { - @Nonnull IFruitProvider getProvider(); @Nullable String getModelName(); - @Nonnull String getModID(); } diff --git a/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java b/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java deleted file mode 100644 index a15563fd4..000000000 --- a/src/main/java/forestry/api/arboriculture/IAlleleGrowth.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.arboriculture; - -import forestry.api.genetics.IAllele; - -/** - * Simple allele encapsulating an {@link IGrowthProvider}. - */ -public interface IAlleleGrowth extends IAllele { - - IGrowthProvider getProvider(); - -} diff --git a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java index 626ea828c..74a52b991 100644 --- a/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java +++ b/src/main/java/forestry/api/arboriculture/IAlleleTreeSpecies.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import java.util.Collection; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -21,47 +20,40 @@ import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IFruitFamily; public interface IAlleleTreeSpecies extends IAlleleSpecies, IAlleleProperty { - - @Nonnull + @Override ITreeRoot getRoot(); /** * @return Native plant type of this species. */ - @Nonnull EnumPlantType getPlantType(); /** * @return List of all {@link IFruitFamily}s which can grow on leaves generated by this species. */ - @Nonnull Collection getSuitableFruit(); /** * @return Tree generator for this species. */ - @Nonnull ITreeGenerator getGenerator(); /** * @return The modid from the mod of the species. */ - @Nonnull String getModID(); IWoodProvider getWoodProvider(); /* MODELS AND OVERRIDES */ @SideOnly(Side.CLIENT) - @Nonnull ILeafSpriteProvider getLeafSpriteProvider(); @SideOnly(Side.CLIENT) int getGermlingColour(EnumGermlingType type, int renderPass); @SideOnly(Side.CLIENT) - @Nonnull ModelResourceLocation getGermlingModel(EnumGermlingType type); @SideOnly(Side.CLIENT) diff --git a/src/main/java/forestry/api/arboriculture/IFruitProvider.java b/src/main/java/forestry/api/arboriculture/IFruitProvider.java index 3cf67dbe7..5abb9ad73 100644 --- a/src/main/java/forestry/api/arboriculture/IFruitProvider.java +++ b/src/main/java/forestry/api/arboriculture/IFruitProvider.java @@ -5,13 +5,12 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; import java.util.Map; import java.util.Random; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; @@ -23,7 +22,6 @@ import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.genetics.IFruitFamily; public interface IFruitProvider { - IFruitFamily getFamily(); int getColour(ITreeGenome genome, IBlockAccess world, BlockPos pos, int ripeningTime); @@ -36,15 +34,12 @@ public interface IFruitProvider { int getRipeningPeriod(); // / Products, Chance - @Nonnull Map getProducts(); // / Specialty, Chance - @Nonnull Map getSpecialty(); - @Nonnull - List getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime); + NonNullList getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime); /** * @return Short, human-readable identifier used in the treealyzer. @@ -54,7 +49,6 @@ public interface IFruitProvider { @Nullable String getModelName(); - @Nonnull String getModID(); /* TEXTURE OVERLAY */ diff --git a/src/main/java/forestry/api/arboriculture/IGermlingModelProvider.java b/src/main/java/forestry/api/arboriculture/IGermlingModelProvider.java index ac5ea1f23..bb5738ce0 100644 --- a/src/main/java/forestry/api/arboriculture/IGermlingModelProvider.java +++ b/src/main/java/forestry/api/arboriculture/IGermlingModelProvider.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; - import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; @@ -23,8 +21,7 @@ import forestry.api.core.IModelManager; public interface IGermlingModelProvider { @SideOnly(Side.CLIENT) void registerModels(Item item, IModelManager manager, EnumGermlingType type); - - @Nonnull + ModelResourceLocation getModel(EnumGermlingType type); /** diff --git a/src/main/java/forestry/api/arboriculture/IGrowthProvider.java b/src/main/java/forestry/api/arboriculture/IGrowthProvider.java deleted file mode 100644 index c6591d647..000000000 --- a/src/main/java/forestry/api/arboriculture/IGrowthProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.arboriculture; - -import javax.annotation.Nullable; - -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -/** - * @deprecated this is being removed to simplify trees - */ -@Deprecated -public interface IGrowthProvider { - - /** - * Check to see whether a sapling at the given location with the given genome can grow into a tree. - * - * @param genome Genome of the tree this is called for. - * @param world Minecraft world the tree will inhabit. - * @param pos Coordinates to attempt growth at. - * @param expectedGirth Trunk size of the tree to generate. - * @param expectedHeight Height of the tree to generate. - * @return position that the tree can grow, null otherwise. - */ - @Nullable - BlockPos canGrow(ITreeGenome genome, World world, BlockPos pos, int expectedGirth, int expectedHeight); - - /** - * @return Short, human-readable identifier used in the treealyzer. - */ - String getDescription(); - - /** - * @return Detailed description of growth behaviour used in the treealyzer. - */ - String[] getInfo(); - -} diff --git a/src/main/java/forestry/api/arboriculture/ILeafSpriteProvider.java b/src/main/java/forestry/api/arboriculture/ILeafSpriteProvider.java index 9100afb24..650ac65d3 100644 --- a/src/main/java/forestry/api/arboriculture/ILeafSpriteProvider.java +++ b/src/main/java/forestry/api/arboriculture/ILeafSpriteProvider.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; - import net.minecraft.util.ResourceLocation; /** @@ -17,7 +15,6 @@ import net.minecraft.util.ResourceLocation; * Icon registration is not done here because these icons are heavily reused. */ public interface ILeafSpriteProvider { - @Nonnull ResourceLocation getSprite(boolean pollinated, boolean fancy); int getColor(boolean pollinated); diff --git a/src/main/java/forestry/api/arboriculture/ITree.java b/src/main/java/forestry/api/arboriculture/ITree.java index 1204a9ede..4c30c6883 100644 --- a/src/main/java/forestry/api/arboriculture/ITree.java +++ b/src/main/java/forestry/api/arboriculture/ITree.java @@ -5,9 +5,7 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; import java.util.Map; import com.mojang.authlib.GameProfile; @@ -15,6 +13,7 @@ import forestry.api.genetics.IEffectData; import forestry.api.genetics.IIndividual; import forestry.api.world.ITreeGenData; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -28,10 +27,10 @@ public interface ITree extends IIndividual, ITreeGenData { IEffectData[] doFX(IEffectData[] storedData, World world, BlockPos pos); - @Nonnull @Override ITreeGenome getGenome(); + @Nullable ITreeGenome getMate(); /** @@ -40,15 +39,12 @@ public interface ITree extends IIndividual, ITreeGenData { ITree[] getSaplings(World world, GameProfile playerProfile, BlockPos pos, float modifier); // Products, Chance - @Nonnull Map getProducts(); // Specialties, Chance - @Nonnull Map getSpecialties(); - @Nonnull - List produceStacks(World world, BlockPos pos, int ripeningTime); + NonNullList produceStacks(World world, BlockPos pos, int ripeningTime); /** * @return Boolean indicating whether a sapling can stay planted at the given position. @@ -72,7 +68,7 @@ public interface ITree extends IIndividual, ITreeGenData { * @return Integer denoting how resilient leaf blocks are against adverse influences (i.e. caterpillars). */ int getResilience(); - + /** * @return Integer denoting the size of the tree trunk. */ diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java index b90f6596b..cc25fbe6b 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeGenerator.java +++ b/src/main/java/forestry/api/arboriculture/ITreeGenerator.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.arboriculture; +import javax.annotation.Nullable; + import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -22,5 +24,5 @@ public interface ITreeGenerator { boolean setLogBlock(ITreeGenome genome, World world, BlockPos pos, EnumFacing facing); - boolean setLeaves(ITreeGenome genome, World world, GameProfile owner, BlockPos pos); + boolean setLeaves(ITreeGenome genome, World world, @Nullable GameProfile owner, BlockPos pos); } diff --git a/src/main/java/forestry/api/arboriculture/ITreeGenome.java b/src/main/java/forestry/api/arboriculture/ITreeGenome.java index a6eff24a7..e895f47d6 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeGenome.java +++ b/src/main/java/forestry/api/arboriculture/ITreeGenome.java @@ -5,21 +5,16 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; - import forestry.api.genetics.IGenome; public interface ITreeGenome extends IGenome { @Override - @Nonnull IAlleleTreeSpecies getPrimary(); @Override - @Nonnull IAlleleTreeSpecies getSecondary(); - - @Nonnull + IFruitProvider getFruitProvider(); float getHeight(); diff --git a/src/main/java/forestry/api/arboriculture/ITreeRoot.java b/src/main/java/forestry/api/arboriculture/ITreeRoot.java index a5a07298a..f16cb5511 100644 --- a/src/main/java/forestry/api/arboriculture/ITreeRoot.java +++ b/src/main/java/forestry/api/arboriculture/ITreeRoot.java @@ -5,9 +5,7 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -48,12 +46,13 @@ public interface ITreeRoot extends ISpeciesRootPollinatable { * @return {@link IArboristTracker} associated with the passed world. */ @Override - IArboristTracker getBreedingTracker(World world, GameProfile player); + IArboristTracker getBreedingTracker(World world, @Nullable GameProfile player); /* TREE SPECIFIC */ /** * Register a leaf tick handler. + * * @param handler the {@link ILeafTickHandler} to register. */ void registerLeafTickHandler(ILeafTickHandler handler); @@ -67,6 +66,7 @@ public interface ITreeRoot extends ISpeciesRootPollinatable { @Override EnumGermlingType getType(ItemStack stack); + @Nullable ITree getTree(World world, BlockPos pos); ITree getTree(World world, ITreeGenome genome); @@ -79,7 +79,7 @@ public interface ITreeRoot extends ISpeciesRootPollinatable { @Override IChromosome[] templateAsChromosomes(IAllele[] templateActive, IAllele[] templateInactive); - boolean setFruitBlock(@Nonnull World world, @Nonnull IAlleleFruit allele, float sappiness, BlockPos pos); + boolean setFruitBlock(World world, ITreeGenome genome, IAlleleFruit allele, float sappiness, BlockPos pos); /* GAME MODE */ List getTreekeepingModes(); @@ -93,8 +93,9 @@ public interface ITreeRoot extends ISpeciesRootPollinatable { void setTreekeepingMode(World world, String name); /* TEMPLATES */ + @Override - ArrayList getIndividualTemplates(); + List getIndividualTemplates(); /* MUTATIONS */ @Override diff --git a/src/main/java/forestry/api/arboriculture/IWoodProvider.java b/src/main/java/forestry/api/arboriculture/IWoodProvider.java index feac01f57..d3eecd500 100644 --- a/src/main/java/forestry/api/arboriculture/IWoodProvider.java +++ b/src/main/java/forestry/api/arboriculture/IWoodProvider.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.arboriculture; -import javax.annotation.Nonnull; - import forestry.api.core.ITextureManager; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.item.Item; @@ -19,13 +17,11 @@ public interface IWoodProvider { void registerSprites(Item item, ITextureManager manager); /** - * * @return The texture sprite of the wood. */ @SideOnly(Side.CLIENT) - @Nonnull TextureAtlasSprite getSprite(boolean isTop); - + /** * @return A stack of wood from the tree to craft wood pile's or other things. */ @@ -35,7 +31,7 @@ public interface IWoodProvider { * The amount of charcoal dropped from a charcoal pile of this wood. */ int getCarbonization(); - + /** * The chance that a pile has to drop a extra charcoal */ diff --git a/src/main/java/forestry/api/arboriculture/WoodBlockKind.java b/src/main/java/forestry/api/arboriculture/WoodBlockKind.java index 69031f81b..b2df3929e 100644 --- a/src/main/java/forestry/api/arboriculture/WoodBlockKind.java +++ b/src/main/java/forestry/api/arboriculture/WoodBlockKind.java @@ -3,8 +3,8 @@ package forestry.api.arboriculture; import java.util.HashMap; import java.util.Locale; import java.util.Map; -import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap; import net.minecraftforge.client.model.IModel; import net.minecraftforge.client.model.ModelProcessingHelper; @@ -12,55 +12,55 @@ public enum WoodBlockKind { LOG, PLANKS, SLAB, FENCE, FENCE_GATE, STAIRS, DOOR(false); public final boolean retextureItem; - - private WoodBlockKind() { + + WoodBlockKind() { this(true); } - - private WoodBlockKind(boolean retextureItem) { + + WoodBlockKind(boolean retextureItem) { this.retextureItem = retextureItem; } - + @Override public String toString() { return super.toString().toLowerCase(Locale.ENGLISH); } - - public IModel retextureModel(IModel model, IWoodType type, ImmutableMap customTextures){ + + public IModel retextureModel(IModel model, IWoodType type, ImmutableMap customTextures) { Map textures = new HashMap<>(); switch (this) { - case SLAB: - case STAIRS: - String textureLocation = type.getPlankTexture(); - textures.put("particle", textureLocation); - textures.put("side", textureLocation); - textures.put("top", textureLocation); - textures.put("bottom", textureLocation); - textures.put("all", textureLocation); - break; - case PLANKS: - textures.put("particle", type.getPlankTexture()); - textures.put("all", type.getPlankTexture()); - break; - case FENCE_GATE: - case FENCE: - textures.put("particle", type.getPlankTexture()); - textures.put("side", type.getPlankTexture()); - textures.put("texture", type.getPlankTexture()); - break; - case DOOR: - textures.put("particle", type.getDoorLowerTexture()); - textures.put("bottom", type.getDoorLowerTexture()); - textures.put("top", type.getDoorUpperTexture()); - break; - case LOG: - textures.put("particle", type.getBarkTexture()); - textures.put("side", type.getBarkTexture()); - textures.put("all", type.getBarkTexture()); - textures.put("end", type.getHeartTexture()); - break; - default: - break; + case SLAB: + case STAIRS: + String textureLocation = type.getPlankTexture(); + textures.put("particle", textureLocation); + textures.put("side", textureLocation); + textures.put("top", textureLocation); + textures.put("bottom", textureLocation); + textures.put("all", textureLocation); + break; + case PLANKS: + textures.put("particle", type.getPlankTexture()); + textures.put("all", type.getPlankTexture()); + break; + case FENCE_GATE: + case FENCE: + textures.put("particle", type.getPlankTexture()); + textures.put("side", type.getPlankTexture()); + textures.put("texture", type.getPlankTexture()); + break; + case DOOR: + textures.put("particle", type.getDoorLowerTexture()); + textures.put("bottom", type.getDoorLowerTexture()); + textures.put("top", type.getDoorUpperTexture()); + break; + case LOG: + textures.put("particle", type.getBarkTexture()); + textures.put("side", type.getBarkTexture()); + textures.put("all", type.getBarkTexture()); + textures.put("end", type.getHeartTexture()); + break; + default: + break; } textures.putAll(customTextures); return ModelProcessingHelper.retexture(model, new ImmutableMap.Builder().putAll(textures).build()); diff --git a/src/main/java/forestry/api/arboriculture/package-info.java b/src/main/java/forestry/api/arboriculture/package-info.java index e4dedb7c7..19147bbe2 100644 --- a/src/main/java/forestry/api/arboriculture/package-info.java +++ b/src/main/java/forestry/api/arboriculture/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "4.2.1", owner = "ForestryAPI|core", provides = "ForestryAPI|arboriculture") package forestry.api.arboriculture; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/circuits/ICircuitBoard.java b/src/main/java/forestry/api/circuits/ICircuitBoard.java index 751982fc0..7ed2b4962 100644 --- a/src/main/java/forestry/api/circuits/ICircuitBoard.java +++ b/src/main/java/forestry/api/circuits/ICircuitBoard.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.circuits; -import javax.annotation.Nonnull; import java.util.List; import forestry.api.core.INbtWritable; @@ -26,13 +25,11 @@ public interface ICircuitBoard extends INbtWritable { void onTick(Object tile); - @Nonnull ICircuit[] getCircuits(); /** * Specifies where a circuit can be used. */ - @Nonnull ICircuitSocketType getSocketType(); } diff --git a/src/main/java/forestry/api/circuits/ICircuitLayout.java b/src/main/java/forestry/api/circuits/ICircuitLayout.java index 338c38d51..a4c3e358b 100644 --- a/src/main/java/forestry/api/circuits/ICircuitLayout.java +++ b/src/main/java/forestry/api/circuits/ICircuitLayout.java @@ -5,26 +5,20 @@ ******************************************************************************/ package forestry.api.circuits; -import javax.annotation.Nonnull; - public interface ICircuitLayout { /** unique ID for this circuit layout */ - @Nonnull String getUID(); /** localized name for this circuit layout */ - @Nonnull String getName(); /** localized string for how this circuit layout is used */ - @Nonnull String getUsage(); /** * Specifies where a circuit layout is used. */ - @Nonnull ICircuitSocketType getSocketType(); } diff --git a/src/main/java/forestry/api/circuits/ICircuitRegistry.java b/src/main/java/forestry/api/circuits/ICircuitRegistry.java index 9226b9454..fd6af5af9 100644 --- a/src/main/java/forestry/api/circuits/ICircuitRegistry.java +++ b/src/main/java/forestry/api/circuits/ICircuitRegistry.java @@ -5,6 +5,7 @@ ******************************************************************************/ package forestry.api.circuits; +import javax.annotation.Nullable; import java.util.Map; import net.minecraft.item.ItemStack; @@ -30,6 +31,7 @@ public interface ICircuitRegistry { ICircuitLayout getDefaultLayout(); + @Nullable ICircuitBoard getCircuitBoard(ItemStack itemstack); boolean isChipset(ItemStack itemstack); diff --git a/src/main/java/forestry/api/circuits/package-info.java b/src/main/java/forestry/api/circuits/package-info.java index db28a65fa..7d1939f7a 100644 --- a/src/main/java/forestry/api/circuits/package-info.java +++ b/src/main/java/forestry/api/circuits/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "3.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|circuits") package forestry.api.circuits; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/climate/IClimateManager.java b/src/main/java/forestry/api/climate/IClimateManager.java index 601ae9212..6f4ec9605 100644 --- a/src/main/java/forestry/api/climate/IClimateManager.java +++ b/src/main/java/forestry/api/climate/IClimateManager.java @@ -5,39 +5,35 @@ ******************************************************************************/ package forestry.api.climate; +import javax.annotation.Nullable; import java.util.List; import java.util.Map; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public interface IClimateManager { float getTemperature(World world, BlockPos pos); - + float getHumidity(World world, BlockPos pos); - - @Nonnull + IClimateProvider getDefaultClimate(World world, BlockPos pos); - + void addRegion(IClimateRegion region); - + void removeRegion(IClimateRegion region); - + void addSource(IClimateSourceProvider source); - + void removeSource(IClimateSourceProvider source); - + @Nullable IClimatePosition getPosition(World world, BlockPos pos); - + @Nullable IClimateRegion getRegionForPos(World world, BlockPos pos); - - @Nonnull + Map> getRegions(); - + } diff --git a/src/main/java/forestry/api/climate/IClimatePosition.java b/src/main/java/forestry/api/climate/IClimatePosition.java index e604cd3ef..2afd74766 100644 --- a/src/main/java/forestry/api/climate/IClimatePosition.java +++ b/src/main/java/forestry/api/climate/IClimatePosition.java @@ -5,18 +5,14 @@ ******************************************************************************/ package forestry.api.climate; -import javax.annotation.Nonnull; - import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import net.minecraft.util.math.BlockPos; public interface IClimatePosition extends INbtReadable, INbtWritable { - - @Nonnull + IClimateRegion getClimateRegion(); - - @Nonnull + BlockPos getPos(); void setTemperature(float temperature); diff --git a/src/main/java/forestry/api/climate/IClimateRegion.java b/src/main/java/forestry/api/climate/IClimateRegion.java index a5fe4dd27..d00f03616 100644 --- a/src/main/java/forestry/api/climate/IClimateRegion.java +++ b/src/main/java/forestry/api/climate/IClimateRegion.java @@ -8,38 +8,34 @@ package forestry.api.climate; import java.util.Collection; import java.util.Map; -import javax.annotation.Nonnull; - import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public interface IClimateRegion extends INbtReadable, INbtWritable { - - @Nonnull + World getWorld(); - + /** * Update the climate in a region. */ void updateClimate(int ticks); - + int getTicksPerUpdate(); - - @Nonnull + Map getPositions(); - + void addSource(IClimateSource source); - + void removeSource(IClimateSource source); - + Collection getSources(); - + Collection getOtherPositions(); - + float getTemperature(); - + float getHumidity(); - + } diff --git a/src/main/java/forestry/api/climate/IClimateSource.java b/src/main/java/forestry/api/climate/IClimateSource.java index 6e6283000..a7a8f7ed7 100644 --- a/src/main/java/forestry/api/climate/IClimateSource.java +++ b/src/main/java/forestry/api/climate/IClimateSource.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.climate; +import javax.annotation.Nullable; + /** * A climate source is used to change the climate in a region. */ @@ -21,7 +23,8 @@ public interface IClimateSource { * @return The ticks that are required for one change. */ int getTicksForChange(IClimateRegion region); - + + @Nullable IClimateSourceProvider getProvider(); } diff --git a/src/main/java/forestry/api/climate/package-info.java b/src/main/java/forestry/api/climate/package-info.java index 71b75c935..e627a6ed8 100644 --- a/src/main/java/forestry/api/climate/package-info.java +++ b/src/main/java/forestry/api/climate/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "2.1.0", owner = "Forestry", provides = "ForestryAPI|climate") package forestry.api.climate; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/core/BiomeHelper.java b/src/main/java/forestry/api/core/BiomeHelper.java index 4fd11cc34..fa576d735 100644 --- a/src/main/java/forestry/api/core/BiomeHelper.java +++ b/src/main/java/forestry/api/core/BiomeHelper.java @@ -22,7 +22,7 @@ public class BiomeHelper { return isBiomeHellishCache.get(biomeGen); } - boolean isBiomeHellish = BiomeDictionary.isBiomeOfType(biomeGen, BiomeDictionary.Type.NETHER); + boolean isBiomeHellish = BiomeDictionary.hasType(biomeGen, BiomeDictionary.Type.NETHER); isBiomeHellishCache.put(biomeGen, isBiomeHellish); return isBiomeHellish; } diff --git a/src/main/java/forestry/api/core/ICamouflageAccess.java b/src/main/java/forestry/api/core/ICamouflageAccess.java index 28b1fa23d..25a038d2e 100644 --- a/src/main/java/forestry/api/core/ICamouflageAccess.java +++ b/src/main/java/forestry/api/core/ICamouflageAccess.java @@ -5,33 +5,33 @@ ******************************************************************************/ package forestry.api.core; +import javax.annotation.Nullable; import java.util.List; -import javax.annotation.Nonnull; - import net.minecraft.item.ItemStack; public interface ICamouflageAccess { - + /** * Register a item camouflage handler for a type. - * - * @param type The camouflage type for of handler. + * * @param itemHandler The handler that is to register. */ - void registerCamouflageItemHandler(@Nonnull ICamouflageItemHandler itemHandler); - + void registerCamouflageItemHandler(ICamouflageItemHandler itemHandler); + /** * @return A list of all item camouflage handler's that are registered for that camouflage type. */ - List getCamouflageItemHandler(@Nonnull String type); - - void addItemToBlackList(@Nonnull String type, @Nonnull ItemStack camouflageBlock); - - void addModIdToBlackList(@Nonnull String type, @Nonnull String modID); - - boolean isItemBlackListed(@Nonnull String type, @Nonnull ItemStack camouflageBlock); - + @Nullable + List getCamouflageItemHandler(String type); + + void addItemToBlackList(String type, ItemStack camouflageBlock); + + void addModIdToBlackList(String type, String modID); + + boolean isItemBlackListed(String type, ItemStack camouflageBlock); + + @Nullable ICamouflageItemHandler getHandlerFromItem(ItemStack stack); - + } diff --git a/src/main/java/forestry/api/core/ICamouflageItemHandler.java b/src/main/java/forestry/api/core/ICamouflageItemHandler.java index 159322f16..23f30eb86 100644 --- a/src/main/java/forestry/api/core/ICamouflageItemHandler.java +++ b/src/main/java/forestry/api/core/ICamouflageItemHandler.java @@ -5,23 +5,22 @@ ******************************************************************************/ package forestry.api.core; -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; public interface ICamouflageItemHandler { boolean canHandle(ItemStack stack); - + String getType(); - + float getLightTransmittance(ItemStack stack, ICamouflageHandler camouflageHandler); - + @SideOnly(Side.CLIENT) Pair getModel(ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile); - + } diff --git a/src/main/java/forestry/api/core/IErrorLogic.java b/src/main/java/forestry/api/core/IErrorLogic.java index 61e9597bb..45e180618 100644 --- a/src/main/java/forestry/api/core/IErrorLogic.java +++ b/src/main/java/forestry/api/core/IErrorLogic.java @@ -5,10 +5,10 @@ ******************************************************************************/ package forestry.api.core; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; +import net.minecraft.network.PacketBuffer; + /** * Keeps track of all the IErrorStates for an object. * Create a new IErrorLogic instance for your object with ForestryAPI.errorStateRegistry.createErrorLogic(). @@ -39,7 +39,7 @@ public interface IErrorLogic extends IErrorSource { /** * Network serialization for syncing errors to the client from the server. */ - void writeData(DataOutputStream data) throws IOException; + void writeData(PacketBuffer data); - void readData(DataInputStream data) throws IOException; + void readData(PacketBuffer data); } diff --git a/src/main/java/forestry/api/core/IModelBaker.java b/src/main/java/forestry/api/core/IModelBaker.java index 4bc805e00..6c38a4954 100644 --- a/src/main/java/forestry/api/core/IModelBaker.java +++ b/src/main/java/forestry/api/core/IModelBaker.java @@ -1,11 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.block.Block; @@ -25,28 +24,28 @@ import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public interface IModelBaker { - void setRenderBounds(@Nonnull AxisAlignedBB renderBounds); + void setRenderBounds(AxisAlignedBB renderBounds); void setRenderBounds(double d, double e, double f, double g, double h, double i); void setColorIndex(int color); - void addBlockModel(@Nonnull Block block, @Nonnull AxisAlignedBB renderBounds, @Nullable BlockPos pos, @Nonnull TextureAtlasSprite[] sprites, int colorIndex); - - void addBlockModel(@Nonnull Block block, @Nonnull AxisAlignedBB renderBounds, @Nullable BlockPos pos, @Nonnull TextureAtlasSprite sprites, int colorIndex); - - void addModel(@Nonnull AxisAlignedBB renderBounds, @Nonnull TextureAtlasSprite[] textures, int colorIndex); - - void addModel(@Nonnull AxisAlignedBB renderBounds, @Nonnull TextureAtlasSprite texture, int colorIndex); - - void addBakedModel(@Nullable IBlockState state, @Nonnull IBakedModel model); - - void addFace(@Nonnull EnumFacing facing, @Nonnull TextureAtlasSprite sprite); - + void addBlockModel(Block block, AxisAlignedBB renderBounds, @Nullable BlockPos pos, TextureAtlasSprite[] sprites, int colorIndex); + + void addBlockModel(Block block, AxisAlignedBB renderBounds, @Nullable BlockPos pos, TextureAtlasSprite sprites, int colorIndex); + + void addModel(AxisAlignedBB renderBounds, TextureAtlasSprite[] textures, int colorIndex); + + void addModel(AxisAlignedBB renderBounds, TextureAtlasSprite texture, int colorIndex); + + void addBakedModel(@Nullable IBlockState state, IBakedModel model); + + void addFace(EnumFacing facing, TextureAtlasSprite sprite); + void setModelState(@Nullable IModelState modelState); - - void setParticleSprite(@Nullable TextureAtlasSprite particleSprite); - + + void setParticleSprite(TextureAtlasSprite particleSprite); + IModelBakerModel bakeModel(boolean flip); - + } diff --git a/src/main/java/forestry/api/core/IModelBakerModel.java b/src/main/java/forestry/api/core/IModelBakerModel.java index 6809dbfb0..04aa47a06 100644 --- a/src/main/java/forestry/api/core/IModelBakerModel.java +++ b/src/main/java/forestry/api/core/IModelBakerModel.java @@ -1,11 +1,10 @@ /******************************************************************************* * Copyright 2011-2014 SirSengir - * + * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ package forestry.api.core; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.client.renderer.block.model.BakedQuad; @@ -18,23 +17,21 @@ import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public interface IModelBakerModel extends IPerspectiveAwareModel { - + void setGui3d(boolean gui3d); - + void setAmbientOcclusion(boolean ambientOcclusion); - - void setParticleSprite(@Nullable TextureAtlasSprite particleSprite); - - void addQuad(@Nullable EnumFacing facing, @Nonnull BakedQuad quad); - + + void setParticleSprite(TextureAtlasSprite particleSprite); + + void addQuad(@Nullable EnumFacing facing, BakedQuad quad); + void setRotation(float[] rotation); void setTranslation(float[] translation); void setScale(float[] scale); - - IModelState getModelState(); - + float[] getRotation(); float[] getTranslation(); diff --git a/src/main/java/forestry/api/core/IToolPipette.java b/src/main/java/forestry/api/core/IToolPipette.java index 5230aa3ef..8873fa489 100644 --- a/src/main/java/forestry/api/core/IToolPipette.java +++ b/src/main/java/forestry/api/core/IToolPipette.java @@ -12,43 +12,12 @@ package forestry.api.core; import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; - /** * Taken from BuildCraft 5.0.x */ public interface IToolPipette { - /** - * @param pipette - * ItemStack of the pipette. - * @return Capacity of the pipette. - */ - int getCapacity(ItemStack pipette); - - /** - * @param pipette * @return true if the pipette can pipette. */ boolean canPipette(ItemStack pipette); - - /** - * Fills the pipette with the given liquid stack. - * - * @param pipette - * @param liquid - * @param doFill - * @return Amount of liquid used in filling the pipette. - */ - int fill(ItemStack pipette, FluidStack liquid, boolean doFill); - - /** - * Drains liquid from the pipette - * - * @param pipette - * @param maxDrain - * @param doDrain - * @return Fluid stack representing the liquid and amount drained from the pipette. - */ - FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain); } diff --git a/src/main/java/forestry/api/core/package-info.java b/src/main/java/forestry/api/core/package-info.java index 9a7a6451e..9adb764c4 100644 --- a/src/main/java/forestry/api/core/package-info.java +++ b/src/main/java/forestry/api/core/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "5.1.0", owner = "Forestry", provides = "ForestryAPI|core") package forestry.api.core; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/farming/DefaultFarmListener.java b/src/main/java/forestry/api/farming/DefaultFarmListener.java index 7ee6e0a4c..0caaba217 100644 --- a/src/main/java/forestry/api/farming/DefaultFarmListener.java +++ b/src/main/java/forestry/api/farming/DefaultFarmListener.java @@ -8,6 +8,7 @@ package forestry.api.farming; import java.util.Collection; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; /** @@ -27,7 +28,7 @@ public class DefaultFarmListener implements IFarmListener { } @Override - public void hasCollected(Collection collected, IFarmLogic logic) { + public void hasCollected(NonNullList collected, IFarmLogic logic) { } diff --git a/src/main/java/forestry/api/farming/FarmDirection.java b/src/main/java/forestry/api/farming/FarmDirection.java index 0d49e2657..b32eb399e 100644 --- a/src/main/java/forestry/api/farming/FarmDirection.java +++ b/src/main/java/forestry/api/farming/FarmDirection.java @@ -23,7 +23,6 @@ public enum FarmDirection { return forgeDirection; } - @SuppressWarnings("incomplete-switch") public static FarmDirection getFarmDirection(EnumFacing forgeDirection) { switch (forgeDirection) { case NORTH: @@ -34,7 +33,8 @@ public enum FarmDirection { return SOUTH; case WEST: return WEST; + default: + throw new IllegalArgumentException("Farm directios can only be NORTH, EAST, SOUTH, or WEST. Got: " + forgeDirection); } - return null; } } diff --git a/src/main/java/forestry/api/farming/Farmables.java b/src/main/java/forestry/api/farming/Farmables.java index e3a5fd975..f949570ec 100644 --- a/src/main/java/forestry/api/farming/Farmables.java +++ b/src/main/java/forestry/api/farming/Farmables.java @@ -11,19 +11,16 @@ import com.google.common.collect.Multimap; import net.minecraft.item.ItemStack; import java.util.LinkedHashMap; - -import javax.annotation.Nonnull; +import java.util.Map; public class Farmables { /** * Can be used to add IFarmables to some of the vanilla farm logics. - * + *

* Identifiers: farmArboreal farmWheat farmGourd farmInfernal farmPoales farmSucculentes farmVegetables farmShroom */ - @Nonnull public static final Multimap farmables = HashMultimap.create(); - @Nonnull - public static final LinkedHashMap fertilizers = new LinkedHashMap(); + public static final Map fertilizers = new LinkedHashMap<>(); } diff --git a/src/main/java/forestry/api/farming/ICrop.java b/src/main/java/forestry/api/farming/ICrop.java index 8b29e79ed..f57bca7e9 100644 --- a/src/main/java/forestry/api/farming/ICrop.java +++ b/src/main/java/forestry/api/farming/ICrop.java @@ -5,11 +5,10 @@ ******************************************************************************/ package forestry.api.farming; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Collection; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; public interface ICrop { @@ -17,11 +16,10 @@ public interface ICrop { /** * Harvests this crop. Performs the necessary manipulations to set the crop into a "harvested" state. * - * @return Products harvested. + * @return Products harvested. Null if this crop cannot be harvested */ @Nullable - Collection harvest(); + NonNullList harvest(); - @Nonnull BlockPos getPosition(); } diff --git a/src/main/java/forestry/api/farming/IFarmInventory.java b/src/main/java/forestry/api/farming/IFarmInventory.java index f086cf86b..7f9a793d8 100644 --- a/src/main/java/forestry/api/farming/IFarmInventory.java +++ b/src/main/java/forestry/api/farming/IFarmInventory.java @@ -7,11 +7,12 @@ package forestry.api.farming; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public interface IFarmInventory { - boolean hasResources(ItemStack[] resources); + boolean hasResources(NonNullList resources); - void removeResources(ItemStack[] resources); + void removeResources(NonNullList resources); boolean acceptsAsGermling(ItemStack itemstack); diff --git a/src/main/java/forestry/api/farming/IFarmListener.java b/src/main/java/forestry/api/farming/IFarmListener.java index fbf99122f..01bdff53b 100644 --- a/src/main/java/forestry/api/farming/IFarmListener.java +++ b/src/main/java/forestry/api/farming/IFarmListener.java @@ -8,6 +8,7 @@ package forestry.api.farming; import java.util.Collection; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; public interface IFarmListener { @@ -33,7 +34,7 @@ public interface IFarmListener { * * @param collected Collection of collected stacks. May be manipulated. Ensure removal of stacks with 0 or less items! */ - void hasCollected(Collection collected, IFarmLogic logic); + void hasCollected(NonNullList collected, IFarmLogic logic); /** * Called after farmland has successfully been cultivated by a farm logic. diff --git a/src/main/java/forestry/api/farming/IFarmLogic.java b/src/main/java/forestry/api/farming/IFarmLogic.java index 985db22ea..cf6729497 100644 --- a/src/main/java/forestry/api/farming/IFarmLogic.java +++ b/src/main/java/forestry/api/farming/IFarmLogic.java @@ -8,6 +8,7 @@ package forestry.api.farming; import java.util.Collection; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -25,7 +26,7 @@ public interface IFarmLogic { boolean isAcceptedGermling(ItemStack itemstack); - Collection collect(World world, IFarmHousing farmHousing); + NonNullList collect(World world, IFarmHousing farmHousing); boolean cultivate(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent); diff --git a/src/main/java/forestry/api/farming/package-info.java b/src/main/java/forestry/api/farming/package-info.java index 00a3edefb..68fab74ac 100644 --- a/src/main/java/forestry/api/farming/package-info.java +++ b/src/main/java/forestry/api/farming/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "2.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|farming") package forestry.api.farming; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/food/BeverageManager.java b/src/main/java/forestry/api/food/BeverageManager.java index 39ef247db..78fcd790b 100644 --- a/src/main/java/forestry/api/food/BeverageManager.java +++ b/src/main/java/forestry/api/food/BeverageManager.java @@ -6,7 +6,7 @@ package forestry.api.food; public class BeverageManager { - public static IBeverageEffect[] effectList = new IBeverageEffect[128]; + public static final IBeverageEffect[] effectList = new IBeverageEffect[128]; public static IInfuserManager infuserManager; public static IIngredientManager ingredientManager; diff --git a/src/main/java/forestry/api/food/IInfuserManager.java b/src/main/java/forestry/api/food/IInfuserManager.java index da843bb66..66f0579d8 100644 --- a/src/main/java/forestry/api/food/IInfuserManager.java +++ b/src/main/java/forestry/api/food/IInfuserManager.java @@ -6,19 +6,20 @@ package forestry.api.food; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public interface IInfuserManager { void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect); - void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect); + void addMixture(int meta, NonNullList ingredients, IBeverageEffect effect); - ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients); + ItemStack getSeasoned(ItemStack base, NonNullList ingredients); - boolean hasMixtures(ItemStack[] ingredients); + boolean hasMixtures(NonNullList ingredients); boolean isIngredient(ItemStack itemstack); - ItemStack[] getRequired(ItemStack[] ingredients); + NonNullList getRequired(NonNullList ingredients); } diff --git a/src/main/java/forestry/api/food/IIngredientManager.java b/src/main/java/forestry/api/food/IIngredientManager.java index 7331d6bdd..f1fd1ba2e 100644 --- a/src/main/java/forestry/api/food/IIngredientManager.java +++ b/src/main/java/forestry/api/food/IIngredientManager.java @@ -5,10 +5,13 @@ ******************************************************************************/ package forestry.api.food; +import javax.annotation.Nullable; + import net.minecraft.item.ItemStack; public interface IIngredientManager { + @Nullable String getDescription(ItemStack itemstack); void addIngredient(ItemStack ingredient, String description); diff --git a/src/main/java/forestry/api/food/package-info.java b/src/main/java/forestry/api/food/package-info.java index fbaab061f..3a83c56fe 100644 --- a/src/main/java/forestry/api/food/package-info.java +++ b/src/main/java/forestry/api/food/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "1.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|food") package forestry.api.food; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/fuels/MoistenerFuel.java b/src/main/java/forestry/api/fuels/MoistenerFuel.java index c691bd860..007d0f151 100644 --- a/src/main/java/forestry/api/fuels/MoistenerFuel.java +++ b/src/main/java/forestry/api/fuels/MoistenerFuel.java @@ -5,6 +5,7 @@ ******************************************************************************/ package forestry.api.fuels; +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; public class MoistenerFuel { @@ -14,6 +15,10 @@ public class MoistenerFuel { private final int stage; public MoistenerFuel(ItemStack item, ItemStack product, int stage, int moistenerValue) { + Preconditions.checkNotNull(item); + Preconditions.checkNotNull(product); + Preconditions.checkArgument(!item.isEmpty()); + Preconditions.checkArgument(!product.isEmpty()); this.item = item; this.product = product; this.stage = stage; diff --git a/src/main/java/forestry/api/fuels/package-info.java b/src/main/java/forestry/api/fuels/package-info.java index 39e4780a9..6d98b92a0 100644 --- a/src/main/java/forestry/api/fuels/package-info.java +++ b/src/main/java/forestry/api/fuels/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "3.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|fuels") package forestry.api.fuels; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/genetics/AlleleManager.java b/src/main/java/forestry/api/genetics/AlleleManager.java index 8a8f8366e..7fc3839a5 100644 --- a/src/main/java/forestry/api/genetics/AlleleManager.java +++ b/src/main/java/forestry/api/genetics/AlleleManager.java @@ -23,12 +23,12 @@ public class AlleleManager { /** * Translates plain leaf blocks into genetic data. Used by bees and butterflies to convert and pollinate foreign leaf blocks. */ - public static Map leafTranslators = new HashMap<>(); + public static final Map leafTranslators = new HashMap<>(); /** * Translates plain saplings into genetic data. Used by the treealyzer and the farm to convert foreign saplings. */ - public static Map saplingTranslation = new HashMap<>(); + public static final Map saplingTranslation = new HashMap<>(); /** * Queryable instance of an {@link IClimateHelper} for easier implementation. diff --git a/src/main/java/forestry/api/genetics/IAlleleEffect.java b/src/main/java/forestry/api/genetics/IAlleleEffect.java index 314d6a8d7..dfe7749ae 100644 --- a/src/main/java/forestry/api/genetics/IAlleleEffect.java +++ b/src/main/java/forestry/api/genetics/IAlleleEffect.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; +import javax.annotation.Nullable; + /** * Basic effect allele. */ diff --git a/src/main/java/forestry/api/genetics/IAllelePlantType.java b/src/main/java/forestry/api/genetics/IAllelePlantType.java deleted file mode 100644 index 0e18e95b4..000000000 --- a/src/main/java/forestry/api/genetics/IAllelePlantType.java +++ /dev/null @@ -1,16 +0,0 @@ -/******************************************************************************* - * Copyright 2011-2014 SirSengir - * - * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. - ******************************************************************************/ -package forestry.api.genetics; - -import java.util.EnumSet; - -import net.minecraftforge.common.EnumPlantType; - -public interface IAllelePlantType extends IAllele { - - EnumSet getPlantTypes(); - -} diff --git a/src/main/java/forestry/api/genetics/IAlleleProperty.java b/src/main/java/forestry/api/genetics/IAlleleProperty.java index c7ecc3941..bb1030ee0 100644 --- a/src/main/java/forestry/api/genetics/IAlleleProperty.java +++ b/src/main/java/forestry/api/genetics/IAlleleProperty.java @@ -1,13 +1,11 @@ package forestry.api.genetics; -import javax.annotation.Nonnull; - public interface IAlleleProperty> extends IAllele, Comparable { /** * To compare the allele for the properties */ @Override - int compareTo(@Nonnull A o); + int compareTo(A o); } diff --git a/src/main/java/forestry/api/genetics/IAlleleRegistry.java b/src/main/java/forestry/api/genetics/IAlleleRegistry.java index 7b249ec7e..7a2ca5957 100644 --- a/src/main/java/forestry/api/genetics/IAlleleRegistry.java +++ b/src/main/java/forestry/api/genetics/IAlleleRegistry.java @@ -5,6 +5,7 @@ ******************************************************************************/ package forestry.api.genetics; +import javax.annotation.Nullable; import java.util.Collection; import java.util.Map; @@ -39,6 +40,7 @@ public interface IAlleleRegistry { * @param uid Unique id for the species class, i.e. "rootBees", "rootTrees", "rootButterflies". * @return {@link ISpeciesRoot} if it exists, null otherwise. */ + @Nullable ISpeciesRoot getSpeciesRoot(String uid); /** @@ -46,6 +48,7 @@ public interface IAlleleRegistry { * @param stack An itemstack possibly containing NBT data which can be converted by a species root. * @return {@link ISpeciesRoot} if found, null otherwise. */ + @Nullable ISpeciesRoot getSpeciesRoot(ItemStack stack); /** @@ -53,8 +56,14 @@ public interface IAlleleRegistry { * @param clz Class extending {@link IIndividual}. * @return {@link ISpeciesRoot} if found, null otherwise. */ + @Nullable ISpeciesRoot getSpeciesRoot(Class clz); + /** + * Retrieve a matching {@link ISpeciesRoot} for the given {@link IIndividual} + */ + ISpeciesRoot getSpeciesRoot(IIndividual individual); + /* INDIVIDUAL */ /** @@ -72,6 +81,7 @@ public interface IAlleleRegistry { * Stack to retrieve genetic information for. * @return IIndividual containing genetic information, null if none could be extracted. */ + @Nullable IIndividual getIndividual(ItemStack stack); /* ALLELES */ diff --git a/src/main/java/forestry/api/genetics/IBreedingTracker.java b/src/main/java/forestry/api/genetics/IBreedingTracker.java index 13f67a70b..5dce75ee1 100644 --- a/src/main/java/forestry/api/genetics/IBreedingTracker.java +++ b/src/main/java/forestry/api/genetics/IBreedingTracker.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; +import javax.annotation.Nullable; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; @@ -20,6 +22,7 @@ public interface IBreedingTracker { /** * @return Name of the current {@link IBeekeepingMode}. */ + @Nullable String getModeName(); /** diff --git a/src/main/java/forestry/api/genetics/IClassification.java b/src/main/java/forestry/api/genetics/IClassification.java index b681537c2..d8fd97213 100644 --- a/src/main/java/forestry/api/genetics/IClassification.java +++ b/src/main/java/forestry/api/genetics/IClassification.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; +import javax.annotation.Nullable; + /** * Biological classifications from domain down to genus. * @@ -62,12 +64,12 @@ public interface IClassification { /** * A branch approximates a "genus" in real life. Real life examples: "Micrapis", "Megapis" * - * @return flavour text (may be null) + * @return flavour text */ String getScientific(); /** - * @return Localized description of this branch. (May be null.) + * @return Localized description of this branch. */ String getDescription(); @@ -96,12 +98,11 @@ public interface IClassification { /** * @return Parent classification, null if this is root. */ + @Nullable IClassification getParent(); /** * Only used internally by the AlleleRegistry if this classification has been added to another one. - * - * @param parent */ void setParent(IClassification parent); } diff --git a/src/main/java/forestry/api/genetics/IEffectData.java b/src/main/java/forestry/api/genetics/IEffectData.java index d8841dce1..9e3a3f003 100644 --- a/src/main/java/forestry/api/genetics/IEffectData.java +++ b/src/main/java/forestry/api/genetics/IEffectData.java @@ -16,13 +16,9 @@ import forestry.api.core.INbtWritable; public interface IEffectData extends INbtWritable, INbtReadable { void setInteger(int index, int val); - void setFloat(int index, float val); - void setBoolean(int index, boolean val); int getInteger(int index); - float getFloat(int index); - boolean getBoolean(int index); } diff --git a/src/main/java/forestry/api/genetics/IFlowerProvider.java b/src/main/java/forestry/api/genetics/IFlowerProvider.java index b50ace224..17e590318 100644 --- a/src/main/java/forestry/api/genetics/IFlowerProvider.java +++ b/src/main/java/forestry/api/genetics/IFlowerProvider.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; +import java.util.List; + import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -29,5 +31,5 @@ public interface IFlowerProvider { * If this flowerProvider does not affect the products, it should return the products unchanged. * @return Array of itemstacks being the (modified or unmodified) produce. */ - ItemStack[] affectProducts(World world, IIndividual individual, BlockPos pos, ItemStack[] products); + List affectProducts(World world, IIndividual individual, BlockPos pos, List products); } diff --git a/src/main/java/forestry/api/genetics/IFlowerRegistry.java b/src/main/java/forestry/api/genetics/IFlowerRegistry.java index 974aace92..a4b7f8b25 100644 --- a/src/main/java/forestry/api/genetics/IFlowerRegistry.java +++ b/src/main/java/forestry/api/genetics/IFlowerRegistry.java @@ -5,17 +5,15 @@ ******************************************************************************/ package forestry.api.genetics; -import javax.annotation.Nonnull; import java.util.List; +import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeHousing; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.api.apiculture.IBee; -import forestry.api.apiculture.IBeeHousing; - // See {@link forestry.api.apiculture.FlowerManager}.FlowerType___ for basic Forestry flower types. // Each IFlowerProvider has one flower type, and multiple IFlowerProviders may share one type. // "Acceptable flowers" allow nearby bees to do work. @@ -43,6 +41,7 @@ public interface IFlowerRegistry { * Registers custom logic for accepted flowers. * These rules are inefficient compared to ones made with registerAcceptableFlower, but may be necessary for tile entity flowers. * The flower types built into Forestry can not be used here. + * * @since Forestry 4.0.8 */ void registerAcceptableFlowerRule(IFlowerAcceptableRule flowerAcceptableRule, String... flowerTypes); @@ -51,7 +50,7 @@ public interface IFlowerRegistry { * Registers a plantable flower. * The distribution is based on its own weight and the total number of plants for this flowerType. * - * @param weight Weight for the Flower (Vanilla = 1.0, Modded flowers < 1.0) + * @param weight Weight for the Flower (Vanilla = 1.0, Modded flowers < 1.0) * @param flowerTypes See {@link forestry.api.apiculture.FlowerManager}.FlowerTypeXXX */ void registerPlantableFlower(IBlockState blockState, double weight, String... flowerTypes); @@ -63,12 +62,11 @@ public interface IFlowerRegistry { /** * @param beeHousing The bee housing that will help determine the size of the area to check. - * @param bee The bee that will help determine the size of the area to check. + * @param bee The bee that will help determine the size of the area to check. * @param flowerType See {@link forestry.api.apiculture.FlowerManager}.FlowerTypeXXX * @param maxFlowers the largest number of flowers to check for before returning. Use 1 if you only need 1. * @return the coordinates of nearby accepted flowers, with size from 0 to maxFlowers. */ - @Nonnull List getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType, int maxFlowers); /** diff --git a/src/main/java/forestry/api/genetics/IFruitBearer.java b/src/main/java/forestry/api/genetics/IFruitBearer.java index 61df0e2c3..dc1062b52 100644 --- a/src/main/java/forestry/api/genetics/IFruitBearer.java +++ b/src/main/java/forestry/api/genetics/IFruitBearer.java @@ -5,9 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; -import java.util.Collection; - import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; /** * Can be implemented by tile entities which can bear fruit. @@ -30,10 +29,10 @@ public interface IFruitBearer { * Picks the fruits of this tile, resetting it to unripe fruits. * * @param tool - * Tool used in picking the fruits. May be null. + * Tool used in picking the fruits. May be empty. * @return Picked fruits. */ - Collection pickFruit(ItemStack tool); + NonNullList pickFruit(ItemStack tool); /** * @return float indicating the ripeness of the fruit with >= 1.0f indicating full ripeness. diff --git a/src/main/java/forestry/api/genetics/IGenome.java b/src/main/java/forestry/api/genetics/IGenome.java index a74bad3ac..156fe2d7e 100644 --- a/src/main/java/forestry/api/genetics/IGenome.java +++ b/src/main/java/forestry/api/genetics/IGenome.java @@ -5,34 +5,26 @@ ******************************************************************************/ package forestry.api.genetics; -import javax.annotation.Nonnull; - import forestry.api.core.INbtWritable; /** * Holds the {@link IChromosome}s which comprise the traits of a given individual. - * + *

* Only the default implementation is supported. */ public interface IGenome extends INbtWritable { - @Nonnull IAlleleSpecies getPrimary(); - @Nonnull IAlleleSpecies getSecondary(); - @Nonnull IChromosome[] getChromosomes(); - @Nonnull IAllele getActiveAllele(IChromosomeType chromosomeType); - @Nonnull IAllele getInactiveAllele(IChromosomeType chromosomeType); boolean isGeneticEqual(IGenome other); - @Nonnull ISpeciesRoot getSpeciesRoot(); } diff --git a/src/main/java/forestry/api/genetics/IIndividual.java b/src/main/java/forestry/api/genetics/IIndividual.java index 0e473f157..e470860dd 100644 --- a/src/main/java/forestry/api/genetics/IIndividual.java +++ b/src/main/java/forestry/api/genetics/IIndividual.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.genetics; -import javax.annotation.Nonnull; import java.util.List; import forestry.api.core.INbtWritable; @@ -35,7 +34,6 @@ public interface IIndividual extends INbtWritable { boolean isSecret(); - @Nonnull IGenome getGenome(); /** diff --git a/src/main/java/forestry/api/genetics/IIndividualLiving.java b/src/main/java/forestry/api/genetics/IIndividualLiving.java index a1f8c7598..e90737630 100644 --- a/src/main/java/forestry/api/genetics/IIndividualLiving.java +++ b/src/main/java/forestry/api/genetics/IIndividualLiving.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.genetics; +import javax.annotation.Nullable; + import net.minecraft.world.World; public interface IIndividualLiving extends IIndividual { @@ -12,6 +14,7 @@ public interface IIndividualLiving extends IIndividual { /** * @return Genetic information of the mate, null if unmated. */ + @Nullable IGenome getMate(); /** diff --git a/src/main/java/forestry/api/genetics/ISpeciesRoot.java b/src/main/java/forestry/api/genetics/ISpeciesRoot.java index 9b3caea73..bc694c1bc 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesRoot.java +++ b/src/main/java/forestry/api/genetics/ISpeciesRoot.java @@ -6,7 +6,6 @@ package forestry.api.genetics; import javax.annotation.Nullable; -import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -39,6 +38,7 @@ public interface ISpeciesRoot { /** * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class. + * * @param stack itemstack to check. * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. */ @@ -46,14 +46,16 @@ public interface ISpeciesRoot { /** * Used to check whether a given itemstack contains genetic data corresponding to an {@link IIndividual} of this class and matches the given type. + * * @param stack itemstack to check. - * @param type Integer denoting the type needed to match. (i.e. butterfly vs. butterfly serum; bee queens, princesses, drones; etc.) + * @param type Integer denoting the type needed to match. (i.e. butterfly vs. butterfly serum; bee queens, princesses, drones; etc.) * @return true if the itemstack contains an {@link IIndividual} of this class, false otherwise. */ boolean isMember(ItemStack stack, ISpeciesType type); /** * Used to check whether the given {@link IIndividual} is member of this class. + * * @param individual {@link IIndividual} to check. * @return true if the individual is member of this class, false otherwise. */ @@ -66,13 +68,15 @@ public interface ISpeciesRoot { @Nullable ISpeciesType getType(ItemStack itemStack); - /** Species type used to represent this species in icons */ + /** + * Species type used to represent this species in icons + */ ISpeciesType getIconType(); ItemStack getMemberStack(IIndividual individual, ISpeciesType type); /* BREEDING TRACKER */ - IBreedingTracker getBreedingTracker(World world, GameProfile player); + IBreedingTracker getBreedingTracker(World world, @Nullable GameProfile player); /* GENOME MANIPULATION */ IIndividual templateAsIndividual(IAllele[] template); @@ -109,6 +113,7 @@ public interface ISpeciesRoot { * @param identifier species UID * @return Array of {@link IAllele} representing a genome. */ + @Nullable IAllele[] getTemplate(String identifier); /** @@ -124,7 +129,7 @@ public interface ISpeciesRoot { Map getGenomeTemplates(); - ArrayList getIndividualTemplates(); + List getIndividualTemplates(); /* MUTATIONS */ @@ -147,8 +152,8 @@ public interface ISpeciesRoot { List getCombinations(IAllele other); /** - * @since Forestry 3.7 * @return all possible mutations that result from breeding two species + * @since Forestry 3.7 */ List getCombinations(IAlleleSpecies parentSpecies0, IAlleleSpecies parentSpecies1, boolean shuffle); @@ -163,7 +168,8 @@ public interface ISpeciesRoot { /** * Sets an item stack as a valid (generic) research catalyst for this class. - * @param itemstack ItemStack to set as suitable. + * + * @param itemstack ItemStack to set as suitable. * @param suitability Float between 0 and 1 to indicate suitability. */ void setResearchSuitability(ItemStack itemstack, float suitability); diff --git a/src/main/java/forestry/api/genetics/ISpeciesRootPollinatable.java b/src/main/java/forestry/api/genetics/ISpeciesRootPollinatable.java index 368517582..76cecc295 100644 --- a/src/main/java/forestry/api/genetics/ISpeciesRootPollinatable.java +++ b/src/main/java/forestry/api/genetics/ISpeciesRootPollinatable.java @@ -1,5 +1,7 @@ package forestry.api.genetics; +import javax.annotation.Nullable; + import com.mojang.authlib.GameProfile; import net.minecraft.util.math.BlockPos; @@ -12,7 +14,8 @@ import net.minecraft.world.World; public interface ISpeciesRootPollinatable extends ISpeciesRoot { ICheckPollinatable createPollinatable(IIndividual individual); - - IPollinatable tryConvertToPollinatable(GameProfile owner, World world, final BlockPos pos, final IIndividual pollen); + + @Nullable + IPollinatable tryConvertToPollinatable(@Nullable GameProfile owner, World world, final BlockPos pos, final IIndividual pollen); } diff --git a/src/main/java/forestry/api/genetics/package-info.java b/src/main/java/forestry/api/genetics/package-info.java index 58ecf21d7..845f5a609 100644 --- a/src/main/java/forestry/api/genetics/package-info.java +++ b/src/main/java/forestry/api/genetics/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "4.7.1", owner = "ForestryAPI|core", provides = "ForestryAPI|genetics") package forestry.api.genetics; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/greenhouse/GreenhouseEvents.java b/src/main/java/forestry/api/greenhouse/GreenhouseEvents.java index 390e83261..4bbeb8e63 100644 --- a/src/main/java/forestry/api/greenhouse/GreenhouseEvents.java +++ b/src/main/java/forestry/api/greenhouse/GreenhouseEvents.java @@ -5,71 +5,64 @@ ******************************************************************************/ package forestry.api.greenhouse; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraftforge.fml.common.eventhandler.Event; - import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflagedTile; import forestry.api.multiblock.IGreenhouseController; +import net.minecraftforge.fml.common.eventhandler.Event; public class GreenhouseEvents extends Event { - + @Nullable public final IGreenhouseController controller; - + public GreenhouseEvents(@Nullable IGreenhouseController state) { this.controller = state; } - - public static class CamouflageChangeEvent extends GreenhouseEvents{ + + public static class CamouflageChangeEvent extends GreenhouseEvents { @Nullable - public ICamouflagedTile camouflagedBlock; - @Nonnull - public ICamouflageHandler camouflageHandler; - @Nonnull + public final ICamouflagedTile camouflagedBlock; + + public final ICamouflageHandler camouflageHandler; + public final String camouflageType; - - public CamouflageChangeEvent(IGreenhouseController controller, @Nullable ICamouflagedTile camouflagedBlock, @Nonnull ICamouflageHandler camouflageHandler, @Nonnull String camouflageType) { + + public CamouflageChangeEvent(IGreenhouseController controller, @Nullable ICamouflagedTile camouflagedBlock, ICamouflageHandler camouflageHandler, String camouflageType) { super(controller); - + this.camouflagedBlock = camouflagedBlock; this.camouflageHandler = camouflageHandler; this.camouflageType = camouflageType; } } - - public static class InternalBlockEvent extends GreenhouseEvents{ - @Nonnull - public IInternalBlock internalBlock; - - public InternalBlockEvent(IGreenhouseController controller, @Nonnull IInternalBlock internalBlock) { + public static class InternalBlockEvent extends GreenhouseEvents { + public final IInternalBlock internalBlock; + + public InternalBlockEvent(IGreenhouseController controller, IInternalBlock internalBlock) { super(controller); - - this.internalBlock = internalBlock; - } - } - - public static class CreateInternalBlockEvent extends InternalBlockEvent{ + this.internalBlock = internalBlock; + } + } + + public static class CreateInternalBlockEvent extends InternalBlockEvent { public CreateInternalBlockEvent(IGreenhouseController controller, IInternalBlock internalBlock) { super(controller, internalBlock); } } - - public static class CheckInternalBlockFaceEvent extends InternalBlockEvent{ - @Nonnull + public static class CheckInternalBlockFaceEvent extends InternalBlockEvent { public final IInternalBlockFace face; - - public CheckInternalBlockFaceEvent(IGreenhouseController controller, IInternalBlock internalBlock, @Nonnull IInternalBlockFace face) { + + public CheckInternalBlockFaceEvent(IGreenhouseController controller, IInternalBlock internalBlock, IInternalBlockFace face) { super(controller, internalBlock); - + this.face = face; } } - + } diff --git a/src/main/java/forestry/api/greenhouse/IGreenhouseHelper.java b/src/main/java/forestry/api/greenhouse/IGreenhouseHelper.java index d83cdbcd0..3ee9eb4ff 100644 --- a/src/main/java/forestry/api/greenhouse/IGreenhouseHelper.java +++ b/src/main/java/forestry/api/greenhouse/IGreenhouseHelper.java @@ -5,6 +5,7 @@ ******************************************************************************/ package forestry.api.greenhouse; +import javax.annotation.Nullable; import java.util.List; import forestry.api.multiblock.IGreenhouseController; @@ -16,6 +17,7 @@ public interface IGreenhouseHelper { /** * @return A {@link IGreenhouseController} of a greenhouse, when the pos is a greenhouse */ + @Nullable IGreenhouseController getGreenhouseController(World world, BlockPos pos); void addGreenhouseLogic(Class logic); diff --git a/src/main/java/forestry/api/greenhouse/IInternalBlock.java b/src/main/java/forestry/api/greenhouse/IInternalBlock.java index 1adf10009..b2dfdea62 100644 --- a/src/main/java/forestry/api/greenhouse/IInternalBlock.java +++ b/src/main/java/forestry/api/greenhouse/IInternalBlock.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.greenhouse; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; @@ -13,14 +12,12 @@ import java.util.Collection; import net.minecraft.util.math.BlockPos; public interface IInternalBlock { - - @Nonnull + BlockPos getPos(); @Nullable IInternalBlock getRoot(); - - @Nonnull + Collection getFaces(); } diff --git a/src/main/java/forestry/api/greenhouse/IInternalBlockFace.java b/src/main/java/forestry/api/greenhouse/IInternalBlockFace.java index 2845b18aa..5878b4995 100644 --- a/src/main/java/forestry/api/greenhouse/IInternalBlockFace.java +++ b/src/main/java/forestry/api/greenhouse/IInternalBlockFace.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.greenhouse; -import javax.annotation.Nonnull; - import net.minecraft.util.math.BlockPos; import net.minecraft.util.EnumFacing; @@ -15,11 +13,9 @@ public interface IInternalBlockFace { boolean isTested(); void setTested(boolean tested); - - @Nonnull + EnumFacing getFace(); - - @Nonnull + BlockPos getPos(); } diff --git a/src/main/java/forestry/api/greenhouse/package-info.java b/src/main/java/forestry/api/greenhouse/package-info.java index 5a7854a19..277b4b76c 100644 --- a/src/main/java/forestry/api/greenhouse/package-info.java +++ b/src/main/java/forestry/api/greenhouse/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "5.2.0", owner = "ForestryAPI|core", provides = "ForestryAPI|greenhouse") package forestry.api.greenhouse; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java b/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java index 7939ab472..145f5da72 100644 --- a/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java +++ b/src/main/java/forestry/api/lepidopterology/EnumButterflyChromosome.java @@ -72,15 +72,15 @@ public enum EnumButterflyChromosome implements IChromosomeType { COCOON(IAlleleButterflyCocoon.class); - Class clss; + private final Class alleleClass; - EnumButterflyChromosome(Class clss) { - this.clss = clss; + EnumButterflyChromosome(Class alleleClass) { + this.alleleClass = alleleClass; } @Override public Class getAlleleClass() { - return clss; + return alleleClass; } @Override diff --git a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java index b4765a054..504e281cd 100644 --- a/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java +++ b/src/main/java/forestry/api/lepidopterology/IAlleleButterflySpecies.java @@ -5,19 +5,17 @@ ******************************************************************************/ package forestry.api.lepidopterology; -import java.util.EnumSet; import java.util.Map; +import java.util.Set; +import forestry.api.genetics.IAlleleSpecies; import net.minecraft.item.ItemStack; - import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.genetics.IAlleleSpecies; - public interface IAlleleButterflySpecies extends IAlleleSpecies { - + /** * @return the IBeeRoot */ @@ -28,46 +26,46 @@ public interface IAlleleButterflySpecies extends IAlleleSpecies { * @return Path of the texture to use for entity rendering. */ String getEntityTexture(); - + /** * @return Path of the texture to use for item model. */ String getItemTexture(); - + /** * Allows butterflies to restrict random spawns beyond the restrictions set by getTemperature() and getHumidity(). * * @return EnumSet of biome tags this butterfly species can be spawned in. */ - EnumSet getSpawnBiomes(); - + Set getSpawnBiomes(); + /** * @return true if a prospective spawn biome must not match a biome tag outside of getSpawnBiomes. */ boolean strictSpawnMatch(); - + /** * @return Float between 0 and 1 representing the rarity of the species, will affect spawn rate. */ float getRarity(); - + /** * @return Float representing the distance below which this butterfly will take flight if it detects a player which is not sneaking. */ float getFlightDistance(); - + /** * @return true if this species is only active at night. */ boolean isNocturnal(); - + Map getButterflyLoot(); - + Map getCaterpillarLoot(); - + @SideOnly(Side.CLIENT) void registerSprites(); - + /** * @return The modid from the mod of the species. */ diff --git a/src/main/java/forestry/api/lepidopterology/IButterfly.java b/src/main/java/forestry/api/lepidopterology/IButterfly.java index cce055e83..6f03633f1 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterfly.java +++ b/src/main/java/forestry/api/lepidopterology/IButterfly.java @@ -5,16 +5,15 @@ ******************************************************************************/ package forestry.api.lepidopterology; -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; +import javax.annotation.Nullable; import forestry.api.genetics.IIndividualLiving; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; public interface IButterfly extends IIndividualLiving { - @Nonnull @Override IButterflyGenome getGenome(); @@ -28,7 +27,7 @@ public interface IButterfly extends IIndividualLiving { * @return Physical size of the butterfly. */ float getSize(); - + /** * @param world * @param x @@ -60,30 +59,31 @@ public interface IButterfly extends IIndividualLiving { * @param world * @return create a caterpillar with the two genome's from the nursery. */ + @Nullable IButterfly spawnCaterpillar(World world, IButterflyNursery nursery); - + /** * @param entity * @param playerKill Whether or not the butterfly was killed by a player. - * @param lootLevel Loot level according to the weapon used to kill the butterfly. + * @param lootLevel Loot level according to the weapon used to kill the butterfly. * @return Array of itemstacks to drop on death of the given entity. */ - ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel); + NonNullList getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel); /** * @param nursery * @param playerKill Whether or not the nursery was broken by a player. - * @param lootLevel Fortune level. + * @param lootLevel Fortune level. * @return Array of itemstacks to drop on breaking of the nursery. */ - ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel); - + NonNullList getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel); + /** * @param cocoon * @return Array of itemstacks to drop on breaking of the cocoon. */ - ItemStack[] getCocoonDrop(IButterflyCocoon cocoon); - + NonNullList getCocoonDrop(IButterflyCocoon cocoon); + /** * Create an exact copy of this butterfly. */ diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyCocoon.java b/src/main/java/forestry/api/lepidopterology/IButterflyCocoon.java index 170eb786b..c6f1731e3 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyCocoon.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyCocoon.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.api.lepidopterology; +import javax.annotation.Nullable; + import forestry.api.genetics.IHousing; public interface IButterflyCocoon extends IHousing{ @@ -17,7 +19,8 @@ public interface IButterflyCocoon extends IHousing{ IButterfly getCaterpillar(); void setCaterpillar(IButterfly butterfly); - + + @Nullable IButterflyNursery getNursery(); void setNursery(IButterflyNursery nursery); diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java b/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java index 03c4e75ac..5d29db942 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyGenome.java @@ -5,20 +5,16 @@ ******************************************************************************/ package forestry.api.lepidopterology; -import javax.annotation.Nonnull; - import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IFlowerProvider; import forestry.api.genetics.IGenome; public interface IButterflyGenome extends IGenome { - + @Override - @Nonnull IAlleleButterflySpecies getPrimary(); @Override - @Nonnull IAlleleButterflySpecies getSecondary(); float getSize(); @@ -26,7 +22,7 @@ public interface IButterflyGenome extends IGenome { int getLifespan(); int getMetabolism(); - + int getFertility(); float getSpeed(); @@ -44,7 +40,7 @@ public interface IButterflyGenome extends IGenome { IFlowerProvider getFlowerProvider(); IAlleleButterflyEffect getEffect(); - + IAlleleButterflyCocoon getCocoon(); } diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java b/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java index eb956030e..2a03c3b9b 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyNursery.java @@ -5,17 +5,19 @@ ******************************************************************************/ package forestry.api.lepidopterology; +import javax.annotation.Nullable; + import forestry.api.climate.IClimateProvider; import forestry.api.genetics.IHousing; import forestry.api.genetics.IIndividual; public interface IButterflyNursery extends IHousing, IClimateProvider { - + @Nullable IButterfly getCaterpillar(); IIndividual getNanny(); - void setCaterpillar(IButterfly butterfly); + void setCaterpillar(@Nullable IButterfly butterfly); boolean canNurse(IButterfly butterfly); diff --git a/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java b/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java index c0aff0bdb..d6a73355c 100644 --- a/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java +++ b/src/main/java/forestry/api/lepidopterology/IButterflyRoot.java @@ -6,7 +6,6 @@ package forestry.api.lepidopterology; import javax.annotation.Nullable; -import java.util.ArrayList; import java.util.List; import com.mojang.authlib.GameProfile; @@ -43,15 +42,16 @@ public interface IButterflyRoot extends ISpeciesRoot { /* BUTTERFLY SPECIFIC */ @Override - ILepidopteristTracker getBreedingTracker(World world, GameProfile player); + ILepidopteristTracker getBreedingTracker(World world, @Nullable GameProfile player); /** * Spawns the given butterfly in the world. + * * @param butterfly * @return butterfly entity on success, null otherwise. */ EntityLiving spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z); - + boolean plantCocoon(World world, IButterflyNursery nursery, GameProfile owner, int age); /** @@ -61,7 +61,7 @@ public interface IButterflyRoot extends ISpeciesRoot { /* TEMPLATES */ @Override - ArrayList getIndividualTemplates(); + List getIndividualTemplates(); /* MUTATIONS */ @Override diff --git a/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java b/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java index 7716170f0..328cc584d 100644 --- a/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java +++ b/src/main/java/forestry/api/lepidopterology/IEntityButterfly.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.lepidopterology; +import javax.annotation.Nullable; + import net.minecraft.entity.EntityCreature; import net.minecraft.entity.passive.IAnimals; @@ -23,9 +25,10 @@ public interface IEntityButterfly extends IAnimals { */ EntityCreature getEntity(); + @Nullable IIndividual getPollen(); - void setPollen(IIndividual pollen); + void setPollen(@Nullable IIndividual pollen); boolean canMateWith(IEntityButterfly butterfly); diff --git a/src/main/java/forestry/api/lepidopterology/package-info.java b/src/main/java/forestry/api/lepidopterology/package-info.java index ad9aef2e9..4610d9a33 100644 --- a/src/main/java/forestry/api/lepidopterology/package-info.java +++ b/src/main/java/forestry/api/lepidopterology/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "1.3.0", owner = "ForestryAPI|core", provides = "ForestryAPI|lepidopterology") package forestry.api.lepidopterology; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/mail/EnumAddressee.java b/src/main/java/forestry/api/mail/EnumAddressee.java index 7b4482d36..7327e4465 100644 --- a/src/main/java/forestry/api/mail/EnumAddressee.java +++ b/src/main/java/forestry/api/mail/EnumAddressee.java @@ -5,11 +5,13 @@ ******************************************************************************/ package forestry.api.mail; +import javax.annotation.Nullable; import java.util.Locale; public enum EnumAddressee { PLAYER, TRADER; - + + @Nullable public static EnumAddressee fromString(String ident) { ident = ident.toLowerCase(Locale.ENGLISH); for (EnumAddressee addr : values()) { diff --git a/src/main/java/forestry/api/mail/EnumTradeStationState.java b/src/main/java/forestry/api/mail/EnumTradeStationState.java index 609a20bf3..139d762b6 100644 --- a/src/main/java/forestry/api/mail/EnumTradeStationState.java +++ b/src/main/java/forestry/api/mail/EnumTradeStationState.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.mail; -import javax.annotation.Nonnull; - import net.minecraft.util.text.translation.I18n; public enum EnumTradeStationState implements IPostalState { @@ -19,7 +17,7 @@ public enum EnumTradeStationState implements IPostalState { private final String unlocalizedDescription; - EnumTradeStationState(@Nonnull String unlocalizedDescription) { + EnumTradeStationState(String unlocalizedDescription) { this.unlocalizedDescription = unlocalizedDescription; } diff --git a/src/main/java/forestry/api/mail/ILetter.java b/src/main/java/forestry/api/mail/ILetter.java index 661ebb5ae..016143927 100644 --- a/src/main/java/forestry/api/mail/ILetter.java +++ b/src/main/java/forestry/api/mail/ILetter.java @@ -5,16 +5,18 @@ ******************************************************************************/ package forestry.api.mail; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import forestry.api.core.INbtWritable; +import net.minecraft.util.NonNullList; public interface ILetter extends IInventory, INbtWritable { - ItemStack[] getPostage(); + NonNullList getPostage(); void setProcessed(boolean flag); @@ -28,9 +30,10 @@ public interface ILetter extends IInventory, INbtWritable { boolean hasRecipient(); - void setRecipient(IMailAddress address); + void setRecipient(@Nullable IMailAddress address); - IMailAddress[] getRecipients(); + @Nullable + IMailAddress getRecipient(); String getRecipientString(); @@ -46,11 +49,11 @@ public interface ILetter extends IInventory, INbtWritable { void invalidatePostage(); - ItemStack[] getAttachments(); + NonNullList getAttachments(); void addAttachment(ItemStack itemstack); - void addAttachments(ItemStack[] itemstacks); + void addAttachments(NonNullList itemstacks); int countAttachments(); diff --git a/src/main/java/forestry/api/mail/IMailAddress.java b/src/main/java/forestry/api/mail/IMailAddress.java index 956245ca6..5733d97c3 100644 --- a/src/main/java/forestry/api/mail/IMailAddress.java +++ b/src/main/java/forestry/api/mail/IMailAddress.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.mail; +import javax.annotation.Nullable; + import com.mojang.authlib.GameProfile; import forestry.api.core.INbtWritable; @@ -17,5 +19,6 @@ public interface IMailAddress extends INbtWritable { boolean isValid(); + @Nullable GameProfile getPlayerProfile(); } diff --git a/src/main/java/forestry/api/mail/IPostOffice.java b/src/main/java/forestry/api/mail/IPostOffice.java index b97a0715b..298bec0c2 100644 --- a/src/main/java/forestry/api/mail/IPostOffice.java +++ b/src/main/java/forestry/api/mail/IPostOffice.java @@ -8,11 +8,12 @@ package forestry.api.mail; import java.util.Map; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.world.World; public interface IPostOffice { - void collectPostage(ItemStack[] stamps); + void collectPostage(NonNullList stamps); IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge); diff --git a/src/main/java/forestry/api/mail/IPostRegistry.java b/src/main/java/forestry/api/mail/IPostRegistry.java index a5561d25c..15bd4af18 100644 --- a/src/main/java/forestry/api/mail/IPostRegistry.java +++ b/src/main/java/forestry/api/mail/IPostRegistry.java @@ -5,30 +5,29 @@ ******************************************************************************/ package forestry.api.mail; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Map; +import com.mojang.authlib.GameProfile; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import com.mojang.authlib.GameProfile; - public interface IPostRegistry { /* POST OFFICE */ IPostOffice getPostOffice(World world); /* MAIL ADDRESSES */ - @Nonnull - IMailAddress getMailAddress(@Nonnull GameProfile gameProfile); - - IMailAddress getMailAddress(@Nonnull String traderName); + IMailAddress getMailAddress(GameProfile gameProfile); + + IMailAddress getMailAddress(String traderName); /* LETTERS */ boolean isLetter(ItemStack itemstack); ILetter createLetter(IMailAddress sender, IMailAddress recipient); + @Nullable ILetter getLetter(ItemStack itemstack); ItemStack createLetterStack(ILetter letter); @@ -37,10 +36,12 @@ public interface IPostRegistry { /** * Registers a new {@link IPostalCarrier}. See {@link IPostalCarrier} for details. + * * @param carrier {@link IPostalCarrier} to register. */ void registerCarrier(IPostalCarrier carrier); + @Nullable IPostalCarrier getCarrier(EnumAddressee uid); Map getRegisteredCarriers(); @@ -50,6 +51,7 @@ public interface IPostRegistry { ITradeStation getOrCreateTradeStation(World world, GameProfile owner, IMailAddress address); + @Nullable ITradeStation getTradeStation(World world, IMailAddress address); boolean isAvailableTradeAddress(World world, IMailAddress address); diff --git a/src/main/java/forestry/api/mail/ITradeStationInfo.java b/src/main/java/forestry/api/mail/ITradeStationInfo.java index cc0597cef..905acfb39 100644 --- a/src/main/java/forestry/api/mail/ITradeStationInfo.java +++ b/src/main/java/forestry/api/mail/ITradeStationInfo.java @@ -8,6 +8,7 @@ package forestry.api.mail; import net.minecraft.item.ItemStack; import com.mojang.authlib.GameProfile; +import net.minecraft.util.NonNullList; public interface ITradeStationInfo { IMailAddress getAddress(); @@ -16,7 +17,7 @@ public interface ITradeStationInfo { ItemStack getTradegood(); - ItemStack[] getRequired(); + NonNullList getRequired(); EnumTradeStationState getState(); } diff --git a/src/main/java/forestry/api/mail/package-info.java b/src/main/java/forestry/api/mail/package-info.java index e191eccbb..6e927a554 100644 --- a/src/main/java/forestry/api/mail/package-info.java +++ b/src/main/java/forestry/api/mail/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "3.1.0", owner = "ForestryAPI|core", provides = "ForestryAPI|mail") package forestry.api.mail; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/multiblock/ICharcoalPileComponent.java b/src/main/java/forestry/api/multiblock/ICharcoalPileComponent.java index 0f0ab76c3..f85d7cc3e 100644 --- a/src/main/java/forestry/api/multiblock/ICharcoalPileComponent.java +++ b/src/main/java/forestry/api/multiblock/ICharcoalPileComponent.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.multiblock; -import javax.annotation.Nonnull; - import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.EnumPileType; import forestry.api.arboriculture.IAlleleTreeSpecies; @@ -19,22 +17,21 @@ import net.minecraftforge.fml.relauncher.SideOnly; * They are automatically detected and handled by the charcoal pile when they join its structure. */ public interface ICharcoalPileComponent extends IMultiblockComponent { - + @Override T getMultiblockLogic(); IAlleleTreeSpecies getTreeSpecies(); - void setTreeSpecies(@Nonnull IAlleleTreeSpecies treeSpecies); - + void setTreeSpecies(IAlleleTreeSpecies treeSpecies); + @Override - @Nonnull GameProfile getOwner(); - - void setOwner(@Nonnull GameProfile owner); - + + void setOwner(GameProfile owner); + EnumPileType getPileType(); - + @SideOnly(Side.CLIENT) IAlleleTreeSpecies getNextWoodPile(); diff --git a/src/main/java/forestry/api/multiblock/IGreenhouseComponent.java b/src/main/java/forestry/api/multiblock/IGreenhouseComponent.java index ae61c7997..cb55e69b3 100644 --- a/src/main/java/forestry/api/multiblock/IGreenhouseComponent.java +++ b/src/main/java/forestry/api/multiblock/IGreenhouseComponent.java @@ -12,6 +12,7 @@ import forestry.api.climate.IClimatiserDefinition; import forestry.api.greenhouse.IGreenhouseListener; import forestry.api.lepidopterology.IButterflyCocoon; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public interface IGreenhouseComponent extends IMultiblockComponent { @Override @@ -35,7 +36,7 @@ public interface IGreenhouseComponent exte } interface ButterflyHatch extends IGreenhouseComponent { - ItemStack[] addCocoonLoot(IButterflyCocoon cocoon); + NonNullList addCocoonLoot(IButterflyCocoon cocoon); } interface Active extends IGreenhouseComponent { diff --git a/src/main/java/forestry/api/multiblock/IGreenhouseController.java b/src/main/java/forestry/api/multiblock/IGreenhouseController.java index 1a9bba142..bc00e2de0 100644 --- a/src/main/java/forestry/api/multiblock/IGreenhouseController.java +++ b/src/main/java/forestry/api/multiblock/IGreenhouseController.java @@ -7,7 +7,6 @@ package forestry.api.multiblock; import java.util.List; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.api.climate.IClimateControl; @@ -34,7 +33,6 @@ public interface IGreenhouseController extends IMultiblockController, IGreenhous IClimateRegion getRegion(); @Override - @Nonnull IClimateControl getClimateControl(); } diff --git a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java index 42388c04c..d5744ee15 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockComponent.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockComponent.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.multiblock; +import javax.annotation.Nullable; + import net.minecraft.util.math.BlockPos; import com.mojang.authlib.GameProfile; @@ -24,6 +26,7 @@ public interface IMultiblockComponent { /** * @return the gameProfile of the player who owns this single component (not the entire multiblock) */ + @Nullable GameProfile getOwner(); /** diff --git a/src/main/java/forestry/api/multiblock/IMultiblockController.java b/src/main/java/forestry/api/multiblock/IMultiblockController.java index f9e86bdd8..0b1d08a69 100644 --- a/src/main/java/forestry/api/multiblock/IMultiblockController.java +++ b/src/main/java/forestry/api/multiblock/IMultiblockController.java @@ -5,7 +5,7 @@ ******************************************************************************/ package forestry.api.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collection; /** @@ -31,11 +31,11 @@ public interface IMultiblockController { * @return A string representing the last error encountered when trying to assemble this * multiblock, or null if there is no error. */ + @Nullable String getLastValidationError(); /** * @return all the multiblock components attached to this controller */ - @Nonnull Collection getComponents(); } diff --git a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java index baa2a15c3..9df5cc248 100644 --- a/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java +++ b/src/main/java/forestry/api/multiblock/MultiblockTileEntityBase.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.multiblock; -import javax.annotation.Nonnull; - import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; @@ -46,8 +44,7 @@ public abstract class MultiblockTileEntityBase exten super.readFromNBT(data); multiblockLogic.readFromNBT(data); } - - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { data = super.writeToNBT(data); @@ -58,30 +55,28 @@ public abstract class MultiblockTileEntityBase exten @Override public final void invalidate() { super.invalidate(); - multiblockLogic.invalidate(worldObj, this); + multiblockLogic.invalidate(world, this); } @Override public final void onChunkUnload() { super.onChunkUnload(); - multiblockLogic.onChunkUnload(worldObj, this); + multiblockLogic.onChunkUnload(world, this); } @Override public final void validate() { super.validate(); - multiblockLogic.validate(worldObj, this); + multiblockLogic.validate(world, this); } /* Network Communication */ - @Nonnull @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag()); } - @Nonnull @Override public NBTTagCompound getUpdateTag() { NBTTagCompound updateTag = super.getUpdateTag(); @@ -99,7 +94,7 @@ public abstract class MultiblockTileEntityBase exten } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); multiblockLogic.decodeDescriptionPacket(tag); this.decodeDescriptionPacket(tag); diff --git a/src/main/java/forestry/api/multiblock/package-info.java b/src/main/java/forestry/api/multiblock/package-info.java index d13db8ce3..d0cce41fb 100644 --- a/src/main/java/forestry/api/multiblock/package-info.java +++ b/src/main/java/forestry/api/multiblock/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "3.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|multiblock") package forestry.api.multiblock; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/recipes/ICarpenterManager.java b/src/main/java/forestry/api/recipes/ICarpenterManager.java index accc0c199..62a22de91 100644 --- a/src/main/java/forestry/api/recipes/ICarpenterManager.java +++ b/src/main/java/forestry/api/recipes/ICarpenterManager.java @@ -5,6 +5,8 @@ ******************************************************************************/ package forestry.api.recipes; +import javax.annotation.Nullable; + import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.ShapedRecipes; @@ -41,7 +43,7 @@ public interface ICarpenterManager extends ICraftingProvider { * @param packagingTime * Number of work cycles required to craft the recipe once. * @param box - * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. + * ItemStack of one item representing the required box (carton, crate) for this recipe. May be empty. * @param product * Crafting result. * @param materials @@ -57,11 +59,11 @@ public interface ICarpenterManager extends ICraftingProvider { * @param liquid * Liquid required in carpenter's tank. * @param box - * ItemStack of one item representing the required box (carton, crate) for this recipe. May be null. + * ItemStack of one item representing the required box (carton, crate) for this recipe. May be empty. * @param product * Crafting result. * @param materials * Materials needed in the crafting matrix. This gets passed directly to {@link ShapedRecipes}. Notation is the same. */ - void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials); + void addRecipe(int packagingTime, @Nullable FluidStack liquid, ItemStack box, ItemStack product, Object... materials); } diff --git a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java index 12a465ee6..ba7558670 100644 --- a/src/main/java/forestry/api/recipes/ICarpenterRecipe.java +++ b/src/main/java/forestry/api/recipes/ICarpenterRecipe.java @@ -23,10 +23,9 @@ public interface ICarpenterRecipe extends IForestryRecipe { IDescriptiveRecipe getCraftingGridRecipe(); /** - * @return the box required for this recipe. return null if there is no required box. + * @return the box required for this recipe. return empty stack if there is no required box. * Examples of boxes are the Forestry cartons and crates. */ - @Nullable ItemStack getBox(); /** diff --git a/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java b/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java index 4fc8753ac..9054e8c9a 100644 --- a/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java +++ b/src/main/java/forestry/api/recipes/IDescriptiveRecipe.java @@ -5,17 +5,15 @@ ******************************************************************************/ package forestry.api.recipes; -import javax.annotation.Nonnull; - import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.NonNullList; /** - * Extension of IRecipe to give better access to the expected crafting inputs. + * Replacement for IRecipe to give better access to the expected crafting inputs. * It can be matched against regular IInventory instead of just InventoryCrafting. * Useful for displaying crafting recipes. */ -public interface IDescriptiveRecipe extends IRecipe { +public interface IDescriptiveRecipe { /** * @return width of the crafting ingredients in the crafting table @@ -31,9 +29,7 @@ public interface IDescriptiveRecipe extends IRecipe { * @return array of all the ingredients in the crafting table. * Ingredients may be null, ItemStack, ItemStack[], or a List of ItemStack */ - Object[] getIngredients(); + NonNullList> getIngredients(); - @Nonnull - @Override ItemStack getRecipeOutput(); } diff --git a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java index d8bacaf80..7153d7541 100644 --- a/src/main/java/forestry/api/recipes/IFabricatorRecipe.java +++ b/src/main/java/forestry/api/recipes/IFabricatorRecipe.java @@ -5,10 +5,9 @@ ******************************************************************************/ package forestry.api.recipes; -import javax.annotation.Nullable; - import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; public interface IFabricatorRecipe extends IForestryRecipe { @@ -21,7 +20,7 @@ public interface IFabricatorRecipe extends IForestryRecipe { /** * @return the list of ingredients in the crafting grid to create this recipe. */ - Object[] getIngredients(); + NonNullList> getIngredients(); /** * @return the width of ingredients in the crafting grid to create this recipe. @@ -34,9 +33,8 @@ public interface IFabricatorRecipe extends IForestryRecipe { int getHeight(); /** - * @return the plan for this recipe (the item in the top right slot). + * @return the plan for this recipe (the item in the top right slot). may be an empty ItemStack */ - @Nullable ItemStack getPlan(); /** diff --git a/src/main/java/forestry/api/recipes/ISqueezerManager.java b/src/main/java/forestry/api/recipes/ISqueezerManager.java index 0635c4dff..c2fdff64a 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerManager.java +++ b/src/main/java/forestry/api/recipes/ISqueezerManager.java @@ -5,10 +5,9 @@ ******************************************************************************/ package forestry.api.recipes; -import javax.annotation.Nullable; - import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; /** @@ -29,10 +28,21 @@ public interface ISqueezerManager extends ICraftingProvider { * @param timePerItem Number of work cycles required to squeeze one set of resources. * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. * @param liquid {@link FluidStack} representing the output of this recipe. - * @param remnants Item stack representing the possible remnants from this recipe. + * @param remnants Item stack representing the possible remnants from this recipe. May be empty. * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 100. */ - void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance); + void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid, ItemStack remnants, int chance); + + /** + * Add a recipe to the squeezer. + * + * @param timePerItem Number of work cycles required to squeeze one set of resources. + * @param resources item stack representing the required resources for one process. Stack size will be taken into account. + * @param liquid {@link FluidStack} representing the output of this recipe. + * @param remnants Item stack representing the possible remnants from this recipe. May be empty. + * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 100. + */ + void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid, ItemStack remnants, int chance); /** * Add a recipe to the squeezer. @@ -41,7 +51,16 @@ public interface ISqueezerManager extends ICraftingProvider { * @param resources Array of item stacks representing the required resources for one process. Stack size will be taken into account. * @param liquid {@link FluidStack} representing the output of this recipe. */ - void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid); + void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid); + + /** + * Add a recipe to the squeezer. + * + * @param timePerItem Number of work cycles required to squeeze one set of resources. + * @param resources item stack representing the required resources for one process. Stack size will be taken into account. + * @param liquid {@link FluidStack} representing the output of this recipe. + */ + void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid); /** * Add a recipe for a fluid container to the squeezer. @@ -49,8 +68,8 @@ public interface ISqueezerManager extends ICraftingProvider { * * @param timePerItem Number of work cycles required to squeeze one set of resources. * @param emptyContainer The empty version of the fluid container that will be squeezed. - * @param remnants Item stack representing the possible remnants from this recipe. + * @param remnants Item stack representing the possible remnants from this recipe. May be empty. * @param chance Chance remnants will be produced by a single recipe cycle, from 0 to 1. */ - void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance); + void addContainerRecipe(int timePerItem, ItemStack emptyContainer, ItemStack remnants, float chance); } diff --git a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java index 820dc56b2..4cc23e9db 100644 --- a/src/main/java/forestry/api/recipes/ISqueezerRecipe.java +++ b/src/main/java/forestry/api/recipes/ISqueezerRecipe.java @@ -5,10 +5,9 @@ ******************************************************************************/ package forestry.api.recipes; -import javax.annotation.Nullable; - import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; public interface ISqueezerRecipe extends IForestryRecipe { @@ -16,7 +15,7 @@ public interface ISqueezerRecipe extends IForestryRecipe { /** * @return Array of item stacks representing the required resources for one process. Stack size will be taken into account. */ - ItemStack[] getResources(); + NonNullList getResources(); /** * @return Number of work cycles required to squeeze one set of resources. @@ -26,7 +25,6 @@ public interface ISqueezerRecipe extends IForestryRecipe { /** * @return Item stack representing the possible remnants from this recipe. (i.e. tin left over from tin cans) */ - @Nullable ItemStack getRemnants(); /** diff --git a/src/main/java/forestry/api/recipes/package-info.java b/src/main/java/forestry/api/recipes/package-info.java index 9e4ec065c..33d4ca245 100644 --- a/src/main/java/forestry/api/recipes/package-info.java +++ b/src/main/java/forestry/api/recipes/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "5.4.0", owner = "ForestryAPI|core", provides = "ForestryAPI|recipes") package forestry.api.recipes; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/storage/BackpackEvent.java b/src/main/java/forestry/api/storage/BackpackEvent.java index b7d4719d6..9bbe05b35 100644 --- a/src/main/java/forestry/api/storage/BackpackEvent.java +++ b/src/main/java/forestry/api/storage/BackpackEvent.java @@ -10,7 +10,6 @@ import net.minecraft.inventory.IInventory; import net.minecraftforge.fml.common.eventhandler.Event; - public abstract class BackpackEvent extends Event { public final EntityPlayer player; diff --git a/src/main/java/forestry/api/storage/IBackpackDefinition.java b/src/main/java/forestry/api/storage/IBackpackDefinition.java index 5bb2a6fa0..526451f7a 100644 --- a/src/main/java/forestry/api/storage/IBackpackDefinition.java +++ b/src/main/java/forestry/api/storage/IBackpackDefinition.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.storage; -import javax.annotation.Nonnull; import java.util.function.Predicate; import net.minecraft.item.ItemStack; @@ -18,7 +17,6 @@ public interface IBackpackDefinition { /** * @return Human-readable name of the backpack. */ - @Nonnull String getName(ItemStack backpack); /** @@ -41,6 +39,5 @@ public interface IBackpackDefinition { * * @return the backpack's item filter. */ - @Nonnull Predicate getFilter(); } diff --git a/src/main/java/forestry/api/storage/IBackpackInterface.java b/src/main/java/forestry/api/storage/IBackpackInterface.java index 1e4234661..3683b90e8 100644 --- a/src/main/java/forestry/api/storage/IBackpackInterface.java +++ b/src/main/java/forestry/api/storage/IBackpackInterface.java @@ -5,7 +5,6 @@ ******************************************************************************/ package forestry.api.storage; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Predicate; @@ -38,18 +37,18 @@ public interface IBackpackInterface { * @param itemStack The itemStack that the backpack should accept. * {@link OreDictionary#WILDCARD_VALUE} can be used for meta value. */ - void addItemToForestryBackpack(@Nonnull String backpackUid, @Nonnull ItemStack itemStack); + void addItemToForestryBackpack(String backpackUid, ItemStack itemStack); /** * Register a backpack definition with a given uid. */ - void registerBackpackDefinition(@Nonnull String backpackUid, @Nonnull IBackpackDefinition definition); + void registerBackpackDefinition(String backpackUid, IBackpackDefinition definition); /** * Get a backpack definition with a given uid. */ @Nullable - IBackpackDefinition getBackpackDefinition(@Nonnull String backpackUid); + IBackpackDefinition getBackpackDefinition(String backpackUid); /** * Creates a backpack with the given UID and type, returning the item. @@ -59,8 +58,7 @@ public interface IBackpackInterface { * @param type Type of backpack. * @return Created backpack item. */ - @Nonnull - Item createBackpack(@Nonnull String backpackUid, @Nonnull EnumBackpackType type); + Item createBackpack(String backpackUid, EnumBackpackType type); /** * Create a backpack that can hold items from a specific {@link ISpeciesRoot}. @@ -70,7 +68,7 @@ public interface IBackpackInterface { * @param speciesRoot The species root. * @return Created backpack item. */ - Item createNaturalistBackpack(@Nonnull String backpackUid, @Nonnull ISpeciesRoot speciesRoot); + Item createNaturalistBackpack(String backpackUid, ISpeciesRoot speciesRoot); /** * Makes a new configurable backpack filter. Useful for implementing {@link IBackpackDefinition}. diff --git a/src/main/java/forestry/api/storage/ICrateRegistry.java b/src/main/java/forestry/api/storage/ICrateRegistry.java index dd0240850..5aa2f479c 100644 --- a/src/main/java/forestry/api/storage/ICrateRegistry.java +++ b/src/main/java/forestry/api/storage/ICrateRegistry.java @@ -5,8 +5,6 @@ ******************************************************************************/ package forestry.api.storage; -import javax.annotation.Nonnull; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -16,17 +14,17 @@ import net.minecraft.item.ItemStack; * and creates crating and uncrating recipes for the Carpenter. * The icon is rendered automatically from the contained item. * If an oreDictName is specified, it will make recipes using that. - * + *

* Can only be called during the Init stage. */ public interface ICrateRegistry { - void registerCrate(@Nonnull Item item); + void registerCrate(Item item); - void registerCrate(@Nonnull Block block); + void registerCrate(Block block); - void registerCrate(@Nonnull ItemStack stack); + void registerCrate(ItemStack stack); - void registerCrate(@Nonnull String oreDictName); + void registerCrate(String oreDictName); } diff --git a/src/main/java/forestry/api/storage/package-info.java b/src/main/java/forestry/api/storage/package-info.java index 1dbd576ac..016e2a1e0 100644 --- a/src/main/java/forestry/api/storage/package-info.java +++ b/src/main/java/forestry/api/storage/package-info.java @@ -3,7 +3,12 @@ * * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details. ******************************************************************************/ +@ParametersAreNonnullByDefault +@MethodsReturnNonnullByDefault @API(apiVersion = "5.0.0", owner = "ForestryAPI|core", provides = "ForestryAPI|storage") package forestry.api.storage; +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; import net.minecraftforge.fml.common.API; diff --git a/src/main/java/forestry/api/world/ITreeGenData.java b/src/main/java/forestry/api/world/ITreeGenData.java index b5fec434c..da73cd3fe 100644 --- a/src/main/java/forestry/api/world/ITreeGenData.java +++ b/src/main/java/forestry/api/world/ITreeGenData.java @@ -29,7 +29,7 @@ public interface ITreeGenData { @Nullable BlockPos canGrow(World world, BlockPos pos, int expectedGirth, int expectedHeight); - boolean setLeaves(World world, GameProfile owner, BlockPos pos); + boolean setLeaves(World world, @Nullable GameProfile owner, BlockPos pos); boolean setLogBlock(World world, BlockPos pos, EnumFacing facing); diff --git a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java b/src/main/java/forestry/apiculture/ArmorApiaristHelper.java index e5238813b..60e4cbf19 100644 --- a/src/main/java/forestry/apiculture/ArmorApiaristHelper.java +++ b/src/main/java/forestry/apiculture/ArmorApiaristHelper.java @@ -35,7 +35,7 @@ public class ArmorApiaristHelper implements IArmorApiaristHelper { return false; } - return armorApiarist.protectEntity(entity, stack, cause, doProtect); + return armorApiarist != null && armorApiarist.protectEntity(entity, stack, cause, doProtect); } @Override diff --git a/src/main/java/forestry/apiculture/BeekeepingLogic.java b/src/main/java/forestry/apiculture/BeekeepingLogic.java old mode 100755 new mode 100644 index 410cce86b..c130e872d --- a/src/main/java/forestry/apiculture/BeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/BeekeepingLogic.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; @@ -20,20 +19,12 @@ import java.util.List; import java.util.Set; import java.util.Stack; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - +import com.google.common.base.Preconditions; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IApiaristTracker; import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -47,11 +38,18 @@ import forestry.apiculture.network.packets.PacketBeeLogicActive; import forestry.apiculture.network.packets.PacketBeeLogicActiveEntity; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.proxy.Proxies; import forestry.core.utils.Log; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { @@ -65,6 +63,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { private int beeProgressMax; private int queenWorkCycleThrottle; + @Nullable private IEffectData effectData[] = new IEffectData[2]; private final Stack spawn = new Stack<>(); @@ -75,8 +74,9 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { // Client private boolean active; + @Nullable private IBee queen; - private ItemStack queenStack; // used to detect server changes and sync clientQueen + private ItemStack queenStack = ItemStack.EMPTY; // used to detect server changes and sync clientQueen public BeekeepingLogic(IBeeHousing housing) { this.housing = housing; @@ -91,7 +91,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { queenWorkCycleThrottle = nbttagcompound.getInteger("Throttle"); NBTTagCompound queenNBT = nbttagcompound.getCompoundTag("queen"); - queenStack = ItemStack.loadItemStackFromNBT(queenNBT); + queenStack = new ItemStack(queenNBT); queen = BeeManager.beeRoot.getMember(queenStack); setActive(nbttagcompound.getBoolean("Active")); @@ -100,7 +100,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { NBTTagList nbttaglist = nbttagcompound.getTagList("Offspring", 10); for (int i = 0; i < nbttaglist.tagCount(); i++) { - spawn.add(ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i))); + spawn.add(new ItemStack(nbttaglist.getCompoundTagAt(i))); } } @@ -109,7 +109,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { nbttagcompound.setInteger("BreedingTime", beeProgress); nbttagcompound.setInteger("Throttle", queenWorkCycleThrottle); - if (queenStack != null) { + if (!queenStack.isEmpty()) { NBTTagCompound queenNBT = new NBTTagCompound(); queenStack.writeToNBT(queenNBT); nbttagcompound.setTag("queen", queenNBT); @@ -132,7 +132,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeBoolean(active); if (active) { data.writeItemStack(queenStack); @@ -141,7 +141,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { boolean active = data.readBoolean(); setActive(active); if (active) { @@ -190,14 +190,18 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { IBee dyingQueen = BeeManager.beeRoot.getMember(queenStack); Collection spawned = killQueen(dyingQueen, housing, beeListener); spawn.addAll(spawned); - queenStack = null; + queenStack = ItemStack.EMPTY; } } else { - queenStack = null; + queenStack = ItemStack.EMPTY; } if (this.queenStack != queenStack) { - this.queen = BeeManager.beeRoot.getMember(queenStack); + if (!queenStack.isEmpty()) { + this.queen = BeeManager.beeRoot.getMember(queenStack); + } else { + this.queen = null; + } this.queenStack = queenStack; hasFlowersCache.clear(); queenCanWorkCache.clear(); @@ -248,7 +252,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { } } - private void queenWorkTick(@Nullable IBee queen, @Nonnull ItemStack queenStack) { + private void queenWorkTick(@Nullable IBee queen, ItemStack queenStack) { if (queen == null) { beeProgress = 0; beeProgressMax = 0; @@ -268,7 +272,9 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { pollenHandler.doPollination(queen, housing, beeListener); // Age the queen - float lifespanModifier = beeModifier.getLifespanModifier(queen.getGenome(), queen.getMate(), 1.0f); + IBeeGenome mate = queen.getMate(); + Preconditions.checkState(mate != null); + float lifespanModifier = beeModifier.getLifespanModifier(queen.getGenome(), mate, 1.0f); queen.age(housing.getWorldObj(), lifespanModifier); // Write the changed queen back into the item stack. @@ -284,10 +290,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { private static void doProduction(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { // Produce and add stacks - ItemStack[] products = queen.produceStacks(beeHousing); - if (products == null) { - return; - } + List products = queen.produceStacks(beeHousing); beeListener.wearOutEquipment(1); IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); @@ -313,9 +316,11 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { return housingHasSpace; } - /** Checks if a queen is alive. Much faster than reading the whole bee nbt */ + /** + * Checks if a queen is alive. Much faster than reading the whole bee nbt + */ private static boolean isQueenAlive(ItemStack queenStack) { - if (queenStack == null) { + if (queenStack.isEmpty()) { return false; } NBTTagCompound nbtTagCompound = queenStack.getTagCompound(); @@ -365,10 +370,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { BeeManager.beeRoot.getBreedingTracker(housing.getWorldObj(), housing.getOwner()).registerQueen(princess); // Remove drone - beeInventory.getDrone().stackSize--; - if (beeInventory.getDrone().stackSize <= 0) { - beeInventory.setDrone(null); - } + beeInventory.getDrone().shrink(1); // Reset breeding time queen = princess; @@ -377,10 +379,6 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { } private static Collection killQueen(IBee queen, IBeeHousing beeHousing, IBeeListener beeListener) { - if (queen == null) { - return Collections.emptySet(); - } - IBeeHousingInventory beeInventory = beeHousing.getBeeInventory(); Collection spawn; @@ -388,8 +386,8 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { if (queen.canSpawn()) { spawn = spawnOffspring(queen, beeHousing); beeListener.onQueenDeath(); - beeInventory.getQueen().stackSize = 0; - beeInventory.setQueen(null); + beeInventory.getQueen().setCount(0); + beeInventory.setQueen(ItemStack.EMPTY); } else { Log.warning("Tried to spawn offspring off an unmated queen. Devolving her to a princess."); @@ -399,7 +397,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { convert.setTagCompound(nbttagcompound); spawn = Collections.singleton(convert); - beeInventory.setQueen(null); + beeInventory.setQueen(ItemStack.EMPTY); } return spawn; @@ -457,9 +455,10 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { World world = housing.getWorldObj(); if (world != null && !world.isRemote) { if (housing instanceof Entity) { - Proxies.net.sendNetworkPacket(new PacketBeeLogicActiveEntity(housing, (Entity) housing), world); + Entity housingEntity = (Entity) this.housing; + Proxies.net.sendNetworkPacket(new PacketBeeLogicActiveEntity(this.housing, housingEntity), housingEntity.getPosition(), world); } else { - Proxies.net.sendNetworkPacket(new PacketBeeLogicActive(housing), world); + Proxies.net.sendNetworkPacket(new PacketBeeLogicActive(housing), housing.getCoordinates(), world); } } } @@ -501,7 +500,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { } @Override - @Nonnull + public List getFlowerPositions() { return hasFlowersCache.getFlowerCoords(); } @@ -532,6 +531,7 @@ public class BeekeepingLogic implements IBeekeepingLogic, IStreamable { private static class PollenHandler { private static final int MAX_POLLINATION_ATTEMPTS = 20; + @Nullable private IIndividual pollen; private int attemptedPollinations = 0; diff --git a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java index b72108893..d08ff5a19 100644 --- a/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java +++ b/src/main/java/forestry/apiculture/FakeBeekeepingLogic.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.apiculture; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; +import forestry.api.apiculture.IBeekeepingLogic; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; -import forestry.api.apiculture.IBeekeepingLogic; - public class FakeBeekeepingLogic implements IBeekeepingLogic { public static final FakeBeekeepingLogic instance = new FakeBeekeepingLogic(); @@ -67,7 +65,6 @@ public class FakeBeekeepingLogic implements IBeekeepingLogic { } - @Nonnull @Override public List getFlowerPositions() { return Collections.emptyList(); diff --git a/src/main/java/forestry/apiculture/HasFlowersCache.java b/src/main/java/forestry/apiculture/HasFlowersCache.java index 21ebc9d38..c08013ad7 100644 --- a/src/main/java/forestry/apiculture/HasFlowersCache.java +++ b/src/main/java/forestry/apiculture/HasFlowersCache.java @@ -10,18 +10,12 @@ ******************************************************************************/ package forestry.apiculture; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.FlowerManager; import forestry.api.apiculture.IBee; @@ -30,10 +24,13 @@ import forestry.api.apiculture.IBeeModifier; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.api.genetics.IFlowerProvider; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.utils.VectUtil; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3i; +import net.minecraft.world.World; public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable { private static final String nbtKey = "hasFlowerCache"; @@ -44,7 +41,6 @@ public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable private static final int flowerCheckInterval = 128; private final int flowerCheckTime = random.nextInt(flowerCheckInterval); - @Nonnull private List flowerCoords = new ArrayList<>(); private int cooldown = 0; @@ -102,7 +98,7 @@ public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable cooldown = 0; } - @Nonnull + public List getFlowerCoords() { return Collections.unmodifiableList(flowerCoords); } @@ -128,7 +124,7 @@ public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable if (hasFlowerCacheNBT.hasKey(nbtKeyFlowers)) { int[] flowersList = hasFlowerCacheNBT.getIntArray(nbtKeyFlowers); - if (flowersList != null && flowersList.length % 3 == 0) { + if (flowersList.length % 3 == 0) { int flowerCount = flowersList.length / 3; for (int i = 0; i < flowerCount; i++) { BlockPos flowerPos = new BlockPos(flowersList[i], flowersList[i + 1], flowersList[i + 2]); @@ -165,7 +161,7 @@ public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { int size = flowerCoords.size(); data.writeVarInt(size); if (size > 0) { @@ -178,7 +174,7 @@ public class HasFlowersCache implements INbtWritable, INbtReadable, IStreamable } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { flowerCoords.clear(); int size = data.readVarInt(); diff --git a/src/main/java/forestry/apiculture/InventoryBeeHousing.java b/src/main/java/forestry/apiculture/InventoryBeeHousing.java index 203e7af1b..1060249de 100644 --- a/src/main/java/forestry/apiculture/InventoryBeeHousing.java +++ b/src/main/java/forestry/apiculture/InventoryBeeHousing.java @@ -10,15 +10,14 @@ ******************************************************************************/ package forestry.apiculture; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IBeeHousingInventory; import forestry.core.inventory.InventoryAdapterRestricted; import forestry.core.utils.InventoryUtil; import forestry.core.utils.SlotUtil; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryBeeHousing extends InventoryAdapterRestricted implements IBeeHousingInventory { public static final int SLOT_QUEEN = 0; diff --git a/src/main/java/forestry/apiculture/PluginApiculture.java b/src/main/java/forestry/apiculture/PluginApiculture.java index eca89ee46..f7f0e2c4e 100644 --- a/src/main/java/forestry/apiculture/PluginApiculture.java +++ b/src/main/java/forestry/apiculture/PluginApiculture.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture; +import javax.annotation.Nullable; import java.io.File; import java.util.ArrayList; import java.util.List; @@ -17,6 +18,7 @@ import java.util.Objects; import java.util.Random; import java.util.Set; +import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import forestry.Forestry; import forestry.api.apiculture.BeeManager; @@ -50,7 +52,7 @@ import forestry.apiculture.genetics.BeeRoot; import forestry.apiculture.genetics.BeekeepingMode; import forestry.apiculture.genetics.HiveDrop; import forestry.apiculture.genetics.JubilanceFactory; -import forestry.apiculture.genetics.alleles.AlleleEffect; +import forestry.apiculture.genetics.alleles.AlleleEffects; import forestry.apiculture.items.EnumHoneyComb; import forestry.apiculture.items.EnumPollenCluster; import forestry.apiculture.items.EnumPropolis; @@ -81,6 +83,8 @@ import forestry.core.config.LocalizedConfiguration; import forestry.core.entities.ParticleSnow; import forestry.core.fluids.Fluids; import forestry.core.items.EnumElectronTube; +import forestry.core.items.ItemRegistryCore; +import forestry.core.items.ItemRegistryFluids; import forestry.core.network.IPacketRegistry; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.EntityUtil; @@ -95,11 +99,11 @@ import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; import net.minecraft.block.BlockFlower; import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -124,6 +128,7 @@ import net.minecraftforge.fml.relauncher.SideOnly; @ForestryPlugin(pluginID = ForestryPluginUids.APICULTURE, name = "Apiculture", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.apiculture.description") public class PluginApiculture extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.apiculture.proxy.ProxyApicultureClient", serverSide = "forestry.apiculture.proxy.ProxyApiculture") public static ProxyApiculture proxy; private static final String CONFIG_CATEGORY = "apiculture"; @@ -131,11 +136,13 @@ public class PluginApiculture extends BlankForestryPlugin { private static float secondPrincessChance = 0; public static final int ticksPerBeeWorkCycle = 550; + @Nullable public static ItemRegistryApiculture items; + @Nullable public static BlockRegistryApiculture blocks; - + @Nullable public static HiveRegistry hiveRegistry; - + @Nullable public static VillagerRegistry.VillagerProfession villagerApiarist; @Override @@ -237,6 +244,14 @@ public class PluginApiculture extends BlankForestryPlugin { createHives(); registerBeehiveDrops(); + if (items == null) { + throw new IllegalStateException("Items have not been created"); + } + + if (blocks == null) { + throw new IllegalArgumentException("Blocks have not been created"); + } + // Inducers for swarmer BeeManager.inducers.put(items.royalJelly.getItemStack(), 10); @@ -250,8 +265,10 @@ public class PluginApiculture extends BlankForestryPlugin { GameRegistry.registerTileEntity(TileAlvearySieve.class, "forestry.AlvearySieve"); GameRegistry.registerTileEntity(TileCandle.class, "forestry.Candle"); - EntityUtil.registerEntity(EntityMinecartBeehouse.class, "cart.beehouse", 1, 0x000000, 0xffffff, 256, 3, true); - EntityUtil.registerEntity(EntityMinecartApiary.class, "cart.apiary", 2, 0x000000, 0xffffff, 256, 3, true); + ResourceLocation beeHouseCartResource = new ResourceLocation(Constants.MOD_ID, "cart.beehouse"); + EntityUtil.registerEntity(beeHouseCartResource, EntityMinecartBeehouse.class, "cart.beehouse", 1, 0x000000, 0xffffff, 256, 3, true); + ResourceLocation apiaryCartResource = new ResourceLocation(Constants.MOD_ID, "cart.apiary"); + EntityUtil.registerEntity(apiaryCartResource, EntityMinecartApiary.class, "cart.apiary", 2, 0x000000, 0xffffff, 256, 3, true); BeeManager.commonVillageBees.add(BeeDefinition.FOREST.getGenome()); BeeManager.commonVillageBees.add(BeeDefinition.MEADOWS.getGenome()); @@ -279,13 +296,13 @@ public class PluginApiculture extends BlankForestryPlugin { ItemStack provenFrames = items.frameProven.getItemStack(); ItemStack monasticDrone = BeeDefinition.MONASTIC.getMemberStack(EnumBeeType.DRONE); ItemStack endDrone = BeeDefinition.ENDED.getMemberStack(EnumBeeType.DRONE); - ItemStack propolis = new ItemStack(PluginApiculture.items.propolis,1); + ItemStack propolis = new ItemStack(items.propolis, 1); VillagerRegistry.VillagerCareer apiaristCareer = new VillagerRegistry.VillagerCareer(villagerApiarist, "apiarist"); apiaristCareer.addTrade(1, - new VillagerApiaristTrades.GiveRandomCombsForItems(new ItemStack(Items.WHEAT), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)), - new VillagerApiaristTrades.GiveRandomCombsForItems(new ItemStack(Items.CARROT), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)), - new VillagerApiaristTrades.GiveRandomCombsForItems(new ItemStack(Items.POTATO), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)) + new VillagerApiaristTrades.GiveRandomCombsForItems(items.beeComb, new ItemStack(Items.WHEAT), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)), + new VillagerApiaristTrades.GiveRandomCombsForItems(items.beeComb, new ItemStack(Items.CARROT), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)), + new VillagerApiaristTrades.GiveRandomCombsForItems(items.beeComb, new ItemStack(Items.POTATO), new EntityVillager.PriceInfo(8, 12), new EntityVillager.PriceInfo(2, 4)) ); apiaristCareer.addTrade(2, new VillagerTradeLists.GiveItemForEmeralds(new EntityVillager.PriceInfo(1, 4), new ItemStack(items.smoker), null), @@ -298,7 +315,7 @@ public class PluginApiculture extends BlankForestryPlugin { ); apiaristCareer.addTrade(4, new VillagerTradeLists.GiveItemForItemAndEmerald(wildcardPrincess, null, new EntityVillager.PriceInfo(10, 64), monasticDrone, null), - new VillagerTradeLists.GiveItemForTwoItems(wildcardPrincess, null,new ItemStack(Items.ENDER_EYE),new EntityVillager.PriceInfo(12, 16),endDrone, null) + new VillagerTradeLists.GiveItemForTwoItems(wildcardPrincess, null, new ItemStack(Items.ENDER_EYE), new EntityVillager.PriceInfo(12, 16), endDrone, null) ); } @@ -358,8 +375,13 @@ public class PluginApiculture extends BlankForestryPlugin { @Override public void registerCrates() { + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); + Preconditions.checkState(items != null); + Preconditions.checkState(blocks != null); + ICrateRegistry crateRegistry = StorageManager.crateRegistry; - crateRegistry.registerCrate(PluginCore.items.beeswax.getItemStack()); + crateRegistry.registerCrate(coreItems.beeswax.getItemStack()); crateRegistry.registerCrate(items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); crateRegistry.registerCrate(items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1)); crateRegistry.registerCrate(items.propolis.getItemStack()); @@ -380,14 +402,21 @@ public class PluginApiculture extends BlankForestryPlugin { crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MOSSY, 1)); crateRegistry.registerCrate(items.beeComb.get(EnumHoneyComb.MELLOW, 1)); - crateRegistry.registerCrate(PluginCore.items.refractoryWax.getItemStack()); + crateRegistry.registerCrate(coreItems.refractoryWax.getItemStack()); } @Override public void registerRecipes() { + ItemRegistryCore coreItems = PluginCore.items; + ItemRegistryFluids fluidItems = PluginFluids.items; + Preconditions.checkState(coreItems != null); + Preconditions.checkState(fluidItems != null); + Preconditions.checkState(items != null); + Preconditions.checkState(blocks != null); // / APIARIST'S ARMOR - ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); + + ItemStack wovenSilk = coreItems.craftingMaterial.getWovenSilk(); RecipeUtil.addRecipe(items.apiaristHat, "###", "# #", '#', wovenSilk); @@ -433,7 +462,7 @@ public class PluginApiculture extends BlankForestryPlugin { 'S', Items.STRING); RecipeUtil.addRecipe(items.frameImpregnated, "###", "#S#", "###", - '#', PluginCore.items.stickImpregnated, + '#', coreItems.stickImpregnated, 'S', Items.STRING); RecipeUtil.addRecipe(items.minecartBeehouse.getBeeHouseMinecart(), "B", @@ -457,41 +486,41 @@ public class PluginApiculture extends BlankForestryPlugin { RecipeUtil.addRecipe(foodItems.honeyPot, "# #", " X ", "# #", '#', items.honeyDrop, - 'X', PluginFluids.items.waxCapsuleEmpty); + 'X', fluidItems.waxCapsuleEmpty); RecipeUtil.addRecipe(foodItems.ambrosia, "#Y#", "XXX", "###", '#', items.honeydew, 'X', items.royalJelly, - 'Y', PluginFluids.items.waxCapsuleEmpty); + 'Y', fluidItems.waxCapsuleEmpty); } // / CAPSULES int outputCapsuleAmount = ForestryAPI.activeMode.getIntegerSetting("recipe.output.capsule"); if (outputCapsuleAmount > 0) { - ItemStack capsule = PluginFluids.items.waxCapsuleEmpty.getItemStack(outputCapsuleAmount); - RecipeUtil.addRecipe(capsule, "###", '#', PluginCore.items.beeswax); + ItemStack capsule = fluidItems.waxCapsuleEmpty.getItemStack(outputCapsuleAmount); + RecipeUtil.addRecipe(capsule, "###", '#', coreItems.beeswax); } int outputRefractoryAmount = ForestryAPI.activeMode.getIntegerSetting("recipe.output.refractory"); if (outputRefractoryAmount > 0) { - ItemStack capsule = PluginFluids.items.refractoryEmpty.getItemStack(outputRefractoryAmount); - RecipeUtil.addRecipe(capsule, "###", '#', PluginCore.items.refractoryWax); + ItemStack capsule = fluidItems.refractoryEmpty.getItemStack(outputRefractoryAmount); + RecipeUtil.addRecipe(capsule, "###", '#', coreItems.refractoryWax); } // / BITUMINOUS PEAT - RecipeUtil.addRecipe(PluginCore.items.bituminousPeat.getItemStack(), + RecipeUtil.addRecipe(coreItems.bituminousPeat.getItemStack(), " # ", "XYX", " # ", '#', OreDictUtil.DUST_ASH, - 'X', PluginCore.items.peat, + 'X', coreItems.peat, 'Y', items.propolis); // / TORCHES RecipeUtil.addRecipe(new ItemStack(Blocks.TORCH, 3), " # ", " # ", " Y ", - '#', PluginCore.items.beeswax, + '#', coreItems.beeswax, 'Y', OreDictUtil.STICK_WOOD); - RecipeUtil.addRecipe(PluginCore.items.craftingMaterial.getPulsatingMesh(), + RecipeUtil.addRecipe(coreItems.craftingMaterial.getPulsatingMesh(), "# #", " # ", "# #", '#', items.propolis.get(EnumPropolis.PULSATING, 1)); @@ -500,7 +529,7 @@ public class PluginApiculture extends BlankForestryPlugin { "###", "# #", "###", - '#', PluginCore.items.beeswax); + '#', coreItems.beeswax); // / ALVEARY ItemStack alvearyPlainBlock = blocks.getAlvearyBlock(BlockAlvearyType.PLAIN); @@ -508,14 +537,14 @@ public class PluginApiculture extends BlankForestryPlugin { "###", "#X#", "###", - 'X', PluginCore.items.impregnatedCasing, - '#', PluginCore.items.craftingMaterial.getScentedPaneling()); + 'X', coreItems.impregnatedCasing, + '#', coreItems.craftingMaterial.getScentedPaneling()); // SWARMER RecipeUtil.addRecipe(blocks.getAlvearyBlock(BlockAlvearyType.SWARMER), "#G#", " X ", "#G#", - '#', PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), + '#', coreItems.tubes.get(EnumElectronTube.DIAMOND, 1), 'X', alvearyPlainBlock, 'G', OreDictUtil.INGOT_GOLD); // FAN @@ -523,7 +552,7 @@ public class PluginApiculture extends BlankForestryPlugin { "I I", " X ", "I#I", - '#', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + '#', coreItems.tubes.get(EnumElectronTube.GOLD, 1), 'X', alvearyPlainBlock, 'I', OreDictUtil.INGOT_IRON); // HEATER @@ -531,7 +560,7 @@ public class PluginApiculture extends BlankForestryPlugin { "#I#", " X ", "YYY", - '#', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + '#', coreItems.tubes.get(EnumElectronTube.GOLD, 1), 'X', alvearyPlainBlock, 'I', OreDictUtil.INGOT_IRON, 'Y', OreDictUtil.STONE); // HYGROREGULATOR @@ -556,57 +585,68 @@ public class PluginApiculture extends BlankForestryPlugin { "WWW", 'X', alvearyPlainBlock, 'I', OreDictUtil.INGOT_IRON, - 'W', PluginCore.items.craftingMaterial.getWovenSilk()); + 'W', coreItems.craftingMaterial.getWovenSilk()); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FACTORY)) { // / SQUEEZER FluidStack honeyDropFluid = Fluids.FOR_HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{items.honeyDrop.getItemStack()}, honeyDropFluid, items.propolis.getItemStack(), 5); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{items.honeydew.getItemStack()}, honeyDropFluid); + RecipeManagers.squeezerManager.addRecipe(10, items.honeyDrop.getItemStack(), honeyDropFluid, items.propolis.getItemStack(), 5); + RecipeManagers.squeezerManager.addRecipe(10, items.honeydew.getItemStack(), honeyDropFluid); - ItemStack phosphor = PluginCore.items.phosphor.getItemStack(2); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.SAND)}, new FluidStack(FluidRegistry.LAVA, 2000)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.SAND, 1, 1)}, new FluidStack(FluidRegistry.LAVA, 2000)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{phosphor, new ItemStack(Blocks.DIRT)}, new FluidStack(FluidRegistry.LAVA, 1600)); + ItemStack phosphor = coreItems.phosphor.getItemStack(2); + NonNullList lavaIngredients = NonNullList.create(); + lavaIngredients.add(phosphor); + lavaIngredients.add(new ItemStack(Blocks.SAND)); + RecipeManagers.squeezerManager.addRecipe(10, lavaIngredients, new FluidStack(FluidRegistry.LAVA, 2000)); + + lavaIngredients = NonNullList.create(); + lavaIngredients.add(phosphor); + lavaIngredients.add(new ItemStack(Blocks.SAND, 1, 1)); + RecipeManagers.squeezerManager.addRecipe(10, lavaIngredients, new FluidStack(FluidRegistry.LAVA, 2000)); + + lavaIngredients = NonNullList.create(); + lavaIngredients.add(phosphor); + lavaIngredients.add(new ItemStack(Blocks.DIRT)); + RecipeManagers.squeezerManager.addRecipe(10, lavaIngredients, new FluidStack(FluidRegistry.LAVA, 1600)); // / CARPENTER - RecipeManagers.carpenterManager.addRecipe(50, Fluids.FOR_HONEY.getFluid(500), null, PluginCore.items.craftingMaterial.getScentedPaneling(), + RecipeManagers.carpenterManager.addRecipe(50, Fluids.FOR_HONEY.getFluid(500), ItemStack.EMPTY, coreItems.craftingMaterial.getScentedPaneling(), " J ", "###", "WPW", '#', OreDictUtil.PLANK_WOOD, 'J', items.royalJelly, - 'W', PluginCore.items.beeswax, + 'W', coreItems.beeswax, 'P', items.pollenCluster.get(EnumPollenCluster.NORMAL, 1)); - - RecipeManagers.carpenterManager.addRecipe(30, new FluidStack(FluidRegistry.WATER, 600), null, blocks.candle.getUnlitCandle(24), + + RecipeManagers.carpenterManager.addRecipe(30, new FluidStack(FluidRegistry.WATER, 600), ItemStack.EMPTY, blocks.candle.getUnlitCandle(24), " X ", "###", "###", - '#', PluginCore.items.beeswax, + '#', coreItems.beeswax, 'X', Items.STRING); - RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 200), null, blocks.candle.getUnlitCandle(6), + RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 200), ItemStack.EMPTY, blocks.candle.getUnlitCandle(6), "#X#", - '#', PluginCore.items.beeswax, - 'X', PluginCore.items.craftingMaterial.getSilkWisp()); + '#', coreItems.beeswax, + 'X', coreItems.craftingMaterial.getSilkWisp()); RecipeUtil.addShapelessRecipe(blocks.candle.getUnlitCandle(1), blocks.candle.getUnlitCandle(1)); RecipeUtil.addShapelessRecipe(blocks.candle.getLitCandle(1), blocks.candle.getLitCandle(1)); // / CENTRIFUGE // Honey combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.HONEY, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, + coreItems.beeswax.getItemStack(), 1.0f, items.honeyDrop.getItemStack(), 0.9f )); // Cocoa combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.COCOA, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, + coreItems.beeswax.getItemStack(), 1.0f, new ItemStack(Items.DYE, 1, 3), 0.5f )); // Simmering combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.SIMMERING, 1), ImmutableMap.of( - PluginCore.items.refractoryWax.getItemStack(), 1.0f, - PluginCore.items.phosphor.getItemStack(2), 0.7f + coreItems.refractoryWax.getItemStack(), 1.0f, + coreItems.phosphor.getItemStack(2), 0.7f )); // Stringy combs @@ -623,7 +663,7 @@ public class PluginApiculture extends BlankForestryPlugin { // Frozen combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.FROZEN, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 0.8f, + coreItems.beeswax.getItemStack(), 0.8f, items.honeyDrop.getItemStack(), 0.7f, new ItemStack(Items.SNOWBALL), 0.4f, items.pollenCluster.get(EnumPollenCluster.CRYSTALLINE, 1), 0.2f @@ -637,7 +677,7 @@ public class PluginApiculture extends BlankForestryPlugin { // Parched combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.PARCHED, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, + coreItems.beeswax.getItemStack(), 1.0f, items.honeyDrop.getItemStack(), 0.9f )); @@ -654,33 +694,33 @@ public class PluginApiculture extends BlankForestryPlugin { // Powdery combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.POWDERY, 1), ImmutableMap.of( items.honeyDrop.getItemStack(), 0.2f, - PluginCore.items.beeswax.getItemStack(), 0.2f, + coreItems.beeswax.getItemStack(), 0.2f, new ItemStack(Items.GUNPOWDER), 0.9f )); // Wheaten Combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.WHEATEN, 1), ImmutableMap.of( items.honeyDrop.getItemStack(), 0.2f, - PluginCore.items.beeswax.getItemStack(), 0.2f, + coreItems.beeswax.getItemStack(), 0.2f, new ItemStack(Items.WHEAT), 0.8f )); // Mossy Combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.MOSSY, 1), ImmutableMap.of( - PluginCore.items.beeswax.getItemStack(), 1.0f, + coreItems.beeswax.getItemStack(), 1.0f, items.honeyDrop.getItemStack(), 0.9f )); // Mellow Combs RecipeManagers.centrifugeManager.addRecipe(20, items.beeComb.get(EnumHoneyComb.MELLOW, 1), ImmutableMap.of( items.honeydew.getItemStack(), 0.6f, - PluginCore.items.beeswax.getItemStack(), 0.2f, + coreItems.beeswax.getItemStack(), 0.2f, new ItemStack(Items.QUARTZ), 0.3f )); // Silky Propolis RecipeManagers.centrifugeManager.addRecipe(5, items.propolis.get(EnumPropolis.SILKY, 1), ImmutableMap.of( - PluginCore.items.craftingMaterial.getSilkWisp(), 0.6f, + coreItems.craftingMaterial.getSilkWisp(), 0.6f, items.propolis.getItemStack(), 0.1f )); @@ -694,7 +734,7 @@ public class PluginApiculture extends BlankForestryPlugin { "###", 'X', OreDictUtil.SLAB_WOOD, '#', OreDictUtil.PLANK_WOOD, - 'C', PluginCore.items.impregnatedCasing); + 'C', coreItems.impregnatedCasing); RecipeUtil.addRecipe(blocks.beeChest, " # ", @@ -714,6 +754,12 @@ public class PluginApiculture extends BlankForestryPlugin { } private static void registerBeehiveDrops() { + if (items == null) { + throw new IllegalStateException("items have not been created"); + } + if (hiveRegistry == null) { + throw new IllegalStateException("hiveRegistry has not been created"); + } ItemStack honeyComb = items.beeComb.get(EnumHoneyComb.HONEY, 1); hiveRegistry.addDrops(HiveType.FOREST.getHiveUid(), new HiveDrop(0.80, BeeDefinition.FOREST, honeyComb).setIgnobleShare(0.7), @@ -768,6 +814,9 @@ public class PluginApiculture extends BlankForestryPlugin { } private static void createHives() { + if (hiveRegistry == null) { + throw new IllegalStateException("hiveRegistry has not been created"); + } hiveRegistry.registerHive(HiveType.FOREST.getHiveUid(), HiveDescription.FOREST); hiveRegistry.registerHive(HiveType.MEADOWS.getHiveUid(), HiveDescription.MEADOWS); hiveRegistry.registerHive(HiveType.DESERT.getHiveUid(), HiveDescription.DESERT); @@ -789,7 +838,7 @@ public class PluginApiculture extends BlankForestryPlugin { apidae.addMemberGroup(beeBranch.getBranch()); } - AlleleEffect.createAlleles(); + AlleleEffects.registerAlleles(); } public static double getSecondPrincessChance() { @@ -848,7 +897,6 @@ public class PluginApiculture extends BlankForestryPlugin { @SubscribeEvent @SideOnly(Side.CLIENT) public void textureHook(TextureStitchEvent.Pre event) { - ParticleSnow.sprites = new TextureAtlasSprite[3]; for (int i = 0; i < ParticleSnow.sprites.length; i++) { ParticleSnow.sprites[i] = event.getMap().registerSprite(new ResourceLocation("forestry:entity/particles/snow." + (i + 1))); } @@ -859,7 +907,7 @@ public class PluginApiculture extends BlankForestryPlugin { @Override public boolean isAcceptableFlower(IBlockState blockState, World world, BlockPos pos, String flowerType) { Biome biomeGenForCoords = world.getBiome(pos); - return BiomeDictionary.isBiomeOfType(biomeGenForCoords, BiomeDictionary.Type.END); + return BiomeDictionary.hasType(biomeGenForCoords, BiomeDictionary.Type.END); } } } diff --git a/src/main/java/forestry/apiculture/VillageCreationApiculture.java b/src/main/java/forestry/apiculture/VillageCreationApiculture.java index 51b0bf875..b8433c25f 100644 --- a/src/main/java/forestry/apiculture/VillageCreationApiculture.java +++ b/src/main/java/forestry/apiculture/VillageCreationApiculture.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture; +import javax.annotation.Nullable; import java.util.List; import java.util.Random; @@ -31,7 +32,7 @@ public class VillageCreationApiculture implements VillagerRegistry.IVillageCreat @Override public StructureVillagePieces.PieceWeight getVillagePieceWeight(Random random, int size) { - return new StructureVillagePieces.PieceWeight(VillageApiaristHouse.class, 15, MathHelper.getRandomIntegerInRange(random, size, 1 + size)); + return new StructureVillagePieces.PieceWeight(VillageApiaristHouse.class, 15, MathHelper.getInt(random, size, 1 + size)); } @Override @@ -40,6 +41,7 @@ public class VillageCreationApiculture implements VillagerRegistry.IVillageCreat } @Override + @Nullable public StructureVillagePieces.Village buildComponent(StructureVillagePieces.PieceWeight villagePiece, StructureVillagePieces.Start startPiece, List pieces, Random random, int p1, int p2, int p3, EnumFacing facing, int p5) { return VillageApiaristHouse.buildComponent(startPiece, pieces, random, p1, p2, p3, facing, p5); } diff --git a/src/main/java/forestry/apiculture/VillagerApiaristTrades.java b/src/main/java/forestry/apiculture/VillagerApiaristTrades.java index 73bd2c631..4d62de529 100644 --- a/src/main/java/forestry/apiculture/VillagerApiaristTrades.java +++ b/src/main/java/forestry/apiculture/VillagerApiaristTrades.java @@ -1,34 +1,36 @@ package forestry.apiculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Random; +import forestry.api.apiculture.EnumBeeType; +import forestry.apiculture.genetics.BeeDefinition; +import forestry.apiculture.items.ItemHoneyComb; +import net.minecraft.entity.IMerchant; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.item.ItemStack; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -import forestry.api.apiculture.EnumBeeType; -import forestry.apiculture.genetics.BeeDefinition; - public class VillagerApiaristTrades { public static class GiveRandomCombsForItems implements EntityVillager.ITradeList { - public ItemStack itemToBuy; + public final ItemHoneyComb honeyComb; + public final ItemStack itemToBuy; @Nullable - public EntityVillager.PriceInfo buyInfo; + public final EntityVillager.PriceInfo buyInfo; @Nullable - public EntityVillager.PriceInfo priceInfo; + public final EntityVillager.PriceInfo priceInfo; - public GiveRandomCombsForItems(ItemStack stack, @Nullable EntityVillager.PriceInfo buyInfo, @Nullable EntityVillager.PriceInfo priceInfo) { + public GiveRandomCombsForItems(ItemHoneyComb honeyComb, ItemStack stack, @Nullable EntityVillager.PriceInfo buyInfo, @Nullable EntityVillager.PriceInfo priceInfo) { + this.honeyComb = honeyComb; this.itemToBuy = stack; this.buyInfo = buyInfo; this.priceInfo = priceInfo; } @Override - public void modifyMerchantRecipeList(@Nonnull MerchantRecipeList recipeList, @Nonnull Random random) { + public void addMerchantRecipe(IMerchant p_190888_1_, MerchantRecipeList recipeList, Random random) { int sellAmount = 1; if (this.priceInfo != null) { sellAmount = this.priceInfo.getPrice(random); @@ -40,25 +42,26 @@ public class VillagerApiaristTrades { } ItemStack itemToBuy = this.itemToBuy.copy(); - itemToBuy.stackSize = buyAmount; - ItemStack randomComb = PluginApiculture.items.beeComb.getRandomComb(sellAmount, random, false); - recipeList.add(new MerchantRecipe(itemToBuy, randomComb)); + itemToBuy.setCount(buyAmount); + ItemStack randomComb = honeyComb.getRandomComb(sellAmount, random, false); + if (!randomComb.isEmpty()) { + recipeList.add(new MerchantRecipe(itemToBuy, randomComb)); + } } } + public static class GiveRandomHiveDroneForItems implements EntityVillager.ITradeList { - @Nonnull - public ItemStack buyingItemStack; + public final ItemStack buyingItemStack; @Nullable - public EntityVillager.PriceInfo buyingPriceInfo; - @Nonnull - public ItemStack buyingItemStackTwo; + public final EntityVillager.PriceInfo buyingPriceInfo; + public final ItemStack buyingItemStackTwo; @Nullable - public EntityVillager.PriceInfo buyingPriceItemTwoInfo; + public final EntityVillager.PriceInfo buyingPriceItemTwoInfo; public GiveRandomHiveDroneForItems( - @Nonnull ItemStack buyingItemStack, + ItemStack buyingItemStack, @Nullable EntityVillager.PriceInfo buyingPriceInfo, - @Nonnull ItemStack buyingItemStackTwo, + ItemStack buyingItemStackTwo, @Nullable EntityVillager.PriceInfo buyingPriceItemTwoInfo) { this.buyingItemStack = buyingItemStack; this.buyingPriceInfo = buyingPriceInfo; @@ -67,8 +70,7 @@ public class VillagerApiaristTrades { } @Override - public void modifyMerchantRecipeList(@Nonnull MerchantRecipeList recipeList, @Nonnull Random random) { - + public void addMerchantRecipe(IMerchant p_190888_1_, MerchantRecipeList recipeList, Random random) { int buyAmount = 1; if (this.buyingPriceInfo != null) { buyAmount = this.buyingPriceInfo.getPrice(random); @@ -78,12 +80,12 @@ public class VillagerApiaristTrades { if (this.buyingPriceItemTwoInfo != null) { buyTwoAmount = this.buyingPriceItemTwoInfo.getPrice(random); } - BeeDefinition [] forestryMundane = new BeeDefinition[] { BeeDefinition.FOREST, BeeDefinition.MEADOWS, BeeDefinition.MODEST, BeeDefinition.WINTRY, BeeDefinition.TROPICAL, BeeDefinition.MARSHY }; + BeeDefinition[] forestryMundane = new BeeDefinition[]{BeeDefinition.FOREST, BeeDefinition.MEADOWS, BeeDefinition.MODEST, BeeDefinition.WINTRY, BeeDefinition.TROPICAL, BeeDefinition.MARSHY}; ItemStack randomHiveDrone = forestryMundane[random.nextInt(forestryMundane.length)].getMemberStack(EnumBeeType.DRONE); ItemStack buyItemStack = this.buyingItemStack.copy(); - buyItemStack.stackSize = buyAmount; + buyItemStack.setCount(buyAmount); ItemStack buyItemStackTwo = this.buyingItemStackTwo.copy(); - buyItemStackTwo.stackSize = buyTwoAmount; + buyItemStackTwo.setCount(buyTwoAmount); recipeList.add(new MerchantRecipe(buyItemStack, buyItemStackTwo, randomHiveDrone)); } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java index 8d62c9476..1be8b906e 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockAlveary.java +++ b/src/main/java/forestry/apiculture/blocks/BlockAlveary.java @@ -10,31 +10,12 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.block.SoundType; -import net.minecraft.block.properties.PropertyEnum; -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.client.renderer.block.statemap.StateMapperBase; -import net.minecraft.item.Item; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.IStringSerializable; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.core.IModelManager; import forestry.api.core.IStateMapperRegister; import forestry.api.core.Tabs; @@ -48,17 +29,33 @@ import forestry.apiculture.multiblock.TileAlvearyPlain; import forestry.apiculture.multiblock.TileAlvearySieve; import forestry.apiculture.multiblock.TileAlvearyStabiliser; import forestry.apiculture.multiblock.TileAlvearySwarmer; -import forestry.apiculture.network.packets.PacketAlveryChange; +import forestry.apiculture.network.packets.PacketAlvearyChange; import forestry.core.blocks.BlockStructure; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; import forestry.core.tiles.TileUtil; import forestry.core.utils.BlockUtil; +import net.minecraft.block.Block; +import net.minecraft.block.SoundType; +import net.minecraft.block.properties.PropertyEnum; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.client.renderer.block.statemap.StateMapperBase; +import net.minecraft.item.Item; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.IStringSerializable; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BlockAlveary extends BlockStructure implements IStateMapperRegister { private static final PropertyEnum STATE = PropertyEnum.create("state", State.class); private static final PropertyEnum PLAIN_TYPE = PropertyEnum.create("type", AlvearyPlainType.class); - + private enum State implements IStringSerializable { ON, OFF; @@ -67,7 +64,7 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe return name().toLowerCase(Locale.ENGLISH); } } - + private enum AlvearyPlainType implements IStringSerializable { NORMAL, ENTRANCE, ENTRANCE_LEFT, ENTRANCE_RIGHT; @@ -81,7 +78,6 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe Map blockMap = new EnumMap<>(BlockAlvearyType.class); for (final BlockAlvearyType type : BlockAlvearyType.VALUES) { BlockAlveary block = new BlockAlveary() { - @Nonnull @Override public BlockAlvearyType getAlvearyType() { return type; @@ -110,7 +106,6 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe setSoundType(SoundType.WOOD); } - @Nonnull public abstract BlockAlvearyType getAlvearyType(); @Override @@ -151,7 +146,7 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe public void registerModel(Item item, IModelManager manager) { manager.registerItemModel(item, 0, "apiculture/alveary." + getAlvearyType()); } - + @Override protected BlockStateContainer createBlockState() { BlockAlvearyType alvearyType = getAlvearyType(); @@ -164,7 +159,7 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe return new BlockStateContainer(this); } } - + @Override public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { TileAlveary tile = TileUtil.getTile(world, pos, TileAlveary.class); @@ -211,7 +206,7 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe return super.getActualState(state, world, pos); } - @Nonnull + private static List getBlocksTouching(IBlockAccess world, BlockPos blockPos) { List touching = new ArrayList<>(); for (EnumFacing direction : EnumFacing.HORIZONTALS) { @@ -222,19 +217,18 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe } return touching; } - + @Override @SideOnly(Side.CLIENT) public void registerStateMapper() { Proxies.render.registerStateMapper(this, new AlvearyStateMapper(getAlvearyType())); } - + @SideOnly(Side.CLIENT) private static class AlvearyStateMapper extends StateMapperBase { - @Nonnull private final BlockAlvearyType type; - public AlvearyStateMapper(@Nonnull BlockAlvearyType type) { + public AlvearyStateMapper(BlockAlvearyType type) { this.type = type; } @@ -249,7 +243,7 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe } @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { TileEntity tileEntity = worldIn.getTileEntity(pos); if (tileEntity instanceof TileAlveary) { TileAlveary tileAlveary = (TileAlveary) tileEntity; @@ -257,9 +251,8 @@ public abstract class BlockAlveary extends BlockStructure implements IStateMappe // We must check that the slabs on top were not removed IAlvearyControllerInternal alveary = tileAlveary.getMultiblockLogic().getController(); alveary.reassemble(); - if(alveary.getReferenceCoord() != null){ - Proxies.net.sendNetworkPacket(new PacketAlveryChange(alveary), worldIn); - } + BlockPos referenceCoord = alveary.getReferenceCoord(); + Proxies.net.sendNetworkPacket(new PacketAlvearyChange(referenceCoord), referenceCoord, worldIn); } } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockBeeHives.java b/src/main/java/forestry/apiculture/blocks/BlockBeeHives.java index e2fe5262b..77aa984cc 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockBeeHives.java +++ b/src/main/java/forestry/apiculture/blocks/BlockBeeHives.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -26,6 +26,7 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumBlockRenderType; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -74,7 +75,7 @@ public class BlockBeeHives extends BlockContainer implements IItemModelRegister, return getDefaultState().withProperty(HIVE_TYPES, HiveType.VALUES[meta]); } - public IBlockState getStateForType(@Nonnull HiveType type) { + public IBlockState getStateForType(HiveType type) { return getDefaultState().withProperty(HIVE_TYPES, type); } @@ -168,7 +169,11 @@ public class BlockBeeHives extends BlockContainer implements IItemModelRegister, return PluginApiculture.hiveRegistry.getDrops(hiveName); } + @Nullable private static String getHiveNameForMeta(int meta) { + if (meta < 0 || meta >= HiveType.VALUES.length) { + return null; + } return HiveType.VALUES[meta].getHiveUid(); } @@ -177,11 +182,11 @@ public class BlockBeeHives extends BlockContainer implements IItemModelRegister, } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (IBlockState blockState : getBlockState().getValidStates()) { if (getHiveType(blockState) != HiveType.SWARM) { int meta = getMetaFromState(blockState); - itemList.add(new ItemStack(this, 1, meta)); + list.add(new ItemStack(this, 1, meta)); } } } diff --git a/src/main/java/forestry/apiculture/blocks/BlockCandle.java b/src/main/java/forestry/apiculture/blocks/BlockCandle.java index 0635f9170..efe1a5689 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockCandle.java +++ b/src/main/java/forestry/apiculture/blocks/BlockCandle.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.apiculture.blocks; +import javax.annotation.Nullable; + import com.google.common.collect.ImmutableMap; import java.awt.Color; @@ -39,6 +41,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.IStringSerializable; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; @@ -149,12 +152,12 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { + list.add(new ItemStack(this, 1, 0)); } @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { TileEntity tileEntity = worldIn.getTileEntity(pos); if (!(tileEntity instanceof TileCandle)) { return false; @@ -166,19 +169,21 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile boolean flag = false; boolean toggleLitState = true; + ItemStack heldItem = playerIn.getHeldItem(hand); + if (!isLit) { - if (heldItem == null || !lightingItems.contains(heldItem.getItem())) { + if (heldItem.isEmpty() || !lightingItems.contains(heldItem.getItem())) { toggleLitState = false; } else if (ItemStackUtil.equals(this, heldItem) && isLit(heldItem)) { toggleLitState = true; } } - if (heldItem != null) { + if (!heldItem.isEmpty()) { if (ItemStackUtil.equals(this, heldItem)) { if (!isLit(heldItem)) { // Copy the colour of an unlit, coloured candle. - if (heldItem.hasTagCompound() && heldItem.getTagCompound().hasKey(colourTagName)) { + if (heldItem.getTagCompound() != null && heldItem.getTagCompound().hasKey(colourTagName)) { tileCandle.setColour(heldItem.getTagCompound().getInteger(colourTagName)); } else { // Reset to white if item has no @@ -262,11 +267,10 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile } private ItemStack getCandleDrop(IBlockAccess world, BlockPos pos) { - TileEntity tileEntity = world.getTileEntity(pos); - if (!(tileEntity instanceof TileCandle)) { - return null; + TileCandle tileCandle = TileUtil.getTile(world, pos, TileCandle.class); + if (tileCandle == null) { + return new ItemStack(this); } - TileCandle tileCandle = (TileCandle) tileEntity; int colour = tileCandle.getColour(); int newMeta = tileCandle.isLit() ? 1 : 0; @@ -282,15 +286,17 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { - TileCandle tileCandle = (TileCandle) world.getTileEntity(pos); - int colour = getColourValueFromItemStack(stack); - boolean isLit = isLit(stack); - tileCandle.setColour(colour); - tileCandle.setLit(isLit); - if (tileCandle.isLit()) { - world.theProfiler.startSection("checkLight"); - world.checkLight(pos); - world.theProfiler.endSection(); + TileCandle tileCandle = TileUtil.getTile(world, pos, TileCandle.class); + if (tileCandle != null) { + int colour = getColourValueFromItemStack(stack); + boolean isLit = isLit(stack); + tileCandle.setColour(colour); + tileCandle.setLit(isLit); + if (tileCandle.isLit()) { + world.theProfiler.startSection("checkLight"); + world.checkLight(pos); + world.theProfiler.endSection(); + } } } @@ -304,7 +310,7 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile private static int getColourValueFromItemStack(ItemStack itemStack) { int value = 0xffffff; // default to white. - if (itemStack.hasTagCompound()) { + if (itemStack.getTagCompound() != null) { NBTTagCompound tag = itemStack.getTagCompound(); if (tag.hasKey(colourTagName)) { value = tag.getInteger(colourTagName); @@ -318,10 +324,6 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile } public static void addItemToLightingList(Item item) { - if (item == null) { - throw new NullPointerException(); - } - if (!lightingItems.contains(item)) { lightingItems.add(item); } @@ -336,10 +338,12 @@ public class BlockCandle extends BlockTorch implements IItemModelRegister, ITile } @Override - public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex) { - TileCandle tileCandle = TileUtil.getTile(worldIn, pos, TileCandle.class); - if (tileCandle != null) { - return tileCandle.getColour(); + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { + if (worldIn != null && pos != null) { + TileCandle tileCandle = TileUtil.getTile(worldIn, pos, TileCandle.class); + if (tileCandle != null) { + return tileCandle.getColour(); + } } return 0xffffff; } diff --git a/src/main/java/forestry/apiculture/blocks/BlockStump.java b/src/main/java/forestry/apiculture/blocks/BlockStump.java index 84c5949a9..e0a93b47b 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockStump.java +++ b/src/main/java/forestry/apiculture/blocks/BlockStump.java @@ -10,9 +10,14 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import java.util.List; import java.util.Random; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.Tabs; +import forestry.apiculture.PluginApiculture; +import forestry.apiculture.tiles.TileCandle; +import forestry.core.config.Constants; import net.minecraft.block.Block; import net.minecraft.block.BlockTorch; import net.minecraft.block.SoundType; @@ -23,19 +28,12 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.Tabs; -import forestry.apiculture.PluginApiculture; -import forestry.apiculture.tiles.TileCandle; -import forestry.core.config.Constants; - public class BlockStump extends BlockTorch implements IItemModelRegister { public BlockStump() { @@ -51,13 +49,14 @@ public class BlockStump extends BlockTorch implements IItemModelRegister { } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { + list.add(new ItemStack(this, 1, 0)); } @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { - if (heldItem != null && BlockCandle.lightingItems.contains(heldItem.getItem())) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + ItemStack heldItem = playerIn.getHeldItem(hand); + if (BlockCandle.lightingItems.contains(heldItem.getItem())) { IBlockState blockState = worldIn.getBlockState(pos); Block block = blockState.getBlock(); IBlockState activatedState = PluginApiculture.blocks.candle.getStateFromMeta(block.getMetaFromState(blockState)); diff --git a/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java b/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java index c816df00a..6d5100151 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java +++ b/src/main/java/forestry/apiculture/blocks/BlockTypeApiculture.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import javax.annotation.Nonnull; - import forestry.apiculture.tiles.TileApiary; import forestry.apiculture.tiles.TileBeeHouse; import forestry.core.blocks.IBlockType; @@ -25,14 +23,12 @@ public enum BlockTypeApiculture implements IBlockType { public static final BlockTypeApiculture[] VALUES = values(); - @Nonnull private final IMachineProperties machineProperties; - BlockTypeApiculture(@Nonnull Class teClass, @Nonnull String name) { + BlockTypeApiculture(Class teClass, String name) { this.machineProperties = new MachineProperties<>(teClass, name); } - @Nonnull @Override public IMachineProperties getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/apiculture/blocks/BlockTypeApicultureTesr.java b/src/main/java/forestry/apiculture/blocks/BlockTypeApicultureTesr.java index 0b0f05eaa..2008317b1 100644 --- a/src/main/java/forestry/apiculture/blocks/BlockTypeApicultureTesr.java +++ b/src/main/java/forestry/apiculture/blocks/BlockTypeApicultureTesr.java @@ -10,12 +10,8 @@ ******************************************************************************/ package forestry.apiculture.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.util.math.AxisAlignedBB; - import forestry.apiculture.tiles.TileApiaristChest; import forestry.core.blocks.IBlockTypeTesr; import forestry.core.blocks.IMachinePropertiesTesr; @@ -24,20 +20,20 @@ import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileForestry; import forestry.core.tiles.TileNaturalistChest; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.util.math.AxisAlignedBB; public enum BlockTypeApicultureTesr implements IBlockTypeTesr { APIARIST_CHEST(TileApiaristChest.class, "api_chest", Proxies.render.getRenderChest("apiaristchest"), TileNaturalistChest.chestBoundingBox); public static final BlockTypeApicultureTesr[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeApicultureTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, AxisAlignedBB boundingBox) { + BlockTypeApicultureTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, AxisAlignedBB boundingBox) { this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, boundingBox, Constants.MOD_ID + ":blocks/" + name + ".0", false); } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/apiculture/blocks/package-info.java b/src/main/java/forestry/apiculture/blocks/package-info.java new file mode 100644 index 000000000..94724a24b --- /dev/null +++ b/src/main/java/forestry/apiculture/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/capabilities/package-info.java b/src/main/java/forestry/apiculture/capabilities/package-info.java new file mode 100644 index 000000000..57bfea1b1 --- /dev/null +++ b/src/main/java/forestry/apiculture/capabilities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.capabilities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/commands/BeeModeHelper.java b/src/main/java/forestry/apiculture/commands/BeeModeHelper.java index e54fe20e9..336023fa4 100644 --- a/src/main/java/forestry/apiculture/commands/BeeModeHelper.java +++ b/src/main/java/forestry/apiculture/commands/BeeModeHelper.java @@ -10,7 +10,9 @@ ******************************************************************************/ package forestry.apiculture.commands; +import javax.annotation.Nullable; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import net.minecraft.world.World; @@ -23,7 +25,7 @@ public class BeeModeHelper implements ICommandModeHelper { @Override public String[] getModeNames() { - ArrayList beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); + List beekeepingModes = BeeManager.beeRoot.getBeekeepingModes(); int modeStringCount = beekeepingModes.size(); List modeStrings = new ArrayList<>(modeStringCount); for (IBeekeepingMode mode : beekeepingModes) { @@ -34,6 +36,7 @@ public class BeeModeHelper implements ICommandModeHelper { } @Override + @Nullable public String getModeNameMatching(String desired) { IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(desired); if (mode == null) { @@ -55,6 +58,9 @@ public class BeeModeHelper implements ICommandModeHelper { @Override public Iterable getDescription(String modeName) { IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(modeName); + if (mode == null) { + return Collections.emptyList(); + } return mode.getDescription(); } diff --git a/src/main/java/forestry/apiculture/commands/CommandBeeGive.java b/src/main/java/forestry/apiculture/commands/CommandBeeGive.java index 8be47754a..7b95a3533 100644 --- a/src/main/java/forestry/apiculture/commands/CommandBeeGive.java +++ b/src/main/java/forestry/apiculture/commands/CommandBeeGive.java @@ -12,17 +12,10 @@ package forestry.apiculture.commands; import javax.annotation.Nullable; import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; -import net.minecraft.command.CommandBase; -import net.minecraft.command.ICommandSender; -import net.minecraft.command.PlayerNotFoundException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.math.BlockPos; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpecies; @@ -34,6 +27,13 @@ import forestry.core.commands.CommandHelpers; import forestry.core.commands.SpeciesNotFoundException; import forestry.core.commands.SubCommand; import forestry.core.commands.TemplateNotFoundException; +import net.minecraft.command.CommandBase; +import net.minecraft.command.CommandException; +import net.minecraft.command.ICommandSender; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.util.math.BlockPos; public class CommandBeeGive extends SubCommand { @@ -65,7 +65,7 @@ public class CommandBeeGive extends SubCommand { } @Override - public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws SpeciesNotFoundException, TemplateNotFoundException, PlayerNotFoundException { + public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { if (args.length < 2) { printHelp(sender); return; @@ -84,10 +84,6 @@ public class CommandBeeGive extends SubCommand { } else { player = CommandBase.getPlayer(server, sender, sender.getName()); } - if (player == null) { - printHelp(sender); - return; - } IBee bee = BeeManager.beeRoot.getBee(beeGenome); @@ -139,7 +135,7 @@ public class CommandBeeGive extends SubCommand { } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(args, getSpecies()); tabCompletion.add("help"); @@ -147,9 +143,9 @@ public class CommandBeeGive extends SubCommand { } else if (args.length == 2) { return CommandHelpers.getListOfStringsMatchingLastWord(args, beeTypeArr); } else if (args.length == 3) { - return CommandHelpers.getListOfStringsMatchingLastWord(args, server.getPlayerList().getAllUsernames()); + return CommandHelpers.getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames()); } - return null; + return Collections.emptyList(); } private static String[] getSpecies() { diff --git a/src/main/java/forestry/apiculture/commands/package-info.java b/src/main/java/forestry/apiculture/commands/package-info.java new file mode 100644 index 000000000..fdf17b4c9 --- /dev/null +++ b/src/main/java/forestry/apiculture/commands/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.commands; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java b/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java index e0afe9f84..0d966c98e 100644 --- a/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java +++ b/src/main/java/forestry/apiculture/compat/ApicultureJeiPlugin.java @@ -24,9 +24,9 @@ public class ApicultureJeiPlugin extends BlankModPlugin { return species == null ? null : species.getUID(); }; - subtypeRegistry.registerNbtInterpreter(items.beeDroneGE, beeSubtypeInterpreter); - subtypeRegistry.registerNbtInterpreter(items.beePrincessGE, beeSubtypeInterpreter); - subtypeRegistry.registerNbtInterpreter(items.beeQueenGE, beeSubtypeInterpreter); + subtypeRegistry.registerSubtypeInterpreter(items.beeDroneGE, beeSubtypeInterpreter); + subtypeRegistry.registerSubtypeInterpreter(items.beePrincessGE, beeSubtypeInterpreter); + subtypeRegistry.registerSubtypeInterpreter(items.beeQueenGE, beeSubtypeInterpreter); } @Override diff --git a/src/main/java/forestry/apiculture/compat/package-info.java b/src/main/java/forestry/apiculture/compat/package-info.java new file mode 100644 index 000000000..15bb400cf --- /dev/null +++ b/src/main/java/forestry/apiculture/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java index 2848d03cb..17aff290f 100644 --- a/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java +++ b/src/main/java/forestry/apiculture/entities/AIAvoidPlayers.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.apiculture.entities; +import javax.annotation.Nullable; + import net.minecraft.entity.EntityCreature; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.RandomPositionGenerator; @@ -21,15 +23,16 @@ import net.minecraft.util.math.Vec3d; public class AIAvoidPlayers extends EntityAIBase { private final EntityCreature mob; + private final PathNavigate pathNavigator; private final float farSpeed; private final float nearSpeed; private final float minDistance; + @Nullable private Path path; - private final PathNavigate pathNavigator; - + @Nullable private EntityPlayer player; public AIAvoidPlayers(EntityCreature mob, float minDistance, float farSpeed, float nearSpeed) { @@ -44,7 +47,7 @@ public class AIAvoidPlayers extends EntityAIBase { @Override public boolean shouldExecute() { - player = mob.worldObj.getClosestPlayerToEntity(mob, minDistance); + player = mob.world.getClosestPlayerToEntity(mob, minDistance); if (player == null) { return false; @@ -86,7 +89,7 @@ public class AIAvoidPlayers extends EntityAIBase { @Override public void updateTask() { - if (mob.getDistanceSqToEntity(player) < 49.0D) { + if (player != null && mob.getDistanceSqToEntity(player) < 49.0D) { mob.getNavigator().setSpeed(nearSpeed); } else { mob.getNavigator().setSpeed(farSpeed); diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java b/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java index ab30aa4d8..20ed47c72 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartApiary.java @@ -10,17 +10,11 @@ ******************************************************************************/ package forestry.apiculture.entities; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -35,13 +29,16 @@ import forestry.apiculture.inventory.IApiaryInventory; import forestry.apiculture.inventory.InventoryApiary; import forestry.core.config.Config; import forestry.core.inventory.IInventoryAdapter; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class EntityMinecartApiary extends EntityMinecartBeeHousingBase implements IApiary { - @Nonnull + private static final IBeeModifier beeModifier = new ApiaryBeeModifier(); - @Nonnull + private final IBeeListener beeListener = new ApiaryBeeListener(this); - @Nonnull private final InventoryApiary inventory = new InventoryApiary(); @SuppressWarnings("unused") @@ -68,12 +65,11 @@ public class EntityMinecartApiary extends EntityMinecartBeeHousingBase implement return inventory; } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return inventory; } - + @Override public IBlockState getDisplayTile() { return PluginApiculture.blocks.apiary.getDefaultState(); diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java b/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java index 6951fc4af..dc0d061b0 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartBeeHousingBase.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.apiculture.entities; -import javax.annotation.Nonnull; import java.io.IOException; +import java.util.Optional; import java.util.Random; -import com.google.common.base.Optional; import com.mojang.authlib.GameProfile; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IBeeHousing; @@ -27,10 +26,9 @@ import forestry.apiculture.gui.IGuiBeeHousingInventory; import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; import forestry.apiculture.tiles.TileBeeHousingBase; import forestry.core.entities.EntityMinecartContainerForestry; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketServer; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.owner.GameProfileDataSerializer; import forestry.core.owner.IOwnedTile; import forestry.core.owner.IOwnerHandler; @@ -60,7 +58,7 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain private final IErrorLogic errorLogic = ForestryAPI.errorStateRegistry.createErrorLogic(); private final OwnerHandler ownerHandler = new OwnerHandler() { @Override - public void setOwner(@Nonnull GameProfile owner) { + public void setOwner(GameProfile owner) { super.setOwner(owner); dataManager.set(OWNER, Optional.of(owner)); } @@ -68,11 +66,7 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain @Override public GameProfile getOwner() { Optional gameProfileOptional = dataManager.get(OWNER); - if (gameProfileOptional.isPresent()) { - return gameProfileOptional.get(); - } else { - return null; - } + return gameProfileOptional.orElse(null); } }; @@ -92,7 +86,7 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain @Override protected void entityInit() { super.entityInit(); - this.dataManager.register(OWNER, Optional.absent()); + this.dataManager.register(OWNER, Optional.empty()); } /* IOwnedTile */ @@ -109,7 +103,7 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain @Override public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(getBiome(), worldObj, getPosition()); + return EnumTemperature.getFromBiome(getBiome(), world, getPosition()); } @Override @@ -119,37 +113,37 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain @Override public float getExactTemperature() { - return ForestryAPI.climateManager.getTemperature(worldObj, getPosition()); + return ForestryAPI.climateManager.getTemperature(world, getPosition()); } @Override public float getExactHumidity() { - return ForestryAPI.climateManager.getHumidity(worldObj, getPosition()); + return ForestryAPI.climateManager.getHumidity(world, getPosition()); } @Override public int getBlockLightValue() { - return worldObj.getLightFromNeighbors(getPosition().up()); + return world.getLightFromNeighbors(getPosition().up()); } @Override public boolean canBlockSeeTheSky() { - return worldObj.canBlockSeeSky(getPosition().up()); + return world.canBlockSeeSky(getPosition().up()); } - + @Override public boolean isRaining() { - return worldObj.canBlockSeeSky(getPosition().up()); + return world.isRaining(); } @Override public World getWorldObj() { - return worldObj; + return world; } @Override public Biome getBiome() { - return worldObj.getBiome(getPosition()); + return world.getBiome(getPosition()); } @Override @@ -173,12 +167,12 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { data.writeVarInt(beeLogic.getBeeProgressPercent()); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { breedingProgressPercent = data.readVarInt(); } @@ -190,7 +184,7 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain @Override public void onUpdate() { super.onUpdate(); - if (!worldObj.isRemote) { + if (!world.isRemote) { if (beeLogic.canWork()) { beeLogic.doWork(); } @@ -202,12 +196,12 @@ public abstract class EntityMinecartBeeHousingBase extends EntityMinecartContain } if (beeLogic.canDoBeeFX()) { - if (worldObj.getTotalWorldTime() % beeFXInterval == beeFXTime) { + if (world.getTotalWorldTime() % beeFXInterval == beeFXTime) { beeLogic.doBeeFX(); } - if (worldObj.getTotalWorldTime() % pollenFXInterval == pollenFXTime) { - TileBeeHousingBase.doPollenFX(worldObj, posX - 0.5, posY - 0.1, posZ - 0.5); + if (world.getTotalWorldTime() % pollenFXInterval == pollenFXTime) { + TileBeeHousingBase.doPollenFX(world, posX - 0.5, posY - 0.1, posZ - 0.5); } } } diff --git a/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java b/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java index 4395df345..d1d1ece1d 100644 --- a/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java +++ b/src/main/java/forestry/apiculture/entities/EntityMinecartBeehouse.java @@ -10,15 +10,9 @@ ******************************************************************************/ package forestry.apiculture.entities; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.apiculture.DefaultBeeListener; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -30,6 +24,10 @@ import forestry.apiculture.gui.ContainerMinecartBeehouse; import forestry.apiculture.gui.GuiBeeHousing; import forestry.core.config.Config; import forestry.core.inventory.IInventoryAdapter; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; public class EntityMinecartBeehouse extends EntityMinecartBeeHousingBase { private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); @@ -51,7 +49,7 @@ public class EntityMinecartBeehouse extends EntityMinecartBeeHousingBase { public List getHints() { return Config.hints.get("bee.house"); } - + @Override public IBlockState getDisplayTile() { return PluginApiculture.blocks.beeHouse.getDefaultState(); @@ -73,7 +71,6 @@ public class EntityMinecartBeehouse extends EntityMinecartBeeHousingBase { return Collections.singleton(beeListener); } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return beeInventory; diff --git a/src/main/java/forestry/apiculture/entities/ParticleBeeExplore.java b/src/main/java/forestry/apiculture/entities/ParticleBeeExplore.java index 5187a47e9..f8438609b 100644 --- a/src/main/java/forestry/apiculture/entities/ParticleBeeExplore.java +++ b/src/main/java/forestry/apiculture/entities/ParticleBeeExplore.java @@ -52,7 +52,7 @@ public class ParticleBeeExplore extends Particle { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); if (this.particleAge == this.particleMaxAge / 2) { this.motionX = (origin.xCoord - this.posX) * 0.03; @@ -125,11 +125,11 @@ public class ParticleBeeExplore extends Particle { // avoid calculating collisions @Override - public void moveEntity(double x, double y, double z) { - this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); + public void move(double x, double y, double z) { + this.setBoundingBox(this.getBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } - + @Override public int getFXLayer() { return 1; diff --git a/src/main/java/forestry/apiculture/entities/ParticleBeeRoundTrip.java b/src/main/java/forestry/apiculture/entities/ParticleBeeRoundTrip.java index f681665a7..c00700129 100644 --- a/src/main/java/forestry/apiculture/entities/ParticleBeeRoundTrip.java +++ b/src/main/java/forestry/apiculture/entities/ParticleBeeRoundTrip.java @@ -54,7 +54,7 @@ public class ParticleBeeRoundTrip extends Particle { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); if (this.particleAge == this.particleMaxAge / 2) { this.motionX = (origin.xCoord - this.posX) * 0.03 + 0.1 * rand.nextFloat(); @@ -128,8 +128,8 @@ public class ParticleBeeRoundTrip extends Particle { // avoid calculating collisions @Override - public void moveEntity(double x, double y, double z) { - this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); + public void move(double x, double y, double z) { + this.setBoundingBox(this.getBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } diff --git a/src/main/java/forestry/apiculture/entities/ParticleBeeTargetEntity.java b/src/main/java/forestry/apiculture/entities/ParticleBeeTargetEntity.java index 5f585afcd..7289f9d8e 100644 --- a/src/main/java/forestry/apiculture/entities/ParticleBeeTargetEntity.java +++ b/src/main/java/forestry/apiculture/entities/ParticleBeeTargetEntity.java @@ -54,7 +54,7 @@ public class ParticleBeeTargetEntity extends Particle { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); if (this.particleAge == this.particleMaxAge / 2) { this.motionX = (origin.xCoord - this.posX) * 0.03; @@ -125,8 +125,8 @@ public class ParticleBeeTargetEntity extends Particle { // avoid calculating collisions @Override - public void moveEntity(double x, double y, double z) { - this.setEntityBoundingBox(this.getEntityBoundingBox().offset(x, y, z)); + public void move(double x, double y, double z) { + this.setBoundingBox(this.getBoundingBox().offset(x, y, z)); this.resetPositionToBB(); } diff --git a/src/main/java/forestry/apiculture/entities/package-info.java b/src/main/java/forestry/apiculture/entities/package-info.java new file mode 100644 index 000000000..a32e04c55 --- /dev/null +++ b/src/main/java/forestry/apiculture/entities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.entities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/flowers/FlowerProvider.java b/src/main/java/forestry/apiculture/flowers/FlowerProvider.java index a9a4cb72a..32c667778 100644 --- a/src/main/java/forestry/apiculture/flowers/FlowerProvider.java +++ b/src/main/java/forestry/apiculture/flowers/FlowerProvider.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.apiculture.flowers; +import java.util.List; + import forestry.api.apiculture.FlowerManager; import forestry.api.genetics.ICheckPollinatable; import forestry.api.genetics.IFlowerProvider; @@ -56,7 +58,7 @@ public class FlowerProvider implements IFlowerProvider { } @Override - public ItemStack[] affectProducts(World world, IIndividual individual, BlockPos pos, ItemStack[] products) { + public List affectProducts(World world, IIndividual individual, BlockPos pos, List products) { return products; } diff --git a/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java b/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java index f98c6414c..7a1ecbd69 100644 --- a/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java +++ b/src/main/java/forestry/apiculture/flowers/FlowerRegistry.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.apiculture.flowers; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableSet; - -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -23,13 +18,8 @@ import java.util.Random; import java.util.Set; import java.util.TreeMap; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; - +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.HashMultimap; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.FlowerManager; import forestry.api.apiculture.IBee; @@ -43,21 +33,14 @@ import forestry.api.genetics.IFlowerRegistry; import forestry.api.genetics.IIndividual; import forestry.core.utils.Log; import forestry.core.utils.VectUtil; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3i; +import net.minecraft.world.World; public final class FlowerRegistry implements IFlowerRegistry, IFlowerGrowthHelper { - - private final Set defaultFlowerTypes = ImmutableSet.of( - FlowerManager.FlowerTypeVanilla, - FlowerManager.FlowerTypeNether, - FlowerManager.FlowerTypeCacti, - FlowerManager.FlowerTypeMushrooms, - FlowerManager.FlowerTypeEnd, - FlowerManager.FlowerTypeJungle, - FlowerManager.FlowerTypeSnow, - FlowerManager.FlowerTypeWheat, - FlowerManager.FlowerTypeGourd - ); - private final HashMultimap registeredRules; private final HashMultimap acceptableBlocks; private final HashMultimap acceptableBlockStates; @@ -152,7 +135,7 @@ public final class FlowerRegistry implements IFlowerRegistry, IFlowerGrowthHelpe } @Override - @Nonnull + public List getAcceptedFlowerCoordinates(IBeeHousing beeHousing, IBee bee, String flowerType, int maxFlowers) { Set acceptableRules = this.registeredRules.get(flowerType); Set acceptedBlockStates = this.acceptableBlockStates.get(flowerType); diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java index d627c5efa..b174ce922 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleDirtGrass.java @@ -27,11 +27,8 @@ public class GrowthRuleDirtGrass implements IFlowerGrowthRule { } Block ground = world.getBlockState(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ())).getBlock(); - if (ground != Blocks.DIRT && ground != Blocks.GRASS) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, pos); + return (ground == Blocks.DIRT || ground == Blocks.GRASS) && + helper.plantRandomFlower(flowerType, world, pos); } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java index 7e8ea3339..480b20a4d 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleMycelium.java @@ -27,11 +27,8 @@ public class GrowthRuleMycelium implements IFlowerGrowthRule { } Block ground = world.getBlockState(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ())).getBlock(); - if (ground != Blocks.MYCELIUM) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, pos); + return ground == Blocks.MYCELIUM && + helper.plantRandomFlower(flowerType, world, pos); } } diff --git a/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java b/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java index 3b65d330a..a572366c9 100644 --- a/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java +++ b/src/main/java/forestry/apiculture/flowers/GrowthRuleSnow.java @@ -27,11 +27,8 @@ public class GrowthRuleSnow implements IFlowerGrowthRule { } Block ground = world.getBlockState(new BlockPos(pos.getX(), pos.getY() - 1, pos.getZ())).getBlock(); - if (ground != Blocks.DIRT && ground != Blocks.GRASS) { - return false; - } - - return helper.plantRandomFlower(flowerType, world, pos); + return (ground == Blocks.DIRT || ground == Blocks.GRASS) && + helper.plantRandomFlower(flowerType, world, pos); } } diff --git a/src/main/java/forestry/apiculture/flowers/package-info.java b/src/main/java/forestry/apiculture/flowers/package-info.java new file mode 100644 index 000000000..00c276d4f --- /dev/null +++ b/src/main/java/forestry/apiculture/flowers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.flowers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java index 192369da1..83b7ca817 100755 --- a/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java +++ b/src/main/java/forestry/apiculture/genetics/ApiaristTracker.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IApiaristTracker; @@ -22,10 +17,14 @@ import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.BreedingTracker; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; public class ApiaristTracker extends BreedingTracker implements IApiaristTracker { - /** Required for creation from map storage */ + /** + * Required for creation from map storage + */ public ApiaristTracker(String s) { super(s); } @@ -35,7 +34,7 @@ public class ApiaristTracker extends BreedingTracker implements IApiaristTracker private int princessesTotal = 0; @Override - public void readFromNBT(@Nonnull NBTTagCompound nbttagcompound) { + public void readFromNBT(NBTTagCompound nbttagcompound) { queensTotal = nbttagcompound.getInteger("QueensTotal"); princessesTotal = nbttagcompound.getInteger("PrincessesTotal"); @@ -45,9 +44,8 @@ public class ApiaristTracker extends BreedingTracker implements IApiaristTracker } - @Nonnull @Override - public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound nbttagcompound) { + public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setInteger("QueensTotal", queensTotal); nbttagcompound.setInteger("PrincessesTotal", princessesTotal); @@ -87,7 +85,6 @@ public class ApiaristTracker extends BreedingTracker implements IApiaristTracker @Override public void registerPrincess(IIndividual bee) { - princessesTotal++; registerBirth(bee); } @@ -110,7 +107,7 @@ public class ApiaristTracker extends BreedingTracker implements IApiaristTracker @Override protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return BeeManager.beeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + return BeeManager.beeRoot.getBreedingTracker(player.world, player.getGameProfile()); } @Override diff --git a/src/main/java/forestry/apiculture/genetics/Bee.java b/src/main/java/forestry/apiculture/genetics/Bee.java index ddf70d82f..dc97a69ef 100644 --- a/src/main/java/forestry/apiculture/genetics/Bee.java +++ b/src/main/java/forestry/apiculture/genetics/Bee.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashSet; @@ -19,18 +18,7 @@ import java.util.Map; import java.util.Random; import java.util.Set; -import net.minecraft.item.EnumRarity; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; - import com.mojang.authlib.GameProfile; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.FlowerManager; @@ -64,22 +52,29 @@ import forestry.core.genetics.Chromosome; import forestry.core.genetics.GenericRatings; import forestry.core.genetics.IndividualLiving; import forestry.core.utils.GeneticsUtil; -import forestry.core.utils.Log; import forestry.core.utils.Translator; import forestry.core.utils.VectUtil; +import net.minecraft.item.EnumRarity; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3i; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.World; +import net.minecraft.world.biome.Biome; public class Bee extends IndividualLiving implements IBee { private int generation; private boolean isNatural = true; - @Nonnull private final IBeeGenome genome; @Nullable private IBeeGenome mate; /* CONSTRUCTOR */ - public Bee(@Nonnull NBTTagCompound nbt) { + public Bee(NBTTagCompound nbt) { super(nbt); if (nbt.hasKey("NA")) { @@ -101,16 +96,16 @@ public class Bee extends IndividualLiving implements IBee { } } - public Bee(@Nonnull IBeeGenome genome, IBee mate) { + public Bee(IBeeGenome genome, IBee mate) { this(genome); this.mate = mate.getGenome(); } - public Bee(@Nonnull IBeeGenome genome) { + public Bee(IBeeGenome genome) { this(genome, true, 0); } - private Bee(@Nonnull IBeeGenome genome, boolean isNatural, int generation) { + private Bee(IBeeGenome genome, boolean isNatural, int generation) { super(genome.getLifespan()); this.genome = genome; this.isNatural = isNatural; @@ -162,10 +157,6 @@ public class Bee extends IndividualLiving implements IBee { public IEffectData[] doEffect(IEffectData[] storedData, IBeeHousing housing) { IAlleleBeeEffect effect = genome.getEffect(); - if (effect == null) { - return null; - } - storedData[0] = doEffect(effect, storedData[0], housing); // Return here if the primary can already not be combined @@ -192,10 +183,6 @@ public class Bee extends IndividualLiving implements IBee { public IEffectData[] doFX(IEffectData[] storedData, IBeeHousing housing) { IAlleleBeeEffect effect = genome.getEffect(); - if (effect == null) { - return null; - } - storedData[0] = doFX(effect, storedData[0], housing); // Return here if the primary can already not be combined @@ -218,7 +205,6 @@ public class Bee extends IndividualLiving implements IBee { } // / INFORMATION - @Nonnull @Override public IBeeGenome getGenome() { return genome; @@ -235,7 +221,6 @@ public class Bee extends IndividualLiving implements IBee { NBTTagCompound nbttagcompound = new NBTTagCompound(); this.writeToNBT(nbttagcompound); return new Bee(nbttagcompound); - } @Override @@ -246,7 +231,6 @@ public class Bee extends IndividualLiving implements IBee { @Override public Set getCanWork(IBeeHousing housing) { World world = housing.getWorldObj(); - BlockPos housingCoords = housing.getCoordinates(); Set errorStates = new HashSet<>(); @@ -279,7 +263,7 @@ public class Bee extends IndividualLiving implements IBee { } // / Check for the sky, except if in hell - if (!world.provider.getHasNoSky()) { + if (!world.provider.hasNoSky()) { if (!housing.canBlockSeeTheSky() && !canWorkUnderground(beeModifier)) { errorStates.add(EnumErrorCode.NO_SKY); } @@ -335,10 +319,6 @@ public class Bee extends IndividualLiving implements IBee { } private boolean isSuitableBiome(Biome biome) { - if (biome == null) { - return false; - } - EnumTemperature temperature = EnumTemperature.getFromBiome(biome); EnumHumidity humidity = EnumHumidity.getFromValue(biome.getRainfall()); return isSuitableClimate(temperature, humidity); @@ -351,8 +331,8 @@ public class Bee extends IndividualLiving implements IBee { } @Override - public ArrayList getSuitableBiomes() { - ArrayList suitableBiomes = new ArrayList<>(); + public List getSuitableBiomes() { + List suitableBiomes = new ArrayList<>(); for (Biome biome : Biome.REGISTRY) { if (isSuitableBiome(biome)) { suitableBiomes.add(biome); @@ -473,17 +453,9 @@ public class Bee extends IndividualLiving implements IBee { } @Override - public ItemStack[] produceStacks(IBeeHousing housing) { - if (housing == null) { - Log.warning("Failed to produce in an apiary because the beehousing was null."); - return null; - } + public List produceStacks(IBeeHousing housing) { World world = housing.getWorldObj(); IBeekeepingMode mode = BeeManager.beeRoot.getBeekeepingMode(world); - if (mode == null) { - Log.warning("Failed to produce in an apiary because the beekeeping mode was null."); - return null; - } List products = new ArrayList<>(); @@ -523,13 +495,13 @@ public class Bee extends IndividualLiving implements IBee { } } - ItemStack[] productsArray = products.toArray(new ItemStack[products.size()]); BlockPos housingCoordinates = housing.getCoordinates(); - return genome.getFlowerProvider().affectProducts(world, this, housingCoordinates, productsArray); + return genome.getFlowerProvider().affectProducts(world, this, housingCoordinates, products); } /* REPRODUCTION */ @Override + @Nullable public IBee spawnPrincess(IBeeHousing housing) { // We need a mated queen to produce offspring. @@ -542,17 +514,18 @@ public class Bee extends IndividualLiving implements IBee { return null; } - return createOffspring(housing, getGeneration() + 1); + return createOffspring(housing, mate, getGeneration() + 1); } @Override + @Nullable public IBee[] spawnDrones(IBeeHousing housing) { World world = housing.getWorldObj(); // We need a mated queen to produce offspring. if (mate == null) { - return null; + return new IBee[]{}; } List bees = new ArrayList<>(); @@ -565,11 +538,9 @@ public class Bee extends IndividualLiving implements IBee { } for (int i = 0; i < toCreate; i++) { - IBee offspring = createOffspring(housing, 0); - if (offspring != null) { - offspring.setIsNatural(true); - bees.add(offspring); - } + IBee offspring = createOffspring(housing, mate, 0); + offspring.setIsNatural(true); + bees.add(offspring); } if (!bees.isEmpty()) { @@ -579,7 +550,7 @@ public class Bee extends IndividualLiving implements IBee { } } - private IBee createOffspring(IBeeHousing housing, int generation) { + private IBee createOffspring(IBeeHousing housing, IBeeGenome mate, int generation) { World world = housing.getWorldObj(); @@ -588,7 +559,7 @@ public class Bee extends IndividualLiving implements IBee { IChromosome[] parent2 = mate.getChromosomes(); // Check for mutation. Replace one of the parents with the mutation - // template if mutation occured. + // template if mutation occurred. IChromosome[] mutated1 = mutateSpecies(housing, genome, mate); if (mutated1 != null) { parent1 = mutated1; @@ -608,6 +579,7 @@ public class Bee extends IndividualLiving implements IBee { return new Bee(new BeeGenome(chromosomes), mode.isNaturalOffspring(this), generation); } + @Nullable private static IChromosome[] mutateSpecies(IBeeHousing housing, IBeeGenome genomeOne, IBeeGenome genomeTwo) { World world = housing.getWorldObj(); @@ -665,6 +637,7 @@ public class Bee extends IndividualLiving implements IBee { /* FLOWERS */ @Override + @Nullable public IIndividual retrievePollen(IBeeHousing housing) { IBeeModifier beeModifier = BeeManager.beeRoot.createBeeHousingModifier(housing); diff --git a/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java b/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java index 7d64837f3..e5feba7ea 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java +++ b/src/main/java/forestry/apiculture/genetics/BeeAlyzerPlugin.java @@ -1,16 +1,9 @@ package forestry.apiculture.genetics; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; @@ -29,6 +22,11 @@ import forestry.core.gui.widgets.ItemStackWidget; import forestry.core.gui.widgets.WidgetManager; import forestry.core.utils.StringUtil; import forestry.core.utils.Translator; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class BeeAlyzerPlugin implements IAlyzerPlugin { public static final BeeAlyzerPlugin INSTANCE = new BeeAlyzerPlugin(); @@ -36,7 +34,7 @@ public class BeeAlyzerPlugin implements IAlyzerPlugin { protected final Map iconStacks = new HashMap<>(); private BeeAlyzerPlugin() { - ArrayList beeList = new ArrayList<>(); + NonNullList beeList = NonNullList.create(); PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); for (ItemStack beeStack : beeList) { IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); @@ -56,6 +54,9 @@ public class BeeAlyzerPlugin implements IAlyzerPlugin { return; } EnumBeeType type = BeeManager.beeRoot.getType(itemStack); + if (type == null) { + return; + } TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); diff --git a/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java b/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java index 1d2401f26..c0c1d1f13 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java +++ b/src/main/java/forestry/apiculture/genetics/BeeBranchDefinition.java @@ -1,5 +1,6 @@ package forestry.apiculture.genetics; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.Locale; @@ -7,7 +8,7 @@ import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.genetics.IAllele; import forestry.api.genetics.IClassification; -import forestry.apiculture.genetics.alleles.AlleleEffect; +import forestry.apiculture.genetics.alleles.AlleleEffects; import forestry.core.genetics.IBranchDefinition; import forestry.core.genetics.alleles.AlleleHelper; import forestry.core.genetics.alleles.EnumAllele; @@ -20,96 +21,96 @@ public enum BeeBranchDefinition implements IBranchDefinition { INFERNAL("Diapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.NETHER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.NETHER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.AVERAGE); } }, AUSTERE("Modapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.CACTI); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.CACTI); } }, TROPICAL("Caldapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.JUNGLE); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMiasmic); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.JUNGLE); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.EFFECT, AlleleEffects.effectMiasmic); } }, END("Finapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.END); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectMisanthrope); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.END); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.EFFECT, AlleleEffects.effectMisanthrope); } }, FROZEN("Coagapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.SNOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectGlacial); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.SNOW); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.EFFECT, AlleleEffects.effectGlacial); } }, VENGEFUL("Punapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGEST); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.EFFECT, AlleleEffect.effectRadioactive); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGEST); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.EFFECT, AlleleEffects.effectRadioactive); } }, FESTIVE("Festapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); } }, AGRARIAN("Rustapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); } }, BOGGY("Paludapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.MUSHROOMS); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.MUSHROOMS); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); } }, MONASTIC("Monapis") { @Override protected void setBranchProperties(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.CAVE_DWELLING, true); - AlleleHelper.instance.set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.LOW); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTER); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.getInstance().set(alleles, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.WHEAT); } }; @@ -135,24 +136,25 @@ public enum BeeBranchDefinition implements IBranchDefinition { return branch; } + @Nullable private static IAllele[] defaultTemplate; private static IAllele[] getDefaultTemplate() { if (defaultTemplate == null) { defaultTemplate = new IAllele[EnumBeeChromosome.values().length]; - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.NORMAL); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.NEVER_SLEEPS, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TOLERATES_RAIN, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.CAVE_DWELLING, false); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumBeeChromosome.EFFECT, AlleleEffect.effectNone); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.NORMAL); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.NEVER_SLEEPS, false); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.TOLERATES_RAIN, false); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.CAVE_DWELLING, false); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWEST); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); + AlleleHelper.getInstance().set(defaultTemplate, EnumBeeChromosome.EFFECT, AlleleEffects.effectNone); } return Arrays.copyOf(defaultTemplate, defaultTemplate.length); } diff --git a/src/main/java/forestry/apiculture/genetics/BeeDefinition.java b/src/main/java/forestry/apiculture/genetics/BeeDefinition.java index 7df6c49c6..259afceb3 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeDefinition.java +++ b/src/main/java/forestry/apiculture/genetics/BeeDefinition.java @@ -10,18 +10,12 @@ ******************************************************************************/ package forestry.apiculture.genetics; +import javax.annotation.Nullable; import java.awt.Color; import java.util.Arrays; import java.util.EnumSet; import java.util.Locale; -import org.apache.commons.lang3.text.WordUtils; - -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.common.MinecraftForge; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; @@ -35,13 +29,18 @@ import forestry.api.core.EnumTemperature; import forestry.api.genetics.AlleleSpeciesRegisterEvent; import forestry.api.genetics.IAllele; import forestry.apiculture.PluginApiculture; -import forestry.apiculture.genetics.alleles.AlleleEffect; +import forestry.apiculture.genetics.alleles.AlleleEffects; import forestry.apiculture.items.EnumHoneyComb; import forestry.apiculture.items.EnumPollenCluster; import forestry.core.PluginCore; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleHelper; import forestry.core.genetics.alleles.EnumAllele; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.common.MinecraftForge; +import org.apache.commons.lang3.text.WordUtils; public enum BeeDefinition implements IBeeDefinition { /* HONEY BRANCH */ @@ -53,8 +52,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.HIGH); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.HIGH); } @Override @@ -70,7 +69,7 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOWER); } @Override @@ -86,7 +85,7 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); } @Override @@ -108,8 +107,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.FAST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.FAST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); } @Override @@ -129,9 +128,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); } @Override @@ -147,9 +146,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); } @Override @@ -167,9 +166,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectBeatific); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectBeatific); } @Override @@ -187,9 +186,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.SLOW); } @Override @@ -205,8 +204,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTENED); } @Override @@ -224,9 +223,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FAST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FAST); } @Override @@ -245,10 +244,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.CAVE_DWELLING, true); } @Override @@ -265,10 +264,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.CAVE_DWELLING, true); } @Override @@ -285,11 +284,11 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.CAVE_DWELLING, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectHeroic); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.CAVE_DWELLING, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectHeroic); } @Override @@ -310,9 +309,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectAggressive); } @Override @@ -334,9 +333,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectAggressive); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectAggressive); } @Override @@ -359,9 +358,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectIgnition); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectIgnition); } @Override @@ -382,8 +381,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } @Override @@ -401,8 +400,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); } @Override @@ -427,10 +426,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectCreeper); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_2); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectCreeper); } @Override @@ -452,8 +451,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } @Override @@ -471,8 +470,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONG); } @Override @@ -491,10 +490,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); - AlleleHelper.instance.set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectExploration); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectExploration); } @Override @@ -530,7 +529,7 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectReanimation); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectReanimation); } @Override @@ -548,9 +547,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectResurrection); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectResurrection); } @Override @@ -569,9 +568,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); } @Override @@ -589,8 +588,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } @Override @@ -610,8 +609,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } @Override @@ -631,8 +630,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); } @Override @@ -649,8 +648,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.NORMAL); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGER); } @Override @@ -669,8 +668,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOWEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.LIFESPAN, EnumAllele.Lifespan.LONGEST); } @Override @@ -692,7 +691,7 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFestiveEaster); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectFestiveEaster); } @Override @@ -720,8 +719,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectSnowing); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectSnowing); } @Override @@ -749,8 +748,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectDrunkard); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectDrunkard); } @Override @@ -782,9 +781,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERATES_RAIN, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.GOURD); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TOLERATES_RAIN, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.GOURD); } @Override @@ -827,8 +826,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); } @Override @@ -846,10 +845,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(template, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_2); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectFertile); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.BOTH_2); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectFertile); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGE); } @Override @@ -886,9 +885,9 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERATES_RAIN, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FERTILITY, EnumAllele.Fertility.MAXIMUM); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TOLERATES_RAIN, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); } @Override @@ -908,10 +907,10 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERATES_RAIN, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.NEVER_SLEEPS, true); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectMycophilic); - AlleleHelper.instance.set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGER); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TOLERATES_RAIN, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.NEVER_SLEEPS, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectMycophilic); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TERRITORY, EnumAllele.Territory.LARGER); } @Override @@ -950,7 +949,7 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); } @Override @@ -968,8 +967,8 @@ public enum BeeDefinition implements IBeeDefinition { @Override protected void setAlleles(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); - AlleleHelper.instance.set(template, EnumBeeChromosome.EFFECT, AlleleEffect.effectRepulsion); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.FLOWERING, EnumAllele.Flowering.FASTEST); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.EFFECT, AlleleEffects.effectRepulsion); } @Override @@ -983,7 +982,9 @@ public enum BeeDefinition implements IBeeDefinition { private final BeeBranchDefinition branch; private final IAlleleBeeSpecies species; + @Nullable private IAllele[] template; + @Nullable private IBeeGenome genome; BeeDefinition(BeeBranchDefinition branch, String binomial, boolean dominant, Color primary, Color secondary) { @@ -1029,7 +1030,7 @@ public enum BeeDefinition implements IBeeDefinition { private void init() { template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumBeeChromosome.SPECIES, species); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.SPECIES, species); setAlleles(template); genome = BeeManager.beeRoot.templateAsGenome(template); diff --git a/src/main/java/forestry/apiculture/genetics/BeeGenome.java b/src/main/java/forestry/apiculture/genetics/BeeGenome.java index 5311d3c30..c4d98a704 100755 --- a/src/main/java/forestry/apiculture/genetics/BeeGenome.java +++ b/src/main/java/forestry/apiculture/genetics/BeeGenome.java @@ -10,9 +10,9 @@ ******************************************************************************/ package forestry.apiculture.genetics; -import javax.annotation.Nonnull; import java.util.concurrent.TimeUnit; +import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -60,16 +60,12 @@ public class BeeGenome extends Genome implements IBeeGenome { .expireAfterAccess(1, TimeUnit.MINUTES) .build(new CacheLoader() { @Override - public BeeGenome load(@Nonnull NBTTagCompound tagCompound) { + public BeeGenome load(NBTTagCompound tagCompound) { return new BeeGenome(tagCompound); } }); public static BeeGenome fromNBT(NBTTagCompound nbtTagCompound) { - if (nbtTagCompound == null) { - return null; - } - return beeGenomeCache.getUnchecked(nbtTagCompound); } @@ -84,9 +80,7 @@ public class BeeGenome extends Genome implements IBeeGenome { // NBT RETRIEVAL public static IAlleleBeeSpecies getSpecies(ItemStack itemStack) { - if (!BeeManager.beeRoot.isMember(itemStack)) { - return null; - } + Preconditions.checkArgument(BeeManager.beeRoot.isMember(itemStack), "itemStack must be a bee"); IAlleleSpecies species = getSpeciesDirectly(BeeManager.beeRoot, itemStack); if (species instanceof IAlleleBeeSpecies) { @@ -98,13 +92,11 @@ public class BeeGenome extends Genome implements IBeeGenome { // / INFORMATION RETRIEVAL @Override - @Nonnull public IAlleleBeeSpecies getPrimary() { return (IAlleleBeeSpecies) getActiveAllele(EnumBeeChromosome.SPECIES); } @Override - @Nonnull public IAlleleBeeSpecies getSecondary() { return (IAlleleBeeSpecies) getInactiveAllele(EnumBeeChromosome.SPECIES); } @@ -170,7 +162,6 @@ public class BeeGenome extends Genome implements IBeeGenome { } @Override - @Nonnull public ISpeciesRoot getSpeciesRoot() { return BeeManager.beeRoot; } diff --git a/src/main/java/forestry/apiculture/genetics/BeeRoot.java b/src/main/java/forestry/apiculture/genetics/BeeRoot.java index b5f80c505..4006c111c 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeRoot.java +++ b/src/main/java/forestry/apiculture/genetics/BeeRoot.java @@ -17,6 +17,7 @@ import java.util.List; import java.util.Locale; import java.util.Map.Entry; +import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeChromosome; @@ -44,6 +45,7 @@ import forestry.apiculture.BeeHousingListener; import forestry.apiculture.BeeHousingModifier; import forestry.apiculture.BeekeepingLogic; import forestry.apiculture.PluginApiculture; +import forestry.apiculture.items.ItemRegistryApiculture; import forestry.core.genetics.SpeciesRoot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -54,8 +56,16 @@ import net.minecraftforge.fml.common.FMLCommonHandler; public class BeeRoot extends SpeciesRoot implements IBeeRoot { private static int beeSpeciesCount = -1; + private static final List beeTemplates = new ArrayList<>(); + /** List of possible mutations on species alleles. */ + private static final List beeMutations = new ArrayList<>(); public static final String UID = "rootBees"; + private final List beekeepingModes = new ArrayList<>(); + + @Nullable + private static IBeekeepingMode activeBeekeepingMode; + @Override public String getUID() { return UID; @@ -99,31 +109,29 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { @Override public ItemStack getMemberStack(IIndividual individual, ISpeciesType type) { - if (!isMember(individual)) { - return null; - } - IBee bee = (IBee) individual; - if (!(type instanceof EnumBeeType)) { - return null; - } + Preconditions.checkArgument(individual instanceof IBee, "individual is not a bee"); + Preconditions.checkArgument(type instanceof EnumBeeType, "type is not an EnumBeeType"); + ItemRegistryApiculture apicultureItems = PluginApiculture.items; + Preconditions.checkState(apicultureItems != null, "Apiculture items are null"); + IBee bee = (IBee) individual; Item beeItem; switch ((EnumBeeType) type) { case QUEEN: - beeItem = PluginApiculture.items.beeQueenGE; + beeItem = apicultureItems.beeQueenGE; // ensure a queen is always mated if (bee.getMate() == null) { bee.mate(bee); } break; case PRINCESS: - beeItem = PluginApiculture.items.beePrincessGE; + beeItem = apicultureItems.beePrincessGE; break; case DRONE: - beeItem = PluginApiculture.items.beeDroneGE; + beeItem = apicultureItems.beeDroneGE; break; case LARVAE: - beeItem = PluginApiculture.items.beeLarvaeGE; + beeItem = apicultureItems.beeLarvaeGE; break; default: throw new RuntimeException("Cannot instantiate a bee of type " + type); @@ -139,19 +147,17 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { @Nullable @Override public EnumBeeType getType(ItemStack stack) { - if (stack == null) { - return null; - } - Item item = stack.getItem(); + ItemRegistryApiculture apicultureItems = PluginApiculture.items; + Preconditions.checkState(apicultureItems != null, "Apiculture items are null"); - if (PluginApiculture.items.beeDroneGE == item) { + if (apicultureItems.beeDroneGE == item) { return EnumBeeType.DRONE; - } else if (PluginApiculture.items.beePrincessGE == item) { + } else if (apicultureItems.beePrincessGE == item) { return EnumBeeType.PRINCESS; - } else if (PluginApiculture.items.beeQueenGE == item) { + } else if (apicultureItems.beeQueenGE == item) { return EnumBeeType.QUEEN; - } else if (PluginApiculture.items.beeLarvaeGE == item) { + } else if (apicultureItems.beeLarvaeGE == item) { return EnumBeeType.LARVAE; } @@ -180,9 +186,8 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { @Override public IBee getMember(ItemStack stack) { - if (!isMember(stack) || !stack.hasTagCompound()) { - return null; - } + Preconditions.checkArgument(isMember(stack), "ItemStack must be a bee."); + Preconditions.checkArgument(stack.getTagCompound() != null, "ItemStack must have a tag compound."); return new Bee(stack.getTagCompound()); } @@ -225,10 +230,8 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { } /* TEMPLATES */ - private static final ArrayList beeTemplates = new ArrayList<>(); - @Override - public ArrayList getIndividualTemplates() { + public List getIndividualTemplates() { return beeTemplates; } @@ -246,11 +249,6 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { } /* MUTATIONS */ - /** - * List of possible mutations on species alleles. - */ - private static final List beeMutations = new ArrayList<>(); - @Override public List getMutations(boolean shuffle) { if (shuffle) { @@ -275,16 +273,13 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { } /* BREEDING MODES */ - private final ArrayList beekeepingModes = new ArrayList<>(); - private static IBeekeepingMode activeBeekeepingMode; - @Override public void resetBeekeepingMode() { activeBeekeepingMode = null; } @Override - public ArrayList getBeekeepingModes() { + public List getBeekeepingModes() { return this.beekeepingModes; } @@ -331,14 +326,14 @@ public class BeeRoot extends SpeciesRoot implements IBeeRoot { } @Override - public IApiaristTracker getBreedingTracker(World world, GameProfile player) { + public IApiaristTracker getBreedingTracker(World world, @Nullable GameProfile player) { String filename = "ApiaristTracker." + (player == null ? "common" : player.getId()); - ApiaristTracker tracker = (ApiaristTracker) world.loadItemData(ApiaristTracker.class, filename); + ApiaristTracker tracker = (ApiaristTracker) world.loadData(ApiaristTracker.class, filename); // Create a tracker if there is none yet. if (tracker == null) { tracker = new ApiaristTracker(filename); - world.setItemData(filename, tracker); + world.setData(filename, tracker); } tracker.setUsername(player); diff --git a/src/main/java/forestry/apiculture/genetics/BeeVariation.java b/src/main/java/forestry/apiculture/genetics/BeeVariation.java index 686e38a47..ed37c214e 100644 --- a/src/main/java/forestry/apiculture/genetics/BeeVariation.java +++ b/src/main/java/forestry/apiculture/genetics/BeeVariation.java @@ -51,7 +51,7 @@ public abstract class BeeVariation implements IBeeDefinition { @Override protected void initializeTemplate(IAllele[] template) { - AlleleHelper.instance.set(template, EnumBeeChromosome.TOLERATES_RAIN, true); + AlleleHelper.getInstance().set(template, EnumBeeChromosome.TOLERATES_RAIN, true); } } } diff --git a/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java b/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java index c20c8621e..f849d087f 100755 --- a/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java +++ b/src/main/java/forestry/apiculture/genetics/BeekeepingMode.java @@ -11,6 +11,7 @@ package forestry.apiculture.genetics; import java.util.ArrayList; +import java.util.List; import java.util.Locale; import java.util.Random; @@ -53,8 +54,8 @@ public class BeekeepingMode implements IBeekeepingMode { } @Override - public ArrayList getDescription() { - ArrayList ret = new ArrayList<>(); + public List getDescription() { + List ret = new ArrayList<>(); ret.add("beemode." + name.toLowerCase(Locale.ENGLISH) + ".desc"); return ret; } diff --git a/src/main/java/forestry/apiculture/genetics/DefaultBeeModelProvider.java b/src/main/java/forestry/apiculture/genetics/DefaultBeeModelProvider.java index 8a5025083..9934b337c 100644 --- a/src/main/java/forestry/apiculture/genetics/DefaultBeeModelProvider.java +++ b/src/main/java/forestry/apiculture/genetics/DefaultBeeModelProvider.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.genetics; +import javax.annotation.Nullable; import java.util.Locale; import net.minecraft.client.renderer.block.model.ModelBakery; @@ -34,6 +35,7 @@ public class DefaultBeeModelProvider implements IBeeModelProvider { } @SideOnly(Side.CLIENT) + @Nullable private static ModelResourceLocation[] models; @Override diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java index 6208b09b1..1e9b97f5d 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleBeeSpecies.java @@ -76,8 +76,8 @@ public class AlleleBeeSpecies extends AlleleSpecies implements IAlleleBeeSpecies @Override public IAlleleBeeSpeciesBuilder addProduct(ItemStack product, Float chance) { - if (product == null || product.getItem() == null) { - throw new IllegalArgumentException("Tried to add null product"); + if (product.isEmpty()) { + throw new IllegalArgumentException("Tried to add empty product"); } if (chance <= 0.0f || chance > 1.0f) { throw new IllegalArgumentException("chance must be in the range (0, 1]"); @@ -88,8 +88,8 @@ public class AlleleBeeSpecies extends AlleleSpecies implements IAlleleBeeSpecies @Override public IAlleleBeeSpeciesBuilder addSpecialty(ItemStack specialty, Float chance) { - if (specialty == null || specialty.getItem() == null) { - throw new IllegalArgumentException("Tried to add null specialty"); + if (specialty.isEmpty()) { + throw new IllegalArgumentException("Tried to add empty specialty"); } if (chance <= 0.0f || chance > 1.0f) { throw new IllegalArgumentException("chance must be in the range (0, 1]"); diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java index 5476b6f2f..7d6d3e860 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffect.java @@ -10,86 +10,32 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; -import java.util.Arrays; import java.util.List; -import net.minecraft.entity.Entity; -import net.minecraft.init.MobEffects; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3i; - import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.IAlleleBeeEffect; import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeModifier; import forestry.api.apiculture.IBeekeepingLogic; -import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IEffectData; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleCategorized; import forestry.core.proxy.Proxies; import forestry.core.utils.VectUtil; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3i; public abstract class AlleleEffect extends AlleleCategorized implements IAlleleBeeEffect { - - public static IAlleleBeeEffect effectNone; - public static IAlleleBeeEffect effectAggressive; - public static IAlleleBeeEffect effectHeroic; - public static IAlleleBeeEffect effectBeatific; - public static IAlleleBeeEffect effectMiasmic; - public static IAlleleBeeEffect effectMisanthrope; - public static IAlleleBeeEffect effectGlacial; - public static IAlleleBeeEffect effectRadioactive; - public static IAlleleBeeEffect effectCreeper; - public static IAlleleBeeEffect effectIgnition; - public static IAlleleBeeEffect effectExploration; - public static IAlleleBeeEffect effectFestiveEaster; - public static IAlleleBeeEffect effectSnowing; - public static IAlleleBeeEffect effectDrunkard; - public static IAlleleBeeEffect effectReanimation; - public static IAlleleBeeEffect effectResurrection; - public static IAlleleBeeEffect effectRepulsion; - public static IAlleleBeeEffect effectFertile; - public static IAlleleBeeEffect effectMycophilic; - - public static void createAlleles() { - List beeEffects = Arrays.asList( - effectNone = new AlleleEffectNone("none", true), - effectAggressive = new AlleleEffectAggressive(), - effectHeroic = new AlleleEffectHeroic(), - effectBeatific = new AlleleEffectPotion("beatific", false, MobEffects.REGENERATION, 100), - effectMiasmic = new AlleleEffectPotion("miasmic", false, MobEffects.POISON, 600, 100, 0.1f), - effectMisanthrope = new AlleleEffectMisanthrope(), - effectGlacial = new AlleleEffectGlacial(), - effectRadioactive = new AlleleEffectRadioactive(), - effectCreeper = new AlleleEffectCreeper(), - effectIgnition = new AlleleEffectIgnition(), - effectExploration = new AlleleEffectExploration(), - effectFestiveEaster = new AlleleEffectNone("festiveEaster", true), - effectSnowing = new AlleleEffectSnowing(), - effectDrunkard = new AlleleEffectPotion("drunkard", false, MobEffects.NAUSEA, 100), - effectReanimation = new AlleleEffectResurrection("reanimation", AlleleEffectResurrection.getReanimationList()), - effectResurrection = new AlleleEffectResurrection("resurrection", AlleleEffectResurrection.getResurrectionList()), - effectRepulsion = new AlleleEffectRepulsion(), - effectFertile = new AlleleEffectFertile(), - effectMycophilic = new AlleleEffectFungification() - ); - - for (IAlleleBeeEffect beeEffect : beeEffects) { - AlleleManager.alleleRegistry.registerAllele(beeEffect, EnumBeeChromosome.EFFECT); - } - } - protected AlleleEffect(String valueName, boolean isDominant) { super(Constants.MOD_ID, "effect", valueName, isDominant); } @Override public IEffectData validateStorage(IEffectData storedData) { - return null; + return storedData; } @Override diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java index ca0c79a19..2547ecc18 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectCreeper.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.entity.player.EntityPlayer; diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java index f8cdc9272..45260dfab 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectFungification.java @@ -1,5 +1,6 @@ package forestry.apiculture.genetics.alleles; +import javax.annotation.Nullable; import java.util.List; import forestry.api.apiculture.IBeeGenome; @@ -105,14 +106,14 @@ public class AlleleEffectFungification extends AlleleEffectThrottled { if (cow instanceof EntityMooshroom) { return false; } - World worldObj = cow.worldObj; + World world = cow.world; cow.setDead(); - EntityMooshroom mooshroom = new EntityMooshroom(worldObj); + EntityMooshroom mooshroom = new EntityMooshroom(world); mooshroom.setLocationAndAngles(cow.posX, cow.posY, cow.posZ, cow.rotationYaw, cow.rotationPitch); mooshroom.setHealth(cow.getHealth()); mooshroom.renderYawOffset = cow.renderYawOffset; - worldObj.spawnEntityInWorld(mooshroom); - worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, cow.posX, cow.posY + cow.height / 2.0F, cow.posZ, 0.0D, 0.0D, 0.0D); + world.spawnEntity(mooshroom); + world.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, cow.posX, cow.posY + cow.height / 2.0F, cow.posZ, 0.0D, 0.0D, 0.0D); return true; } } diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java index b3feac440..1956ee006 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectResurrection.java @@ -101,9 +101,9 @@ public class AlleleEffectResurrection extends AlleleEffectThrottled { ItemStack contained = entity.getEntityItem(); for (Resurrectable entry : resurrectables) { if (ItemStackUtil.isIdenticalItem(entry.res, contained)) { - EntityUtil.spawnEntity(entity.worldObj, entry.risen, entity.posX, entity.posY, entity.posZ); - contained.stackSize--; - if (contained.stackSize <= 0) { + EntityUtil.spawnEntity(entity.world, entry.risen, entity.posX, entity.posY, entity.posZ); + contained.shrink(1); + if (contained.getCount() <= 0) { entity.setDead(); } return true; diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java index 6d047ebbc..a2e9ec313 100644 --- a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffectThrottled.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.apiculture.genetics.alleles; +import javax.annotation.Nullable; + import forestry.api.apiculture.IBeeGenome; import forestry.api.apiculture.IBeeHousing; import forestry.api.genetics.IEffectData; diff --git a/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffects.java b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffects.java new file mode 100644 index 000000000..a78125aec --- /dev/null +++ b/src/main/java/forestry/apiculture/genetics/alleles/AlleleEffects.java @@ -0,0 +1,62 @@ +package forestry.apiculture.genetics.alleles; + +import java.util.Arrays; +import java.util.List; + +import forestry.api.apiculture.EnumBeeChromosome; +import forestry.api.apiculture.IAlleleBeeEffect; +import forestry.api.genetics.AlleleManager; +import net.minecraft.init.MobEffects; + +public class AlleleEffects { + public static final IAlleleBeeEffect effectNone; + public static final IAlleleBeeEffect effectAggressive; + public static final IAlleleBeeEffect effectHeroic; + public static final IAlleleBeeEffect effectBeatific; + public static final IAlleleBeeEffect effectMiasmic; + public static final IAlleleBeeEffect effectMisanthrope; + public static final IAlleleBeeEffect effectGlacial; + public static final IAlleleBeeEffect effectRadioactive; + public static final IAlleleBeeEffect effectCreeper; + public static final IAlleleBeeEffect effectIgnition; + public static final IAlleleBeeEffect effectExploration; + public static final IAlleleBeeEffect effectFestiveEaster; + public static final IAlleleBeeEffect effectSnowing; + public static final IAlleleBeeEffect effectDrunkard; + public static final IAlleleBeeEffect effectReanimation; + public static final IAlleleBeeEffect effectResurrection; + public static final IAlleleBeeEffect effectRepulsion; + public static final IAlleleBeeEffect effectFertile; + public static final IAlleleBeeEffect effectMycophilic; + private static final List beeEffects; + + static { + beeEffects = Arrays.asList( + effectNone = new AlleleEffectNone("none", true), + effectAggressive = new AlleleEffectAggressive(), + effectHeroic = new AlleleEffectHeroic(), + effectBeatific = new AlleleEffectPotion("beatific", false, MobEffects.REGENERATION, 100), + effectMiasmic = new AlleleEffectPotion("miasmic", false, MobEffects.POISON, 600, 100, 0.1f), + effectMisanthrope = new AlleleEffectMisanthrope(), + effectGlacial = new AlleleEffectGlacial(), + effectRadioactive = new AlleleEffectRadioactive(), + effectCreeper = new AlleleEffectCreeper(), + effectIgnition = new AlleleEffectIgnition(), + effectExploration = new AlleleEffectExploration(), + effectFestiveEaster = new AlleleEffectNone("festiveEaster", true), + effectSnowing = new AlleleEffectSnowing(), + effectDrunkard = new AlleleEffectPotion("drunkard", false, MobEffects.NAUSEA, 100), + effectReanimation = new AlleleEffectResurrection("reanimation", AlleleEffectResurrection.getReanimationList()), + effectResurrection = new AlleleEffectResurrection("resurrection", AlleleEffectResurrection.getResurrectionList()), + effectRepulsion = new AlleleEffectRepulsion(), + effectFertile = new AlleleEffectFertile(), + effectMycophilic = new AlleleEffectFungification() + ); + } + + public static void registerAlleles() { + for (IAlleleBeeEffect beeEffect : beeEffects) { + AlleleManager.alleleRegistry.registerAllele(beeEffect, EnumBeeChromosome.EFFECT); + } + } +} diff --git a/src/main/java/forestry/apiculture/genetics/alleles/package-info.java b/src/main/java/forestry/apiculture/genetics/alleles/package-info.java new file mode 100644 index 000000000..23cca36ee --- /dev/null +++ b/src/main/java/forestry/apiculture/genetics/alleles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.genetics.alleles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/genetics/package-info.java b/src/main/java/forestry/apiculture/genetics/package-info.java new file mode 100644 index 000000000..82ba47c72 --- /dev/null +++ b/src/main/java/forestry/apiculture/genetics/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.genetics; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java index 4830e446d..9a72da8a4 100755 --- a/src/main/java/forestry/apiculture/gui/ContainerImprinter.java +++ b/src/main/java/forestry/apiculture/gui/ContainerImprinter.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.apiculture.gui; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; - import forestry.apiculture.inventory.ItemInventoryImprinter; import forestry.apiculture.network.packets.PacketImprintSelectionResponse; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.IGuiSelectable; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; -import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; public class ContainerImprinter extends ContainerItemInventory implements IGuiSelectable { @@ -34,15 +32,15 @@ public class ContainerImprinter extends ContainerItemInventory { private static final LinkedListMultimap habitats = LinkedListMultimap.create(); @@ -89,9 +84,10 @@ public class GuiHabitatLocator extends GuiForestry activeBiomeTypes = EnumSet.noneOf(BiomeDictionary.Type.class); + Set activeBiomeTypes = new HashSet<>(); for (Biome biome : inventory.getBiomesToSearch()) { - Collections.addAll(activeBiomeTypes, BiomeDictionary.getTypesForBiome(biome)); + Set biomeTypes = BiomeDictionary.getTypes(biome); + activeBiomeTypes.addAll(biomeTypes); } for (HabitatSlot habitatSlot : habitatSlots) { diff --git a/src/main/java/forestry/apiculture/gui/GuiImprinter.java b/src/main/java/forestry/apiculture/gui/GuiImprinter.java index 07074a10f..fc12d1630 100755 --- a/src/main/java/forestry/apiculture/gui/GuiImprinter.java +++ b/src/main/java/forestry/apiculture/gui/GuiImprinter.java @@ -11,14 +11,9 @@ package forestry.apiculture.gui; import java.io.IOException; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.apiculture.PluginApiculture; import forestry.apiculture.genetics.BeeGenome; @@ -30,6 +25,9 @@ import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public class GuiImprinter extends GuiForestry { @@ -44,7 +42,7 @@ public class GuiImprinter extends GuiForestry beeList = new ArrayList<>(); + NonNullList beeList = NonNullList.create(); PluginApiculture.items.beeDroneGE.addCreativeItems(beeList, false); for (ItemStack beeStack : beeList) { IAlleleBeeSpecies species = BeeGenome.getSpecies(beeStack); diff --git a/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java b/src/main/java/forestry/apiculture/gui/HabitatSlot.java similarity index 74% rename from src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java rename to src/main/java/forestry/apiculture/gui/HabitatSlot.java index b99854873..45c67430f 100644 --- a/src/main/java/forestry/apiculture/gui/widgets/HabitatSlot.java +++ b/src/main/java/forestry/apiculture/gui/HabitatSlot.java @@ -1,75 +1,68 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.gui.widgets; - -import javax.annotation.Nonnull; -import java.util.Collection; -import java.util.Collections; -import java.util.Locale; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.core.render.TextureManager; - -public class HabitatSlot extends Widget { - @Nonnull - private final Collection biomes; - @Nonnull - private final String name; - @Nonnull - private final String iconIndex; - public boolean isActive = false; - - public HabitatSlot(@Nonnull WidgetManager widgetManager, int xPos, int yPos, @Nonnull String name, @Nonnull Collection biomes) { - super(widgetManager, xPos, yPos); - this.biomes = biomes; - this.name = name; - this.iconIndex = "habitats/" + name.toLowerCase(Locale.ENGLISH); - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - ToolTip tooltip = new ToolTip(); - tooltip.add(name); - return tooltip; - } - - @SideOnly(Side.CLIENT) - public TextureAtlasSprite getIcon() { - return TextureManager.getInstance().getDefault(iconIndex); - } - - public void setActive(Collection biomes) { - isActive = !Collections.disjoint(this.biomes, biomes); - } - - @Override - public void draw(int startX, int startY) { - if (getIcon() != null) { - if (!isActive) { - GlStateManager.color(0.2f, 0.2f, 0.2f, 0.2f); - } else { - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - } - - Proxies.render.bindTexture(TextureManager.getInstance().getGuiTextureMap()); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, getIcon(), 16, 16); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.apiculture.gui; + +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; + +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.core.render.TextureManager; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +public class HabitatSlot extends Widget { + private final Collection biomes; + private final String name; + private final String iconIndex; + public boolean isActive = false; + + public HabitatSlot(WidgetManager widgetManager, int xPos, int yPos, String name, Collection biomes) { + super(widgetManager, xPos, yPos); + this.biomes = biomes; + this.name = name; + this.iconIndex = "habitats/" + name.toLowerCase(Locale.ENGLISH); + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + ToolTip tooltip = new ToolTip(); + tooltip.add(name); + return tooltip; + } + + @SideOnly(Side.CLIENT) + public TextureAtlasSprite getIcon() { + return TextureManager.getInstance().getDefault(iconIndex); + } + + public void setActive(Collection biomes) { + isActive = !Collections.disjoint(this.biomes, biomes); + } + + @Override + public void draw(int startX, int startY) { + if (!isActive) { + GlStateManager.color(0.2f, 0.2f, 0.2f, 0.2f); + } else { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + } + + Proxies.render.bindTexture(TextureManager.getInstance().getGuiTextureMap()); + manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, getIcon(), 16, 16); + } +} diff --git a/src/main/java/forestry/apiculture/gui/package-info.java b/src/main/java/forestry/apiculture/gui/package-info.java new file mode 100644 index 000000000..38cb8cb61 --- /dev/null +++ b/src/main/java/forestry/apiculture/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java index 7eb40d1de..74e048c73 100644 --- a/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java +++ b/src/main/java/forestry/apiculture/inventory/InventoryAlvearySieve.java @@ -34,12 +34,12 @@ public class InventoryAlvearySieve extends InventoryAdapterTile getBiomesToSearch() { @@ -98,7 +93,7 @@ public class ItemInventoryHabitatLocator extends ItemInventory implements IError /* IErrorSource */ @Override public ImmutableSet getErrorStates() { - if (getStackInSlot(SLOT_ANALYZED) != null) { + if (!getStackInSlot(SLOT_ANALYZED).isEmpty()) { return ImmutableSet.of(); } diff --git a/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java b/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java index 4bfa289c9..1af4e5903 100644 --- a/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java +++ b/src/main/java/forestry/apiculture/inventory/ItemInventoryImprinter.java @@ -10,15 +10,20 @@ ******************************************************************************/ package forestry.apiculture.inventory; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; +import java.util.List; +import java.util.Map; import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBee; +import forestry.api.apiculture.IBeeGenome; +import forestry.api.apiculture.IBeeRoot; +import forestry.api.genetics.IAllele; import forestry.apiculture.genetics.Bee; import forestry.core.inventory.ItemInventory; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class ItemInventoryImprinter extends ItemInventory { private static final short specimenSlot = 0; @@ -72,9 +77,13 @@ public class ItemInventoryImprinter extends ItemInventory { } public IBee getSelectedBee() { - return new Bee(BeeManager.beeRoot.templateAsGenome( - BeeManager.beeRoot.getGenomeTemplates().get(BeeManager.beeRoot.getIndividualTemplates().get(primaryIndex).getIdent()), - BeeManager.beeRoot.getGenomeTemplates().get(BeeManager.beeRoot.getIndividualTemplates().get(secondaryIndex).getIdent()))); + IBeeRoot beeRoot = BeeManager.beeRoot; + List individualTemplates = beeRoot.getIndividualTemplates(); + Map genomeTemplates = beeRoot.getGenomeTemplates(); + IAllele[] templateActive = genomeTemplates.get(individualTemplates.get(primaryIndex).getIdent()); + IAllele[] templateInactive = genomeTemplates.get(individualTemplates.get(secondaryIndex).getIdent()); + IBeeGenome genome = beeRoot.templateAsGenome(templateActive, templateInactive); + return new Bee(genome); } public int getPrimaryIndex() { @@ -96,7 +105,7 @@ public class ItemInventoryImprinter extends ItemInventory { @Override public void onSlotClick(int slotIndex, EntityPlayer player) { ItemStack specimen = getStackInSlot(specimenSlot); - if (specimen == null) { + if (specimen.isEmpty()) { return; } @@ -106,21 +115,18 @@ public class ItemInventoryImprinter extends ItemInventory { } // Needs space - if (getStackInSlot(imprintedSlot) != null) { + if (!getStackInSlot(imprintedSlot).isEmpty()) { return; } IBee imprint = getSelectedBee(); - if (imprint == null) { - return; - } NBTTagCompound nbttagcompound = new NBTTagCompound(); imprint.writeToNBT(nbttagcompound); specimen.setTagCompound(nbttagcompound); setInventorySlotContents(imprintedSlot, specimen); - setInventorySlotContents(specimenSlot, null); + setInventorySlotContents(specimenSlot, ItemStack.EMPTY); } @Override diff --git a/src/main/java/forestry/apiculture/inventory/package-info.java b/src/main/java/forestry/apiculture/inventory/package-info.java new file mode 100644 index 000000000..472adccc4 --- /dev/null +++ b/src/main/java/forestry/apiculture/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java b/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java index 61e754ce4..2a2359d5e 100644 --- a/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java +++ b/src/main/java/forestry/apiculture/items/HabitatLocatorLogic.java @@ -10,24 +10,22 @@ ******************************************************************************/ package forestry.apiculture.items; +import javax.annotation.Nullable; import java.util.Collection; -import java.util.Collections; import java.util.HashSet; import java.util.Set; +import forestry.api.apiculture.IBee; +import forestry.apiculture.network.packets.PacketHabitatBiomePointer; +import forestry.core.proxy.Proxies; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; - import net.minecraftforge.common.BiomeDictionary; -import forestry.api.apiculture.IBee; -import forestry.apiculture.network.packets.PacketHabitatBiomePointer; -import forestry.core.proxy.Proxies; - public class HabitatLocatorLogic { private static final int maxChecksPerTick = 100; private static final int maxSearchRadiusIterations = 500; @@ -39,19 +37,20 @@ public class HabitatLocatorLogic { private static final Set endBiomes = new HashSet<>(); static { - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.BEACH)); - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.OCEAN)); - Collections.addAll(waterBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.RIVER)); + waterBiomes.addAll(BiomeDictionary.getBiomes(BiomeDictionary.Type.BEACH)); + waterBiomes.addAll(BiomeDictionary.getBiomes(BiomeDictionary.Type.OCEAN)); + waterBiomes.addAll(BiomeDictionary.getBiomes(BiomeDictionary.Type.RIVER)); - Collections.addAll(netherBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.NETHER)); + netherBiomes.addAll(BiomeDictionary.getBiomes(BiomeDictionary.Type.NETHER)); - Collections.addAll(endBiomes, BiomeDictionary.getBiomesForType(BiomeDictionary.Type.END)); + endBiomes.addAll(BiomeDictionary.getBiomes(BiomeDictionary.Type.END)); } private Set targetBiomes = new HashSet<>(); private boolean biomeFound = false; private int searchRadiusIteration = 0; private int searchAngleIteration = 0; + @Nullable private BlockPos searchCenter; public boolean isBiomeFound() { @@ -69,7 +68,7 @@ public class HabitatLocatorLogic { this.biomeFound = false; this.searchCenter = player.getPosition(); - Biome currentBiome = player.worldObj.getBiome(searchCenter); + Biome currentBiome = player.world.getBiome(searchCenter); removeInvalidBiomes(currentBiome, targetBiomes); // reset the locator coordinates @@ -99,11 +98,16 @@ public class HabitatLocatorLogic { } } + @Nullable private BlockPos findNearestBiome(Entity player, Collection biomesToSearch) { + if (searchCenter == null) { + return null; + } + BlockPos playerPos = player.getPosition(); // If we are in a valid spot, we point to ourselves. - BlockPos coordinates = getChunkCoordinates(playerPos, player.worldObj, biomesToSearch); + BlockPos coordinates = getChunkCoordinates(playerPos, player.world, biomesToSearch); if (coordinates != null) { searchAngleIteration = 0; searchRadiusIteration = 0; @@ -139,7 +143,7 @@ public class HabitatLocatorLogic { int zOffset = Math.round((float) (radius * Math.sin(angle))); BlockPos pos = searchCenter.add(xOffset, 0, zOffset); - coordinates = getChunkCoordinates(pos, player.worldObj, biomesToSearch); + coordinates = getChunkCoordinates(pos, player.world, biomesToSearch); if (coordinates != null) { searchAngleIteration = 0; searchRadiusIteration = 0; @@ -150,6 +154,7 @@ public class HabitatLocatorLogic { return null; } + @Nullable private static BlockPos getChunkCoordinates(BlockPos pos, World world, Collection biomesToSearch) { Biome biome; @@ -185,13 +190,13 @@ public class HabitatLocatorLogic { biomesToSearch.removeAll(waterBiomes); - if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.NETHER)) { + if (BiomeDictionary.hasType(currentBiome, BiomeDictionary.Type.NETHER)) { biomesToSearch.retainAll(netherBiomes); } else { biomesToSearch.removeAll(netherBiomes); } - if (BiomeDictionary.isBiomeOfType(currentBiome, BiomeDictionary.Type.END)) { + if (BiomeDictionary.hasType(currentBiome, BiomeDictionary.Type.END)) { biomesToSearch.retainAll(endBiomes); } else { biomesToSearch.removeAll(endBiomes); diff --git a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java index 6817f72eb..0b6cbaba1 100755 --- a/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java +++ b/src/main/java/forestry/apiculture/items/ItemArmorApiarist.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.items; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.api.apiculture.ApicultureCapabilities; @@ -60,9 +59,9 @@ public class ItemArmorApiarist extends ItemArmor implements IItemModelRegister { return false; } - @Nonnull @Override - public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) { + @Nullable + public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return new ICapabilityProvider() { @Override public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { diff --git a/src/main/java/forestry/apiculture/items/ItemBeeGE.java b/src/main/java/forestry/apiculture/items/ItemBeeGE.java index 8d5f04026..f546ef75c 100755 --- a/src/main/java/forestry/apiculture/items/ItemBeeGE.java +++ b/src/main/java/forestry/apiculture/items/ItemBeeGE.java @@ -12,19 +12,7 @@ package forestry.apiculture.items; import java.util.List; -import net.minecraft.client.renderer.ItemMeshDefinition; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextFormatting; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.apiculture.BeeManager; -import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.apiculture.IBee; @@ -38,6 +26,16 @@ import forestry.core.config.Config; import forestry.core.genetics.ItemGE; import forestry.core.items.IColoredItem; import forestry.core.utils.Translator; +import net.minecraft.client.renderer.ItemMeshDefinition; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class ItemBeeGE extends ItemGE implements IColoredItem { @@ -63,7 +61,6 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { @Override public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack.getTagCompound() == null) { return super.getItemStackDisplayName(itemstack); } @@ -81,7 +78,7 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { @Override public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return; } @@ -98,11 +95,11 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { + addCreativeItems(subItems, true); } - public void addCreativeItems(List itemList, boolean hideSecrets) { + public void addCreativeItems(NonNullList subItems, boolean hideSecrets) { for (IBee bee : BeeManager.beeRoot.getIndividualTemplates()) { // Don't show secret bees unless ordered to. if (hideSecrets && bee.isSecret() && !Config.isDebug) { @@ -110,15 +107,15 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { } ItemStack beeStack = BeeManager.beeRoot.getMemberStack(bee, type); - if (beeStack != null) { - itemList.add(beeStack); + if (!beeStack.isEmpty()) { + subItems.add(beeStack); } } } @Override public int getColorFromItemstack(ItemStack itemstack, int tintIndex) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { if (tintIndex == 1) { return 0xffdc16; } else { @@ -127,26 +124,10 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { } IAlleleBeeSpecies species = BeeGenome.getSpecies(itemstack); - if (species instanceof IAlleleBeeSpecies) { - return species.getSpriteColour(tintIndex); - } else { - return 0xffffff; - } + return species.getSpriteColour(tintIndex); } /* MODELS */ - @SideOnly(Side.CLIENT) - @Override - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - - if (species instanceof IAlleleBeeSpecies) { - return species.getSpriteColour(renderPass); - } else { - return 0xffffff; - } - - } - @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { @@ -159,16 +140,11 @@ public class ItemBeeGE extends ItemGE implements IColoredItem { } private class BeeMeshDefinition implements ItemMeshDefinition { - @Override public ModelResourceLocation getModelLocation(ItemStack stack) { IAlleleBeeSpecies species = (IAlleleBeeSpecies) getSpecies(stack); - if (species == null) { - species = (IAlleleBeeSpecies) BeeManager.beeRoot.getDefaultTemplate()[EnumBeeChromosome.SPECIES.ordinal()]; - } return species.getModel(type); } - } public final EnumBeeType getType() { diff --git a/src/main/java/forestry/apiculture/items/ItemBlockCandle.java b/src/main/java/forestry/apiculture/items/ItemBlockCandle.java index f178c8fa6..e50a16d16 100644 --- a/src/main/java/forestry/apiculture/items/ItemBlockCandle.java +++ b/src/main/java/forestry/apiculture/items/ItemBlockCandle.java @@ -31,7 +31,7 @@ public class ItemBlockCandle extends ItemBlockForestry implements I @SideOnly(Side.CLIENT) public int getColorFromItemstack(ItemStack stack, int pass) { int value = 0xffffff; - if (pass == 1 && stack.hasTagCompound()) { + if (pass == 1 && stack.getTagCompound() != null) { NBTTagCompound tag = stack.getTagCompound(); if (tag.hasKey(BlockCandle.colourTagName)) { value = tag.getInteger(BlockCandle.colourTagName); @@ -43,7 +43,7 @@ public class ItemBlockCandle extends ItemBlockForestry implements I @Override public String getUnlocalizedName(ItemStack itemStack) { String value = getBlock().getUnlocalizedName(); - if (itemStack.hasTagCompound() && itemStack.getTagCompound().hasKey(BlockCandle.colourTagName)) { + if (itemStack.getTagCompound() != null && itemStack.getTagCompound().hasKey(BlockCandle.colourTagName)) { value = value + ".dyed"; } diff --git a/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java b/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java index aeddbe33f..6f084c671 100644 --- a/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java +++ b/src/main/java/forestry/apiculture/items/ItemHabitatLocator.java @@ -62,18 +62,18 @@ public class ItemHabitatLocator extends ItemWithGui implements ISpriteRegister { @SideOnly(Side.CLIENT) public void registerSprites(ITextureManager manager) { TextureAtlasSprite texture = new TextureHabitatLocator(iconName); - Minecraft.getMinecraft().getTextureMapBlocks().setTextureEntry(iconName, texture); + Minecraft.getMinecraft().getTextureMapBlocks().setTextureEntry(texture); } @Override public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { super.addInformation(itemstack, player, list, flag); - Biome currentBiome = player.worldObj.getBiome(player.getPosition()); + Biome currentBiome = player.world.getBiome(player.getPosition()); - float temperatureValue = ForestryAPI.climateManager.getTemperature(player.worldObj, player.getPosition()); + float temperatureValue = ForestryAPI.climateManager.getTemperature(player.world, player.getPosition()); EnumTemperature temperature = EnumTemperature.getFromValue(temperatureValue); - EnumHumidity humidity = EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(player.worldObj, player.getPosition())); + EnumHumidity humidity = EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(player.world, player.getPosition())); list.add(Translator.translateToLocal("for.gui.currentBiome") + ": " + currentBiome.getBiomeName()); list.add(Translator.translateToLocal("for.gui.temperature") + ": " + AlleleManager.climateHelper.toDisplay(temperature)); diff --git a/src/main/java/forestry/apiculture/items/ItemHiveFrame.java b/src/main/java/forestry/apiculture/items/ItemHiveFrame.java index f4ff25ca0..984d33fcf 100755 --- a/src/main/java/forestry/apiculture/items/ItemHiveFrame.java +++ b/src/main/java/forestry/apiculture/items/ItemHiveFrame.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.apiculture.items; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.entity.player.EntityPlayer; @@ -38,6 +39,7 @@ public class ItemHiveFrame extends ItemForestry implements IHiveFrame { } @Override + @Nullable public ItemStack frameUsed(IBeeHousing housing, ItemStack frame, IBee queen, int wear) { frame.setItemDamage(frame.getItemDamage() + wear); if (frame.getItemDamage() >= frame.getMaxDamage()) { diff --git a/src/main/java/forestry/apiculture/items/ItemHoneyComb.java b/src/main/java/forestry/apiculture/items/ItemHoneyComb.java index 5d9e161a9..bfa2105d9 100755 --- a/src/main/java/forestry/apiculture/items/ItemHoneyComb.java +++ b/src/main/java/forestry/apiculture/items/ItemHoneyComb.java @@ -10,22 +10,22 @@ ******************************************************************************/ package forestry.apiculture.items; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Random; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.core.IModelManager; import forestry.api.core.Tabs; import forestry.core.config.Config; import forestry.core.items.IColoredItem; import forestry.core.items.ItemForestry; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class ItemHoneyComb extends ItemForestry implements IColoredItem { public ItemHoneyComb() { @@ -51,7 +51,7 @@ public class ItemHoneyComb extends ItemForestry implements IColoredItem { manager.registerItemModel(item, i, "beecombs/" + EnumHoneyComb.VALUES[i].name); } } - + @Override public String getUnlocalizedName(ItemStack stack) { EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[stack.getItemDamage()]; @@ -59,15 +59,16 @@ public class ItemHoneyComb extends ItemForestry implements IColoredItem { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { EnumHoneyComb honeyComb = EnumHoneyComb.VALUES[i]; if (!honeyComb.isSecret() || Config.isDebug) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } } + @Nullable private static EnumHoneyComb getRandomCombType(Random random, boolean includeSecret) { List validCombs = new ArrayList<>(EnumHoneyComb.VALUES.length); for (int i = 0; i < EnumHoneyComb.VALUES.length; i++) { @@ -86,6 +87,9 @@ public class ItemHoneyComb extends ItemForestry implements IColoredItem { public ItemStack getRandomComb(int amount, Random random, boolean includeSecret) { EnumHoneyComb honeyComb = getRandomCombType(random, includeSecret); + if (honeyComb == null) { + return ItemStack.EMPTY; + } return get(honeyComb, amount); } diff --git a/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java b/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java index a46564a38..393eda088 100644 --- a/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java +++ b/src/main/java/forestry/apiculture/items/ItemMinecartBeehouse.java @@ -10,13 +10,16 @@ ******************************************************************************/ package forestry.apiculture.items; -import java.util.List; - +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.apiculture.entities.EntityMinecartApiary; +import forestry.apiculture.entities.EntityMinecartBeeHousingBase; +import forestry.apiculture.entities.EntityMinecartBeehouse; import net.minecraft.block.BlockDispenser; import net.minecraft.block.BlockRailBase; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.dispenser.IBehaviorDispenseItem; -import net.minecraft.dispenser.IBlockSource; +import net.minecraft.entity.item.EntityMinecart; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemMinecart; @@ -24,59 +27,51 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.apiculture.entities.EntityMinecartApiary; -import forestry.apiculture.entities.EntityMinecartBeeHousingBase; -import forestry.apiculture.entities.EntityMinecartBeehouse; - public class ItemMinecartBeehouse extends ItemMinecart implements IItemModelRegister { private final String[] definition = new String[]{"cart.beehouse", "cart.apiary"}; - - private static final IBehaviorDispenseItem dispenserMinecartBehavior = new IBehaviorDispenseItem() { - @Override - public ItemStack dispense(IBlockSource source, ItemStack stack) { - return stack; - } - }; + + private static final IBehaviorDispenseItem dispenserMinecartBehavior = (source, stack) -> stack; public ItemMinecartBeehouse() { - super(null); + super(EntityMinecart.Type.CHEST); setMaxDamage(0); setHasSubtypes(true); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(this, dispenserMinecartBehavior); } @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (!BlockRailBase.isRailBlock(worldIn.getBlockState(pos))) { return EnumActionResult.PASS; } + ItemStack stack = player.getHeldItem(hand); + if (!worldIn.isRemote) { EntityMinecartBeeHousingBase entityMinecart; + if (stack.getItemDamage() == 0) { entityMinecart = new EntityMinecartBeehouse(worldIn, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F); } else { entityMinecart = new EntityMinecartApiary(worldIn, pos.getX() + 0.5F, pos.getY() + 0.5F, pos.getZ() + 0.5F); } - entityMinecart.getOwnerHandler().setOwner(playerIn.getGameProfile()); + entityMinecart.getOwnerHandler().setOwner(player.getGameProfile()); if (stack.hasDisplayName()) { entityMinecart.setCustomNameTag(stack.getDisplayName()); } - worldIn.spawnEntityInWorld(entityMinecart); + worldIn.spawnEntity(entityMinecart); } - --stack.stackSize; + stack.shrink(1); return EnumActionResult.SUCCESS; } @@ -99,9 +94,9 @@ public class ItemMinecartBeehouse extends ItemMinecart implements IItemModelRegi } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < definition.length; i++) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } diff --git a/src/main/java/forestry/apiculture/items/ItemSmoker.java b/src/main/java/forestry/apiculture/items/ItemSmoker.java index e1b233bca..8217e0621 100644 --- a/src/main/java/forestry/apiculture/items/ItemSmoker.java +++ b/src/main/java/forestry/apiculture/items/ItemSmoker.java @@ -1,6 +1,5 @@ package forestry.apiculture.items; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.api.apiculture.ApicultureCapabilities; @@ -42,8 +41,8 @@ public class ItemSmoker extends ItemForestry { @Override public void onUsingTick(ItemStack stack, EntityLivingBase player, int count) { super.onUsingTick(stack, player, count); - World worldObj = player.worldObj; - addSmoke(stack, worldObj, player, (count % 5) + 1); + World world = player.world; + addSmoke(stack, world, player, (count % 5) + 1); } private static EnumHandSide getHandSide(ItemStack stack, Entity entity) { @@ -60,7 +59,7 @@ public class ItemSmoker extends ItemForestry { return EnumHandSide.RIGHT; } - private static void addSmoke(ItemStack stack, World worldObj, Entity entity, int distance) { + private static void addSmoke(ItemStack stack, World world, Entity entity, int distance) { if (distance <= 0) { return; } @@ -78,9 +77,9 @@ public class ItemSmoker extends ItemForestry { Vec3d scaledOffset = handOffset.scale(1.0 / distance); Vec3d smokePos = lookDistance.add(entity.getPositionVector()).add(scaledOffset); - Proxies.render.addEntitySmokeFX(worldObj, smokePos.xCoord, smokePos.yCoord + 1, smokePos.zCoord); + Proxies.render.addEntitySmokeFX(world, smokePos.xCoord, smokePos.yCoord + 1, smokePos.zCoord); BlockPos blockPos = new BlockPos(smokePos.xCoord, smokePos.yCoord + 1, smokePos.zCoord); - TileEntity tileEntity = worldObj.getTileEntity(blockPos); + TileEntity tileEntity = world.getTileEntity(blockPos); if (tileEntity instanceof IHiveTile) { IHiveTile hive = (IHiveTile) tileEntity; hive.calmBees(); @@ -88,19 +87,20 @@ public class ItemSmoker extends ItemForestry { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { - playerIn.setActiveHand(hand); - return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + playerIn.setActiveHand(handIn); + ItemStack itemStack = playerIn.getHeldItem(handIn); + return new ActionResult<>(EnumActionResult.SUCCESS, itemStack); } @Override - public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { + public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { TileEntity tileEntity = world.getTileEntity(pos); if (tileEntity instanceof IHiveTile) { IHiveTile hive = (IHiveTile) tileEntity; hive.calmBees(); } - return super.onItemUseFirst(stack, player, world, pos, side, hitX, hitY, hitZ, hand); + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); } @Override @@ -108,9 +108,8 @@ public class ItemSmoker extends ItemForestry { return 32; } - @Nonnull @Override - public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) { + public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return new ICapabilityProvider() { @Override public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { diff --git a/src/main/java/forestry/apiculture/items/ItemWaxCast.java b/src/main/java/forestry/apiculture/items/ItemWaxCast.java index 8a5f4ea9e..44906bafc 100755 --- a/src/main/java/forestry/apiculture/items/ItemWaxCast.java +++ b/src/main/java/forestry/apiculture/items/ItemWaxCast.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.apiculture.items; -import net.minecraft.item.ItemStack; - import forestry.api.core.Tabs; import forestry.core.items.ICraftingPlan; import forestry.core.items.ItemForestry; +import net.minecraft.item.ItemStack; public class ItemWaxCast extends ItemForestry implements ICraftingPlan { @@ -27,12 +26,8 @@ public class ItemWaxCast extends ItemForestry implements ICraftingPlan { @Override public ItemStack planUsed(ItemStack plan, ItemStack result) { - plan.setItemDamage(plan.getItemDamage() + result.stackSize); - if (plan.getItemDamage() >= plan.getMaxDamage()) { - return null; - } else { - return plan; - } + plan.setItemDamage(plan.getItemDamage() + result.getCount()); + return plan; } } diff --git a/src/main/java/forestry/apiculture/items/package-info.java b/src/main/java/forestry/apiculture/items/package-info.java new file mode 100644 index 000000000..21da7cdb5 --- /dev/null +++ b/src/main/java/forestry/apiculture/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java index d71863db5..539cec0c0 100644 --- a/src/main/java/forestry/apiculture/multiblock/AlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/AlvearyController.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.HashSet; import java.util.Set; @@ -36,8 +35,7 @@ import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.proxy.Proxies; import forestry.core.utils.BlockUtil; import forestry.core.utils.ClimateUtil; @@ -51,8 +49,6 @@ import net.minecraft.world.World; import net.minecraft.world.biome.Biome; public class AlvearyController extends RectangularMultiblockControllerBase implements IAlvearyControllerInternal, IClimateControlled { - - @Nonnull private final InventoryBeeHousing inventory; private final IBeekeepingLogic beekeepingLogic; @@ -76,7 +72,6 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple this.beeModifiers.add(new AlvearyBeeModifier()); } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return inventory; @@ -87,7 +82,6 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple return beekeepingLogic; } - @Nonnull @Override public IInventoryAdapter getInternalInventory() { if (isAssembled()) { @@ -175,9 +169,9 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple for (int slabX = minimumCoord.getX(); slabX <= maximumCoord.getX(); slabX++) { for (int slabZ = minimumCoord.getZ(); slabZ <= maximumCoord.getZ(); slabZ++) { BlockPos pos = new BlockPos(slabX, slabY, slabZ); - IBlockState state = worldObj.getBlockState(pos); + IBlockState state = world.getBlockState(pos); Block block = state.getBlock(); - if (!BlockUtil.isWoodSlabBlock(state, block, worldObj, pos)) { + if (!BlockUtil.isWoodSlabBlock(state, block, world, pos)) { throw new MultiblockValidationException(Translator.translateToLocal("for.multiblock.alveary.error.needSlabs")); } @@ -196,9 +190,8 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple if (isCoordInMultiblock(airX, airY, airZ)) { continue; } - IBlockState blockState = worldObj.getBlockState(new BlockPos(airX, airY, airZ)); - Block block = blockState.getBlock(); - if (block.isOpaqueCube(blockState)) { + IBlockState blockState = world.getBlockState(new BlockPos(airX, airY, airZ)); + if (blockState.isOpaqueCube()) { throw new MultiblockValidationException(Translator.translateToLocal("for.multiblock.alveary.error.needSpace")); } } @@ -278,15 +271,15 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple float fxZ = center.getZ() + 0.5F; float distanceFromCenter = 1.6F; - float leftRightSpreadFromCenter = distanceFromCenter * (worldObj.rand.nextFloat() - 0.5F); - float upSpread = worldObj.rand.nextFloat() * 0.8F; + float leftRightSpreadFromCenter = distanceFromCenter * (world.rand.nextFloat() - 0.5F); + float upSpread = world.rand.nextFloat() * 0.8F; fxY += upSpread; // display fx on all 4 sides - Proxies.render.addEntityHoneyDustFX(worldObj, fxX - distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); - Proxies.render.addEntityHoneyDustFX(worldObj, fxX + distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); - Proxies.render.addEntityHoneyDustFX(worldObj, fxX + leftRightSpreadFromCenter, fxY, fxZ - distanceFromCenter); - Proxies.render.addEntityHoneyDustFX(worldObj, fxX + leftRightSpreadFromCenter, fxY, fxZ + distanceFromCenter); + Proxies.render.addEntityHoneyDustFX(world, fxX - distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); + Proxies.render.addEntityHoneyDustFX(world, fxX + distanceFromCenter, fxY, fxZ + leftRightSpreadFromCenter); + Proxies.render.addEntityHoneyDustFX(world, fxX + leftRightSpreadFromCenter, fxY, fxZ - distanceFromCenter); + Proxies.render.addEntityHoneyDustFX(world, fxX + leftRightSpreadFromCenter, fxY, fxZ + distanceFromCenter); } } } @@ -383,30 +376,30 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple @Override public Biome getBiome() { BlockPos coords = getReferenceCoord(); - return worldObj.getBiome(coords); + return world.getBiome(coords); } @Override public int getBlockLightValue() { BlockPos topCenter = getTopCenterCoord(); - return worldObj.getLightFromNeighbors(topCenter.up()); + return world.getLightFromNeighbors(topCenter.up()); } @Override public boolean canBlockSeeTheSky() { BlockPos topCenter = getTopCenterCoord(); - return worldObj.canBlockSeeSky(topCenter.add(0, 2, 0)); + return world.canBlockSeeSky(topCenter.add(0, 2, 0)); } - + @Override public boolean isRaining() { BlockPos topCenter = getTopCenterCoord(); - return worldObj.isRainingAt(topCenter.add(0, 2, 0)); + return world.isRainingAt(topCenter.add(0, 2, 0)); } @Override public void addTemperatureChange(float change, float boundaryDown, float boundaryUp) { - float temperature = ForestryAPI.climateManager.getTemperature(worldObj, getReferenceCoord()); + float temperature = ForestryAPI.climateManager.getTemperature(world, getReferenceCoord()); tempChange += change; tempChange = Math.max(boundaryDown - temperature, tempChange); @@ -415,7 +408,7 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple @Override public void addHumidityChange(float change, float boundaryDown, float boundaryUp) { - float humidity = ForestryAPI.climateManager.getHumidity(worldObj, getReferenceCoord()); + float humidity = ForestryAPI.climateManager.getHumidity(world, getReferenceCoord()); humidChange += change; humidChange = Math.max(boundaryDown - humidity, humidChange); @@ -429,25 +422,24 @@ public class AlvearyController extends RectangularMultiblockControllerBase imple } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { data.writeVarInt(beekeepingLogic.getBeeProgressPercent()); data.writeVarInt(Math.round(tempChange * 100)); data.writeVarInt(Math.round(humidChange * 100)); - IClimatePosition position = ForestryAPI.climateManager.getPosition(worldObj, getReferenceCoord()); - if(position != null){ + IClimatePosition position = ForestryAPI.climateManager.getPosition(world, getReferenceCoord()); + if (position != null) { ClimateUtil.writePositionData(position, data); } } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { breedingProgressPercent = data.readVarInt(); tempChange = data.readVarInt() / 100.0F; humidChange = data.readVarInt() / 100.0F; - IClimatePosition position = ForestryAPI.climateManager.getPosition(worldObj, getReferenceCoord()); - if(position != null){ + IClimatePosition position = ForestryAPI.climateManager.getPosition(world, getReferenceCoord()); + if (position != null) { ClimateUtil.readPositionData(position, data); } } - } diff --git a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java index ed2010ca5..d42cb2027 100644 --- a/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java +++ b/src/main/java/forestry/apiculture/multiblock/FakeAlvearyController.java @@ -10,15 +10,10 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.biome.Biome; - import com.mojang.authlib.GameProfile; - import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -28,6 +23,10 @@ import forestry.apiculture.tiles.FakeBeeHousingInventory; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.FakeMultiblockController; +import net.minecraft.init.Biomes; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.biome.Biome; public class FakeAlvearyController extends FakeMultiblockController implements IAlvearyControllerInternal { public static final FakeAlvearyController instance = new FakeAlvearyController(); @@ -46,7 +45,6 @@ public class FakeAlvearyController extends FakeMultiblockController implements I return Collections.emptyList(); } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return FakeBeeHousingInventory.instance; @@ -66,30 +64,31 @@ public class FakeAlvearyController extends FakeMultiblockController implements I public boolean canBlockSeeTheSky() { return false; } - + @Override public boolean isRaining() { return false; } @Override + @Nullable public GameProfile getOwner() { return null; } @Override public BlockPos getCoordinates() { - return null; + return BlockPos.ORIGIN; } @Override public Vec3d getBeeFXCoordinates() { - return null; + return new Vec3d(0, 0, 0); } @Override public Biome getBiome() { - return null; + return Biomes.PLAINS; } @Override diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java index ecfac5556..dc98a4253 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlveary.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlveary.java @@ -10,19 +10,9 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.List; -import forestry.core.owner.IOwnedTile; -import forestry.core.owner.IOwnerHandler; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; - import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -40,11 +30,18 @@ import forestry.core.config.Config; import forestry.core.gui.IHintSource; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.MultiblockTileEntityForestry; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; +import forestry.core.owner.IOwnedTile; +import forestry.core.owner.IOwnerHandler; import forestry.core.tiles.IClimatised; import forestry.core.tiles.ITitled; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.World; +import net.minecraft.world.biome.Biome; public abstract class TileAlveary extends MultiblockTileEntityForestry implements IBeeHousing, IAlvearyComponent, IOwnedTile, IStreamableGui, ITitled, IClimatised, IHintSource { private final String unlocalizedTitle; @@ -61,10 +58,10 @@ public abstract class TileAlveary extends MultiblockTileEntityForestry 0); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -115,28 +112,22 @@ public abstract class TileAlvearyClimatiser extends TileAlveary implements IEner this.active = active; - if (worldObj != null) { - if (worldObj.isRemote) { - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + if (world != null) { + if (world.isRemote) { + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } else { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), pos, world); } } } @Override - public EnergyManager getEnergyManager() { - return energyManager; - } - - @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability( Capability capability, @Nullable EnumFacing facing) { return energyManager.hasCapability(capability) || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability( Capability capability, @Nullable EnumFacing facing) { T energyCapability = energyManager.getCapability(capability); if (energyCapability != null) { return energyCapability; diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java index 8bd597a86..7a27344ca 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearyHygroregulator.java @@ -10,18 +10,8 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import forestry.api.climate.IClimateControlled; import forestry.api.multiblock.IAlvearyComponent; import forestry.apiculture.blocks.BlockAlvearyType; @@ -32,9 +22,18 @@ import forestry.core.config.Constants; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.Fluids; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; +import forestry.core.fluids.FilteredTank; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.ILiquidTankTile; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileAlvearyHygroregulator extends TileAlveary implements IInventory, ILiquidTankTile, IAlvearyComponent.Climatiser { private final HygroregulatorRecipe[] recipes; @@ -43,6 +42,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory private final FilteredTank liquidTank; private final IInventoryAdapter inventory; + @Nullable private HygroregulatorRecipe currentRecipe; private int transferTime; @@ -75,6 +75,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory } /* UPDATING */ + @Nullable private HygroregulatorRecipe getRecipe(FluidStack liquid) { HygroregulatorRecipe recipe = null; for (HygroregulatorRecipe rec : recipes) { @@ -88,12 +89,15 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory @Override public void changeClimate(int tickCount, IClimateControlled climateControlled) { - if (transferTime <= 0 && liquidTank.getFluidAmount() > 0) { - currentRecipe = getRecipe(liquidTank.getFluid()); + if (transferTime <= 0) { + FluidStack fluid = liquidTank.getFluid(); + if (fluid != null && fluid.amount > 0) { + currentRecipe = getRecipe(fluid); - if (currentRecipe != null) { - liquidTank.drainInternal(currentRecipe.liquid.amount, true); - transferTime = currentRecipe.transferTime; + if (currentRecipe != null) { + liquidTank.drainInternal(currentRecipe.liquid.amount, true); + transferTime = currentRecipe.transferTime; + } } } @@ -128,7 +132,7 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory } } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -144,22 +148,21 @@ public class TileAlvearyHygroregulator extends TileAlveary implements IInventory } /* ILIQUIDTANKCONTAINER */ - @Nonnull + @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { - if (super.hasCapability(capability, facing)) { - return true; - } - return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY; + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || + super.hasCapability(capability, facing); } @Override - public T getCapability(Capability capability, EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { return super.getCapability(capability, facing); } diff --git a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java index 27cc3ae3b..6d295207f 100644 --- a/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java +++ b/src/main/java/forestry/apiculture/multiblock/TileAlvearySwarmer.java @@ -10,16 +10,10 @@ ******************************************************************************/ package forestry.apiculture.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Map.Entry; import java.util.Stack; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import forestry.api.apiculture.BeeManager; import forestry.api.apiculture.EnumBeeType; import forestry.api.apiculture.IBee; @@ -36,6 +30,11 @@ import forestry.core.inventory.IInventoryAdapter; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; import forestry.core.utils.ItemStackUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, IActivatable, IAlvearyComponent.Active { @@ -85,7 +84,7 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, } // Try to spawn princess - if (worldObj.rand.nextInt(1000) >= chance) { + if (world.rand.nextInt(1000) >= chance) { return; } @@ -100,6 +99,7 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, } + @Nullable private ItemStack getPrincessStack() { ItemStack princessStack = getMultiblockLogic().getController().getBeeInventory().getQueen(); @@ -111,10 +111,6 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, } private int consumeInducerAndGetChance() { - if (getInternalInventory() == null) { - return 0; - } - for (int slotIndex = 0; slotIndex < getSizeInventory(); slotIndex++) { ItemStack stack = getStackInSlot(slotIndex); for (Entry entry : BeeManager.inducers.entrySet()) { @@ -134,10 +130,10 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, HiveDescriptionSwarmer hiveDescription = new HiveDescriptionSwarmer(toSpawn); Hive hive = new Hive(hiveDescription); - int x = getPos().getX() + worldObj.rand.nextInt(40 * 2) - 40; - int z = getPos().getZ() + worldObj.rand.nextInt(40 * 2) - 40; + int x = getPos().getX() + world.rand.nextInt(40 * 2) - 40; + int z = getPos().getZ() + world.rand.nextInt(40 * 2) - 40; - if (HiveDecorator.tryGenHive(worldObj, worldObj.rand, x, z, hive)) { + if (HiveDecorator.tryGenHive(world, world.rand, x, z, hive)) { pendingSpawns.pop(); } } @@ -165,11 +161,11 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, NBTTagList nbttaglist = nbttagcompound.getTagList("PendingSpawns", 10); for (int i = 0; i < nbttaglist.tagCount(); i++) { NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - pendingSpawns.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); + pendingSpawns.add(new ItemStack(nbttagcompound1)); } } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -202,8 +198,8 @@ public class TileAlvearySwarmer extends TileAlveary implements ISidedInventory, this.active = active; - if (worldObj != null && !worldObj.isRemote) { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + if (world != null && !world.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), pos, world); } } diff --git a/src/main/java/forestry/apiculture/multiblock/package-info.java b/src/main/java/forestry/apiculture/multiblock/package-info.java new file mode 100644 index 000000000..eeba2f252 --- /dev/null +++ b/src/main/java/forestry/apiculture/multiblock/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.multiblock; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java b/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java index 1a77b7c03..b00809da2 100644 --- a/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java +++ b/src/main/java/forestry/apiculture/network/PacketRegistryApiculture.java @@ -11,27 +11,28 @@ package forestry.apiculture.network; import forestry.apiculture.network.packets.PacketActiveUpdate; -import forestry.apiculture.network.packets.PacketAlveryChange; +import forestry.apiculture.network.packets.PacketAlvearyChange; import forestry.apiculture.network.packets.PacketBeeLogicActive; import forestry.apiculture.network.packets.PacketBeeLogicActiveEntity; import forestry.apiculture.network.packets.PacketBeeLogicEntityRequest; import forestry.apiculture.network.packets.PacketCandleUpdate; import forestry.apiculture.network.packets.PacketHabitatBiomePointer; import forestry.apiculture.network.packets.PacketImprintSelectionResponse; -import forestry.core.network.PacketRegistry; +import forestry.core.network.IPacketRegistry; +import forestry.core.network.PacketIdClient; +import forestry.core.network.PacketIdServer; -public class PacketRegistryApiculture extends PacketRegistry { +public class PacketRegistryApiculture implements IPacketRegistry { @Override public void registerPackets() { - registerClientPacket(new PacketImprintSelectionResponse()); - registerClientPacket(new PacketActiveUpdate()); - registerClientPacket(new PacketBeeLogicActive()); - registerClientPacket(new PacketBeeLogicActiveEntity()); - registerClientPacket(new PacketHabitatBiomePointer()); - registerClientPacket(new PacketCandleUpdate()); - - registerServerPacket(new PacketBeeLogicEntityRequest()); - - registerClientPacket(new PacketAlveryChange()); + PacketIdClient.IMPRINT_SELECTION_RESPONSE.setPacketHandler(new PacketImprintSelectionResponse.Handler()); + PacketIdClient.TILE_FORESTRY_ACTIVE.setPacketHandler(new PacketActiveUpdate.Handler()); + PacketIdClient.BEE_LOGIC_ACTIVE.setPacketHandler(new PacketBeeLogicActive.Handler()); + PacketIdClient.BEE_LOGIC_ACTIVE_ENTITY.setPacketHandler(new PacketBeeLogicActiveEntity.Handler()); + PacketIdClient.HABITAT_BIOME_POINTER.setPacketHandler(new PacketHabitatBiomePointer.Handler()); + PacketIdClient.CANDLE_UPDATE.setPacketHandler(new PacketCandleUpdate.Handler()); + PacketIdClient.ALVERAY_CONTROLLER_CHANGE.setPacketHandler(new PacketAlvearyChange.Handler()); + + PacketIdServer.BEE_LOGIC_ACTIVE_ENTITY_REQUEST.setPacketHandler(new PacketBeeLogicEntityRequest.Handler()); } } diff --git a/src/main/java/forestry/apiculture/network/package-info.java b/src/main/java/forestry/apiculture/network/package-info.java new file mode 100644 index 000000000..076c4afb2 --- /dev/null +++ b/src/main/java/forestry/apiculture/network/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.network; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java b/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java index 0e4d3c182..5433a2df0 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketActiveUpdate.java @@ -12,26 +12,24 @@ package forestry.apiculture.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.proxy.Proxies; import forestry.core.tiles.IActivatable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -public class PacketActiveUpdate extends PacketCoordinates implements IForestryPacketClient { - - private boolean active; - - public PacketActiveUpdate() { - } +public class PacketActiveUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final boolean active; public PacketActiveUpdate(IActivatable tile) { - super(tile.getCoordinates()); + this.pos = tile.getCoordinates(); this.active = tile.isActive(); } @@ -41,27 +39,26 @@ public class PacketActiveUpdate extends PacketCoordinates implements IForestryPa } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeBoolean(active); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - active = data.readBoolean(); - } + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) { + BlockPos pos = data.readBlockPos(); + boolean active = data.readBoolean(); - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IActivatable) { - ((IActivatable) tile).setActive(active); - }else{ - if(tile instanceof IMultiblockComponent){ - IMultiblockComponent component = (IMultiblockComponent) tile; - if(component.getMultiblockLogic().isConnected() && component.getMultiblockLogic().getController() instanceof IActivatable){ - ((IActivatable)component.getMultiblockLogic().getController()).setActive(active); + TileEntity tile = Proxies.common.getRenderWorld().getTileEntity(pos); + if (tile instanceof IActivatable) { + ((IActivatable) tile).setActive(active); + } else { + if (tile instanceof IMultiblockComponent) { + IMultiblockComponent component = (IMultiblockComponent) tile; + if (component.getMultiblockLogic().isConnected() && component.getMultiblockLogic().getController() instanceof IActivatable) { + ((IActivatable) component.getMultiblockLogic().getController()).setActive(active); + } } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketAlveryChange.java b/src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java similarity index 51% rename from src/main/java/forestry/apiculture/network/packets/PacketAlveryChange.java rename to src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java index 8bd1a2068..ae0337da7 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketAlveryChange.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketAlvearyChange.java @@ -10,24 +10,25 @@ ******************************************************************************/ package forestry.apiculture.network.packets; +import java.io.IOException; + +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import forestry.api.multiblock.IMultiblockComponent; -import forestry.apiculture.multiblock.IAlvearyControllerInternal; -import forestry.core.network.DataInputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.proxy.Proxies; +import net.minecraft.util.math.BlockPos; -public class PacketAlveryChange extends PacketCoordinates implements IForestryPacketClient { +public class PacketAlvearyChange extends ForestryPacket implements IForestryPacketClient { + private final BlockPos controllerPos; - public PacketAlveryChange() { - } - - public PacketAlveryChange(IAlvearyControllerInternal controller) { - super(controller.getReferenceCoord()); + public PacketAlvearyChange(BlockPos controllerPos) { + this.controllerPos = controllerPos; } @Override @@ -36,10 +37,18 @@ public class PacketAlveryChange extends PacketCoordinates implements IForestryPa } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IMultiblockComponent) { - ((IMultiblockComponent) tile).getMultiblockLogic().getController().reassemble(); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(controllerPos); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + TileEntity tile = Proxies.common.getRenderWorld().getTileEntity(pos); + if (tile instanceof IMultiblockComponent) { + ((IMultiblockComponent) tile).getMultiblockLogic().getController().reassemble(); + } } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java index 167bed090..e60a175b5 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActive.java @@ -12,27 +12,26 @@ package forestry.apiculture.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeekeepingLogic; import forestry.apiculture.BeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.proxy.Proxies; +import net.minecraft.util.math.BlockPos; -public class PacketBeeLogicActive extends PacketCoordinates implements IForestryPacketClient { - private BeekeepingLogic beekeepingLogic; - - public PacketBeeLogicActive() { - } +public class PacketBeeLogicActive extends ForestryPacket implements IForestryPacketClient { + private final BlockPos tilePos; + private final BeekeepingLogic beekeepingLogic; public PacketBeeLogicActive(IBeeHousing tile) { - super(tile.getCoordinates()); + this.tilePos = tile.getCoordinates(); this.beekeepingLogic = (BeekeepingLogic) tile.getBeekeepingLogic(); } @@ -42,19 +41,23 @@ public class PacketBeeLogicActive extends PacketCoordinates implements IForestry } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(tilePos); beekeepingLogic.writeData(data); } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) tile; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic instanceof BeekeepingLogic) { - ((BeekeepingLogic) beekeepingLogic).readData(data); + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos tilePos = data.readBlockPos(); + + TileEntity tile = Proxies.common.getRenderWorld().getTileEntity(tilePos); + if (tile instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) tile; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); + if (beekeepingLogic instanceof BeekeepingLogic) { + ((BeekeepingLogic) beekeepingLogic).readData(data); + } } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java index 0b94cd232..af6aa2e8a 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicActiveEntity.java @@ -12,27 +12,23 @@ package forestry.apiculture.network.packets; import java.io.IOException; -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.apiculture.IBeeHousing; import forestry.api.apiculture.IBeekeepingLogic; import forestry.apiculture.BeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketEntityUpdate; -import forestry.core.proxy.Proxies; +import net.minecraft.entity.Entity; +import net.minecraft.entity.player.EntityPlayer; -public class PacketBeeLogicActiveEntity extends PacketEntityUpdate implements IForestryPacketClient { - private BeekeepingLogic beekeepingLogic; - - public PacketBeeLogicActiveEntity() { - } +public class PacketBeeLogicActiveEntity extends ForestryPacket implements IForestryPacketClient { + private final Entity entity; + private final BeekeepingLogic beekeepingLogic; public PacketBeeLogicActiveEntity(IBeeHousing housing, Entity entity) { - super(entity); + this.entity = entity; this.beekeepingLogic = (BeekeepingLogic) housing.getBeekeepingLogic(); } @@ -42,19 +38,21 @@ public class PacketBeeLogicActiveEntity extends PacketEntityUpdate implements IF } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeEntityById(entity); beekeepingLogic.writeData(data); } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(Proxies.common.getRenderWorld()); - if (entity instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) entity; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic instanceof BeekeepingLogic) { - ((BeekeepingLogic) beekeepingLogic).readData(data); + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + Entity entity = data.readEntityById(player.world); + if (entity instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) entity; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); + if (beekeepingLogic instanceof BeekeepingLogic) { + ((BeekeepingLogic) beekeepingLogic).readData(data); + } } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java index ec94f48b4..8fec0e58e 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketBeeLogicEntityRequest.java @@ -12,23 +12,21 @@ package forestry.apiculture.network.packets; import java.io.IOException; +import forestry.api.apiculture.IBeeHousing; +import forestry.api.apiculture.IBeekeepingLogic; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdServer; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; -import forestry.api.apiculture.IBeeHousing; -import forestry.api.apiculture.IBeekeepingLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketEntityUpdate; - -public class PacketBeeLogicEntityRequest extends PacketEntityUpdate implements IForestryPacketServer { - - public PacketBeeLogicEntityRequest() { - } +public class PacketBeeLogicEntityRequest extends ForestryPacket implements IForestryPacketServer { + private final Entity entity; public PacketBeeLogicEntityRequest(Entity entity) { - super(entity); + this.entity = entity; } @Override @@ -37,15 +35,19 @@ public class PacketBeeLogicEntityRequest extends PacketEntityUpdate implements I } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - Entity entity = getTarget(player.worldObj); - if (entity instanceof IBeeHousing) { - IBeeHousing beeHousing = (IBeeHousing) entity; - IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); - if (beekeepingLogic != null) { + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeEntityById(entity); + } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + Entity entity = data.readEntityById(player.world); + if (entity instanceof IBeeHousing) { + IBeeHousing beeHousing = (IBeeHousing) entity; + IBeekeepingLogic beekeepingLogic = beeHousing.getBeekeepingLogic(); beekeepingLogic.syncToClient(player); } } } - } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java b/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java index 4200ac7d1..7f3fbc865 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketCandleUpdate.java @@ -12,28 +12,23 @@ package forestry.apiculture.network.packets; import java.io.IOException; +import forestry.apiculture.tiles.TileCandle; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.apiculture.tiles.TileCandle; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketCandleUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int colour; - private boolean lit; - - public PacketCandleUpdate() { - } +public class PacketCandleUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final int colour; + private final boolean lit; public PacketCandleUpdate(TileCandle tileCandle) { - super(tileCandle); - + pos = tileCandle.getPos(); colour = tileCandle.getColour(); lit = tileCandle.isLit(); } @@ -44,24 +39,23 @@ public class PacketCandleUpdate extends PacketCoordinates implements IForestryPa } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeInt(colour); data.writeBoolean(lit); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - colour = data.readInt(); - lit = data.readBoolean(); - } + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + int colour = data.readInt(); + boolean lit = data.readBoolean(); - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); - if (tileEntity instanceof TileCandle) { - ((TileCandle) tileEntity).onPacketUpdate(colour, lit); + TileEntity tileEntity = player.world.getTileEntity(pos); + if (tileEntity instanceof TileCandle) { + ((TileCandle) tileEntity).onPacketUpdate(colour, lit); + } } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java b/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java index ac1914271..0513e82de 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketHabitatBiomePointer.java @@ -12,22 +12,25 @@ package forestry.apiculture.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketHabitatBiomePointer extends PacketCoordinates implements IForestryPacketClient { - - public PacketHabitatBiomePointer() { - } +public class PacketHabitatBiomePointer extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; public PacketHabitatBiomePointer(BlockPos coordinates) { - super(coordinates); + this.pos = coordinates; + } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); } @Override @@ -35,8 +38,11 @@ public class PacketHabitatBiomePointer extends PacketCoordinates implements IFor return PacketIdClient.HABITAT_BIOME_POINTER; } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Proxies.render.setHabitatLocatorTexture(player, getPos()); + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + Proxies.render.setHabitatLocatorTexture(player, pos); + } } } diff --git a/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java b/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java index bd1905fc4..d05f59a59 100644 --- a/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java +++ b/src/main/java/forestry/apiculture/network/packets/PacketImprintSelectionResponse.java @@ -12,22 +12,22 @@ package forestry.apiculture.network.packets; import java.io.IOException; +import forestry.apiculture.gui.ContainerImprinter; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; -import forestry.apiculture.gui.ContainerImprinter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketGuiSelect; - -public class PacketImprintSelectionResponse extends PacketGuiSelect implements IForestryPacketClient { - - public PacketImprintSelectionResponse() { - } +public class PacketImprintSelectionResponse extends ForestryPacket implements IForestryPacketClient { + private final int primary; + private final int secondary; public PacketImprintSelectionResponse(int primaryIndex, int secondaryIndex) { - super(primaryIndex, secondaryIndex); + this.primary = primaryIndex; + this.secondary = secondaryIndex; } @Override @@ -36,12 +36,21 @@ public class PacketImprintSelectionResponse extends PacketGuiSelect implements I } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof ContainerImprinter)) { - return; - } + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeVarInt(primary); + data.writeVarInt(secondary); + } - ((ContainerImprinter) container).setSelection(this); + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + Container container = player.openContainer; + if (container instanceof ContainerImprinter) { + int primaryIndex = data.readVarInt(); + int secondaryIndex = data.readVarInt(); + + ((ContainerImprinter) container).setSelection(primaryIndex, secondaryIndex); + } + } } } diff --git a/src/main/java/forestry/apiculture/network/packets/package-info.java b/src/main/java/forestry/apiculture/network/packets/package-info.java new file mode 100644 index 000000000..cc88e6559 --- /dev/null +++ b/src/main/java/forestry/apiculture/network/packets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.network.packets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/package-info.java b/src/main/java/forestry/apiculture/package-info.java new file mode 100644 index 000000000..c7e8cd695 --- /dev/null +++ b/src/main/java/forestry/apiculture/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/proxy/package-info.java b/src/main/java/forestry/apiculture/proxy/package-info.java new file mode 100644 index 000000000..0d78f64ab --- /dev/null +++ b/src/main/java/forestry/apiculture/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/render/ModelAnalyzer.java b/src/main/java/forestry/apiculture/render/ModelAnalyzer.java index 5e4164881..18ed1aad6 100755 --- a/src/main/java/forestry/apiculture/render/ModelAnalyzer.java +++ b/src/main/java/forestry/apiculture/render/ModelAnalyzer.java @@ -61,9 +61,6 @@ public class ModelAnalyzer extends ModelBase { GlStateManager.translate(posX, posY, posZ); float[] angle = {0, 0, 0}; - if (orientation == null) { - orientation = EnumFacing.WEST; - } switch (orientation) { case EAST: angle[1] = (float) Math.PI / 2; diff --git a/src/main/java/forestry/apiculture/render/ModelBee.java b/src/main/java/forestry/apiculture/render/ModelBee.java deleted file mode 100755 index a7ad29c9d..000000000 --- a/src/main/java/forestry/apiculture/render/ModelBee.java +++ /dev/null @@ -1,163 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.render; - -import net.minecraft.client.model.ModelBase; -import net.minecraft.client.model.ModelRenderer; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.entity.Entity; -import net.minecraft.util.math.MathHelper; - -import forestry.api.apiculture.EnumBeeType; - -public class ModelBee extends ModelBase { - - //fields - private final ModelRenderer snout; - private final ModelRenderer torsoWing; - private final ModelRenderer rump; - private final ModelRenderer tail; - private final ModelRenderer tailEnd; - private final ModelRenderer bridge; - private final ModelRenderer eyeRight; - private final ModelRenderer eyeLeft; - private final ModelRenderer wingLeft; - private final ModelRenderer wingRight; - private final ModelRenderer crownQueen; - private final ModelRenderer crownPrincess; - - private EnumBeeType type = EnumBeeType.DRONE; - - public ModelBee() { - textureWidth = 64; - textureHeight = 32; - - snout = new ModelRenderer(this, 18, 11); - snout.addBox(0F, 0F, 0F, 1, 2, 1); - snout.setRotationPoint(0F, 1F, -2F); - snout.setTextureSize(64, 32); - snout.mirror = true; - setRotation(snout, 0F, 0F, 0F); - torsoWing = new ModelRenderer(this, 28, 14); - torsoWing.addBox(0F, 0F, 0F, 3, 3, 1); - torsoWing.setRotationPoint(-1F, 0F, -1F); - torsoWing.setTextureSize(64, 32); - torsoWing.mirror = true; - setRotation(torsoWing, 0F, 0F, 0F); - rump = new ModelRenderer(this, 10, 14); - rump.addBox(-1F, -1F, 0F, 3, 3, 3); - rump.setRotationPoint(0F, 1F, 1F); - rump.setTextureSize(64, 32); - rump.mirror = true; - setRotation(rump, 0F, 0F, 0F); - tail = new ModelRenderer(this, 4, 14); - tail.addBox(0F, 0F, 0F, 2, 2, 1); - tail.setRotationPoint(-0.5F, 0.5333334F, 4F); - tail.setTextureSize(64, 32); - tail.mirror = true; - setRotation(tail, 0F, 0F, 0F); - tailEnd = new ModelRenderer(this, 0, 14); - tailEnd.addBox(0F, 0F, 0F, 1, 1, 1); - tailEnd.setRotationPoint(0F, 1F, 5F); - tailEnd.setTextureSize(64, 32); - tailEnd.mirror = true; - setRotation(tailEnd, 0F, 0F, 0F); - bridge = new ModelRenderer(this, 22, 14); - bridge.addBox(0F, 0F, 0F, 2, 2, 1); - bridge.setRotationPoint(-0.5F, 0.5F, 0F); - bridge.setTextureSize(64, 32); - bridge.mirror = true; - setRotation(bridge, 0F, 0F, 0F); - eyeRight = new ModelRenderer(this, 22, 9); - eyeRight.addBox(0F, 0F, 0F, 1, 1, 1); - eyeRight.setRotationPoint(-1F, 0F, -2F); - eyeRight.setTextureSize(64, 32); - eyeRight.mirror = true; - setRotation(eyeRight, 0F, 0F, 0F); - eyeLeft = new ModelRenderer(this, 18, 9); - eyeLeft.addBox(0F, 0F, 0F, 1, 1, 1); - eyeLeft.setRotationPoint(1F, 0F, -2F); - eyeLeft.setTextureSize(64, 32); - eyeLeft.mirror = true; - setRotation(eyeLeft, 0F, 0F, 0F); - wingLeft = new ModelRenderer(this, 0, 0); - wingLeft.addBox(0F, 0F, 0F, 3, 1, 6); - wingLeft.setRotationPoint(1F, -0.1F, -0.5F); - wingLeft.setTextureSize(64, 32); - wingLeft.mirror = true; - setRotation(wingLeft, 0F, 0.1396263F, 0F); - wingRight = new ModelRenderer(this, 0, 7); - wingRight.addBox(-3F, 0F, 0F, 3, 1, 6); - wingRight.setRotationPoint(0F, -0.1F, -0.5F); - wingRight.setTextureSize(64, 32); - wingRight.mirror = true; - setRotation(wingRight, 0F, -0.1396263F, 0F); - - crownQueen = new ModelRenderer(this, 0, 17); - crownQueen.addBox(0F, 0F, 0F, 2, 1, 2); - crownQueen.setRotationPoint(-0.5F, -1.5F, -1.5F); - crownQueen.setTextureSize(64, 32); - crownQueen.mirror = true; - setRotation(crownQueen, 0F, 0F, 0F); - - crownPrincess = new ModelRenderer(this, 0, 20); - crownPrincess.addBox(0F, 0F, 0F, 2, 1, 2); - crownPrincess.setRotationPoint(-0.5F, -1.5F, -1.5F); - crownPrincess.setTextureSize(64, 32); - crownPrincess.mirror = true; - setRotation(crownPrincess, 0F, 0F, 0F); - - } - - public void setType(EnumBeeType type) { - this.type = type; - } - - @Override - public void render(Entity entity, float f, float f1, float swing, float f3, float f4, float f5) { - super.render(entity, f, f1, swing, f3, f4, f5); - //setRotationAngles(f, f1, f2, f3, f4, f5, entity); - - wingRight.rotateAngleZ = MathHelper.cos(swing * 1.3F) * (float) Math.PI * 0.25F; - wingLeft.rotateAngleZ = -wingRight.rotateAngleZ; - - GlStateManager.pushMatrix(); - float scale = 0.75f; - GlStateManager.scale(scale, scale, scale); - GlStateManager.translate(0.0F, 12.0f / scale * f5, 0.0F); - - snout.render(f5); - torsoWing.render(f5); - rump.render(f5); - tail.render(f5); - tailEnd.render(f5); - bridge.render(f5); - eyeRight.render(f5); - eyeLeft.render(f5); - wingLeft.render(f5); - wingRight.render(f5); - - if (type == EnumBeeType.PRINCESS) { - crownPrincess.render(f5); - } else if (type == EnumBeeType.QUEEN) { - crownQueen.render(f5); - } - - GlStateManager.popMatrix(); - } - - private static void setRotation(ModelRenderer model, float x, float y, float z) { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } - -} diff --git a/src/main/java/forestry/apiculture/render/RenderBeeItem.java b/src/main/java/forestry/apiculture/render/RenderBeeItem.java deleted file mode 100644 index c72e5f5d3..000000000 --- a/src/main/java/forestry/apiculture/render/RenderBeeItem.java +++ /dev/null @@ -1,209 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.apiculture.render; - -public class RenderBeeItem/* implements IItemRenderer*/ { - - /*private EntityBee entity; - - private static float getWingYaw(IBee bee) { - float wingYaw = 1f; - - if (bee.isAlive()) { - long systemTime = System.currentTimeMillis(); - long flapping = systemTime + bee.getIdent().hashCode(); - float flap = (float) (flapping % 1000) / 1000; // 0 to 1 - - wingYaw = getIrregularWingYaw(flapping, flap); - - } - - return wingYaw; - } - - private static float getIrregularWingYaw(long flapping, float flap) { - long irregular = flapping / 1000; - float wingYaw; - - if (irregular % 11 == 0) { - wingYaw = 0.75f; - } else { - if (irregular % 7 == 0 || irregular % 19 == 0) { - flap *= 8; - flap = flap % 1; - } - wingYaw = getRegularWingYaw(flap); - } - - return wingYaw; - } - - private static float getRegularWingYaw(float flap) { - return flap < 0.5 ? 0.75f + flap : 1.75f - flap; - } - - private IBee initBee(ItemStack item, boolean scaled) { - IBee bee = BeeManager.beeRoot.getMember(item); - if (bee == null) { - bee = BeeManager.beeRoot.templateAsIndividual(BeeManager.beeRoot.getDefaultTemplate()); - } - - if (entity == null) { - entity = new EntityBee(Proxies.common.getClientInstance().theWorld); - } - entity.setSpecies(bee.getGenome().getPrimary()); - entity.setType(BeeManager.beeRoot.getType(item));*/ - /* - if(scaled) - entity.setScale(butterfly.getSize()); - else - entity.setScale(EntityButterfly.DEFAULT_BUTTERFLY_SIZE); - */ - - /* return bee; - }*/ - - /*private void renderBeeHalo() { - - IIcon background = TextureManager.getInstance().getDefault("habitats/desert"); - float xPos = 1.0f; float yPos = 1.0f; - float width = 1f; float height = 1f; - - Proxies.render.bindTexture(SpriteSheet.ITEMS); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + height), 0f, (double)background.getMinU(), (double)background.getMaxV()); - tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + height), 0f, (double)background.getMaxU(), (double)background.getMaxV()); - tessellator.addVertexWithUV((double)(xPos + width), (double)(yPos + 0), 0f, (double)background.getMaxU(), (double)background.getMinV()); - tessellator.addVertexWithUV((double)(xPos + 0), (double)(yPos + 0), 0f, (double)background.getMinU(), (double)background.getMinV()); - tessellator.draw(); - }*/ - - /*private void renderBeeItem(IBee bee, float translateX, float translateY, float translateZ) { - float yaw = 1; - float pitch = 1; - - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); - - GlStateManager.pushMatrix(); - - GlStateManager.scale(2.0f, 2.0f, 2.0f); - GlStateManager.translate(translateX, translateY, translateZ); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(-((float) Math.atan(pitch / 40.0F)) * 20.0F, 1.0F, 0.0F, 0.0F); - - entity.renderYawOffset = (float) Math.atan(yaw / 40.0F) * 20.0F; - entity.rotationYaw = (float) Math.atan(yaw / 40.0F) * 40.0F; - entity.rotationPitch = -((float) Math.atan(pitch / 40.0F)) * 20.0F; - entity.rotationYawHead = entity.rotationYaw; - - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); - - GlStateManager.popMatrix(); - - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); - - } - - private void renderBeeInInventory(IBee bee) {*/ - - /* - GlStateManager.pushMatrix(); - //GlStateManager.translate(-0.3f, -2.5f, 0f); - GlStateManager.scale(-1.0f, 1.0f, 1.0f); - //GlStateManager.scale((float)Math.PI / 2, 1.0f, 1.0f); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F); - //GlStateManager.rotate(-((float) Math.atan((double) (1 / 40.0F))) * 20.0F, 1.0F, 0.0F, 0.0F); - renderBeeHalo(); - GlStateManager.popMatrix(); - */ - - /*GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glEnable(GL11.GL_COLOR_MATERIAL); - RenderHelper.enableStandardItemLighting(); - - GlStateManager.pushMatrix(); - - GlStateManager.translate(-0.3f, -2.5f, 0f); - GlStateManager.scale(-3.0f, 3.0f, 3.0f); - GlStateManager.rotate(32.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.scale(1.6f, 1f, 1f); - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - entity.renderYawOffset = 0; - entity.rotationYaw = 0; - entity.rotationPitch = 0; - entity.rotationYawHead = entity.rotationYaw; - - RenderManager.instance.renderEntityWithPosYaw(entity, 0.0D, 0.0D, 0.0D, 0.0F, getWingYaw(bee)); - - GlStateManager.popMatrix(); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - OpenGlHelper.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GL11.glDisable(GL11.GL_TEXTURE_2D); - OpenGlHelper.setActiveTexture(OpenGlHelper.defaultTexUnit); - GL11.glPopAttrib(); - } - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - switch (type) { - case ENTITY: - return true; - case EQUIPPED: - return true; - case INVENTORY: - return true; - default: - return false; - } - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { - switch (helper) { - case ENTITY_BOBBING: - case ENTITY_ROTATION: - return false; - default: - return true; - } - } - - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - - switch (type) { - case ENTITY: - renderBeeItem(initBee(item, true), 0f, 0f, 0f); - break; - case EQUIPPED: - renderBeeItem(initBee(item, true), 1.0f, 0f, 0.5f); - break; - case INVENTORY: - renderBeeInInventory(initBee(item, false)); - break; - default: - } - }*/ - -} diff --git a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java b/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java index a9a0fcfc4..62f88b4d3 100644 --- a/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java +++ b/src/main/java/forestry/apiculture/render/TextureHabitatLocator.java @@ -48,8 +48,8 @@ public class TextureHabitatLocator extends TextureAtlasSprite { public void updateAnimation() { Minecraft minecraft = Minecraft.getMinecraft(); - if (minecraft.theWorld != null && minecraft.thePlayer != null) { - updateCompass(minecraft.theWorld, minecraft.thePlayer.posX, minecraft.thePlayer.posZ, minecraft.thePlayer.rotationYaw); + if (minecraft.world != null && minecraft.player != null) { + updateCompass(minecraft.world, minecraft.player.posX, minecraft.player.posZ, minecraft.player.rotationYaw); } else { updateCompass(null, 0.0d, 0.0d, 0.0d); } diff --git a/src/main/java/forestry/apiculture/render/package-info.java b/src/main/java/forestry/apiculture/render/package-info.java new file mode 100644 index 000000000..697931a8b --- /dev/null +++ b/src/main/java/forestry/apiculture/render/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.render; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/tiles/FakeBeeHousingInventory.java b/src/main/java/forestry/apiculture/tiles/FakeBeeHousingInventory.java index 734368368..03cb8ed07 100644 --- a/src/main/java/forestry/apiculture/tiles/FakeBeeHousingInventory.java +++ b/src/main/java/forestry/apiculture/tiles/FakeBeeHousingInventory.java @@ -1,13 +1,10 @@ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; - import net.minecraft.item.ItemStack; import forestry.api.apiculture.IBeeHousingInventory; public class FakeBeeHousingInventory implements IBeeHousingInventory { - @Nonnull public static final FakeBeeHousingInventory instance = new FakeBeeHousingInventory(); private FakeBeeHousingInventory() { @@ -16,12 +13,12 @@ public class FakeBeeHousingInventory implements IBeeHousingInventory { @Override public ItemStack getQueen() { - return null; + return ItemStack.EMPTY; } @Override public ItemStack getDrone() { - return null; + return ItemStack.EMPTY; } @Override diff --git a/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java b/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java index dad680c90..7dd343438 100644 --- a/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java +++ b/src/main/java/forestry/apiculture/tiles/HiveBeeHousingInventory.java @@ -1,6 +1,6 @@ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.item.ItemStack; @@ -10,12 +10,14 @@ import forestry.api.apiculture.IBee; import forestry.api.apiculture.IBeeHousingInventory; class HiveBeeHousingInventory implements IBeeHousingInventory { + @Nullable private ItemStack queen; + @Nullable private ItemStack drone; private final TileHive hive; - public HiveBeeHousingInventory(@Nonnull TileHive hive) { + public HiveBeeHousingInventory(TileHive hive) { this.hive = hive; } @@ -23,9 +25,7 @@ class HiveBeeHousingInventory implements IBeeHousingInventory { public ItemStack getQueen() { if (queen == null) { IBee bee = hive.getContainedBee(); - if (bee != null) { - queen = BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.QUEEN); - } + queen = BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.QUEEN); } return queen; } @@ -34,9 +34,7 @@ class HiveBeeHousingInventory implements IBeeHousingInventory { public ItemStack getDrone() { if (drone == null) { IBee bee = hive.getContainedBee(); - if (bee != null) { - drone = BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.DRONE); - } + drone = BeeManager.beeRoot.getMemberStack(bee, EnumBeeType.DRONE); } return drone; } diff --git a/src/main/java/forestry/apiculture/tiles/TileApiary.java b/src/main/java/forestry/apiculture/tiles/TileApiary.java index 2b5bcd887..1c7f15c43 100644 --- a/src/main/java/forestry/apiculture/tiles/TileApiary.java +++ b/src/main/java/forestry/apiculture/tiles/TileApiary.java @@ -10,14 +10,11 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; import forestry.api.apiculture.IBeeModifier; @@ -29,13 +26,11 @@ import forestry.apiculture.gui.ContainerBeeHousing; import forestry.apiculture.gui.GuiBeeHousing; import forestry.apiculture.inventory.IApiaryInventory; import forestry.apiculture.inventory.InventoryApiary; +import net.minecraft.entity.player.EntityPlayer; public class TileApiary extends TileBeeHousingBase implements IApiary { - @Nonnull private final IBeeModifier beeModifier = new ApiaryBeeModifier(); - @Nonnull private final IBeeListener beeListener = new ApiaryBeeListener(this); - @Nonnull private final InventoryApiary inventory = new InventoryApiary(); public TileApiary() { @@ -43,7 +38,6 @@ public class TileApiary extends TileBeeHousingBase implements IApiary { setInternalInventory(inventory); } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return inventory; diff --git a/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java b/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java index bfc72e184..4ab649787 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeeHouse.java @@ -10,11 +10,8 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; import java.util.Collections; -import net.minecraft.entity.player.EntityPlayer; - import forestry.api.apiculture.DefaultBeeListener; import forestry.api.apiculture.IBeeHousingInventory; import forestry.api.apiculture.IBeeListener; @@ -23,14 +20,12 @@ import forestry.apiculture.BeehouseBeeModifier; import forestry.apiculture.InventoryBeeHousing; import forestry.apiculture.gui.ContainerBeeHousing; import forestry.apiculture.gui.GuiBeeHousing; +import net.minecraft.entity.player.EntityPlayer; public class TileBeeHouse extends TileBeeHousingBase { - @Nonnull private static final IBeeModifier beeModifier = new BeehouseBeeModifier(); - @Nonnull private final IBeeListener beeListener; - @Nonnull private final InventoryBeeHousing beeInventory; public TileBeeHouse() { @@ -42,7 +37,6 @@ public class TileBeeHouse extends TileBeeHousingBase { setInternalInventory(beeInventory); } - @Nonnull @Override public IBeeHousingInventory getBeeInventory() { return beeInventory; diff --git a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java index a0b4467db..5408e7cfc 100644 --- a/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java +++ b/src/main/java/forestry/apiculture/tiles/TileBeeHousingBase.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; import java.io.IOException; import com.mojang.authlib.GameProfile; @@ -22,9 +21,8 @@ import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; import forestry.api.core.ForestryAPI; import forestry.apiculture.gui.IGuiBeeHousingInventory; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.owner.IOwnedTile; import forestry.core.owner.IOwnerHandler; import forestry.core.owner.OwnerHandler; @@ -55,7 +53,6 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing } /* LOADING & SAVING */ - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -71,7 +68,6 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing ownerHandler.readFromNBT(nbttagcompound); } - @Nonnull @Override public NBTTagCompound getUpdateTag() { NBTTagCompound updateTag = super.getUpdateTag(); @@ -81,7 +77,7 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); beeLogic.readFromNBT(tag); ownerHandler.readFromNBT(tag); @@ -95,7 +91,7 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing /* ICLIMATISED */ @Override public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(getBiome(), worldObj, getPos()); + return EnumTemperature.getFromBiome(getBiome(), world, getPos()); } @Override @@ -105,12 +101,12 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing @Override public float getExactTemperature() { - return ForestryAPI.climateManager.getTemperature(worldObj, getPos()); + return ForestryAPI.climateManager.getTemperature(world, getPos()); } @Override public float getExactHumidity() { - return ForestryAPI.climateManager.getHumidity(worldObj, getPos()); + return ForestryAPI.climateManager.getHumidity(world, getPos()); } /* UPDATING */ @@ -120,7 +116,7 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing beeLogic.doBeeFX(); if (updateOnInterval(50)) { - doPollenFX(worldObj, getPos().getX(), getPos().getY(), getPos().getZ()); + doPollenFX(world, getPos().getX(), getPos().getY(), getPos().getZ()); } } } @@ -153,19 +149,19 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { data.writeVarInt(beeLogic.getBeeProgressPercent()); - IClimatePosition position = ForestryAPI.climateManager.getPosition(worldObj, getPos()); - if(position != null){ + IClimatePosition position = ForestryAPI.climateManager.getPosition(world, getPos()); + if (position != null) { ClimateUtil.writePositionData(position, data); } } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { breedingProgressPercent = data.readVarInt(); - IClimatePosition position = ForestryAPI.climateManager.getPosition(worldObj, getPos()); - if(position != null){ + IClimatePosition position = ForestryAPI.climateManager.getPosition(world, getPos()); + if (position != null) { ClimateUtil.readPositionData(position, data); } } @@ -173,22 +169,22 @@ public abstract class TileBeeHousingBase extends TileBase implements IBeeHousing // / IBEEHOUSING @Override public Biome getBiome() { - return worldObj.getBiome(getPos()); + return world.getBiome(getPos()); } @Override public int getBlockLightValue() { - return worldObj.getLightFromNeighbors(getPos().up()); + return world.getLightFromNeighbors(getPos().up()); } @Override public boolean canBlockSeeTheSky() { - return worldObj.canBlockSeeSky(getPos().up()); + return world.canBlockSeeSky(getPos().up()); } - + @Override public boolean isRaining() { - return worldObj.isRainingAt(getPos().up()); + return world.isRainingAt(getPos().up()); } @Override diff --git a/src/main/java/forestry/apiculture/tiles/TileCandle.java b/src/main/java/forestry/apiculture/tiles/TileCandle.java index a0c005986..c1a6c7340 100644 --- a/src/main/java/forestry/apiculture/tiles/TileCandle.java +++ b/src/main/java/forestry/apiculture/tiles/TileCandle.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; - import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; @@ -21,7 +19,6 @@ public class TileCandle extends TileEntity { private int colour; private boolean lit; - @Nonnull @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(getPos(), 0, getUpdateTag()); @@ -34,7 +31,6 @@ public class TileCandle extends TileEntity { handleUpdateTag(nbt); } - @Nonnull @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = super.getUpdateTag(); @@ -42,7 +38,7 @@ public class TileCandle extends TileEntity { } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag( NBTTagCompound tag) { super.handleUpdateTag(tag); readFromNBT(tag); } @@ -59,7 +55,6 @@ public class TileCandle extends TileEntity { lit = tagRoot.getBoolean("lit"); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound tagRoot) { tagRoot = super.writeToNBT(tagRoot); diff --git a/src/main/java/forestry/apiculture/tiles/TileHive.java b/src/main/java/forestry/apiculture/tiles/TileHive.java index a8392e4e8..fbd4cefe9 100644 --- a/src/main/java/forestry/apiculture/tiles/TileHive.java +++ b/src/main/java/forestry/apiculture/tiles/TileHive.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.apiculture.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; @@ -69,17 +68,13 @@ import net.minecraft.world.biome.Biome; public class TileHive extends TileEntity implements ITickable, IHiveTile, IActivatable, IBeeHousing { private static final DamageSource damageSourceBeeHive = new DamageSourceForestry("bee.hive"); - @Nonnull private final InventoryAdapter contained = new InventoryAdapter(2, "Contained"); - @Nonnull private final HiveBeeHousingInventory inventory; - @Nonnull private final BeekeepingLogic beeLogic; - @Nonnull private final IErrorLogic errorLogic; - @Nonnull private final Predicate beeTargetPredicate; + @Nullable private IBee containedBee = null; private boolean active = false; private boolean angry = false; @@ -104,11 +99,11 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv return; } - if (worldObj.isRemote) { - if (!updatedLight && worldObj.getWorldTime() % 100 == 0) { - updatedLight = worldObj.checkLightFor(EnumSkyBlock.BLOCK, getPos()); + if (world.isRemote) { + if (!updatedLight && world.getWorldTime() % 100 == 0) { + updatedLight = world.checkLightFor(EnumSkyBlock.BLOCK, getPos()); } - if (active && worldObj.rand.nextInt(4) == 0) { + if (active && world.rand.nextInt(4) == 0) { if (beeLogic.canDoBeeFX()) { beeLogic.doBeeFX(); } @@ -116,11 +111,11 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv } else { boolean canWork = beeLogic.canWork(); // must be called every tick to stay updated - if (worldObj.rand.nextInt(angry ? 10 : 200) == 0) { + if (world.rand.nextInt(angry ? 10 : 200) == 0) { if (calmTime == 0) { if (canWork) { AxisAlignedBB boundingBox = AlleleEffect.getBounding(getContainedBee().getGenome(), this); - List entities = worldObj.getEntitiesWithinAABB(EntityLivingBase.class, boundingBox, beeTargetPredicate); + List entities = world.getEntitiesWithinAABB(EntityLivingBase.class, boundingBox, beeTargetPredicate); if (!entities.isEmpty()) { Collections.shuffle(entities); EntityLivingBase entity = entities.get(0); @@ -141,7 +136,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv if (this.containedBee == null) { IBeeGenome beeGenome = null; ItemStack containedBee = contained.getStackInSlot(0); - if (containedBee != null) { + if (!containedBee.isEmpty()) { IBee bee = BeeManager.beeRoot.getMember(containedBee); if (bee != null) { beeGenome = bee.getGenome(); @@ -158,25 +153,24 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv return this.containedBee; } + @Nullable private IBeeGenome getGenomeFromBlock() { - IBlockState blockState = worldObj.getBlockState(pos); - if (blockState != null) { + if (world.isBlockLoaded(pos)) { + IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); if (block instanceof BlockBeeHives) { IHiveRegistry.HiveType hiveType = BlockBeeHives.getHiveType(blockState); - if (hiveType != null) { - String speciesUid = hiveType.getSpeciesUid(); - IAllele[] template = BeeManager.beeRoot.getTemplate(speciesUid); - if (template != null) { - return BeeManager.beeRoot.templateAsGenome(template); - } + String speciesUid = hiveType.getSpeciesUid(); + IAllele[] template = BeeManager.beeRoot.getTemplate(speciesUid); + if (template != null) { + return BeeManager.beeRoot.templateAsGenome(template); } } } return null; } - public void setContained(@Nonnull List bees) { + public void setContained(List bees) { for (ItemStack itemstack : bees) { InventoryUtil.addStack(contained, itemstack, true); } @@ -189,7 +183,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv beeLogic.readFromNBT(nbttagcompound); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -226,19 +220,19 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv if (canHarvest) { for (ItemStack beeStack : InventoryUtil.getStacks(contained)) { if (beeStack != null) { - ItemStackUtil.dropItemStackAsEntity(beeStack, worldObj, pos); + ItemStackUtil.dropItemStackAsEntity(beeStack, world, pos); } } } } private static void attack(EntityLivingBase entity, int maxDamage) { - double attackAmount = entity.worldObj.rand.nextDouble() / 2.0 + 0.5; + double attackAmount = entity.world.rand.nextDouble() / 2.0 + 0.5; int damage = (int) (attackAmount * maxDamage); if (damage > 0) { // Entities are not attacked if they wear a full set of apiarist's armor. int count = BeeManager.armorApiaristHelper.wearsItems(entity, damageSourceBeeHive.damageType, true); - if (entity.worldObj.rand.nextInt(4) >= count) { + if (entity.world.rand.nextInt(4) >= count) { entity.attackEntityFrom(damageSourceBeeHive, damage); } } @@ -256,8 +250,8 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv } this.active = active; - if (!worldObj.isRemote) { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + if (!world.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), pos, world); } } @@ -267,7 +261,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv return new SPacketUpdateTileEntity(pos, 0, getUpdateTag()); } - @Nonnull + @Override public NBTTagCompound getUpdateTag() { NBTTagCompound nbt = super.getUpdateTag(); @@ -277,7 +271,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); setActive(tag.getBoolean("active")); beeLogic.readFromNBT(tag); @@ -300,7 +294,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv return Collections.emptyList(); } - @Nonnull + @Override public IBeeHousingInventory getBeeInventory() { return inventory; @@ -331,15 +325,15 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv public boolean canBlockSeeTheSky() { return true; // hives may have the sky obstructed but should still be active } - + @Override public boolean isRaining() { - return worldObj.isRainingAt(getPos().up()); + return world.isRainingAt(getPos().up()); } @Override public World getWorldObj() { - return worldObj; + return world; } @Override @@ -348,6 +342,7 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv } @Override + @Nullable public GameProfile getOwner() { return null; } @@ -358,7 +353,6 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv return new Vec3d(pos.getX() + 0.5, pos.getY() + 0.25, pos.getZ() + 0.5); } - @Nonnull @Override public IErrorLogic getErrorLogic() { return errorLogic; @@ -370,10 +364,10 @@ public class TileHive extends TileEntity implements ITickable, IHiveTile, IActiv } private static class BeeTargetPredicate implements Predicate { - @Nonnull + private final IHiveTile hive; - public BeeTargetPredicate(@Nonnull IHiveTile hive) { + public BeeTargetPredicate(IHiveTile hive) { this.hive = hive; } diff --git a/src/main/java/forestry/apiculture/tiles/package-info.java b/src/main/java/forestry/apiculture/tiles/package-info.java new file mode 100644 index 000000000..edf75b3b5 --- /dev/null +++ b/src/main/java/forestry/apiculture/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/trigger/package-info.java b/src/main/java/forestry/apiculture/trigger/package-info.java new file mode 100644 index 000000000..3d53ea468 --- /dev/null +++ b/src/main/java/forestry/apiculture/trigger/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.trigger; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/apiculture/worldgen/Hive.java b/src/main/java/forestry/apiculture/worldgen/Hive.java index 358ec70b7..067bec4c7 100644 --- a/src/main/java/forestry/apiculture/worldgen/Hive.java +++ b/src/main/java/forestry/apiculture/worldgen/Hive.java @@ -31,9 +31,6 @@ public final class Hive { private final List drops = new ArrayList<>(); public Hive(IHiveDescription hiveDescription) { - if (hiveDescription == null) { - throw new IllegalArgumentException("Tried to create hive with null hive description"); - } this.hiveDescription = hiveDescription; } diff --git a/src/main/java/forestry/apiculture/worldgen/HiveDescription.java b/src/main/java/forestry/apiculture/worldgen/HiveDescription.java index df6fe262c..fa4aa451c 100644 --- a/src/main/java/forestry/apiculture/worldgen/HiveDescription.java +++ b/src/main/java/forestry/apiculture/worldgen/HiveDescription.java @@ -65,7 +65,7 @@ public enum HiveDescription implements IHiveDescription { END(IHiveRegistry.HiveType.END, 2.0f, BeeDefinition.ENDED, HiveManager.genHelper.ground(Blocks.END_STONE, Blocks.END_BRICKS)) { @Override public boolean isGoodBiome(Biome biome) { - return BiomeDictionary.isBiomeOfType(biome, BiomeDictionary.Type.END); + return BiomeDictionary.hasType(biome, BiomeDictionary.Type.END); } }, SNOW(IHiveRegistry.HiveType.SNOW, 2.0f, BeeDefinition.WINTRY, HiveManager.genHelper.ground(Blocks.DIRT, Blocks.GRASS, Blocks.SNOW)) { diff --git a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java b/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java index f8bea0fee..cd35e92df 100644 --- a/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java +++ b/src/main/java/forestry/apiculture/worldgen/VillageApiaristHouse.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.apiculture.worldgen; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -107,6 +107,7 @@ public class VillageApiaristHouse extends StructureVillagePieces.House1 { this.fenceGate = woodAccess.getBlock(woodType, WoodBlockKind.FENCE_GATE, fireproof); } + @Nullable public static VillageApiaristHouse buildComponent(StructureVillagePieces.Start startPiece, List pieces, Random random, int structureMinX, int structureMinY, int structureMinZ, EnumFacing facing, int componentType) { StructureBoundingBox bbox = StructureBoundingBox.getComponentToAddBoundingBox(structureMinX, structureMinY, structureMinZ, -4, 0, 0, 12, 9, 12, facing); if (!canVillageGoDeeper(bbox) || StructureComponent.findIntersecting(pieces, bbox) != null) { @@ -117,7 +118,7 @@ public class VillageApiaristHouse extends StructureVillagePieces.House1 { } @Override - public boolean addComponentParts(@Nonnull World world, @Nonnull Random random, @Nonnull StructureBoundingBox structBoundingBox) { + public boolean addComponentParts(World world, Random random, StructureBoundingBox structBoundingBox) { if (averageGroundLevel < 0) { averageGroundLevel = getAverageGroundLevel(world, structBoundingBox); @@ -165,7 +166,7 @@ public class VillageApiaristHouse extends StructureVillagePieces.House1 { fillWithBlocks(world, structBoundingBox, 8, 3, 0, 8, 3, 5, planks, planks, false); fillWithBlocks(world, structBoundingBox, 1, 2, 0, 7, 3, 0, planks, planks, false); fillWithBlocks(world, structBoundingBox, 1, 2, 5, 7, 3, 5, planks, planks, false); - + // Ceiling IBlockState slabCeiling = slabs.withProperty(BlockSlab.HALF, BlockSlab.EnumBlockHalf.TOP); fillWithBlocks(world, structBoundingBox, 1, 4, 1, 7, 4, 4, slabCeiling, slabCeiling, false); diff --git a/src/main/java/forestry/apiculture/worldgen/package-info.java b/src/main/java/forestry/apiculture/worldgen/package-info.java new file mode 100644 index 000000000..f0db835b3 --- /dev/null +++ b/src/main/java/forestry/apiculture/worldgen/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.apiculture.worldgen; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/CamouflageHandlerArbDoor.java b/src/main/java/forestry/arboriculture/CamouflageHandlerArbDoor.java index 2472490e0..81a49cb11 100644 --- a/src/main/java/forestry/arboriculture/CamouflageHandlerArbDoor.java +++ b/src/main/java/forestry/arboriculture/CamouflageHandlerArbDoor.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.arboriculture; +import com.google.common.base.Preconditions; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; import forestry.api.core.ICamouflagedTile; import forestry.arboriculture.items.ItemBlockWoodDoor; -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.BlockDoor; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -25,21 +24,15 @@ import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; public class CamouflageHandlerArbDoor implements ICamouflageItemHandler { @Override public boolean canHandle(ItemStack stack) { - if(stack == null || stack.getItem() == null || stack.stackSize <= 0){ - return false; - } - if(stack.getItem() instanceof ItemBlockWoodDoor){ - return true; - } - return false; + return stack.getItem() instanceof ItemBlockWoodDoor; } @Override @@ -55,9 +48,9 @@ public class CamouflageHandlerArbDoor implements ICamouflageItemHandler { @SideOnly(Side.CLIENT) @Override public Pair getModel(ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile) { - if(camouflageHandler == null || stack == null || stack.getItem() == null || stack.stackSize <= 0 || !(stack.getItem() instanceof ItemBlockWoodDoor)){ - return null; - } + Preconditions.checkArgument(!stack.isEmpty(), "Stack must not be empty"); + Preconditions.checkArgument(stack.getItem() instanceof ItemBlockWoodDoor, "Item must be ItemBlockWoodDoor"); + World world = camouflageHandler.getWorldObj(); BlockPos pos = camouflageTile.getCoordinates(); IBlockState blockState = world.getBlockState(pos); diff --git a/src/main/java/forestry/arboriculture/FruitProviderNone.java b/src/main/java/forestry/arboriculture/FruitProviderNone.java index 561a8d025..caacd2cfb 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderNone.java +++ b/src/main/java/forestry/arboriculture/FruitProviderNone.java @@ -10,27 +10,25 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Random; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - import forestry.api.arboriculture.IFruitProvider; import forestry.api.arboriculture.ITreeGenome; import forestry.api.genetics.IFruitFamily; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.utils.Translator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; public class FruitProviderNone implements IFruitProvider { @@ -59,6 +57,7 @@ public class FruitProviderNone implements IFruitProvider { protected int ripeningPeriod = 10; + @Nullable private OverlayType overlay = null; public FruitProviderNone(String unlocalizedDescription, IFruitFamily family) { @@ -76,10 +75,9 @@ public class FruitProviderNone implements IFruitProvider { return family; } - @Nonnull @Override - public List getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { - return Collections.emptyList(); + public NonNullList getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { + return NonNullList.create(); } @Override @@ -112,13 +110,11 @@ public class FruitProviderNone implements IFruitProvider { return ripeningPeriod; } - @Nonnull @Override public Map getProducts() { return Collections.emptyMap(); } - @Nonnull @Override public Map getSpecialty() { return Collections.emptyMap(); @@ -161,7 +157,6 @@ public class FruitProviderNone implements IFruitProvider { return null; } - @Nonnull @Override public String getModID() { return Constants.MOD_ID; diff --git a/src/main/java/forestry/arboriculture/FruitProviderPod.java b/src/main/java/forestry/arboriculture/FruitProviderPod.java index 1f5f7ecf6..5a9ce44c3 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderPod.java +++ b/src/main/java/forestry/arboriculture/FruitProviderPod.java @@ -10,16 +10,15 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; -import java.util.ArrayList; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; @@ -43,7 +42,7 @@ public class FruitProviderPod extends FruitProviderNone { } private final EnumPodType type; - @Nonnull + private final Map drops; public FruitProviderPod(String unlocalizedDescription, IFruitFamily family, EnumPodType type, ItemStack... dropOnMature) { @@ -60,22 +59,21 @@ public class FruitProviderPod extends FruitProviderNone { return true; } - @Nonnull @Override - public List getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { + public NonNullList getFruits(@Nullable ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { if (drops.isEmpty()) { - return Collections.emptyList(); + return NonNullList.create(); } if (ripeningTime >= 2) { - List drops = new ArrayList<>(); + NonNullList drops = NonNullList.create(); for (ItemStack aDrop : this.drops.keySet()) { drops.add(aDrop.copy()); } return drops; } - return Collections.emptyList(); + return NonNullList.create(); } @Override @@ -89,7 +87,7 @@ public class FruitProviderPod extends FruitProviderNone { return BlockUtil.tryPlantCocoaPod(world, pos); } else { IAlleleFruit activeAllele = (IAlleleFruit) genome.getActiveAllele(EnumTreeChromosome.FRUITS); - return TreeManager.treeRoot.setFruitBlock(world, activeAllele, genome.getSappiness(), pos); + return TreeManager.treeRoot.setFruitBlock(world, genome, activeAllele, genome.getSappiness(), pos); } } @@ -102,8 +100,7 @@ public class FruitProviderPod extends FruitProviderNone { public ResourceLocation getDecorativeSprite() { return null; } - - @Nonnull + @Override public Map getProducts() { return Collections.unmodifiableMap(drops); @@ -112,11 +109,9 @@ public class FruitProviderPod extends FruitProviderNone { @Override public void registerSprites() { } - - @Nonnull + @Override public String getModelName() { return type.getModelName(); } - } diff --git a/src/main/java/forestry/arboriculture/FruitProviderRandom.java b/src/main/java/forestry/arboriculture/FruitProviderRandom.java index 56c35c7bd..34acd6865 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderRandom.java +++ b/src/main/java/forestry/arboriculture/FruitProviderRandom.java @@ -10,15 +10,13 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; import java.awt.Color; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -31,8 +29,6 @@ import forestry.api.genetics.IFruitFamily; * Simple fruit provider which drops from any leaf block according to yield and either marks all leave blocks as fruit leaves or none. */ public class FruitProviderRandom extends FruitProviderNone { - - @Nonnull private final Map products = new HashMap<>(); private int colour = 0xffffff; @@ -56,10 +52,9 @@ public class FruitProviderRandom extends FruitProviderNone { return colour; } - @Nonnull @Override - public List getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { - List product = new ArrayList<>(); + public NonNullList getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { + NonNullList product = NonNullList.create(); float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); @@ -72,7 +67,6 @@ public class FruitProviderRandom extends FruitProviderNone { return product; } - @Nonnull @Override public Map getProducts() { return Collections.unmodifiableMap(products); diff --git a/src/main/java/forestry/arboriculture/FruitProviderRipening.java b/src/main/java/forestry/arboriculture/FruitProviderRipening.java index 25038f666..50b4fa450 100755 --- a/src/main/java/forestry/arboriculture/FruitProviderRipening.java +++ b/src/main/java/forestry/arboriculture/FruitProviderRipening.java @@ -10,15 +10,13 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; import java.awt.Color; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Map; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; @@ -28,12 +26,8 @@ import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.IFruitFamily; public class FruitProviderRipening extends FruitProviderNone { - - @Nonnull private final Map products = new HashMap<>(); - private int colourCallow = 0xffffff; - private int diffR; private int diffG; private int diffB; @@ -67,28 +61,24 @@ public class FruitProviderRipening extends FruitProviderNone { return (float) ripeningTime / ripeningPeriod; } - @Nonnull @Override - public List getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { - ArrayList product = new ArrayList<>(); + public NonNullList getFruits(ITreeGenome genome, World world, BlockPos pos, int ripeningTime) { + NonNullList product = NonNullList.create(); float stage = getRipeningStage(ripeningTime); - if (stage < 0.5f) { - return Collections.emptyList(); - } + if (stage >= 0.5f) { + float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); - float modeYieldMod = TreeManager.treeRoot.getTreekeepingMode(world).getYieldModifier(genome, 1f); - - for (Map.Entry entry : products.entrySet()) { - if (world.rand.nextFloat() <= genome.getYield() * entry.getValue() * modeYieldMod * 5.0f * stage) { - product.add(entry.getKey().copy()); + for (Map.Entry entry : products.entrySet()) { + if (world.rand.nextFloat() <= genome.getYield() * entry.getValue() * modeYieldMod * 5.0f * stage) { + product.add(entry.getKey().copy()); + } } } return product; } - - @Nonnull + @Override public Map getProducts() { return Collections.unmodifiableMap(products); diff --git a/src/main/java/forestry/arboriculture/IWoodTyped.java b/src/main/java/forestry/arboriculture/IWoodTyped.java index d3b13f19c..a24fe4f3f 100755 --- a/src/main/java/forestry/arboriculture/IWoodTyped.java +++ b/src/main/java/forestry/arboriculture/IWoodTyped.java @@ -10,21 +10,16 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; - import java.util.Collection; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.WoodBlockKind; public interface IWoodTyped { - @Nonnull WoodBlockKind getBlockKind(); boolean isFireproof(); - @Nonnull IWoodType getWoodType(int meta); - - @Nonnull + Collection getWoodTypes(); } diff --git a/src/main/java/forestry/arboriculture/PluginArboriculture.java b/src/main/java/forestry/arboriculture/PluginArboriculture.java index c37c0ac23..9deaf173e 100644 --- a/src/main/java/forestry/arboriculture/PluginArboriculture.java +++ b/src/main/java/forestry/arboriculture/PluginArboriculture.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.Map.Entry; import java.util.Set; +import com.google.common.base.Preconditions; import forestry.api.arboriculture.EnumForestryWoodType; import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumPileType; @@ -37,11 +38,11 @@ import forestry.api.genetics.ISaplingTranslator; import forestry.api.recipes.RecipeManagers; import forestry.api.storage.ICrateRegistry; import forestry.api.storage.StorageManager; +import forestry.arboriculture.blocks.BlockArbLog; +import forestry.arboriculture.blocks.BlockArbSlab; import forestry.arboriculture.blocks.BlockForestryLeaves; import forestry.arboriculture.blocks.BlockPile; import forestry.arboriculture.blocks.BlockRegistryArboriculture; -import forestry.arboriculture.blocks.log.BlockArbLog; -import forestry.arboriculture.blocks.slab.BlockArbSlab; import forestry.arboriculture.capabilities.ArmorNaturalist; import forestry.arboriculture.commands.CommandTree; import forestry.arboriculture.genetics.TreeBranchDefinition; @@ -50,9 +51,9 @@ import forestry.arboriculture.genetics.TreeFactory; import forestry.arboriculture.genetics.TreeMutationFactory; import forestry.arboriculture.genetics.TreeRoot; import forestry.arboriculture.genetics.TreekeepingMode; -import forestry.arboriculture.genetics.alleles.AlleleFruit; -import forestry.arboriculture.genetics.alleles.AlleleGrowth; -import forestry.arboriculture.genetics.alleles.AlleleLeafEffect; +import forestry.arboriculture.genetics.alleles.AlleleFruits; +import forestry.arboriculture.genetics.alleles.AlleleLeafEffects; +import forestry.arboriculture.items.ItemGermlingGE; import forestry.arboriculture.items.ItemGrafter; import forestry.arboriculture.items.ItemRegistryArboriculture; import forestry.arboriculture.models.TextureLeaves; @@ -69,8 +70,8 @@ import forestry.core.capabilities.NullStorage; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.fluids.Fluids; -import forestry.core.genetics.alleles.AllelePlantType; import forestry.core.items.ItemFruit.EnumFruit; +import forestry.core.items.ItemRegistryCore; import forestry.core.network.IPacketRegistry; import forestry.core.proxy.Proxies; import forestry.core.recipes.RecipeUtil; @@ -79,7 +80,6 @@ import forestry.core.utils.IMCUtil; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.OreDictUtil; import forestry.core.utils.VillagerTradeLists; -import forestry.factory.recipes.FabricatorRecipe; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; @@ -115,15 +115,18 @@ import net.minecraftforge.oredict.OreDictionary; @ForestryPlugin(pluginID = ForestryPluginUids.ARBORICULTURE, name = "Arboriculture", author = "Binnie & SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.arboriculture.description") public class PluginArboriculture extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.arboriculture.proxy.ProxyArboricultureClient", serverSide = "forestry.arboriculture.proxy.ProxyArboriculture") public static ProxyArboriculture proxy; public static String treekeepingMode = "NORMAL"; public static final List validFences = new ArrayList<>(); + @Nullable public static ItemRegistryArboriculture items; + @Nullable public static BlockRegistryArboriculture blocks; - + @Nullable public static VillagerRegistry.VillagerProfession villagerArborist; @Override @@ -165,6 +168,7 @@ public class PluginArboriculture extends BlankForestryPlugin { @Override public void preInit() { super.preInit(); + Preconditions.checkState(blocks != null, "Blocks have not been created"); MinecraftForge.EVENT_BUS.register(this); @@ -195,7 +199,7 @@ public class PluginArboriculture extends BlankForestryPlugin { // Commands PluginCore.rootCommand.addChildCommand(new CommandTree()); - + CamouflageManager.camouflageAccess.registerCamouflageItemHandler(new CamouflageHandlerArbDoor()); } @@ -210,7 +214,7 @@ public class PluginArboriculture extends BlankForestryPlugin { super.doInit(); // Create alleles - createAlleles(); + registerAlleles(); TreeDefinition.initTrees(); registerErsatzGenomes(); @@ -219,6 +223,8 @@ public class PluginArboriculture extends BlankForestryPlugin { GameRegistry.registerTileEntity(TileFruitPod.class, "forestry.Pods"); GameRegistry.registerTileEntity(TilePile.class, "forestry.Piles"); + Preconditions.checkState(blocks != null, "Blocks have not been created"); + Preconditions.checkState(items != null, "Items have not been created"); blocks.treeChest.init(); if (Config.enableVillagers) { @@ -260,6 +266,10 @@ public class PluginArboriculture extends BlankForestryPlugin { @Override public void registerRecipes() { + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null, "Core Items have not been created"); + Preconditions.checkState(blocks != null, "Blocks have not been created"); + Preconditions.checkState(items != null, "Items have not been created"); for (BlockArbLog log : blocks.logs) { ItemStack logInput = new ItemStack(log, 1, OreDictionary.WILDCARD_VALUE); @@ -288,38 +298,38 @@ public class PluginArboriculture extends BlankForestryPlugin { ItemStack fireproofStairs = TreeManager.woodAccess.getStack(woodType, WoodBlockKind.STAIRS, true); if (woodType instanceof EnumForestryWoodType) { - planks.stackSize = 4; - logs.stackSize = 1; + planks.setCount(4); + logs.setCount(1); RecipeUtil.addShapelessRecipe(planks.copy(), logs.copy()); - slabs.stackSize = 6; - planks.stackSize = 1; + slabs.setCount(6); + planks.setCount(1); RecipeUtil.addPriorityRecipe(slabs.copy(), "###", '#', planks.copy()); - fences.stackSize = 3; - planks.stackSize = 1; + fences.setCount(3); + planks.setCount(1); RecipeUtil.addRecipe(fences.copy(), "#X#", "#X#", '#', planks.copy(), 'X', "stickWood"); - fenceGates.stackSize = 1; - planks.stackSize = 1; + fenceGates.setCount(1); + planks.setCount(1); RecipeUtil.addRecipe(fenceGates.copy(), "X#X", "X#X", '#', planks.copy(), 'X', "stickWood"); - stairs.stackSize = 4; - planks.stackSize = 1; + stairs.setCount(4); + planks.setCount(1); RecipeUtil.addPriorityRecipe(stairs.copy(), "# ", "## ", "###", '#', planks.copy()); - doors.stackSize = 3; - planks.stackSize = 1; + doors.setCount(3); + planks.setCount(1); RecipeUtil.addPriorityRecipe(doors.copy(), "## ", "## ", @@ -327,40 +337,40 @@ public class PluginArboriculture extends BlankForestryPlugin { '#', planks.copy()); } - fireproofPlanks.stackSize = 4; - fireproofLogs.stackSize = 1; + fireproofPlanks.setCount(4); + fireproofLogs.setCount(1); RecipeUtil.addShapelessRecipe(fireproofPlanks.copy(), fireproofLogs.copy()); - fireproofSlabs.stackSize = 6; - fireproofPlanks.stackSize = 1; + fireproofSlabs.setCount(6); + fireproofPlanks.setCount(1); RecipeUtil.addPriorityRecipe(fireproofSlabs.copy(), "###", '#', fireproofPlanks.copy()); - fireproofFences.stackSize = 3; - fireproofPlanks.stackSize = 1; + fireproofFences.setCount(3); + fireproofPlanks.setCount(1); RecipeUtil.addRecipe(fireproofFences.copy(), "#X#", "#X#", '#', fireproofPlanks.copy(), 'X', "stickWood"); - fireproofFenceGates.stackSize = 1; - fireproofPlanks.stackSize = 1; + fireproofFenceGates.setCount(1); + fireproofPlanks.setCount(1); RecipeUtil.addRecipe(fireproofFenceGates.copy(), "X#X", "X#X", '#', fireproofPlanks.copy(), 'X', "stickWood"); - fireproofStairs.stackSize = 4; - fireproofPlanks.stackSize = 1; + fireproofStairs.setCount(4); + fireproofPlanks.setCount(1); RecipeUtil.addPriorityRecipe(fireproofStairs.copy(), "# ", "## ", "###", '#', fireproofPlanks.copy()); - doors.stackSize = 3; - fireproofPlanks.stackSize = 1; + doors.setCount(3); + fireproofPlanks.setCount(1); RecipeUtil.addPriorityRecipe(doors.copy(), "## ", "## ", @@ -369,23 +379,23 @@ public class PluginArboriculture extends BlankForestryPlugin { // Fabricator recipes if (ForestryAPI.enabledPlugins.containsAll(Arrays.asList(ForestryPluginUids.FACTORY, ForestryPluginUids.APICULTURE))) { - logs.stackSize = 1; - fireproofLogs.stackSize = 1; - RecipeManagers.fabricatorManager.addRecipe(new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofLogs.copy(), new Object[]{ + logs.setCount(1); + fireproofLogs.setCount(1); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), fireproofLogs.copy(), new Object[]{ " # ", "#X#", " # ", - '#', PluginCore.items.refractoryWax, - 'X', logs.copy()})); + '#', coreItems.refractoryWax, + 'X', logs.copy()}); - planks.stackSize = 1; - fireproofPlanks.stackSize = 5; - RecipeManagers.fabricatorManager.addRecipe(new FabricatorRecipe(null, Fluids.GLASS.getFluid(500), fireproofPlanks.copy(), new Object[]{ + planks.setCount(1); + fireproofPlanks.setCount(5); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), fireproofPlanks.copy(), new Object[]{ "X#X", "#X#", "X#X", - '#', PluginCore.items.refractoryWax, - 'X', planks.copy()})); + '#', coreItems.refractoryWax, + 'X', planks.copy()}); } } @@ -395,14 +405,14 @@ public class PluginArboriculture extends BlankForestryPlugin { int seedOilMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); int juiceMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); int mulchMultiplier = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); - ItemStack mulch = new ItemStack(PluginCore.items.mulch); - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{EnumFruit.CHERRY.getStack()}, Fluids.SEED_OIL.getFluid(5 * seedOilMultiplier), mulch, 5); - RecipeManagers.squeezerManager.addRecipe(60, new ItemStack[]{EnumFruit.WALNUT.getStack()}, Fluids.SEED_OIL.getFluid(18 * seedOilMultiplier), mulch, 5); - RecipeManagers.squeezerManager.addRecipe(70, new ItemStack[]{EnumFruit.CHESTNUT.getStack()}, Fluids.SEED_OIL.getFluid(22 * seedOilMultiplier), mulch, 2); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.LEMON.getStack()}, Fluids.JUICE.getFluid(juiceMultiplier * 2), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.PLUM.getStack()}, Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.5f)), mulch, mulchMultiplier * 3); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.PAPAYA.getStack()}, Fluids.JUICE.getFluid(juiceMultiplier * 3), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{EnumFruit.DATES.getStack()}, Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.25)), mulch, mulchMultiplier); + ItemStack mulch = new ItemStack(coreItems.mulch); + RecipeManagers.squeezerManager.addRecipe(20, EnumFruit.CHERRY.getStack(), Fluids.SEED_OIL.getFluid(5 * seedOilMultiplier), mulch, 5); + RecipeManagers.squeezerManager.addRecipe(60, EnumFruit.WALNUT.getStack(), Fluids.SEED_OIL.getFluid(18 * seedOilMultiplier), mulch, 5); + RecipeManagers.squeezerManager.addRecipe(70, EnumFruit.CHESTNUT.getStack(), Fluids.SEED_OIL.getFluid(22 * seedOilMultiplier), mulch, 2); + RecipeManagers.squeezerManager.addRecipe(10, EnumFruit.LEMON.getStack(), Fluids.JUICE.getFluid(juiceMultiplier * 2), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); + RecipeManagers.squeezerManager.addRecipe(10, EnumFruit.PLUM.getStack(), Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.5f)), mulch, mulchMultiplier * 3); + RecipeManagers.squeezerManager.addRecipe(10, EnumFruit.PAPAYA.getStack(), Fluids.JUICE.getFluid(juiceMultiplier * 3), mulch, (int) Math.floor(mulchMultiplier * 0.5f)); + RecipeManagers.squeezerManager.addRecipe(10, EnumFruit.DATES.getStack(), Fluids.JUICE.getFluid((int) Math.floor(juiceMultiplier * 0.25)), mulch, mulchMultiplier); RecipeUtil.addFermenterRecipes(items.sapling.getItemStack(), ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); } @@ -422,28 +432,23 @@ public class PluginArboriculture extends BlankForestryPlugin { '#', "blockGlass", 'X', "treeSapling", 'Y', "chestWood"); - + //Wood Piles for (ITree tree : TreeManager.treeRoot.getIndividualTemplates()) { IAlleleTreeSpecies treeSpecies = tree.getGenome().getPrimary(); ItemStack log = treeSpecies.getWoodProvider().getWoodStack().copy(); - log.stackSize = 1; + log.setCount(1); ItemStack woodPile = BlockPile.createWoodPile(treeSpecies); RecipeUtil.addShapelessRecipe(woodPile, log, log, log, log); } - + //Dirt Pile Block - RecipeUtil.addShapelessRecipe(new ItemStack(PluginArboriculture.blocks.piles.get(EnumPileType.DIRT), 4), Items.CLAY_BALL, PluginCore.items.fertilizerBio, Items.CLAY_BALL, OreDictUtil.SAND, Items.CLAY_BALL, OreDictUtil.SAND, Items.CLAY_BALL, PluginCore.items.fertilizerBio, Items.CLAY_BALL); - + RecipeUtil.addShapelessRecipe(new ItemStack(blocks.piles.get(EnumPileType.DIRT), 4), Items.CLAY_BALL, coreItems.fertilizerBio, Items.CLAY_BALL, OreDictUtil.SAND, Items.CLAY_BALL, OreDictUtil.SAND, Items.CLAY_BALL, coreItems.fertilizerBio, Items.CLAY_BALL); } - private static void createAlleles() { - - TreeBranchDefinition.createAlleles(); - - AlleleGrowth.createAlleles(); - AlleleLeafEffect.createAlleles(); - AllelePlantType.createAlleles(); + private static void registerAlleles() { + TreeBranchDefinition.registerAlleles(); + AlleleLeafEffects.registerAlleles(); } private static void registerErsatzGenomes() { @@ -509,7 +514,8 @@ public class PluginArboriculture extends BlankForestryPlugin { @Override public IFuelHandler getFuelHandler() { - return new FuelHandler(); + Preconditions.checkState(items != null, "Items have not been created"); + return new FuelHandler(items.sapling); } @Override @@ -534,19 +540,25 @@ public class PluginArboriculture extends BlankForestryPlugin { @Override public void getHiddenItems(List hiddenItems) { + Preconditions.checkState(blocks != null, "Blocks have not been created"); // sapling itemBlock is different from the normal item hiddenItems.add(new ItemStack(blocks.saplingGE)); } private static class FuelHandler implements IFuelHandler { + private final ItemGermlingGE sapling; + + public FuelHandler(ItemGermlingGE sapling) { + this.sapling = sapling; + } + @Override public int getBurnTime(ItemStack fuel) { Item item = fuel.getItem(); - - if (items.sapling == item) { + if (sapling == item) { return 100; } - + Block block = Block.getBlockFromItem(item); if (block instanceof IWoodTyped) { @@ -555,7 +567,7 @@ public class PluginArboriculture extends BlankForestryPlugin { return 0; } else if (block instanceof BlockArbSlab) { return 150; - }else{ + } else { return 300; } } @@ -563,38 +575,38 @@ public class PluginArboriculture extends BlankForestryPlugin { return 0; } } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void registerSprites(TextureStitchEvent.Pre event) { TextureLeaves.registerAllSprites(); WoodTextures.deserializeFile(Proxies.render.getSelectedTexturePack()); - for (IAlleleFruit alleleFruit : AlleleFruit.getFruitAlleles()) { + for (IAlleleFruit alleleFruit : AlleleFruits.getFruitAlleles()) { alleleFruit.getProvider().registerSprites(); } List textures = new ArrayList<>(); - for(IWoodType type : TreeManager.woodAccess.getRegisteredWoodTypes()){ + for (IWoodType type : TreeManager.woodAccess.getRegisteredWoodTypes()) { textures.add(new ResourceLocation(type.getHeartTexture())); textures.add(new ResourceLocation(type.getBarkTexture())); textures.add(new ResourceLocation(type.getDoorLowerTexture())); textures.add(new ResourceLocation(type.getDoorUpperTexture())); textures.add(new ResourceLocation(type.getPlankTexture())); - for(WoodBlockKind kind : WoodBlockKind.values()){ - for(Entry loc : WoodTextures.getLocations(type, kind).entrySet()){ + for (WoodBlockKind kind : WoodBlockKind.values()) { + for (Entry loc : WoodTextures.getLocations(type, kind).entrySet()) { textures.add(new ResourceLocation(loc.getValue())); } } } - for(ResourceLocation loc : textures){ + for (ResourceLocation loc : textures) { TextureManager.getInstance(); TextureManager.registerSprite(loc); } } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void onModelBake(ModelBakeEvent event) { - ((ProxyArboricultureClient)proxy).onModelBake(event); + ((ProxyArboricultureClient) proxy).onModelBake(event); } @SubscribeEvent @@ -605,19 +617,18 @@ public class PluginArboriculture extends BlankForestryPlugin { EntityPlayer player = event.getHarvester(); if (player != null) { ItemStack harvestingTool = player.getHeldItemMainhand(); - if (harvestingTool != null && harvestingTool.getItem() instanceof ItemGrafter) { + if (harvestingTool.getItem() instanceof ItemGrafter) { if (event.getDrops().isEmpty()) { World world = event.getWorld(); Item itemDropped = block.getItemDropped(state, world.rand, 3); - if (itemDropped != null) { + if (itemDropped != Items.AIR) { event.getDrops().add(new ItemStack(itemDropped, 1, block.damageDropped(state))); } } harvestingTool.damageItem(1, player); - if (harvestingTool.stackSize <= 0) { + if (harvestingTool.isEmpty()) { net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, harvestingTool, EnumHand.MAIN_HAND); - player.setHeldItem(EnumHand.MAIN_HAND, null); } } } diff --git a/src/main/java/forestry/arboriculture/VillagerArboristTrades.java b/src/main/java/forestry/arboriculture/VillagerArboristTrades.java index 81a8be149..d58c028e2 100644 --- a/src/main/java/forestry/arboriculture/VillagerArboristTrades.java +++ b/src/main/java/forestry/arboriculture/VillagerArboristTrades.java @@ -1,6 +1,5 @@ package forestry.arboriculture; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -16,6 +15,7 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IIndividual; +import net.minecraft.entity.IMerchant; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -26,9 +26,9 @@ public class VillagerArboristTrades { public static class GiveLogsForEmeralds implements EntityVillager.ITradeList { @Nullable - public EntityVillager.PriceInfo emeraldPriceInfo; + public final EntityVillager.PriceInfo emeraldPriceInfo; @Nullable - public EntityVillager.PriceInfo sellInfo; + public final EntityVillager.PriceInfo sellInfo; public GiveLogsForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, @Nullable EntityVillager.PriceInfo sellInfo) { this.emeraldPriceInfo = emeraldPriceInfo; @@ -36,7 +36,7 @@ public class VillagerArboristTrades { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant p_190888_1_, MerchantRecipeList recipeList, Random random) { int i = 1; if (this.sellInfo != null) { i = this.sellInfo.getPrice(random); @@ -49,7 +49,7 @@ public class VillagerArboristTrades { EnumForestryWoodType woodType = EnumForestryWoodType.getRandom(random); ItemStack sellStack = TreeManager.woodAccess.getStack(woodType, WoodBlockKind.LOG, false); - sellStack.stackSize = i; + sellStack.setCount(i); ItemStack emeralds = new ItemStack(Items.EMERALD, j); @@ -59,9 +59,9 @@ public class VillagerArboristTrades { public static class GivePlanksForEmeralds implements EntityVillager.ITradeList { @Nullable - public EntityVillager.PriceInfo emeraldPriceInfo; + public final EntityVillager.PriceInfo emeraldPriceInfo; @Nullable - public EntityVillager.PriceInfo sellInfo; + public final EntityVillager.PriceInfo sellInfo; public GivePlanksForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, @Nullable EntityVillager.PriceInfo sellInfo) { this.emeraldPriceInfo = emeraldPriceInfo; @@ -69,7 +69,7 @@ public class VillagerArboristTrades { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant p_190888_1_, MerchantRecipeList recipeList, Random random) { int i = 1; if (this.sellInfo != null) { i = this.sellInfo.getPrice(random); @@ -82,7 +82,7 @@ public class VillagerArboristTrades { EnumForestryWoodType woodType = EnumForestryWoodType.getRandom(random); ItemStack sellStack = TreeManager.woodAccess.getStack(woodType, WoodBlockKind.PLANKS, false); - sellStack.stackSize = i; + sellStack.setCount(i); ItemStack emeralds = new ItemStack(Items.EMERALD, j); @@ -92,15 +92,15 @@ public class VillagerArboristTrades { public static class GivePollenForEmeralds implements EntityVillager.ITradeList { @Nullable - public EntityVillager.PriceInfo emeraldPriceInfo; + public final EntityVillager.PriceInfo emeraldPriceInfo; @Nullable - public EntityVillager.PriceInfo sellInfo; - @Nonnull + public final EntityVillager.PriceInfo sellInfo; + private final EnumGermlingType type; private final int maxComplexity; - public GivePollenForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, @Nullable EntityVillager.PriceInfo sellInfo, @Nonnull EnumGermlingType type, int maxComplexity) { + public GivePollenForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, @Nullable EntityVillager.PriceInfo sellInfo, EnumGermlingType type, int maxComplexity) { this.emeraldPriceInfo = emeraldPriceInfo; this.sellInfo = sellInfo; this.type = type; @@ -108,7 +108,7 @@ public class VillagerArboristTrades { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant p_190888_1_, MerchantRecipeList recipeList, Random random) { int i = 1; if (this.sellInfo != null) { i = this.sellInfo.getPrice(random); @@ -140,7 +140,7 @@ public class VillagerArboristTrades { IIndividual individual = TreeManager.treeRoot.templateAsIndividual(template); ItemStack sellStack = TreeManager.treeRoot.getMemberStack(individual, type); - sellStack.stackSize = i; + sellStack.setCount(i); ItemStack emeralds = new ItemStack(Items.EMERALD, j); diff --git a/src/main/java/forestry/arboriculture/WoodAccess.java b/src/main/java/forestry/arboriculture/WoodAccess.java index e833d326a..9e178ff93 100644 --- a/src/main/java/forestry/arboriculture/WoodAccess.java +++ b/src/main/java/forestry/arboriculture/WoodAccess.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; @@ -18,18 +17,19 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.google.common.base.Preconditions; import forestry.api.arboriculture.EnumVanillaWoodType; import forestry.api.arboriculture.IWoodAccess; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.WoodBlockKind; import forestry.arboriculture.blocks.BlockArbDoor; +import forestry.arboriculture.blocks.BlockForestryFence; import forestry.arboriculture.blocks.BlockForestryFenceGate; +import forestry.arboriculture.blocks.BlockForestryLog; +import forestry.arboriculture.blocks.BlockForestryPlanks; +import forestry.arboriculture.blocks.BlockForestrySlab; import forestry.arboriculture.blocks.BlockForestryStairs; -import forestry.arboriculture.blocks.fence.BlockForestryFence; -import forestry.arboriculture.blocks.log.BlockForestryLog; -import forestry.arboriculture.blocks.planks.BlockForestryPlanks; -import forestry.arboriculture.blocks.property.PropertyWoodType; -import forestry.arboriculture.blocks.slab.BlockForestrySlab; +import forestry.arboriculture.blocks.PropertyWoodType; import net.minecraft.block.Block; import net.minecraft.block.BlockNewLog; import net.minecraft.block.BlockOldLog; @@ -52,32 +52,24 @@ public class WoodAccess implements IWoodAccess { } private static class WoodMap { - @Nonnull private final Map normalItems = new HashMap<>(); - @Nonnull private final Map fireproofItems = new HashMap<>(); - @Nonnull private final Map normalBlocks = new HashMap<>(); - @Nonnull private final Map fireproofBlocks = new HashMap<>(); - @Nonnull private final WoodBlockKind woodBlockKind; - public WoodMap(@Nonnull WoodBlockKind woodBlockKind) { + public WoodMap(WoodBlockKind woodBlockKind) { this.woodBlockKind = woodBlockKind; } - @Nonnull public String getName() { return woodBlockKind.name(); } - @Nonnull public Map getItem(boolean fireproof) { return fireproof ? this.fireproofItems : this.normalItems; } - @Nonnull public Map getBlock(boolean fireproof) { return fireproof ? this.fireproofBlocks : this.normalBlocks; } @@ -106,7 +98,7 @@ public class WoodAccess implements IWoodAccess { registerWithVariants(block, WoodBlockKind.FENCE, block.getVariant()); } } - + public static void registerFenceGates(List blocks) { for (BlockForestryFenceGate block : blocks) { registerWithoutVariants(block, WoodBlockKind.FENCE_GATE); @@ -195,7 +187,7 @@ public class WoodAccess implements IWoodAccess { int meta = woodTyped.getMetaFromState(blockState); IWoodType woodType = woodTyped.getWoodType(meta); ItemStack itemStack = new ItemStack(woodTyped, 1, meta); - if(!(woodType instanceof EnumVanillaWoodType)){ + if (!(woodType instanceof EnumVanillaWoodType)) { PluginArboriculture.proxy.registerWoodModel(woodTyped, true); } register(woodType, woodBlockKind, fireproof, blockState, itemStack); @@ -210,7 +202,7 @@ public class WoodAccess implements IWoodAccess { IBlockState blockState = woodTyped.getDefaultState(); IWoodType woodType = woodTyped.getWoodType(0); ItemStack itemStack = new ItemStack(woodTyped); - if(!(woodType instanceof EnumVanillaWoodType)){ + if (!(woodType instanceof EnumVanillaWoodType)) { PluginArboriculture.proxy.registerWoodModel(woodTyped, false); } register(woodType, woodBlockKind, fireproof, blockState, itemStack); @@ -220,11 +212,9 @@ public class WoodAccess implements IWoodAccess { if (woodBlockKind == WoodBlockKind.DOOR) { fireproof = true; } - if (itemStack == null || itemStack.getItem() == null) { - throw new NullPointerException("Invalid itemStack: " + itemStack); - } + Preconditions.checkArgument(!itemStack.isEmpty(), "Empty Itemstack"); WoodMap woodMap = woodMaps.get(woodBlockKind); - if(!registeredWoodTypes.contains(woodType)){ + if (!registeredWoodTypes.contains(woodType)) { registeredWoodTypes.add(woodType); } woodMap.getItem(fireproof).put(woodType, itemStack); @@ -258,7 +248,7 @@ public class WoodAccess implements IWoodAccess { } return blockState; } - + @Override public List getRegisteredWoodTypes() { return registeredWoodTypes; diff --git a/src/main/java/forestry/arboriculture/WoodHelper.java b/src/main/java/forestry/arboriculture/WoodHelper.java index f10b4eb77..2c2ca79b9 100644 --- a/src/main/java/forestry/arboriculture/WoodHelper.java +++ b/src/main/java/forestry/arboriculture/WoodHelper.java @@ -1,16 +1,8 @@ package forestry.arboriculture; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumForestryWoodType; import forestry.api.arboriculture.EnumVanillaWoodType; import forestry.api.arboriculture.IWoodItemMeshDefinition; @@ -21,9 +13,14 @@ import forestry.api.core.ForestryAPI; import forestry.arboriculture.models.WoodModelLoader; import forestry.core.config.Constants; import forestry.core.utils.Translator; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class WoodHelper { - @Nonnull + public static String getDisplayName(IWoodTyped wood, IWoodType woodType) { WoodBlockKind blockKind = wood.getBlockKind(); @@ -51,7 +48,7 @@ public class WoodHelper { return displayName; } - + public static ResourceLocation getDefaultResourceLocations(IWoodTyped typed) { return new ResourceLocation(Constants.MOD_ID, typed.getBlockKind().toString()); } @@ -71,16 +68,16 @@ public class WoodHelper { @SideOnly(Side.CLIENT) public static class WoodMeshDefinition implements IWoodItemMeshDefinition { - @Nonnull - public IWoodTyped wood; - public WoodMeshDefinition(@Nonnull IWoodTyped wood) { + public final IWoodTyped wood; + + public WoodMeshDefinition(IWoodTyped wood) { this.wood = wood; } @Override public ModelResourceLocation getModelLocation(ItemStack stack) { - if(!WoodModelLoader.INSTANCE.isRegistered){ + if (!WoodModelLoader.INSTANCE.isRegistered) { return new ModelResourceLocation(getDefaultModelLocation(stack), "inventory"); } int meta = stack.getMetadata(); @@ -94,7 +91,7 @@ public class WoodHelper { throw new IllegalArgumentException("Unknown wood type: " + woodType); } } - + @Override public ResourceLocation getDefaultModelLocation(ItemStack stack) { WoodBlockKind blockKind = wood.getBlockKind(); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockArbDoor.java b/src/main/java/forestry/arboriculture/blocks/BlockArbDoor.java index 8ffcff07d..caec444b8 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockArbDoor.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArbDoor.java @@ -10,23 +10,10 @@ ******************************************************************************/ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; import java.util.Random; -import net.minecraft.block.BlockDoor; -import net.minecraft.block.material.Material; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumForestryWoodType; import forestry.api.arboriculture.TreeManager; import forestry.api.arboriculture.WoodBlockKind; @@ -37,6 +24,17 @@ import forestry.api.core.Tabs; import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.WoodHelper; import forestry.core.proxy.Proxies; +import net.minecraft.block.BlockDoor; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelBakery; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class BlockArbDoor extends BlockDoor implements IWoodTyped, IItemModelRegister, IStateMapperRegister { private final EnumForestryWoodType woodType; @@ -62,7 +60,6 @@ public class BlockArbDoor extends BlockDoor implements IWoodTyped, IItemModelReg Proxies.render.registerStateMapper(this, new WoodTypeStateMapper(this, null).addPropertyToRemove(POWERED)); } - @Nonnull @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.DOOR; @@ -73,13 +70,11 @@ public class BlockArbDoor extends BlockDoor implements IWoodTyped, IItemModelReg return false; } - @Nonnull @Override public EnumForestryWoodType getWoodType(int meta) { return woodType; } - @Nonnull @Override public Collection getWoodTypes() { return Collections.singleton(woodType); @@ -97,7 +92,7 @@ public class BlockArbDoor extends BlockDoor implements IWoodTyped, IItemModelReg */ @Override public Item getItemDropped(IBlockState state, Random rand, int fortune) { - return state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER ? null : getItem(); + return state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER ? Items.AIR : getItem(); } @Override diff --git a/src/main/java/forestry/arboriculture/blocks/fence/BlockArbFence.java b/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java similarity index 91% rename from src/main/java/forestry/arboriculture/blocks/fence/BlockArbFence.java rename to src/main/java/forestry/arboriculture/blocks/BlockArbFence.java index edf48d83f..a6c6a035e 100644 --- a/src/main/java/forestry/arboriculture/blocks/fence/BlockArbFence.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArbFence.java @@ -8,9 +8,8 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.fence; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -18,7 +17,6 @@ import forestry.api.arboriculture.EnumForestryWoodType; import forestry.api.core.IItemModelRegister; import forestry.api.core.IStateMapperRegister; import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.blocks.property.PropertyForestryWoodType; public abstract class BlockArbFence extends BlockForestryFence implements IWoodTyped, IItemModelRegister, IStateMapperRegister { public static List create(boolean fireproof) { @@ -28,7 +26,6 @@ public abstract class BlockArbFence extends BlockForestryFence { public static List create(boolean fireproof) { @@ -24,7 +22,6 @@ public abstract class BlockArbLog extends BlockForestryLog for (int i = 0; i < variants.length; i++) { PropertyForestryWoodType variant = variants[i]; BlockArbLog block = new BlockArbLog(fireproof, i) { - @Nonnull @Override public PropertyForestryWoodType getVariant() { return variant; @@ -39,7 +36,6 @@ public abstract class BlockArbLog extends BlockForestryLog super(fireproof, blockNumber); } - @Nonnull @Override public EnumForestryWoodType getWoodType(int meta) { int variantCount = getVariant().getAllowedValues().size(); diff --git a/src/main/java/forestry/arboriculture/blocks/planks/BlockArbPlanks.java b/src/main/java/forestry/arboriculture/blocks/BlockArbPlanks.java similarity index 90% rename from src/main/java/forestry/arboriculture/blocks/planks/BlockArbPlanks.java rename to src/main/java/forestry/arboriculture/blocks/BlockArbPlanks.java index a5f880e34..64d5aabc1 100644 --- a/src/main/java/forestry/arboriculture/blocks/planks/BlockArbPlanks.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockArbPlanks.java @@ -8,14 +8,12 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.planks; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import forestry.api.arboriculture.EnumForestryWoodType; -import forestry.arboriculture.blocks.property.PropertyForestryWoodType; public abstract class BlockArbPlanks extends BlockForestryPlanks { public static List create(boolean fireproof) { @@ -24,7 +22,6 @@ public abstract class BlockArbPlanks extends BlockForestryPlanks implements IWoodTyped, IItemModelRegister, IStateMapperRegister { public static List create(boolean fireproof, final boolean doubleSlab) { @@ -27,7 +25,6 @@ public abstract class BlockArbSlab extends BlockForestrySlab list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (IBlockState state : getBlockState().getValidStates()) { int meta = getMetaFromState(state); - ItemStack itemStack = new ItemStack(item, 1, meta); + ItemStack itemStack = new ItemStack(itemIn, 1, meta); list.add(itemStack); } } + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { TreeDefinition treeDefinition = blockState.getValue(getVariant()); if (TreeDefinition.Willow.equals(treeDefinition)) { return null; @@ -113,8 +109,7 @@ public abstract class BlockDecorativeLeaves extends Block implements IItemModelR } @Override - public boolean isVisuallyOpaque() - { + public boolean causesSuffocation(IBlockState state) { return false; } @@ -145,7 +140,6 @@ public abstract class BlockDecorativeLeaves extends Block implements IItemModelR return getDefaultState().withProperty(getVariant(), type); } - @Nonnull public TreeDefinition getTreeType(int meta) { int variantCount = getVariant().getAllowedValues().size(); int variantMeta = (meta % variantCount) + blockNumber * VARIANTS_PER_BLOCK; @@ -168,7 +162,7 @@ public abstract class BlockDecorativeLeaves extends Block implements IItemModelR } @Override - public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { + public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) { TreeDefinition type = getTreeType(meta); return getDefaultState().withProperty(getVariant(), type); } @@ -208,12 +202,8 @@ public abstract class BlockDecorativeLeaves extends Block implements IItemModelR @Override @SideOnly(Side.CLIENT) - public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex) { + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { TreeDefinition treeDefinition = state.getValue(getVariant()); - if (treeDefinition == null) { - return PluginArboriculture.proxy.getFoliageColorBasic(); - } - ITreeGenome genome = treeDefinition.getGenome(); if (tintIndex == 0) { diff --git a/src/main/java/forestry/arboriculture/blocks/fence/BlockFireproofVanillaFence.java b/src/main/java/forestry/arboriculture/blocks/BlockFireproofVanillaFence.java similarity index 86% rename from src/main/java/forestry/arboriculture/blocks/fence/BlockFireproofVanillaFence.java rename to src/main/java/forestry/arboriculture/blocks/BlockFireproofVanillaFence.java index 7acf41a2e..bfd0dbb7f 100644 --- a/src/main/java/forestry/arboriculture/blocks/fence/BlockFireproofVanillaFence.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockFireproofVanillaFence.java @@ -1,11 +1,9 @@ -package forestry.arboriculture.blocks.fence; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import forestry.api.arboriculture.EnumVanillaWoodType; -import forestry.arboriculture.blocks.property.PropertyVanillaWoodType; public abstract class BlockFireproofVanillaFence extends BlockForestryFence { public static List create() { @@ -15,7 +13,6 @@ public abstract class BlockFireproofVanillaFence extends BlockForestryFence { public static List create() { @@ -24,7 +22,6 @@ public abstract class BlockFireproofVanillaLog extends BlockForestryLog { public static List create() { @@ -14,7 +12,6 @@ public abstract class BlockFireproofVanillaPlanks extends BlockForestryPlanks implements IWoodTyped, IItemModelRegister, IStateMapperRegister { public static List create(final boolean doubleSlab) { @@ -27,7 +25,6 @@ public abstract class BlockFireproofVanillaSlab extends BlockForestrySlab & IWoodType> extends BlockFence implements IWoodTyped, IItemModelRegister, IStateMapperRegister { protected static final int VARIANTS_PER_BLOCK = 16; @@ -67,7 +63,6 @@ public abstract class BlockForestryFence & IWoodType> extends setCreativeTab(Tabs.tabArboriculture); } - @Nonnull public abstract PropertyWoodType getVariant(); @Override @@ -88,7 +83,7 @@ public abstract class BlockForestryFence & IWoodType> extends } if (block != Blocks.BARRIER) { - Material blockMaterial = block.getMaterial(blockState); + Material blockMaterial = blockState.getMaterial(); if (block instanceof BlockFence || block instanceof BlockFenceGate) { return blockMaterial == this.blockMaterial; } @@ -130,7 +125,6 @@ public abstract class BlockForestryFence & IWoodType> extends return 5; } - @Nonnull @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.FENCE; @@ -147,11 +141,9 @@ public abstract class BlockForestryFence & IWoodType> extends return getDefaultState().withProperty(getVariant(), woodType); } - @Nonnull @Override public abstract T getWoodType(int meta); - @Nonnull @Override public Collection getWoodTypes() { return getVariant().getAllowedValues(); @@ -168,13 +160,13 @@ public abstract class BlockForestryFence & IWoodType> extends } @Override - public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { + public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) { T woodType = getWoodType(meta); return getDefaultState().withProperty(getVariant(), woodType); } @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (T woodType : getVariant().getAllowedValues()) { list.add(TreeManager.woodAccess.getStack(woodType, getBlockKind(), fireproof)); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java index d8720f141..8706899bc 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryFenceGate.java @@ -10,26 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; -import java.util.List; - -import net.minecraft.block.BlockFenceGate; -import net.minecraft.block.BlockPlanks.EnumType; -import net.minecraft.block.SoundType; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.TreeManager; @@ -42,6 +24,21 @@ import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.WoodHelper; import forestry.arboriculture.WoodHelper.WoodMeshDefinition; import forestry.core.proxy.Proxies; +import net.minecraft.block.BlockFenceGate; +import net.minecraft.block.BlockPlanks.EnumType; +import net.minecraft.block.SoundType; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelBakery; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class BlockForestryFenceGate & IWoodType> extends BlockFenceGate implements IWoodTyped, IItemModelRegister, IStateMapperRegister { @@ -52,17 +49,17 @@ public class BlockForestryFenceGate & IWoodType> extends Block super(EnumType.OAK); this.fireproof = fireproof; this.woodType = woodType; - + setHardness(2.0F); setResistance(5.0F); setSoundType(SoundType.WOOD); - setCreativeTab(Tabs.tabArboriculture); - } - - @Override - public boolean isFireproof() { - return fireproof; - } + setCreativeTab(Tabs.tabArboriculture); + } + + @Override + public boolean isFireproof() { + return fireproof; + } @Override public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) { @@ -79,20 +76,17 @@ public class BlockForestryFenceGate & IWoodType> extends Block } return 5; } - - @Nonnull + @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.FENCE_GATE; } - - @Nonnull + @Override public T getWoodType(int meta) { return woodType; } - - @Nonnull + @Override public Collection getWoodTypes() { return Collections.singleton(woodType); @@ -103,19 +97,19 @@ public class BlockForestryFenceGate & IWoodType> extends Block public void registerStateMapper() { Proxies.render.registerStateMapper(this, new WoodTypeStateMapper(this, null).addPropertyToRemove(POWERED)); } - + @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { list.add(TreeManager.woodAccess.getStack(woodType, getBlockKind(), fireproof)); } - + @Override public float getBlockHardness(IBlockState blockState, World worldIn, BlockPos pos) { int meta = getMetaFromState(blockState); T woodType = getWoodType(meta); return woodType.getHardness(); } - + @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java index a4be1dccc..34e540c64 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryLeaves.java @@ -33,8 +33,8 @@ import forestry.arboriculture.PluginArboriculture; import forestry.arboriculture.genetics.TreeDefinition; import forestry.arboriculture.tiles.TileLeaves; import forestry.core.blocks.IColoredBlock; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileUtil; import forestry.core.utils.BlockUtil; @@ -58,6 +58,7 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; @@ -113,9 +114,8 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi return new TileLeaves(); } - @SideOnly(Side.CLIENT) @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { } @@ -135,12 +135,11 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi float saplingModifier = 1.0f; ItemStack held = player.inventory.getCurrentItem(); - if (held != null && held.getItem() instanceof IToolGrafter) { + if (held.getItem() instanceof IToolGrafter) { saplingModifier = ((IToolGrafter) held.getItem()).getSaplingModifier(held, world, player, pos); held.damageItem(1, player); - if (held.stackSize <= 0) { + if (held.isEmpty()) { net.minecraftforge.event.ForgeEventFactory.onPlayerDestroyItem(player, held, EnumHand.MAIN_HAND); - player.setHeldItem(EnumHand.MAIN_HAND, null); } } @@ -196,12 +195,12 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { TileLeaves leaves = TileUtil.getTile(world, pos, TileLeaves.class); if (leaves == null) { - return null; + return ItemStack.EMPTY; } ITree tree = leaves.getTree(); if (tree == null) { - return null; + return ItemStack.EMPTY; } String speciesUid = tree.getGenome().getPrimary().getUID(); @@ -219,12 +218,18 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi speciesUid = tree.getGenome().getPrimary().getUID(); } } - - return Collections.singletonList(PluginArboriculture.blocks.getDecorativeLeaves(speciesUid)); + + ItemStack decorativeLeaves = PluginArboriculture.blocks.getDecorativeLeaves(speciesUid); + if (decorativeLeaves.isEmpty()) { + return Collections.emptyList(); + } else { + return Collections.singletonList(decorativeLeaves); + } } - + + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { TileLeaves tileLeaves = TileUtil.getTile(worldIn, pos, TileLeaves.class); if (tileLeaves != null && TreeDefinition.Willow.getUID().equals(tileLeaves.getSpeciesUID())) { return null; @@ -304,17 +309,18 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi } @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { TileEntity tile = worldIn.getTileEntity(pos); IButterfly caterpillar = tile instanceof TileLeaves ? ((TileLeaves) tile).getCaterpillar() : null; - if (heldItem != null && heldItem.getItem() instanceof IToolScoop && caterpillar != null) { + ItemStack heldItem = playerIn.getHeldItem(hand); + if (heldItem.getItem() instanceof IToolScoop && caterpillar != null) { ItemStack butterfly = ButterflyManager.butterflyRoot.getMemberStack(caterpillar, EnumFlutterType.CATERPILLAR); ItemStackUtil.dropItemStackAsEntity(butterfly, worldIn, pos); ((TileLeaves) tile).setCaterpillar(null); return true; } - return super.onBlockActivated(worldIn, pos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ); + return super.onBlockActivated(worldIn, pos, state, playerIn, hand, facing, hitX, hitY, hitZ); } /* IGrowable */ @@ -322,10 +328,7 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi @Override public boolean canGrow(World world, BlockPos pos, IBlockState state, boolean isClient) { TileLeaves leafTile = TileUtil.getTile(world, pos, TileLeaves.class); - if (leafTile != null) { - return leafTile.hasFruit() && leafTile.getRipeness() < 1.0f; - } - return false; + return leafTile != null && leafTile.hasFruit() && leafTile.getRipeness() < 1.0f; } @Override @@ -342,17 +345,18 @@ public class BlockForestryLeaves extends BlockLeaves implements ITileEntityProvi } @Override - public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex) { - TileLeaves leaves = TileUtil.getTile(worldIn, pos, TileLeaves.class); - if (leaves == null) { - return PluginArboriculture.proxy.getFoliageColorBasic(); - } - - if (tintIndex == 0) { - EntityPlayer thePlayer = Proxies.common.getPlayer(); - return leaves.getFoliageColour(thePlayer); - } else { - return leaves.getFruitColour(); + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { + if (worldIn != null && pos != null) { + TileLeaves leaves = TileUtil.getTile(worldIn, pos, TileLeaves.class); + if (leaves != null) { + if (tintIndex == 0) { + EntityPlayer thePlayer = Proxies.common.getPlayer(); + return leaves.getFoliageColour(thePlayer); + } else { + return leaves.getFruitColour(); + } + } } + return PluginArboriculture.proxy.getFoliageColorBasic(); } } diff --git a/src/main/java/forestry/arboriculture/blocks/log/BlockForestryLog.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java similarity index 86% rename from src/main/java/forestry/arboriculture/blocks/log/BlockForestryLog.java rename to src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java index 866cdc8b9..f173e0ca0 100644 --- a/src/main/java/forestry/arboriculture/blocks/log/BlockForestryLog.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryLog.java @@ -1,24 +1,6 @@ -package forestry.arboriculture.blocks.log; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; -import java.util.List; - -import net.minecraft.block.BlockLog; -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.TreeManager; @@ -29,9 +11,22 @@ import forestry.api.core.IStateMapperRegister; import forestry.api.core.Tabs; import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.WoodHelper; -import forestry.arboriculture.blocks.WoodTypeStateMapper; -import forestry.arboriculture.blocks.property.PropertyWoodType; import forestry.core.proxy.Proxies; +import net.minecraft.block.BlockLog; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelBakery; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BlockForestryLog & IWoodType> extends BlockLog implements IWoodTyped, IStateMapperRegister, IItemModelRegister { protected static final int VARIANTS_PER_BLOCK = 4; @@ -50,7 +45,7 @@ public abstract class BlockForestryLog & IWoodType> extends Bl setCreativeTab(Tabs.tabArboriculture); } - @Nonnull + @Override public final WoodBlockKind getBlockKind() { return WoodBlockKind.LOG; @@ -104,14 +99,11 @@ public abstract class BlockForestryLog & IWoodType> extends Bl return i; } - @Nonnull public abstract PropertyWoodType getVariant(); - @Nonnull @Override public abstract T getWoodType(int meta); - @Nonnull @Override public final Collection getWoodTypes() { return getVariant().getAllowedValues(); @@ -122,27 +114,20 @@ public abstract class BlockForestryLog & IWoodType> extends Bl return new BlockStateContainer(this, getVariant(), LOG_AXIS); } - @Override - protected final ItemStack createStackedBlock(IBlockState state) { - int meta = damageDropped(state); - Item item = Item.getItemFromBlock(this); - return new ItemStack(item, 1, meta); - } - @Override public final int damageDropped(IBlockState state) { return state.getValue(getVariant()).getMetadata() - blockNumber * VARIANTS_PER_BLOCK; } @Override - public final IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { + public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { EnumAxis axis = EnumAxis.fromFacingAxis(facing.getAxis()); T woodType = getWoodType(meta); return getDefaultState().withProperty(getVariant(), woodType).withProperty(LOG_AXIS, axis); } @Override - public final void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (T woodType : getVariant().getAllowedValues()) { list.add(TreeManager.woodAccess.getStack(woodType, getBlockKind(), fireproof)); } diff --git a/src/main/java/forestry/arboriculture/blocks/planks/BlockForestryPlanks.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryPlanks.java similarity index 88% rename from src/main/java/forestry/arboriculture/blocks/planks/BlockForestryPlanks.java rename to src/main/java/forestry/arboriculture/blocks/BlockForestryPlanks.java index 68cb7e5df..7b2118daf 100644 --- a/src/main/java/forestry/arboriculture/blocks/planks/BlockForestryPlanks.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryPlanks.java @@ -1,9 +1,17 @@ -package forestry.arboriculture.blocks.planks; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; -import java.util.List; +import forestry.api.arboriculture.IWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.arboriculture.WoodBlockKind; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.WoodHelper; +import forestry.core.proxy.Proxies; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; @@ -15,26 +23,14 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.arboriculture.IWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.arboriculture.WoodBlockKind; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.WoodHelper; -import forestry.arboriculture.blocks.WoodTypeStateMapper; -import forestry.arboriculture.blocks.property.PropertyWoodType; -import forestry.core.proxy.Proxies; - public abstract class BlockForestryPlanks & IWoodType> extends Block implements IWoodTyped, IStateMapperRegister, IItemModelRegister { protected static final int VARIANTS_PER_BLOCK = 16; @@ -60,10 +56,8 @@ public abstract class BlockForestryPlanks & IWoodType> extends return fireproof; } - @Nonnull public abstract PropertyWoodType getVariant(); - @Nonnull @Override public abstract T getWoodType(int meta); @@ -71,7 +65,6 @@ public abstract class BlockForestryPlanks & IWoodType> extends return blockNumber; } - @Nonnull @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.PLANKS; @@ -83,7 +76,6 @@ public abstract class BlockForestryPlanks & IWoodType> extends return getDefaultState().withProperty(getVariant(), woodType); } - @Nonnull @Override public Collection getWoodTypes() { return getVariant().getAllowedValues(); @@ -105,13 +97,13 @@ public abstract class BlockForestryPlanks & IWoodType> extends } @Override - public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) { + public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) { T woodType = getWoodType(meta); return getDefaultState().withProperty(getVariant(), woodType); } @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (T woodType : getVariant().getAllowedValues()) { list.add(TreeManager.woodAccess.getStack(woodType, getBlockKind(), fireproof)); } diff --git a/src/main/java/forestry/arboriculture/blocks/slab/BlockForestrySlab.java b/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java similarity index 93% rename from src/main/java/forestry/arboriculture/blocks/slab/BlockForestrySlab.java rename to src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java index defa0c3ce..193a69921 100644 --- a/src/main/java/forestry/arboriculture/blocks/slab/BlockForestrySlab.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestrySlab.java @@ -1,10 +1,18 @@ -package forestry.arboriculture.blocks.slab; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; -import java.util.List; import java.util.Random; +import forestry.api.arboriculture.IWoodType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.arboriculture.WoodBlockKind; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.api.core.Tabs; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.WoodHelper; +import forestry.core.proxy.Proxies; import net.minecraft.block.BlockSlab; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; @@ -16,26 +24,13 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.arboriculture.IWoodType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.arboriculture.WoodBlockKind; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.api.core.Tabs; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.WoodHelper; -import forestry.arboriculture.blocks.WoodTypeStateMapper; -import forestry.arboriculture.blocks.property.PropertyWoodType; -import forestry.core.proxy.Proxies; - public abstract class BlockForestrySlab & IWoodType> extends BlockSlab implements IWoodTyped, IItemModelRegister, IStateMapperRegister { protected static final int VARIANTS_PER_BLOCK = 8; @@ -69,20 +64,17 @@ public abstract class BlockForestrySlab & IWoodType> extends B return fireproof; } - @Nonnull public abstract PropertyWoodType getVariant(); public int getBlockNumber() { return blockNumber; } - @Nonnull @Override protected BlockStateContainer createBlockState() { return this.isDouble() ? new BlockStateContainer(this, getVariant()) : new BlockStateContainer(this, HALF, getVariant()); } - @Nonnull @Override public IBlockState getStateFromMeta(int meta) { T woodType = getWoodType(meta); @@ -95,7 +87,6 @@ public abstract class BlockForestrySlab & IWoodType> extends B return iblockstate; } - @Nonnull @Override public abstract T getWoodType(int meta); @@ -145,7 +136,7 @@ public abstract class BlockForestrySlab & IWoodType> extends B } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { if (!isDouble()) { for (T woodType : getVariant().getAllowedValues()) { list.add(TreeManager.woodAccess.getStack(woodType, getBlockKind(), fireproof)); @@ -170,7 +161,6 @@ public abstract class BlockForestrySlab & IWoodType> extends B return fireproof ? 0 : 5; } - @Nonnull @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.SLAB; @@ -186,7 +176,6 @@ public abstract class BlockForestrySlab & IWoodType> extends B return getWoodType(stack.getMetadata()); } - @Nonnull @Override public Collection getWoodTypes() { return getVariant().getAllowedValues(); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java b/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java index 5bbed4878..320ee5789 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockForestryStairs.java @@ -1,21 +1,8 @@ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; import java.util.Collections; -import net.minecraft.block.BlockStairs; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.item.Item; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.WoodBlockKind; import forestry.api.core.IItemModelRegister; @@ -25,6 +12,16 @@ import forestry.api.core.Tabs; import forestry.arboriculture.IWoodTyped; import forestry.arboriculture.WoodHelper; import forestry.core.proxy.Proxies; +import net.minecraft.block.BlockStairs; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelBakery; +import net.minecraft.item.Item; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class BlockForestryStairs & IWoodType> extends BlockStairs implements IWoodTyped, IItemModelRegister, IStateMapperRegister { private final boolean fireproof; @@ -57,19 +54,16 @@ public class BlockForestryStairs & IWoodType> extends BlockSta return fireproof; } - @Nonnull @Override public WoodBlockKind getBlockKind() { return WoodBlockKind.STAIRS; } - @Nonnull @Override public T getWoodType(int meta) { return woodType; } - @Nonnull @Override public Collection getWoodTypes() { return Collections.singleton(woodType); diff --git a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java index d4b253f11..7121011e3 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockFruitPod.java @@ -10,12 +10,12 @@ ******************************************************************************/ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import net.minecraft.block.BlockCocoa; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.state.IBlockState; @@ -33,7 +33,6 @@ import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.core.IStateMapperRegister; -import forestry.arboriculture.genetics.alleles.AlleleFruit; import forestry.arboriculture.render.FruitPodStateMapper; import forestry.arboriculture.tiles.TileFruitPod; import forestry.core.proxy.Proxies; @@ -45,21 +44,19 @@ public class BlockFruitPod extends BlockCocoa implements IStateMapperRegister, I public static List create() { List blocks = new ArrayList<>(); - for (IAlleleFruit fruit : AlleleFruit.getFruitAllelesWithModels()) { + for (IAlleleFruit fruit : AlleleFruits.getFruitAllelesWithModels()) { BlockFruitPod block = new BlockFruitPod(fruit); blocks.add(block); } return blocks; } - @Nonnull private final IAlleleFruit fruit; - private BlockFruitPod(@Nonnull IAlleleFruit fruit) { + private BlockFruitPod( IAlleleFruit fruit) { this.fruit = fruit; } - - @Nonnull + public IAlleleFruit getFruit() { return fruit; } @@ -68,7 +65,7 @@ public class BlockFruitPod extends BlockCocoa implements IStateMapperRegister, I public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { TileFruitPod tile = TileUtil.getTile(world, pos, TileFruitPod.class); if (tile == null) { - return null; + return ItemStack.EMPTY; } return tile.getPickBlock(); } @@ -135,10 +132,7 @@ public class BlockFruitPod extends BlockCocoa implements IStateMapperRegister, I @Override public boolean canGrow(World world, BlockPos pos, IBlockState state, boolean isClient) { TileFruitPod podTile = TileUtil.getTile(world, pos, TileFruitPod.class); - if (podTile != null) { - return podTile.canMature(); - } - return false; + return podTile != null && podTile.canMature(); } @Override diff --git a/src/main/java/forestry/arboriculture/blocks/BlockPile.java b/src/main/java/forestry/arboriculture/blocks/BlockPile.java index 99a3662dc..7adbb604c 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockPile.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockPile.java @@ -1,6 +1,6 @@ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; @@ -31,8 +31,8 @@ import forestry.arboriculture.render.PileStateMapper; import forestry.arboriculture.tiles.TilePile; import forestry.core.PluginCore; import forestry.core.blocks.BlockStructure; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.multiblock.MultiblockLogic; import forestry.core.proxy.Proxies; import forestry.core.render.ParticleHelper; @@ -61,12 +61,12 @@ import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.property.ExtendedBlockState; @@ -77,103 +77,103 @@ import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BlockPile extends BlockStructure implements ITileEntityProvider, IStateMapperRegister, ISpriteRegister { - /** - * B: .. T: x. - * B: .. T: x. - */ - protected static final AxisAlignedBB AABB_QTR_TOP_WEST = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 0.5D, 1.0D, 1.0D); - /** - * B: .. T: .x - * B: .. T: .x - */ - protected static final AxisAlignedBB AABB_QTR_TOP_EAST = new AxisAlignedBB(0.5D, 0.5D, 0.0D, 1.0D, 1.0D, 1.0D); - /** - * B: .. T: xx - * B: .. T: .. - */ - protected static final AxisAlignedBB AABB_QTR_TOP_NORTH = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 1.0D, 1.0D, 0.5D); - /** - * B: .. T: .. - * B: .. T: xx - */ - protected static final AxisAlignedBB AABB_QTR_TOP_SOUTH = new AxisAlignedBB(0.0D, 0.5D, 0.5D, 1.0D, 1.0D, 1.0D); - /** - * B: .. T: x. - * B: .. T: .. - */ - protected static final AxisAlignedBB AABB_OCT_TOP_NW = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 0.5D, 1.0D, 0.5D); - /** - * B: .. T: .x - * B: .. T: .. - */ - protected static final AxisAlignedBB AABB_OCT_TOP_NE = new AxisAlignedBB(0.5D, 0.5D, 0.0D, 1.0D, 1.0D, 0.5D); - /** - * B: .. T: .. - * B: .. T: x. - */ - protected static final AxisAlignedBB AABB_OCT_TOP_SW = new AxisAlignedBB(0.0D, 0.5D, 0.5D, 0.5D, 1.0D, 1.0D); - /** - * B: .. T: .. - * B: .. T: .x - */ - protected static final AxisAlignedBB AABB_OCT_TOP_SE = new AxisAlignedBB(0.5D, 0.5D, 0.5D, 1.0D, 1.0D, 1.0D); - /** - * B: xx T: .. - * B: xx T: .. - */ - protected static final AxisAlignedBB AABB_SLAB_BOTTOM = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5D, 1.0D); - + /** + * B: .. T: x. + * B: .. T: x. + */ + protected static final AxisAlignedBB AABB_QTR_TOP_WEST = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 0.5D, 1.0D, 1.0D); + /** + * B: .. T: .x + * B: .. T: .x + */ + protected static final AxisAlignedBB AABB_QTR_TOP_EAST = new AxisAlignedBB(0.5D, 0.5D, 0.0D, 1.0D, 1.0D, 1.0D); + /** + * B: .. T: xx + * B: .. T: .. + */ + protected static final AxisAlignedBB AABB_QTR_TOP_NORTH = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 1.0D, 1.0D, 0.5D); + /** + * B: .. T: .. + * B: .. T: xx + */ + protected static final AxisAlignedBB AABB_QTR_TOP_SOUTH = new AxisAlignedBB(0.0D, 0.5D, 0.5D, 1.0D, 1.0D, 1.0D); + /** + * B: .. T: x. + * B: .. T: .. + */ + protected static final AxisAlignedBB AABB_OCT_TOP_NW = new AxisAlignedBB(0.0D, 0.5D, 0.0D, 0.5D, 1.0D, 0.5D); + /** + * B: .. T: .x + * B: .. T: .. + */ + protected static final AxisAlignedBB AABB_OCT_TOP_NE = new AxisAlignedBB(0.5D, 0.5D, 0.0D, 1.0D, 1.0D, 0.5D); + /** + * B: .. T: .. + * B: .. T: x. + */ + protected static final AxisAlignedBB AABB_OCT_TOP_SW = new AxisAlignedBB(0.0D, 0.5D, 0.5D, 0.5D, 1.0D, 1.0D); + /** + * B: .. T: .. + * B: .. T: .x + */ + protected static final AxisAlignedBB AABB_OCT_TOP_SE = new AxisAlignedBB(0.5D, 0.5D, 0.5D, 1.0D, 1.0D, 1.0D); + /** + * B: xx T: .. + * B: xx T: .. + */ + protected static final AxisAlignedBB AABB_SLAB_BOTTOM = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.5D, 1.0D); + public static final PropertyEnum PILE_POSITION = PropertyEnum.create("position", EnumPilePosition.class); public final ParticleHelper.Callback particleCallback; - + public static Map create() { Map blockMap = new EnumMap<>(EnumPileType.class); for (final EnumPileType type : EnumPileType.VALUES) { BlockPile pile = new BlockPile() { - + @Override public String getHarvestTool(IBlockState state) { - if(type == EnumPileType.WOOD){ + if (type == EnumPileType.WOOD) { return "axe"; - }else{ + } else { return "shovel"; } } - + @Override public int getHarvestLevel(IBlockState state) { return 0; } - + @Override public EnumPileType getPileType() { return type; } - + @Override - public SoundType getSoundType() { - if(type == EnumPileType.DIRT){ - return Blocks.DIRT.getSoundType(); - }else if(type == EnumPileType.ASH){ - return Blocks.SAND.getSoundType(); - }else if(type == EnumPileType.WOOD){ - return Blocks.LOG.getSoundType(); + public SoundType getSoundType(IBlockState state, World world, BlockPos pos, @Nullable Entity entity) { + if (type == EnumPileType.DIRT) { + return Blocks.DIRT.getSoundType(state, world, pos, entity); + } else if (type == EnumPileType.ASH) { + return Blocks.SAND.getSoundType(state, world, pos, entity); + } else if (type == EnumPileType.WOOD) { + return Blocks.LOG.getSoundType(state, world, pos, entity); } - return super.getSoundType(); + return super.getSoundType(state, world, pos, entity); } }; blockMap.put(type, pile); } return blockMap; } - + public BlockPile() { super(Material.GROUND); setHardness(1.0F); setUnlocalizedName("charcoal.pile"); setCreativeTab(Tabs.tabArboriculture); setDefaultState(blockState.getBaseState().withProperty(PILE_POSITION, EnumPilePosition.INTERIOR)); - + particleCallback = new PileParticleCallback(this); } @@ -181,64 +181,60 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro protected BlockStateContainer createBlockState() { return new ExtendedBlockState(this, new IProperty[]{PILE_POSITION}, new IUnlistedProperty[]{UnlistedBlockPos.POS, UnlistedBlockAccess.BLOCKACCESS}); } - + @Override public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { return ((IExtendedBlockState) super.getExtendedState(state, world, pos)).withProperty(UnlistedBlockPos.POS, pos) .withProperty(UnlistedBlockAccess.BLOCKACCESS, world); } - - @Override - public RayTraceResult collisionRayTrace(IBlockState blockState, World worldIn, BlockPos pos, Vec3d start, Vec3d end){ - List list = Lists.newArrayList(); - for (AxisAlignedBB axisalignedbb : getCollisionBoxList(this.getActualState(blockState, worldIn, pos))) - { - list.add(this.rayTrace(pos, start, end, axisalignedbb)); - } + @Override + public RayTraceResult collisionRayTrace(IBlockState blockState, World worldIn, BlockPos pos, Vec3d start, Vec3d end) { + List list = Lists.newArrayList(); - RayTraceResult raytraceresult1 = null; - double d1 = 0.0D; + for (AxisAlignedBB axisalignedbb : getCollisionBoxList(this.getActualState(blockState, worldIn, pos))) { + list.add(this.rayTrace(pos, start, end, axisalignedbb)); + } - for (RayTraceResult raytraceresult : list) - { - if (raytraceresult != null) - { - double d0 = raytraceresult.hitVec.squareDistanceTo(end); + RayTraceResult raytraceresult1 = null; + double d1 = 0.0D; - if (d0 > d1) - { - raytraceresult1 = raytraceresult; - d1 = d0; - } - } - } + for (RayTraceResult raytraceresult : list) { + if (raytraceresult != null) { + double d0 = raytraceresult.hitVec.squareDistanceTo(end); - return raytraceresult1; - } - - @Override - public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List collidingBoxes, Entity entityIn){ - state = this.getActualState(state, worldIn, pos); + if (d0 > d1) { + raytraceresult1 = raytraceresult; + d1 = d0; + } + } + } - for (AxisAlignedBB axisalignedbb : getCollisionBoxList(state)){ - addCollisionBoxToList(pos, entityBox, collidingBoxes, axisalignedbb); - } - } + return raytraceresult1; + } - private static List getCollisionBoxList(IBlockState state){ - List list = Lists.newArrayList(); - EnumPilePosition position = state.getValue(PILE_POSITION); - - if(position != EnumPilePosition.INTERIOR){ - list.add(AABB_SLAB_BOTTOM); - - switch (position) { + @Override + public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List collidingBoxes, @Nullable Entity entityIn) { + state = this.getActualState(state, worldIn, pos); + + for (AxisAlignedBB axisalignedbb : getCollisionBoxList(state)) { + addCollisionBoxToList(pos, entityBox, collidingBoxes, axisalignedbb); + } + } + + private static List getCollisionBoxList(IBlockState state) { + List list = Lists.newArrayList(); + EnumPilePosition position = state.getValue(PILE_POSITION); + + if (position != EnumPilePosition.INTERIOR) { + list.add(AABB_SLAB_BOTTOM); + + switch (position) { case BACK: list.add(AABB_QTR_TOP_SOUTH); break; case FRONT: - list.add(AABB_QTR_TOP_NORTH); + list.add(AABB_QTR_TOP_NORTH); break; case SIDE_LEFT: list.add(AABB_QTR_TOP_EAST); @@ -261,28 +257,28 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro default: break; } - }else{ - list.add(Block.FULL_BLOCK_AABB); - } + } else { + list.add(Block.FULL_BLOCK_AABB); + } + + return list; + } - return list; - } - @Override public int getMetaFromState(IBlockState state) { return state.getValue(PILE_POSITION).ordinal(); } - + @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(PILE_POSITION, EnumPilePosition.values()[meta]); } - + @Override public TileEntity createNewTileEntity(World world, int meta) { return new TilePile(); } - + @Override public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); @@ -294,16 +290,16 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro } return super.getLightValue(state, world, pos); } - + @SideOnly(Side.CLIENT) @Override public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { TilePile pile = TileUtil.getTile(world, pos, TilePile.class); - if(pile == null){ + if (pile == null) { return; } MultiblockLogic logic = pile.getMultiblockLogic(); - + if (logic.isConnected() && logic.getController().isAssembled() && logic.getController().isActive() && state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR) { float f = pos.getX() + 0.5F; float f1 = pos.getY() + 0.0F + rand.nextFloat() * 6.0F / 16.0F; @@ -316,7 +312,7 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro @SideOnly(Side.CLIENT) @Override - public void getSubBlocks(Item item, CreativeTabs tab, List subItems) { + public void getSubBlocks(Item item, CreativeTabs tab, NonNullList subItems) { if (getPileType() == EnumPileType.WOOD) { List woodPiles = new ArrayList<>(); for (ITree tree : TreeManager.treeRoot.getIndividualTemplates()) { @@ -329,60 +325,56 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro super.getSubBlocks(item, tab, subItems); } } - + private long previousMessageTick = 0; - + @Override - public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { - if(world.isRemote){ - return false; - } - - if (player.isSneaking()) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + if (worldIn.isRemote) { return false; } - TilePile pile = TileUtil.getTile(world, pos, TilePile.class); - - if(pile == null) { + if (playerIn.isSneaking()) { return false; } - + + TilePile pile = TileUtil.getTile(worldIn, pos, TilePile.class); + + if (pile == null) { + return false; + } + ICharcoalPileControllerInternal controller = pile.getMultiblockLogic().getController(); + ItemStack heldItem = playerIn.getHeldItem(hand); // If the player's hands are empty and they right-click on a multiblock, they get a // multiblock-debugging message if the machine is not assembled. - if (heldItem == null) { - if (controller != null) { - if (!controller.isAssembled()) { - String validationError = controller.getLastValidationError(); - if (validationError != null) { - long tick = world.getTotalWorldTime(); - if (tick > previousMessageTick + 20) { - player.addChatMessage(new TextComponentString(validationError)); - previousMessageTick = tick; - } - return true; + if (heldItem.isEmpty()) { + if (!controller.isAssembled()) { + String validationError = controller.getLastValidationError(); + if (validationError != null) { + long tick = worldIn.getTotalWorldTime(); + if (tick > previousMessageTick + 20) { + playerIn.sendMessage(new TextComponentString(validationError)); + previousMessageTick = tick; } + return true; } - } else { - player.addChatMessage(new TextComponentTranslation("for.multiblock.error.notConnected")); - return true; } - }else if(BlockCandle.lightingItems.contains(heldItem.getItem())) { - if (pile.getMultiblockLogic().isConnected() && controller != null && controller.isAssembled() && !controller.isActive()) { + } else if (BlockCandle.lightingItems.contains(heldItem.getItem())) { + if (pile.getMultiblockLogic().isConnected() && controller.isAssembled() && !controller.isActive()) { controller.setActive(true); return true; } } return false; } - + /* DROP HANDLING */ // Hack: When harvesting we need to get the drops in onBlockHarvested, // because Mojang destroys the block and tile before calling getDrops. private final ThreadLocal> drop = new ThreadLocal<>(); - + @Override public void onBlockHarvested(World world, BlockPos pos, IBlockState state, EntityPlayer player) { if (!world.isRemote) { @@ -390,8 +382,7 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro drop.set(getPileDrop(world, pos, state, fortune)); } } - - @Nonnull + @Override public List getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { List drops = drop.get(); @@ -405,7 +396,6 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro return drops; } - @Nonnull private List getPileDrop(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { List list = new ArrayList<>(); TileEntity tile = world.getTileEntity(pos); @@ -413,23 +403,18 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro ICharcoalPileComponent pile = (ICharcoalPileComponent) tile; if (getPileType() == EnumPileType.ASH) { - if (pile.getTreeSpecies() != null) { - IWoodProvider woodProvider = pile.getTreeSpecies().getWoodProvider(); - int charcoalAmount = woodProvider.getCarbonization(); - ItemStack charcoal = new ItemStack(Items.COAL, charcoalAmount, 1); - while(RANDOM.nextFloat() < woodProvider.getCharcoalChance(charcoalAmount)){ - charcoal.stackSize++; - } - list.add(charcoal); - int ashAmount = (int)(charcoalAmount / 1.5); - if(ashAmount <= 0){ - ashAmount = 1; - } - list.add(new ItemStack(PluginCore.items.ash, ashAmount)); - } else { - list.add(new ItemStack(Blocks.DIRT, 2)); - list.add(new ItemStack(PluginCore.items.ash, 2)); + IWoodProvider woodProvider = pile.getTreeSpecies().getWoodProvider(); + int charcoalAmount = woodProvider.getCarbonization(); + ItemStack charcoal = new ItemStack(Items.COAL, charcoalAmount, 1); + while (RANDOM.nextFloat() < woodProvider.getCharcoalChance(charcoalAmount)) { + charcoal.grow(1); } + list.add(charcoal); + int ashAmount = (int) (charcoalAmount / 1.5); + if (ashAmount <= 0) { + ashAmount = 1; + } + list.add(new ItemStack(PluginCore.items.ash, ashAmount)); } else if (getPileType() == EnumPileType.DIRT) { list.add(new ItemStack(this)); } else { @@ -438,52 +423,43 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro } return list; } - + @Override public void breakBlock(World world, BlockPos pos, IBlockState state) { //use to override world.removeTileEntity } - + @Override public boolean isOpaqueCube(IBlockState state) { - if(state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR){ - return false; - } - return true; + return state.getValue(PILE_POSITION) == EnumPilePosition.INTERIOR; } - + @Override public int getLightOpacity(IBlockState state) { - if(state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR){ + if (state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR) { return 0; } return super.getLightOpacity(state); } - + @Override public boolean isFullBlock(IBlockState state) { - if(state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR){ - return false; - } - return true; + return state.getValue(PILE_POSITION) == EnumPilePosition.INTERIOR; } - + @Override public boolean isFullCube(IBlockState state) { - if(state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR){ - return false; - } - return true; + return state.getValue(PILE_POSITION) == EnumPilePosition.INTERIOR; } - + @Override public EnumBlockRenderType getRenderType(IBlockState state) { - if(state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR){ + if (state.getValue(PILE_POSITION) != EnumPilePosition.INTERIOR) { return EnumBlockRenderType.INVISIBLE; } return EnumBlockRenderType.MODEL; } - + @Override @SideOnly(Side.CLIENT) public void registerStateMapper() { @@ -492,44 +468,44 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { - if(getPileType() == EnumPileType.WOOD){ + if (getPileType() == EnumPileType.WOOD) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof ICharcoalPileComponent) { return createWoodPile(((ICharcoalPileComponent) tile).getTreeSpecies()); } - }else if(getPileType() == EnumPileType.DIRT){ + } else if (getPileType() == EnumPileType.DIRT) { return super.getPickBlock(state, target, world, pos, player); } - return null; + return ItemStack.EMPTY; } @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { - if(getPileType() == EnumPileType.WOOD){ + if (getPileType() == EnumPileType.WOOD) { manager.registerItemModel(item, 0, "woodPile"); - }else if(getPileType() == EnumPileType.DIRT){ + } else if (getPileType() == EnumPileType.DIRT) { manager.registerItemModel(item, 0, "dirtPile"); - }else if(getPileType() == EnumPileType.ASH){ + } else if (getPileType() == EnumPileType.ASH) { manager.registerItemModel(item, 0, "ashPile"); } } - + @SideOnly(Side.CLIENT) @Override public void registerSprites(ITextureManager manager) { - for(IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()){ - if(allele instanceof IAlleleTreeSpecies){ + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleTreeSpecies) { IAlleleTreeSpecies treeSpecies = (IAlleleTreeSpecies) allele; treeSpecies.getWoodProvider().registerSprites(Item.getItemFromBlock(this), manager); } } } - + @SideOnly(Side.CLIENT) @Override - public boolean addHitEffects(IBlockState state, World worldObj, RayTraceResult target, ParticleManager effectRenderer) { - return ParticleHelper.addBlockHitEffects(worldObj, target.getBlockPos(), target.sideHit, effectRenderer, particleCallback); + public boolean addHitEffects(IBlockState state, World world, RayTraceResult target, ParticleManager effectRenderer) { + return ParticleHelper.addBlockHitEffects(world, target.getBlockPos(), target.sideHit, effectRenderer, particleCallback); } @SideOnly(Side.CLIENT) @@ -539,8 +515,9 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro return ParticleHelper.addDestroyEffects(world, this, blockState, pos, effectRenderer, particleCallback); } + @Nullable public static IAlleleTreeSpecies getTreeSpecies(ItemStack stack) { - if (stack != null && stack.hasTagCompound()) { + if (!stack.isEmpty() && stack.getTagCompound() != null) { NBTTagCompound tagCompound = stack.getTagCompound(); // legacy @@ -554,20 +531,16 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro } return null; } - + @Override public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) { - if(getPileType() == EnumPileType.WOOD){ + if (getPileType() == EnumPileType.WOOD) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof ICharcoalPileComponent) { IAlleleTreeSpecies tree = ((ICharcoalPileComponent) tile).getTreeSpecies(); - if (tree != null) { - ItemStack wood = tree.getWoodProvider().getWoodStack(); - if(wood != null){ - Block block = Block.getBlockFromItem(wood.getItem()); - return block.getFlammability(world, pos, face); - } - } + ItemStack wood = tree.getWoodProvider().getWoodStack(); + Block block = Block.getBlockFromItem(wood.getItem()); + return block.getFlammability(world, pos, face); } } return super.getFlammability(world, pos, face); @@ -575,52 +548,41 @@ public abstract class BlockPile extends BlockStructure implements ITileEntityPro @Override public int getFireSpreadSpeed(IBlockAccess world, BlockPos pos, EnumFacing face) { - if(getPileType() == EnumPileType.WOOD){ + if (getPileType() == EnumPileType.WOOD) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof ICharcoalPileComponent) { IAlleleTreeSpecies tree = ((ICharcoalPileComponent) tile).getTreeSpecies(); - if(tree != null){ - ItemStack wood = tree.getWoodProvider().getWoodStack(); - if(wood != null){ - Block block = Block.getBlockFromItem(wood.getItem()); - return block.getFireSpreadSpeed(world, pos, face); - } - } + ItemStack wood = tree.getWoodProvider().getWoodStack(); + Block block = Block.getBlockFromItem(wood.getItem()); + return block.getFireSpreadSpeed(world, pos, face); } } return super.getFireSpreadSpeed(world, pos, face); - + } - + @Override public float getBlockHardness(IBlockState blockState, World world, BlockPos pos) { - if(getPileType() == EnumPileType.WOOD){ + if (getPileType() == EnumPileType.WOOD) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof ICharcoalPileComponent) { IAlleleTreeSpecies tree = ((ICharcoalPileComponent) tile).getTreeSpecies(); - if(tree != null){ - ItemStack wood = tree.getWoodProvider().getWoodStack(); - if (wood != null) { - Block block = Block.getBlockFromItem(wood.getItem()); - return block.getStateFromMeta(wood.getMetadata()).getBlockHardness(world, pos); - } - } + ItemStack wood = tree.getWoodProvider().getWoodStack(); + Block block = Block.getBlockFromItem(wood.getItem()); + return block.getStateFromMeta(wood.getMetadata()).getBlockHardness(world, pos); } } return super.getBlockHardness(blockState, world, pos); } public static ItemStack createWoodPile(IAlleleTreeSpecies treeSpecies) { - if (treeSpecies != null) { - ItemStack stack = new ItemStack(PluginArboriculture.blocks.piles.get(EnumPileType.WOOD)); - NBTTagCompound nbtItem = new NBTTagCompound(); - nbtItem.setString("TreeSpecies", treeSpecies.getUID()); - stack.setTagCompound(nbtItem); - return stack; - } - return null; + ItemStack stack = new ItemStack(PluginArboriculture.blocks.piles.get(EnumPileType.WOOD)); + NBTTagCompound nbtItem = new NBTTagCompound(); + nbtItem.setString("TreeSpecies", treeSpecies.getUID()); + stack.setTagCompound(nbtItem); + return stack; } - + public abstract EnumPileType getPileType(); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java b/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java index 104e419fa..0fb2b78b2 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockRegistryArboriculture.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -17,6 +18,7 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; @@ -24,17 +26,7 @@ import forestry.api.arboriculture.EnumForestryWoodType; import forestry.api.arboriculture.EnumPileType; import forestry.api.arboriculture.EnumVanillaWoodType; import forestry.api.arboriculture.IAlleleFruit; -import forestry.arboriculture.blocks.fence.BlockArbFence; -import forestry.arboriculture.blocks.fence.BlockFireproofVanillaFence; -import forestry.arboriculture.blocks.log.BlockArbLog; -import forestry.arboriculture.blocks.log.BlockFireproofVanillaLog; -import forestry.arboriculture.blocks.planks.BlockArbPlanks; -import forestry.arboriculture.blocks.planks.BlockFireproofVanillaPlanks; -import forestry.arboriculture.blocks.slab.BlockArbSlab; -import forestry.arboriculture.blocks.slab.BlockFireproofVanillaSlab; -import forestry.arboriculture.blocks.slab.BlockForestrySlab; import forestry.arboriculture.genetics.TreeDefinition; -import forestry.arboriculture.genetics.alleles.AlleleFruit; import forestry.arboriculture.items.ItemBlockDecorativeLeaves; import forestry.arboriculture.items.ItemBlockLeaves; import forestry.arboriculture.items.ItemBlockPile; @@ -264,7 +256,7 @@ public class BlockRegistryArboriculture extends BlockRegistry { } // Pods - AlleleFruit.createAlleles(); + AlleleFruits.registerAlleles(); podsMap = new HashMap<>(); for (BlockFruitPod pod : BlockFruitPod.create()) { IAlleleFruit fruit = pod.getFruit(); @@ -280,11 +272,12 @@ public class BlockRegistryArboriculture extends BlockRegistry { public ItemStack getDecorativeLeaves(String speciesUid) { ItemStack itemStack = speciesToLeavesDecorative.get(speciesUid); if (itemStack == null) { - return null; + return ItemStack.EMPTY; } return itemStack.copy(); } + @Nullable public BlockFruitPod getFruitPod(IAlleleFruit fruit) { return podsMap.get(fruit.getUID()); } diff --git a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java index 5f82bc2c4..dbf556c8e 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockSapling.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockSapling.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.blocks; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -40,7 +41,6 @@ import forestry.api.arboriculture.TreeManager; import forestry.api.core.IItemModelRegister; import forestry.api.core.IModelManager; import forestry.api.core.IStateMapperRegister; -import forestry.arboriculture.blocks.property.PropertyTree; import forestry.arboriculture.genetics.TreeDefinition; import forestry.arboriculture.render.SaplingStateMapper; import forestry.arboriculture.tiles.TileSapling; @@ -52,7 +52,8 @@ public class BlockSapling extends BlockTreeContainer implements IGrowable, IStat protected static final AxisAlignedBB SAPLING_AABB = new AxisAlignedBB(0.09999999403953552D, 0.0D, 0.09999999403953552D, 0.8999999761581421D, 0.800000011920929D, 0.8999999761581421D); /* PROPERTYS */ public static final PropertyTree TREE = new PropertyTree("tree"); - + + @Nullable public static TileSapling getSaplingTile(IBlockAccess world, BlockPos pos) { return TileUtil.getTile(world, pos, TileSapling.class); } @@ -75,8 +76,9 @@ public class BlockSapling extends BlockTreeContainer implements IGrowable, IStat /* COLLISION BOX */ + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return null; } @@ -141,16 +143,12 @@ public class BlockSapling extends BlockTreeContainer implements IGrowable, IStat } ITree tree = tile.getTree(); - if (tree == null) { - return false; - } - - return tree.canStay(world, pos); + return tree != null && tree.canStay(world, pos); } @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { - super.neighborChanged(state, worldIn, pos, blockIn); + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { + super.neighborChanged(state, worldIn, pos, blockIn, fromPos); if (!worldIn.isRemote && !canBlockStay(worldIn, pos)) { dropAsSapling(worldIn, pos); worldIn.setBlockToAir(pos); @@ -167,7 +165,7 @@ public class BlockSapling extends BlockTreeContainer implements IGrowable, IStat public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { TileSapling sapling = getSaplingTile(world, pos); if (sapling == null || sapling.getTree() == null) { - return null; + return ItemStack.EMPTY; } return TreeManager.treeRoot.getMemberStack(sapling.getTree(), EnumGermlingType.SAPLING); } @@ -203,10 +201,7 @@ public class BlockSapling extends BlockTreeContainer implements IGrowable, IStat return false; } TileSapling saplingTile = getSaplingTile(world, pos); - if (saplingTile != null) { - return saplingTile.canAcceptBoneMeal(rand); - } - return true; + return saplingTile == null || saplingTile.canAcceptBoneMeal(rand); } @Override diff --git a/src/main/java/forestry/arboriculture/blocks/BlockTypeArboricultureTesr.java b/src/main/java/forestry/arboriculture/blocks/BlockTypeArboricultureTesr.java index 10c204412..62c2e0c8f 100644 --- a/src/main/java/forestry/arboriculture/blocks/BlockTypeArboricultureTesr.java +++ b/src/main/java/forestry/arboriculture/blocks/BlockTypeArboricultureTesr.java @@ -10,12 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.util.math.AxisAlignedBB; - import forestry.arboriculture.tiles.TileArboristChest; import forestry.core.blocks.IBlockTypeTesr; import forestry.core.blocks.IMachinePropertiesTesr; @@ -24,16 +20,17 @@ import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileForestry; import forestry.core.tiles.TileNaturalistChest; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.util.math.AxisAlignedBB; public enum BlockTypeArboricultureTesr implements IBlockTypeTesr { ARB_CHEST(TileArboristChest.class, "arb_chest", Proxies.render.getRenderChest("arbchest"), TileNaturalistChest.chestBoundingBox); public static final BlockTypeArboricultureTesr[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeArboricultureTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nullable AxisAlignedBB boundingBox) { + BlockTypeArboricultureTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, @Nullable AxisAlignedBB boundingBox) { if (boundingBox != null) { this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, boundingBox, Constants.MOD_ID + ":blocks/" + name + ".0"); } else { @@ -41,7 +38,6 @@ public enum BlockTypeArboricultureTesr implements IBlockTypeTesr { } } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/arboriculture/blocks/property/PropertyForestryWoodType.java b/src/main/java/forestry/arboriculture/blocks/PropertyForestryWoodType.java similarity index 82% rename from src/main/java/forestry/arboriculture/blocks/property/PropertyForestryWoodType.java rename to src/main/java/forestry/arboriculture/blocks/PropertyForestryWoodType.java index bd1adb558..3528add4b 100644 --- a/src/main/java/forestry/arboriculture/blocks/property/PropertyForestryWoodType.java +++ b/src/main/java/forestry/arboriculture/blocks/PropertyForestryWoodType.java @@ -1,16 +1,13 @@ -package forestry.arboriculture.blocks.property; +package forestry.arboriculture.blocks; + +import java.util.Collection; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; - -import javax.annotation.Nonnull; -import java.util.Collection; - import forestry.api.arboriculture.EnumForestryWoodType; -import forestry.arboriculture.blocks.WoodTypePredicate; public class PropertyForestryWoodType extends PropertyWoodType { - public static PropertyForestryWoodType[] create(@Nonnull String name, int variantsPerBlock) { + public static PropertyForestryWoodType[] create(String name, int variantsPerBlock) { final int variantCount = (int) Math.ceil((float) EnumForestryWoodType.VALUES.length / variantsPerBlock); PropertyForestryWoodType[] variants = new PropertyForestryWoodType[variantCount]; for (int variantNumber = 0; variantNumber < variantCount; variantNumber++) { diff --git a/src/main/java/forestry/arboriculture/blocks/property/PropertyTree.java b/src/main/java/forestry/arboriculture/blocks/PropertyTree.java similarity index 94% rename from src/main/java/forestry/arboriculture/blocks/property/PropertyTree.java rename to src/main/java/forestry/arboriculture/blocks/PropertyTree.java index 3162d0c96..590c2eb85 100644 --- a/src/main/java/forestry/arboriculture/blocks/property/PropertyTree.java +++ b/src/main/java/forestry/arboriculture/blocks/PropertyTree.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.property; +package forestry.arboriculture.blocks; import com.google.common.base.Objects; @@ -19,7 +19,7 @@ import java.util.Locale; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; -import forestry.core.blocks.propertys.PropertyAllele; +import forestry.core.blocks.properties.PropertyAllele; import forestry.core.config.Constants; public class PropertyTree extends PropertyAllele { diff --git a/src/main/java/forestry/arboriculture/blocks/property/PropertyTreeType.java b/src/main/java/forestry/arboriculture/blocks/PropertyTreeType.java similarity index 86% rename from src/main/java/forestry/arboriculture/blocks/property/PropertyTreeType.java rename to src/main/java/forestry/arboriculture/blocks/PropertyTreeType.java index 88691faf7..f577ae4e4 100644 --- a/src/main/java/forestry/arboriculture/blocks/property/PropertyTreeType.java +++ b/src/main/java/forestry/arboriculture/blocks/PropertyTreeType.java @@ -8,24 +8,21 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.property; +package forestry.arboriculture.blocks; + +import java.util.Collection; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; - -import javax.annotation.Nonnull; -import java.util.Collection; -import net.minecraft.block.properties.PropertyEnum; - -import forestry.arboriculture.blocks.TreeTypePredicate; import forestry.arboriculture.genetics.TreeDefinition; +import net.minecraft.block.properties.PropertyEnum; public class PropertyTreeType extends PropertyEnum { public static int getBlockCount(int variantsPerBlock) { return (int) Math.ceil((float) TreeDefinition.VALUES.length / variantsPerBlock); } - public static PropertyTreeType create(@Nonnull String name, int blockNumber, int variantsPerBlock) { + public static PropertyTreeType create(String name, int blockNumber, int variantsPerBlock) { TreeTypePredicate filter = new TreeTypePredicate(blockNumber, variantsPerBlock); Collection allowedValues = Collections2.filter(Lists.newArrayList(TreeDefinition.class.getEnumConstants()), filter); return new PropertyTreeType(name, TreeDefinition.class, allowedValues); diff --git a/src/main/java/forestry/arboriculture/blocks/property/PropertyVanillaWoodType.java b/src/main/java/forestry/arboriculture/blocks/PropertyVanillaWoodType.java similarity index 87% rename from src/main/java/forestry/arboriculture/blocks/property/PropertyVanillaWoodType.java rename to src/main/java/forestry/arboriculture/blocks/PropertyVanillaWoodType.java index 466dc7fc2..da39fcb1d 100644 --- a/src/main/java/forestry/arboriculture/blocks/property/PropertyVanillaWoodType.java +++ b/src/main/java/forestry/arboriculture/blocks/PropertyVanillaWoodType.java @@ -8,20 +8,17 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.property; +package forestry.arboriculture.blocks; + +import java.util.Collection; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; - -import javax.annotation.Nonnull; -import java.util.Collection; - import forestry.api.arboriculture.EnumVanillaWoodType; -import forestry.arboriculture.blocks.WoodTypePredicate; public class PropertyVanillaWoodType extends PropertyWoodType { - public static PropertyVanillaWoodType[] create(@Nonnull String name, int variantsPerBlock) { + public static PropertyVanillaWoodType[] create(String name, int variantsPerBlock) { final int variantCount = (int) Math.ceil((float) EnumVanillaWoodType.VALUES.length / variantsPerBlock); PropertyVanillaWoodType[] variants = new PropertyVanillaWoodType[variantCount]; for (int variantNumber = 0; variantNumber < variantCount; variantNumber++) { diff --git a/src/main/java/forestry/arboriculture/blocks/property/PropertyWoodType.java b/src/main/java/forestry/arboriculture/blocks/PropertyWoodType.java similarity index 92% rename from src/main/java/forestry/arboriculture/blocks/property/PropertyWoodType.java rename to src/main/java/forestry/arboriculture/blocks/PropertyWoodType.java index 4f486b8cf..b739da196 100644 --- a/src/main/java/forestry/arboriculture/blocks/property/PropertyWoodType.java +++ b/src/main/java/forestry/arboriculture/blocks/PropertyWoodType.java @@ -8,21 +8,18 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.arboriculture.blocks.property; +package forestry.arboriculture.blocks; -import javax.annotation.Nonnull; import java.util.Collection; -import net.minecraft.block.properties.PropertyEnum; - import forestry.api.arboriculture.IWoodType; +import net.minecraft.block.properties.PropertyEnum; public abstract class PropertyWoodType & IWoodType> extends PropertyEnum { protected PropertyWoodType(String name, Class valueClass, Collection allowedValues) { super(name, valueClass, allowedValues); } - @Nonnull public T getFirstType() { return getAllowedValues().iterator().next(); } diff --git a/src/main/java/forestry/arboriculture/blocks/TreeTypePredicate.java b/src/main/java/forestry/arboriculture/blocks/TreeTypePredicate.java index f30e6e24d..59bd9e8cd 100644 --- a/src/main/java/forestry/arboriculture/blocks/TreeTypePredicate.java +++ b/src/main/java/forestry/arboriculture/blocks/TreeTypePredicate.java @@ -17,6 +17,6 @@ public class TreeTypePredicate implements Predicate { @Override public boolean apply(@Nullable TreeDefinition treeDefinition) { - return treeDefinition.getMetadata() >= minMeta && treeDefinition.getMetadata() <= maxMeta; + return treeDefinition != null && treeDefinition.getMetadata() >= minMeta && treeDefinition.getMetadata() <= maxMeta; } } diff --git a/src/main/java/forestry/arboriculture/blocks/WoodTypePredicate.java b/src/main/java/forestry/arboriculture/blocks/WoodTypePredicate.java index 61faba7d9..3eb175c0d 100644 --- a/src/main/java/forestry/arboriculture/blocks/WoodTypePredicate.java +++ b/src/main/java/forestry/arboriculture/blocks/WoodTypePredicate.java @@ -1,5 +1,7 @@ package forestry.arboriculture.blocks; +import javax.annotation.Nullable; + import com.google.common.base.Predicate; import forestry.api.arboriculture.IWoodType; @@ -14,7 +16,7 @@ public class WoodTypePredicate implements Predicate { } @Override - public boolean apply(IWoodType woodType) { - return woodType.getMetadata() >= minWoodTypeMeta && woodType.getMetadata() <= maxWoodTypeMeta; + public boolean apply(@Nullable IWoodType woodType) { + return woodType != null && woodType.getMetadata() >= minWoodTypeMeta && woodType.getMetadata() <= maxWoodTypeMeta; } } diff --git a/src/main/java/forestry/arboriculture/blocks/WoodTypeStateMapper.java b/src/main/java/forestry/arboriculture/blocks/WoodTypeStateMapper.java index 7b93e368e..e28cc0d22 100644 --- a/src/main/java/forestry/arboriculture/blocks/WoodTypeStateMapper.java +++ b/src/main/java/forestry/arboriculture/blocks/WoodTypeStateMapper.java @@ -1,13 +1,18 @@ package forestry.arboriculture.blocks; -import com.google.common.collect.Maps; - -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; +import com.google.common.collect.Maps; +import forestry.api.arboriculture.EnumForestryWoodType; +import forestry.api.arboriculture.EnumVanillaWoodType; +import forestry.api.arboriculture.IWoodStateMapper; +import forestry.api.arboriculture.IWoodType; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.models.WoodModelLoader; +import forestry.core.config.Constants; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; @@ -17,34 +22,22 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.statemap.StateMapperBase; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.arboriculture.EnumForestryWoodType; -import forestry.api.arboriculture.EnumVanillaWoodType; -import forestry.api.arboriculture.IWoodStateMapper; -import forestry.api.arboriculture.IWoodType; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.blocks.property.PropertyWoodType; -import forestry.arboriculture.models.WoodModelLoader; -import forestry.core.config.Constants; @SideOnly(Side.CLIENT) public class WoodTypeStateMapper extends StateMapperBase implements IWoodStateMapper { - - @Nonnull private final IWoodTyped woodTyped; - @Nonnull private final String blockPath; @Nullable private final PropertyWoodType propertyWoodType; - @Nonnull private final List propertiesToRemove = new ArrayList<>(); - public WoodTypeStateMapper(@Nonnull IWoodTyped woodTyped, @Nullable PropertyWoodType propertyWoodType) { + public WoodTypeStateMapper( IWoodTyped woodTyped, @Nullable PropertyWoodType propertyWoodType) { this.woodTyped = woodTyped; this.blockPath = woodTyped.getBlockKind().toString(); this.propertyWoodType = propertyWoodType; } - public WoodTypeStateMapper(@Nonnull IWoodTyped woodTyped, @Nonnull String blockPath, @Nullable PropertyWoodType propertyWoodType) { + public WoodTypeStateMapper( IWoodTyped woodTyped, String blockPath, @Nullable PropertyWoodType propertyWoodType) { this.woodTyped = woodTyped; this.blockPath = blockPath; this.propertyWoodType = propertyWoodType; @@ -59,9 +52,9 @@ public class WoodTypeStateMapper extends StateMapperBase implements IWoodStateMa public ModelResourceLocation getModelLocation(IBlockState state) { return getModelResourceLocation(state); } - + @Override - protected ModelResourceLocation getModelResourceLocation(IBlockState state) { + protected ModelResourceLocation getModelResourceLocation( IBlockState state) { final Map, Comparable> properties; if (propertyWoodType != null) { properties = Maps.newLinkedHashMap(state.getProperties()); diff --git a/src/main/java/forestry/arboriculture/blocks/package-info.java b/src/main/java/forestry/arboriculture/blocks/package-info.java new file mode 100644 index 000000000..2b30cd80b --- /dev/null +++ b/src/main/java/forestry/arboriculture/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/capabilities/package-info.java b/src/main/java/forestry/arboriculture/capabilities/package-info.java new file mode 100644 index 000000000..5c8a068c5 --- /dev/null +++ b/src/main/java/forestry/arboriculture/capabilities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.capabilities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java index d1240f429..7b848b1d2 100644 --- a/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java +++ b/src/main/java/forestry/arboriculture/commands/CommandTreeSpawn.java @@ -10,7 +10,9 @@ ******************************************************************************/ package forestry.arboriculture.commands; +import javax.annotation.Nullable; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; @@ -58,13 +60,13 @@ public final class CommandTreeSpawn extends SubCommand { } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { List tabCompletion = CommandHelpers.getListOfStringsMatchingLastWord(args, getSpecies()); tabCompletion.add("help"); return tabCompletion; } - return null; + return Collections.emptyList(); } private static String[] getSpecies() { diff --git a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java index d4030b4b7..3522b163c 100644 --- a/src/main/java/forestry/arboriculture/commands/ForestSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/ForestSpawner.java @@ -30,14 +30,11 @@ public class ForestSpawner implements ITreeSpawner { int z = (int) Math.round(player.posZ + 16 * look.zCoord); for (int i = 0; i < 16; i++) { - int spawnX = x + player.worldObj.rand.nextInt(32) - 16; - int spawnZ = z + player.worldObj.rand.nextInt(32) - 16; + int spawnX = x + player.world.rand.nextInt(32) - 16; + int spawnZ = z + player.world.rand.nextInt(32) - 16; BlockPos pos = new BlockPos(spawnX, y, spawnZ); WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, pos); - if (gen == null) { - return false; - } TreeGenHelper.generateTree(gen, player, pos); } return true; diff --git a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java b/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java index 9b53c2496..11b88f1c3 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java +++ b/src/main/java/forestry/arboriculture/commands/TreeGenHelper.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.commands; -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.gen.feature.WorldGenerator; - import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; import forestry.api.arboriculture.ITreeGenome; @@ -26,30 +20,31 @@ import forestry.core.commands.SpeciesNotFoundException; import forestry.core.commands.TemplateNotFoundException; import forestry.core.utils.BlockUtil; import forestry.core.worldgen.WorldGenBase; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.gen.feature.WorldGenerator; public final class TreeGenHelper { public static WorldGenerator getWorldGen(String treeName, EntityPlayer player, BlockPos pos) throws SpeciesNotFoundException, TemplateNotFoundException { ITreeGenome treeGenome = getTreeGenome(treeName); - if (treeGenome == null) { - return null; - } - - ITree tree = TreeManager.treeRoot.getTree(player.worldObj, treeGenome); - return tree.getTreeGenerator(player.worldObj, pos, true); + ITree tree = TreeManager.treeRoot.getTree(player.world, treeGenome); + return tree.getTreeGenerator(player.world, pos, true); } public static void generateTree(WorldGenerator gen, EntityPlayer player, BlockPos pos) { - World world = player.worldObj; - - if(world.isAirBlock(pos.down())){ + World world = player.world; + + if (world.isAirBlock(pos.down())) { pos = BlockUtil.getNextSolidDownPos(world, pos); - }else{ + } else { pos = BlockUtil.getNextReplaceableUpPos(world, pos); } IBlockState blockState = world.getBlockState(pos); - if (BlockUtil.canPlaceTree(blockState, world, pos)){ + if (BlockUtil.canPlaceTree(blockState, world, pos)) { if (gen instanceof WorldGenBase) { ((WorldGenBase) gen).generate(world, world.rand, pos, true); } else { diff --git a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java index 733800f2e..a36ea4f54 100644 --- a/src/main/java/forestry/arboriculture/commands/TreeSpawner.java +++ b/src/main/java/forestry/arboriculture/commands/TreeSpawner.java @@ -31,10 +31,6 @@ public class TreeSpawner implements ITreeSpawner { BlockPos pos = new BlockPos(x, y, z); WorldGenerator gen = TreeGenHelper.getWorldGen(treeName, player, pos); - if (gen == null) { - return false; - } - TreeGenHelper.generateTree(gen, player, pos); return true; } diff --git a/src/main/java/forestry/arboriculture/commands/package-info.java b/src/main/java/forestry/arboriculture/commands/package-info.java new file mode 100644 index 000000000..bf61c6f4d --- /dev/null +++ b/src/main/java/forestry/arboriculture/commands/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.commands; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java b/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java index e73269aeb..aa1467559 100644 --- a/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java +++ b/src/main/java/forestry/arboriculture/compat/ArboricultureJeiPlugin.java @@ -1,7 +1,5 @@ package forestry.arboriculture.compat; -import javax.annotation.Nonnull; - import forestry.arboriculture.PluginArboriculture; import forestry.arboriculture.items.ItemRegistryArboriculture; import forestry.core.utils.JeiUtil; @@ -12,7 +10,7 @@ import mezz.jei.api.JEIPlugin; @JEIPlugin public class ArboricultureJeiPlugin extends BlankModPlugin { @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { ItemRegistryArboriculture items = PluginArboriculture.items; JeiUtil.addDescription(registry, diff --git a/src/main/java/forestry/arboriculture/compat/package-info.java b/src/main/java/forestry/arboriculture/compat/package-info.java new file mode 100644 index 000000000..fe5208f4e --- /dev/null +++ b/src/main/java/forestry/arboriculture/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java index 657ffe3e9..b7cc80630 100755 --- a/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java +++ b/src/main/java/forestry/arboriculture/genetics/ArboristTracker.java @@ -27,7 +27,7 @@ public class ArboristTracker extends BreedingTracker implements IArboristTracker @Override protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return TreeManager.treeRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + return TreeManager.treeRoot.getBreedingTracker(player.world, player.getGameProfile()); } @Override diff --git a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java b/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java similarity index 82% rename from src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java rename to src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java index 4b4bf7b26..307cf697c 100644 --- a/src/main/java/forestry/arboriculture/genetics/pollination/CheckPollinatableTree.java +++ b/src/main/java/forestry/arboriculture/genetics/CheckPollinatableTree.java @@ -1,52 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.pollination; - -import forestry.api.arboriculture.ITree; -import forestry.api.genetics.ICheckPollinatable; -import forestry.api.genetics.IIndividual; -import net.minecraftforge.common.EnumPlantType; - -public class CheckPollinatableTree implements ICheckPollinatable { - - private final ITree tree; - - public CheckPollinatableTree(ITree tree) { - this.tree = tree; - } - - @Override - public EnumPlantType getPlantType() { - return tree.getGenome().getPrimary().getPlantType(); - } - - @Override - public ITree getPollen() { - return tree; - } - - @Override - public boolean canMateWith(IIndividual pollen) { - if(pollen instanceof ITree){ - if (tree.getMate() != null) { - return false; - } - - return !tree.isGeneticEqual(pollen); - } - return false; - } - - @Override - public boolean isPollinated() { - return tree.getMate() != null; - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.genetics; + +import forestry.api.arboriculture.ITree; +import forestry.api.genetics.ICheckPollinatable; +import forestry.api.genetics.IIndividual; +import net.minecraftforge.common.EnumPlantType; + +public class CheckPollinatableTree implements ICheckPollinatable { + private final ITree tree; + + public CheckPollinatableTree(ITree tree) { + this.tree = tree; + } + + @Override + public EnumPlantType getPlantType() { + return tree.getGenome().getPrimary().getPlantType(); + } + + @Override + public ITree getPollen() { + return tree; + } + + @Override + public boolean canMateWith(IIndividual pollen) { + return pollen instanceof ITree && + tree.getMate() == null && + !tree.isGeneticEqual(pollen); + } + + @Override + public boolean isPollinated() { + return tree.getMate() != null; + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java b/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java deleted file mode 100755 index 04e5f951e..000000000 --- a/src/main/java/forestry/arboriculture/genetics/GrowthProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics; - -import javax.annotation.Nullable; - -import forestry.api.arboriculture.IGrowthProvider; -import forestry.api.arboriculture.ITreeGenome; -import forestry.core.utils.Translator; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -/** - * @deprecated this is being removed to simplify trees - */ -@Deprecated -public class GrowthProvider implements IGrowthProvider { - - @Override - @Nullable - public BlockPos canGrow(ITreeGenome genome, World world, BlockPos pos, int expectedGirth, int expectedHeight) { - return TreeGrowthHelper.canGrow(world, genome, pos, expectedGirth, expectedHeight); - } - - @Override - public String getDescription() { - return Translator.translateToLocal("for.growth.normal"); - } - - @Override - public String[] getInfo() { - return new String[0]; - } -} diff --git a/src/main/java/forestry/arboriculture/genetics/Tree.java b/src/main/java/forestry/arboriculture/genetics/Tree.java index 1ed02b3b1..2ef6fd7d8 100755 --- a/src/main/java/forestry/arboriculture/genetics/Tree.java +++ b/src/main/java/forestry/arboriculture/genetics/Tree.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -34,7 +33,7 @@ import forestry.api.genetics.IChromosome; import forestry.api.genetics.IEffectData; import forestry.api.genetics.IFruitFamily; import forestry.api.genetics.IMutation; -import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import forestry.core.config.Config; import forestry.core.genetics.Chromosome; import forestry.core.genetics.Individual; @@ -44,6 +43,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.IBlockAccess; @@ -53,17 +53,15 @@ import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; public class Tree extends Individual implements ITree, IPlantable { - - @Nonnull private final ITreeGenome genome; @Nullable private ITreeGenome mate; - public Tree(@Nonnull ITreeGenome genome) { + public Tree(ITreeGenome genome) { this.genome = genome; } - public Tree(@Nonnull NBTTagCompound nbttagcompound) { + public Tree(NBTTagCompound nbttagcompound) { super(nbttagcompound); if (nbttagcompound.hasKey("Genome")) { @@ -104,10 +102,6 @@ public class Tree extends Individual implements ITree, IPlantable { public IEffectData[] doEffect(IEffectData[] storedData, World world, BlockPos pos) { IAlleleLeafEffect effect = (IAlleleLeafEffect) getGenome().getActiveAllele(EnumTreeChromosome.EFFECT); - if (effect == null) { - return null; - } - storedData[0] = doEffect(effect, storedData[0], world, pos); // Return here if the primary can already not be combined @@ -132,7 +126,7 @@ public class Tree extends Individual implements ITree, IPlantable { @Override public IEffectData[] doFX(IEffectData[] storedData, World world, BlockPos pos) { - return null; + return storedData; } /* GROWTH */ @@ -145,16 +139,9 @@ public class Tree extends Individual implements ITree, IPlantable { public boolean canStay(IBlockAccess world, BlockPos pos) { BlockPos blockPos = pos.down(); IBlockState blockState = world.getBlockState(blockPos); - if (blockState == null) { - return false; - } Block block = blockState.getBlock(); - if (block.canSustainPlant(blockState, world, blockPos, EnumFacing.UP, this)) { - return true; - } - - return false; + return block.canSustainPlant(blockState, world, blockPos, EnumFacing.UP, this); } @Override @@ -195,7 +182,7 @@ public class Tree extends Individual implements ITree, IPlantable { } @Override - public boolean setLeaves(World world, GameProfile owner, BlockPos pos) { + public boolean setLeaves(World world, @Nullable GameProfile owner, BlockPos pos) { return genome.getPrimary().getGenerator().setLeaves(genome, world, owner, pos); } @@ -219,15 +206,11 @@ public class Tree extends Individual implements ITree, IPlantable { public boolean trySpawnFruitBlock(World world, Random rand, BlockPos pos) { IFruitProvider provider = getGenome().getFruitProvider(); Collection suitable = genome.getPrimary().getSuitableFruit(); - if (!suitable.contains(provider.getFamily())) { - return false; - } - - return provider.trySpawnFruitBlock(getGenome(), world, rand, pos); + return suitable.contains(provider.getFamily()) && + provider.trySpawnFruitBlock(getGenome(), world, rand, pos); } /* INFORMATION */ - @Nonnull @Override public ITreeGenome getGenome() { return genome; @@ -285,14 +268,13 @@ public class Tree extends Individual implements ITree, IPlantable { } IAllele fruit = getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); - if (fruit != AlleleFruit.fruitNone) { + if (fruit != AlleleFruits.fruitNone) { String strike = ""; if (!canBearFruit()) { strike = TextFormatting.STRIKETHROUGH.toString(); } list.add(strike + TextFormatting.GREEN + "F: " + genome.getFruitProvider().getDescription()); } - } /* REPRODUCTION */ @@ -303,18 +285,17 @@ public class Tree extends Individual implements ITree, IPlantable { float chance = genome.getFertility() * modifier; if (world.rand.nextFloat() <= chance) { - if (this.getMate() == null) { + if (mate == null) { prod.add(TreeManager.treeRoot.getTree(world, new TreeGenome(genome.getChromosomes()))); } else { - prod.add(createOffspring(world, playerProfile, pos)); + prod.add(createOffspring(world, mate, playerProfile, pos)); } } return prod.toArray(new ITree[prod.size()]); } - private ITree createOffspring(World world, GameProfile playerProfile, BlockPos pos) { - + private ITree createOffspring(World world, ITreeGenome mate, GameProfile playerProfile, BlockPos pos) { IChromosome[] chromosomes = new IChromosome[genome.getChromosomes().length]; IChromosome[] parent1 = genome.getChromosomes(); IChromosome[] parent2 = mate.getChromosomes(); @@ -339,8 +320,8 @@ public class Tree extends Individual implements ITree, IPlantable { return new Tree(new TreeGenome(chromosomes)); } + @Nullable private static IChromosome[] mutateSpecies(World world, @Nullable GameProfile playerProfile, BlockPos pos, ITreeGenome genomeOne, ITreeGenome genomeTwo) { - IChromosome[] parent1 = genomeOne.getChromosomes(); IChromosome[] parent2 = genomeTwo.getChromosomes(); @@ -402,22 +383,18 @@ public class Tree extends Individual implements ITree, IPlantable { return genome.getPrimary().getSuitableFruit().contains(genome.getFruitProvider().getFamily()); } - @Nonnull @Override public Map getProducts() { return genome.getFruitProvider().getProducts(); } - @Nonnull @Override public Map getSpecialties() { return genome.getFruitProvider().getSpecialty(); } - @Nonnull @Override - public List produceStacks(World world, BlockPos pos, int ripeningTime) { + public NonNullList produceStacks(World world, BlockPos pos, int ripeningTime) { return genome.getFruitProvider().getFruits(genome, world, pos, ripeningTime); } - } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java b/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java index 49e1b2f76..b737ffe3a 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeAlyzerPlugin.java @@ -27,7 +27,7 @@ import forestry.api.genetics.IAlleleInteger; import forestry.api.genetics.IAlyzerPlugin; import forestry.api.genetics.IFruitFamily; import forestry.arboriculture.PluginArboriculture; -import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import forestry.core.config.Config; import forestry.core.gui.GuiAlyzer; import forestry.core.gui.TextLayoutHelper; @@ -37,6 +37,7 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.Translator; import net.minecraft.client.gui.GuiScreen; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @@ -47,13 +48,11 @@ public class TreeAlyzerPlugin implements IAlyzerPlugin { protected final Map iconStacks = new HashMap<>(); private TreeAlyzerPlugin() { - List treeList = new ArrayList<>(); + NonNullList treeList = NonNullList.create(); PluginArboriculture.items.sapling.addCreativeItems(treeList, false); for (ItemStack treeStack : treeList) { IAlleleTreeSpecies species = TreeGenome.getSpecies(treeStack); - if (species != null) { - iconStacks.put(species.getUID(), treeStack); - } + iconStacks.put(species.getUID(), treeStack); } } @@ -67,6 +66,9 @@ public class TreeAlyzerPlugin implements IAlyzerPlugin { return; } EnumGermlingType type = TreeManager.treeRoot.getType(itemStack); + if (type == null) { + return; + } TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); @@ -181,14 +183,14 @@ public class TreeAlyzerPlugin implements IAlyzerPlugin { textLayout.drawLine(Translator.translateToLocal("for.gui.fruits"), GuiAlyzer.COLUMN_0); String strike = ""; IAllele fruit0 = tree.getGenome().getActiveAllele(EnumTreeChromosome.FRUITS); - if (!tree.canBearFruit() && fruit0 != AlleleFruit.fruitNone) { + if (!tree.canBearFruit() && fruit0 != AlleleFruits.fruitNone) { strike = TextFormatting.STRIKETHROUGH.toString(); } textLayout.drawLine(strike + tree.getGenome().getFruitProvider().getDescription(), GuiAlyzer.COLUMN_1, fruitDominance0); strike = ""; IAlleleFruit fruit1 = (IAlleleFruit) tree.getGenome().getInactiveAllele(EnumTreeChromosome.FRUITS); - if (!tree.getGenome().getSecondary().getSuitableFruit().contains(fruit1.getProvider().getFamily()) && fruit1 != AlleleFruit.fruitNone) { + if (!tree.getGenome().getSecondary().getSuitableFruit().contains(fruit1.getProvider().getFamily()) && fruit1 != AlleleFruits.fruitNone) { strike = TextFormatting.STRIKETHROUGH.toString(); } textLayout.drawLine(strike + fruit1.getProvider().getDescription(), GuiAlyzer.COLUMN_2, fruitDominance1); diff --git a/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java b/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java index b4c8ed105..661714de9 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeBranchDefinition.java @@ -10,24 +10,22 @@ ******************************************************************************/ package forestry.arboriculture.genetics; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.Locale; -import org.apache.commons.lang3.text.WordUtils; - import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleRegistry; import forestry.api.genetics.IClassification; import forestry.api.genetics.IClassification.EnumClassLevel; -import forestry.arboriculture.genetics.alleles.AlleleFruit; -import forestry.arboriculture.genetics.alleles.AlleleGrowth; -import forestry.arboriculture.genetics.alleles.AlleleLeafEffect; +import forestry.arboriculture.genetics.alleles.AlleleFruits; +import forestry.arboriculture.genetics.alleles.AlleleLeafEffects; import forestry.core.genetics.IBranchDefinition; import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.AllelePlantType; import forestry.core.genetics.alleles.EnumAllele; +import org.apache.commons.lang3.text.WordUtils; public enum TreeBranchDefinition implements IBranchDefinition { ACACIA, @@ -78,6 +76,7 @@ public enum TreeBranchDefinition implements IBranchDefinition { branch = new BranchTrees(name, scientific); } + @Nullable private static IAllele[] defaultTemplate; @Override @@ -85,20 +84,15 @@ public enum TreeBranchDefinition implements IBranchDefinition { if (defaultTemplate == null) { defaultTemplate = new IAllele[EnumTreeChromosome.values().length]; - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FRUITS, AlleleFruit.fruitNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GROWTH, AlleleGrowth.growthLightLevel); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.TERRITORY, EnumAllele.Territory.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.EFFECT, AlleleLeafEffect.leavesNone); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.AVERAGE); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.GIRTH, 1); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.COMBUSTIBILITY, 20); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.CARBONIZATION, 4); - AlleleHelper.instance.set(defaultTemplate, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.FALSE); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.FRUITS, AlleleFruits.fruitNone); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWEST); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.EFFECT, AlleleLeafEffects.leavesNone); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.AVERAGE); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.GIRTH, 1); + AlleleHelper.getInstance().set(defaultTemplate, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.FALSE); } return Arrays.copyOf(defaultTemplate, defaultTemplate.length); } @@ -108,7 +102,7 @@ public enum TreeBranchDefinition implements IBranchDefinition { return branch; } - public static void createAlleles() { + public static void registerAlleles() { IAlleleRegistry alleleRegistry = AlleleManager.alleleRegistry; diff --git a/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java b/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java index e6a4b22e5..2fb038972 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeDefinition.java @@ -10,7 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import java.awt.*; +import javax.annotation.Nullable; +import java.awt.Color; import java.util.Arrays; import java.util.Locale; @@ -39,7 +40,7 @@ import forestry.api.genetics.AlleleSpeciesRegisterEvent; import forestry.api.genetics.IAllele; import forestry.api.world.ITreeGenData; import forestry.arboriculture.PluginArboriculture; -import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import forestry.arboriculture.models.ModelProviderFactory; import forestry.arboriculture.tiles.TileLeaves; import forestry.arboriculture.worldgen.WorldGenAcacia; @@ -80,7 +81,6 @@ import forestry.arboriculture.worldgen.WorldGenZebrawood; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleBoolean; import forestry.core.genetics.alleles.AlleleHelper; -import forestry.core.genetics.alleles.AllelePlantType; import forestry.core.genetics.alleles.EnumAllele; import forestry.core.tiles.TileUtil; import net.minecraft.block.Block; @@ -103,9 +103,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitApple); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitApple); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); } @Override @@ -126,9 +126,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -149,8 +149,8 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); } @Override @@ -171,9 +171,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); //Allele.helper.set(alleles, EnumTreeChromosome.EFFECT, Allele.leavesBrimstone); } @@ -204,12 +204,12 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitWalnut); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitWalnut); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -232,11 +232,11 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitChestnut); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitChestnut); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -259,11 +259,11 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCherry); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitCherry); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLER); } @Override @@ -286,10 +286,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitLemon); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitLemon); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); } @Override @@ -311,10 +311,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPlum); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitPlum); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.HIGH); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALLEST); } @Override @@ -336,9 +336,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); } @Override @@ -359,9 +359,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); } @Override @@ -382,9 +382,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); } @Override @@ -406,9 +406,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); } @Override @@ -429,11 +429,11 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 3); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); } @Override @@ -454,11 +454,11 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.GIGANTIC); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 4); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.GIGANTIC); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 4); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FIREPROOF, EnumAllele.Fireproof.TRUE); } @Override @@ -479,9 +479,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitCocoa); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FAST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitCocoa); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FAST); } @Override @@ -502,7 +502,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); } @Override @@ -523,9 +523,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -547,9 +547,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); } @Override @@ -571,10 +571,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 3); } @Override @@ -595,8 +595,8 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -617,10 +617,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -664,7 +664,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); + } @Override @@ -685,8 +685,8 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); } @Override @@ -708,9 +708,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.HIGH); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); } @Override @@ -731,7 +731,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGEST); } @Override @@ -753,8 +753,8 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWEST); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 2); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOWEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 2); } @Override @@ -776,11 +776,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.PLANT, AllelePlantType.plantTypeDesert); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.GIRTH, 3); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.GIRTH, 3); } @Override @@ -803,9 +802,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.HIGH); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.HIGH); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWEST); } @Override @@ -828,9 +827,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.FASTER); } @Override @@ -859,9 +858,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.LARGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOW); } @Override @@ -885,10 +884,10 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitPapaya); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitPapaya); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); } @Override @@ -910,11 +909,11 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FRUITS, AlleleFruit.fruitDates); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FRUITS, AlleleFruits.fruitDates); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.FERTILITY, EnumAllele.Saplings.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.YIELD, EnumAllele.Yield.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.AVERAGE); } @Override @@ -936,9 +935,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); - AlleleHelper.instance.set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.HEIGHT, EnumAllele.Height.SMALL); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.SAPPINESS, EnumAllele.Sappiness.LOW); + AlleleHelper.getInstance().set(alleles, EnumTreeChromosome.MATURATION, EnumAllele.Maturation.SLOWER); } @Override @@ -949,7 +948,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe } }; - public static TreeDefinition[] VALUES = values(); + public static final TreeDefinition[] VALUES = values(); private final TreeBranchDefinition branch; private final IAlleleTreeSpecies species; @@ -994,7 +993,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe } @Override - public boolean setLeaves(ITreeGenome genome, World world, GameProfile owner, BlockPos pos) { + public boolean setLeaves(ITreeGenome genome, World world, @Nullable GameProfile owner, BlockPos pos) { boolean placed = world.setBlockState(pos, PluginArboriculture.blocks.leaves.getDefaultState()); if (!placed) { return false; @@ -1012,7 +1011,9 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe return false; } - tileLeaves.getOwnerHandler().setOwner(owner); + if (owner != null) { + tileLeaves.getOwnerHandler().setOwner(owner); + } tileLeaves.setTree(new Tree(genome)); world.markBlockRangeForRenderUpdate(pos, pos); @@ -1030,7 +1031,7 @@ public enum TreeDefinition implements ITreeDefinition, ITreeGenerator, IStringSe private void init() { template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumTreeChromosome.SPECIES, species); + AlleleHelper.getInstance().set(template, EnumTreeChromosome.SPECIES, species); setAlleles(template); genome = TreeManager.treeRoot.templateAsGenome(template); diff --git a/src/main/java/forestry/arboriculture/genetics/TreeFactory.java b/src/main/java/forestry/arboriculture/genetics/TreeFactory.java index 92932d875..43401fe16 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeFactory.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeFactory.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; import java.awt.Color; import forestry.api.arboriculture.EnumLeafType; @@ -26,7 +25,7 @@ import forestry.arboriculture.models.SpriteProviderLeaves; public class TreeFactory implements ITreeFactory { @Override - public IAlleleTreeSpeciesBuilder createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean dominant, IClassification branch, String binomial, String modID, ILeafSpriteProvider leafSpriteProvider, IGermlingModelProvider germlingModelProvider, @Nonnull IWoodProvider woodProvider, ITreeGenerator generator) { + public IAlleleTreeSpeciesBuilder createSpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, boolean dominant, IClassification branch, String binomial, String modID, ILeafSpriteProvider leafSpriteProvider, IGermlingModelProvider germlingModelProvider, IWoodProvider woodProvider, ITreeGenerator generator) { return new AlleleTreeSpecies(uid, unlocalizedName, authority, unlocalizedDescription, dominant, branch, binomial, modID, leafSpriteProvider, germlingModelProvider, woodProvider, generator); } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java index 77ef0c09c..1fa11a742 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreeGenome.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeGenome.java @@ -10,8 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; - +import com.google.common.base.Preconditions; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.arboriculture.IAlleleLeafEffect; @@ -40,9 +39,7 @@ public class TreeGenome extends Genome implements ITreeGenome { // NBT RETRIEVAL public static IAlleleTreeSpecies getSpecies(ItemStack itemStack) { - if (!TreeManager.treeRoot.isMember(itemStack)) { - return null; - } + Preconditions.checkArgument(TreeManager.treeRoot.isMember(itemStack), "ItemStack must be a tree"); IAlleleSpecies species = getSpeciesDirectly(TreeManager.treeRoot, itemStack); if (species instanceof IAlleleTreeSpecies) { @@ -53,18 +50,16 @@ public class TreeGenome extends Genome implements ITreeGenome { } @Override - @Nonnull public IAlleleTreeSpecies getPrimary() { return (IAlleleTreeSpecies) getActiveAllele(EnumTreeChromosome.SPECIES); } @Override - @Nonnull public IAlleleTreeSpecies getSecondary() { return (IAlleleTreeSpecies) getInactiveAllele(EnumTreeChromosome.SPECIES); } - @Nonnull + @Override public IFruitProvider getFruitProvider() { return ((IAlleleFruit) getActiveAllele(EnumTreeChromosome.FRUITS)).getProvider(); @@ -99,16 +94,14 @@ public class TreeGenome extends Genome implements ITreeGenome { public int getGirth() { return ((IAlleleInteger) getActiveAllele(EnumTreeChromosome.GIRTH)).getValue(); } - + @Override public IAlleleLeafEffect getEffect() { return (IAlleleLeafEffect) getActiveAllele(EnumTreeChromosome.EFFECT); } @Override - @Nonnull public ISpeciesRoot getSpeciesRoot() { return TreeManager.treeRoot; } - } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeGrowthHelper.java b/src/main/java/forestry/arboriculture/genetics/TreeGrowthHelper.java index e5d5e1f60..cddb25451 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeGrowthHelper.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeGrowthHelper.java @@ -75,12 +75,7 @@ public class TreeGrowthHelper { for (int x = 0; x < girth; x++) { for (int z = 0; z < girth; z++) { BlockPos checkPos = startPos.add(x, 0, z); - Boolean knownSapling = knownSaplings.get(checkPos); - if (knownSapling == null) { - knownSapling = isSapling(genome, world, checkPos); - knownSaplings.put(checkPos, knownSapling); - } - + Boolean knownSapling = knownSaplings.computeIfAbsent(checkPos, k -> isSapling(genome, world, checkPos)); if (!knownSapling) { return false; } diff --git a/src/main/java/forestry/arboriculture/genetics/TreeRoot.java b/src/main/java/forestry/arboriculture/genetics/TreeRoot.java index 4a6e7fbd4..4f158248a 100644 --- a/src/main/java/forestry/arboriculture/genetics/TreeRoot.java +++ b/src/main/java/forestry/arboriculture/genetics/TreeRoot.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -19,6 +19,7 @@ import java.util.List; import java.util.Locale; import java.util.Map.Entry; +import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumTreeChromosome; @@ -44,7 +45,6 @@ import forestry.api.genetics.ISpeciesType; import forestry.arboriculture.PluginArboriculture; import forestry.arboriculture.blocks.BlockFruitPod; import forestry.arboriculture.blocks.BlockSapling; -import forestry.arboriculture.genetics.pollination.CheckPollinatableTree; import forestry.arboriculture.tiles.TileFruitPod; import forestry.arboriculture.tiles.TileSapling; import forestry.core.config.Config; @@ -69,11 +69,11 @@ import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.oredict.OreDictionary; public class TreeRoot extends SpeciesRoot implements ITreeRoot { - public static final String UID = "rootTrees"; private static int treeSpeciesCount = -1; + @Nullable private static ITreekeepingMode activeTreekeepingMode; - public static final ArrayList treeTemplates = new ArrayList<>(); + public static final List treeTemplates = new ArrayList<>(); private final ArrayList treekeepingModes = new ArrayList<>(); @@ -124,8 +124,9 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { /* TREE SPECIFIC */ @Override + @Nullable public EnumGermlingType getType(ItemStack stack) { - if (stack == null) { + if (stack.isEmpty()) { return null; } @@ -158,12 +159,8 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { @Override public ITree getMember(ItemStack itemstack) { itemstack = GeneticsUtil.convertToGeneticEquivalent(itemstack); - if (!isMember(itemstack)) { - return null; - } - if (itemstack.getTagCompound() == null) { - return null; - } + Preconditions.checkArgument(isMember(itemstack), "ItemStack must be a tree."); + Preconditions.checkArgument(itemstack.getTagCompound() != null, "ItemStack must have a tag compound."); return new Tree(itemstack.getTagCompound()); } @@ -180,12 +177,8 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { @Override public ItemStack getMemberStack(IIndividual tree, ISpeciesType type) { - if (!isMember(tree)) { - return null; - } - if (!(type instanceof EnumGermlingType)) { - return null; - } + Preconditions.checkArgument(tree instanceof ITree, "individual is not a tree"); + Preconditions.checkArgument(type instanceof EnumGermlingType, "type is not an EnumGermlingType"); Item germlingItem; switch ((EnumGermlingType) type) { @@ -234,13 +227,13 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { sapling.getOwnerHandler().setOwner(owner); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.SoundFXType.BLOCK_PLACE, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } @Override - public boolean setFruitBlock(@Nonnull World world, @Nonnull IAlleleFruit allele, float sappiness, BlockPos pos) { + public boolean setFruitBlock(World world, ITreeGenome genome, IAlleleFruit allele, float sappiness, BlockPos pos) { EnumFacing facing = BlockUtil.getValidPodFacing(world, pos); if (facing == null) { @@ -268,7 +261,7 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { world.setBlockToAir(pos); return false; } - pod.setProperties(allele, sappiness); + pod.setProperties(genome, allele, sappiness); world.markBlockRangeForRenderUpdate(pos, pos); return true; } @@ -296,14 +289,14 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { /* BREEDING TRACKER */ @Override - public IArboristTracker getBreedingTracker(World world, GameProfile player) { + public IArboristTracker getBreedingTracker(World world, @Nullable GameProfile player) { String filename = "ArboristTracker." + (player == null ? "common" : player.getId()); - ArboristTracker tracker = (ArboristTracker) world.loadItemData(ArboristTracker.class, filename); + ArboristTracker tracker = (ArboristTracker) world.loadData(ArboristTracker.class, filename); // Create a tracker if there is none yet. if (tracker == null) { tracker = new ArboristTracker(filename); - world.setItemData(filename, tracker); + world.setData(filename, tracker); } tracker.setUsername(player); @@ -315,7 +308,7 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { /* BREEDING MODES */ @Override - public ArrayList getTreekeepingModes() { + public List getTreekeepingModes() { return this.treekeepingModes; } @@ -364,7 +357,7 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { /* TEMPLATES */ @Override - public ArrayList getIndividualTemplates() { + public List getIndividualTemplates() { return treeTemplates; } @@ -435,19 +428,16 @@ public class TreeRoot extends SpeciesRoot implements ITreeRoot { @Override public ICheckPollinatable createPollinatable(IIndividual individual) { - if(individual instanceof ITree){ - return new CheckPollinatableTree((ITree)individual); - } - return null; + Preconditions.checkArgument(individual instanceof ITree, "individual must be a tree"); + return new CheckPollinatableTree((ITree) individual); } @Override - public IPollinatable tryConvertToPollinatable(GameProfile owner, World world, BlockPos pos, IIndividual pollen) { - if(pollen instanceof ITree){ - if (Config.pollinateVanillaTrees) { - ((ITree)pollen).setLeaves(world, owner, pos); - return (IPollinatable) world.getTileEntity(pos); - } + public IPollinatable tryConvertToPollinatable(@Nullable GameProfile owner, World world, BlockPos pos, IIndividual pollen) { + Preconditions.checkArgument(pollen instanceof ITree, "pollen must be an instance of ITree"); + if (Config.pollinateVanillaTrees) { + ((ITree) pollen).setLeaves(world, owner, pos); + return (IPollinatable) world.getTileEntity(pos); } return null; } diff --git a/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java b/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java index 39c955156..60ea456b9 100755 --- a/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java +++ b/src/main/java/forestry/arboriculture/genetics/TreekeepingMode.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.genetics; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Locale; @@ -56,7 +57,7 @@ public class TreekeepingMode implements ITreekeepingMode { } @Override - public float getYieldModifier(ITreeGenome genome, float currentModifier) { + public float getYieldModifier(@Nullable ITreeGenome genome, float currentModifier) { return yieldModifier; } diff --git a/src/main/java/forestry/arboriculture/genetics/WoodProvider.java b/src/main/java/forestry/arboriculture/genetics/WoodProvider.java index 113b70901..e8ce835da 100644 --- a/src/main/java/forestry/arboriculture/genetics/WoodProvider.java +++ b/src/main/java/forestry/arboriculture/genetics/WoodProvider.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; import java.util.Locale; import forestry.api.arboriculture.EnumForestryWoodType; @@ -37,7 +36,7 @@ public class WoodProvider implements IWoodProvider { this.name = woodType.toString().toLowerCase(Locale.ENGLISH); this.woodType = woodType; } - + @Override public void registerSprites(Item item, ITextureManager manager) { TextureMap textureMap = Proxies.common.getClientInstance().getTextureMapBlocks(); @@ -45,16 +44,15 @@ public class WoodProvider implements IWoodProvider { woodBark = textureMap.registerSprite(new ResourceLocation(Constants.MOD_ID, "blocks/wood/bark." + name)); } - @Nonnull @Override public TextureAtlasSprite getSprite(boolean isTop) { - if(isTop){ + if (isTop) { return woodTop; - }else{ + } else { return woodBark; } } - + @Override public ItemStack getWoodStack() { return TreeManager.woodAccess.getStack(woodType, WoodBlockKind.LOG, false); @@ -64,9 +62,9 @@ public class WoodProvider implements IWoodProvider { public int getCarbonization() { return woodType.getCarbonization(); } - + @Override - public float getCharcoalChance(int numberOfCharcoal){ + public float getCharcoalChance(int numberOfCharcoal) { return woodType.getCharcoalChance(numberOfCharcoal); } diff --git a/src/main/java/forestry/arboriculture/genetics/WoodProviderVanilla.java b/src/main/java/forestry/arboriculture/genetics/WoodProviderVanilla.java index d9ff55c02..b04aa78a7 100644 --- a/src/main/java/forestry/arboriculture/genetics/WoodProviderVanilla.java +++ b/src/main/java/forestry/arboriculture/genetics/WoodProviderVanilla.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.genetics; -import javax.annotation.Nonnull; - import forestry.api.arboriculture.EnumVanillaWoodType; import forestry.api.arboriculture.IWoodProvider; import forestry.api.arboriculture.TreeManager; @@ -64,8 +62,7 @@ public class WoodProviderVanilla implements IWoodProvider { woodTop = textureMap.registerSprite(new ResourceLocation("minecraft", "blocks/log_" + name + "_top")); woodBark = textureMap.registerSprite(new ResourceLocation("minecraft", "blocks/log_" + name)); } - - @Nonnull + @Override public TextureAtlasSprite getSprite(boolean isTop) { if (isTop) { diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java index 8e5a38ea1..073d851f5 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruit.java @@ -10,128 +10,30 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import net.minecraft.init.Items; -import net.minecraft.item.EnumDyeColor; -import net.minecraft.item.ItemStack; - -import forestry.api.arboriculture.EnumFruitFamily; -import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleFruit; import forestry.api.arboriculture.IFruitProvider; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.arboriculture.FruitProviderNone; -import forestry.arboriculture.FruitProviderPod; -import forestry.arboriculture.FruitProviderRandom; -import forestry.arboriculture.FruitProviderRipening; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleCategorized; -import forestry.core.items.ItemFruit; public class AlleleFruit extends AlleleCategorized implements IAlleleFruit { - - public static IAlleleFruit fruitNone; - public static IAlleleFruit fruitApple; - public static IAlleleFruit fruitCocoa; - public static IAlleleFruit fruitChestnut; - public static IAlleleFruit fruitCoconut; - public static IAlleleFruit fruitWalnut; - public static IAlleleFruit fruitCherry; - public static IAlleleFruit fruitDates; - public static IAlleleFruit fruitPapaya; - public static IAlleleFruit fruitLemon; - public static IAlleleFruit fruitPlum; - public static IAlleleFruit fruitJujube; - private static List fruitAlleles; - private static List fruitAllelesWithModels; - - public static void createAlleles() { - List fruitAlleles = Arrays.asList( - fruitNone = new AlleleFruit("none", new FruitProviderNone("for.fruits.none", null)), - fruitApple = new AlleleFruit("apple", new FruitProviderRandom("for.fruits.apple", EnumFruitFamily.POMES, new ItemStack(Items.APPLE), 1.0f) - .setColour(new Color(0xff2e2e)) - .setOverlay("pomes")), - fruitCocoa = new AlleleFruit("cocoa", new FruitProviderPod("for.fruits.cocoa", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.COCOA, new ItemStack(Items.DYE, 1, EnumDyeColor.BROWN.getDyeDamage()))), - // .setColours(0xecdca5, 0xc4d24a), true); - fruitChestnut = new AlleleFruit("chestnut", new FruitProviderRipening("for.fruits.chestnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.CHESTNUT.getStack(), 1.0f) - .setRipeningPeriod(6) - .setColours(new Color(0x7f333d), new Color(0xc4d24a)) - .setOverlay("nuts"), true), - fruitWalnut = new AlleleFruit("walnut", new FruitProviderRipening("for.fruits.walnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.WALNUT.getStack(), 1.0f) - .setRipeningPeriod(8) - .setColours(new Color(0xfba248), new Color(0xc4d24a)) - .setOverlay("nuts"), true), - fruitCherry = new AlleleFruit("cherry", new FruitProviderRipening("for.fruits.cherry", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.CHERRY.getStack(), 1.0f) - .setColours(new Color(0xff2e2e), new Color(0xc4d24a)) - .setOverlay("berries"), true), - fruitDates = new AlleleFruit("dates", new FruitProviderPod("for.fruits.dates", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.DATES, ItemFruit.EnumFruit.DATES.getStack(4))), - fruitPapaya = new AlleleFruit("papaya", new FruitProviderPod("for.fruits.papaya", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.PAPAYA, ItemFruit.EnumFruit.PAPAYA.getStack())), - fruitLemon = new AlleleFruit("lemon", new FruitProviderRipening("for.fruits.lemon", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.LEMON.getStack(), 1.0f) - .setColours(new Color(0xeeee00), new Color(0x99ff00)) - .setOverlay("citrus"), true), - fruitPlum = new AlleleFruit("plum", new FruitProviderRipening("for.fruits.plum", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.PLUM.getStack(), 1.0f) - .setColours(new Color(0x663446), new Color(0xeeff1a)) - .setOverlay("plums"), true) - ); - - for (IAlleleFruit fruitAllele : fruitAlleles) { - AlleleManager.alleleRegistry.registerAllele(fruitAllele, EnumTreeChromosome.FRUITS); - } - } - - public static List getFruitAlleles() { - if (fruitAlleles == null) { - fruitAlleles = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleFruit) { - IAlleleFruit alleleFruit = (IAlleleFruit) allele; - fruitAlleles.add(alleleFruit); - } - } - } - return fruitAlleles; - } - - public static List getFruitAllelesWithModels() { - if (fruitAllelesWithModels == null) { - fruitAllelesWithModels = new ArrayList<>(); - for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { - if (allele instanceof IAlleleFruit) { - IAlleleFruit alleleFruit = (IAlleleFruit) allele; - if (alleleFruit.getModelName() != null) { - fruitAllelesWithModels.add(alleleFruit); - } - } - } - } - return fruitAllelesWithModels; - } - - @Nonnull private final IFruitProvider provider; - public AlleleFruit(@Nonnull String name, @Nonnull IFruitProvider provider) { + public AlleleFruit(String name, IFruitProvider provider) { this(name, provider, false); } - public AlleleFruit(@Nonnull String name, @Nonnull IFruitProvider provider, boolean isDominant) { + public AlleleFruit(String name, IFruitProvider provider, boolean isDominant) { super(Constants.MOD_ID, "fruit", name, isDominant); this.provider = provider; } - @Nonnull @Override public IFruitProvider getProvider() { return this.provider; } - + @Override public String getName() { return getProvider().getDescription(); @@ -143,15 +45,14 @@ public class AlleleFruit extends AlleleCategorized implements IAlleleFruit { return getProvider().getModelName(); } - @Nonnull + @Override public String getModID() { return getProvider().getModID(); } - + @Override - public int compareTo(@Nonnull IAlleleFruit o) { + public int compareTo(IAlleleFruit o) { return 0; } - } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruits.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruits.java new file mode 100644 index 000000000..020b721d6 --- /dev/null +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleFruits.java @@ -0,0 +1,86 @@ +package forestry.arboriculture.genetics.alleles; + +import javax.annotation.Nullable; +import java.awt.Color; +import java.util.ArrayList; +import java.util.List; + +import forestry.api.arboriculture.EnumFruitFamily; +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.arboriculture.IAlleleFruit; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.arboriculture.FruitProviderNone; +import forestry.arboriculture.FruitProviderPod; +import forestry.arboriculture.FruitProviderRandom; +import forestry.arboriculture.FruitProviderRipening; +import forestry.core.items.ItemFruit; +import net.minecraft.init.Items; +import net.minecraft.item.EnumDyeColor; +import net.minecraft.item.ItemStack; + +public class AlleleFruits { + public static final IAlleleFruit fruitNone = new AlleleFruit("none", new FruitProviderNone("for.fruits.none", EnumFruitFamily.NONE)); + public static final IAlleleFruit fruitApple = new AlleleFruit("apple", new FruitProviderRandom("for.fruits.apple", EnumFruitFamily.POMES, new ItemStack(Items.APPLE), 1.0f) + .setColour(new Color(0xff2e2e)) + .setOverlay("pomes")); + public static final IAlleleFruit fruitCocoa = new AlleleFruit("cocoa", new FruitProviderPod("for.fruits.cocoa", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.COCOA, new ItemStack(Items.DYE, 1, EnumDyeColor.BROWN.getDyeDamage()))); + // .setColours(0xecdca5, 0xc4d24a), true); + public static final IAlleleFruit fruitChestnut = new AlleleFruit("chestnut", new FruitProviderRipening("for.fruits.chestnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.CHESTNUT.getStack(), 1.0f) + .setRipeningPeriod(6) + .setColours(new Color(0x7f333d), new Color(0xc4d24a)) + .setOverlay("nuts"), true); + public static final IAlleleFruit fruitWalnut = new AlleleFruit("walnut", new FruitProviderRipening("for.fruits.walnut", EnumFruitFamily.NUX, ItemFruit.EnumFruit.WALNUT.getStack(), 1.0f) + .setRipeningPeriod(8) + .setColours(new Color(0xfba248), new Color(0xc4d24a)) + .setOverlay("nuts"), true); + public static final IAlleleFruit fruitCherry = new AlleleFruit("cherry", new FruitProviderRipening("for.fruits.cherry", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.CHERRY.getStack(), 1.0f) + .setColours(new Color(0xff2e2e), new Color(0xc4d24a)) + .setOverlay("berries"), true); + public static final IAlleleFruit fruitDates = new AlleleFruit("dates", new FruitProviderPod("for.fruits.dates", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.DATES, ItemFruit.EnumFruit.DATES.getStack(4))); + public static final IAlleleFruit fruitPapaya = new AlleleFruit("papaya", new FruitProviderPod("for.fruits.papaya", EnumFruitFamily.JUNGLE, FruitProviderPod.EnumPodType.PAPAYA, ItemFruit.EnumFruit.PAPAYA.getStack())); + public static final IAlleleFruit fruitLemon = new AlleleFruit("lemon", new FruitProviderRipening("for.fruits.lemon", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.LEMON.getStack(), 1.0f) + .setColours(new Color(0xeeee00), new Color(0x99ff00)) + .setOverlay("citrus"), true); + public static final IAlleleFruit fruitPlum = new AlleleFruit("plum", new FruitProviderRipening("for.fruits.plum", EnumFruitFamily.PRUNES, ItemFruit.EnumFruit.PLUM.getStack(), 1.0f) + .setColours(new Color(0x663446), new Color(0xeeff1a)) + .setOverlay("plums"), true); + @Nullable + private static List fruitAlleles; + @Nullable + private static List fruitAllelesWithModels; + + public static void registerAlleles() { + for (IAlleleFruit fruitAllele : getFruitAlleles()) { + AlleleManager.alleleRegistry.registerAllele(fruitAllele, EnumTreeChromosome.FRUITS); + } + } + + public static List getFruitAlleles() { + if (fruitAlleles == null) { + fruitAlleles = new ArrayList<>(); + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleFruit) { + IAlleleFruit alleleFruit = (IAlleleFruit) allele; + fruitAlleles.add(alleleFruit); + } + } + } + return fruitAlleles; + } + + public static List getFruitAllelesWithModels() { + if (fruitAllelesWithModels == null) { + fruitAllelesWithModels = new ArrayList<>(); + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleFruit) { + IAlleleFruit alleleFruit = (IAlleleFruit) allele; + if (alleleFruit.getModelName() != null) { + fruitAllelesWithModels.add(alleleFruit); + } + } + } + } + return fruitAllelesWithModels; + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java deleted file mode 100644 index f1d3993eb..000000000 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleGrowth.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.genetics.alleles; - -import java.util.Arrays; -import java.util.List; - -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.arboriculture.IAlleleGrowth; -import forestry.api.arboriculture.IGrowthProvider; -import forestry.api.genetics.AlleleManager; -import forestry.arboriculture.genetics.GrowthProvider; -import forestry.core.config.Constants; -import forestry.core.genetics.alleles.AlleleCategorized; - -/** - * @deprecated this is being removed to simplify trees - */ -@Deprecated -public class AlleleGrowth extends AlleleCategorized implements IAlleleGrowth { - - public static IAlleleGrowth growthLightLevel; - public static IAlleleGrowth growthAcacia; - public static IAlleleGrowth growthTropical; - - public static void createAlleles() { - List growthAlleles = Arrays.asList( - growthLightLevel = new AlleleGrowth("lightlevel", new GrowthProvider()), - growthAcacia = new AlleleGrowth("acacia", new GrowthProvider()), - growthTropical = new AlleleGrowth("tropical", new GrowthProvider()) - ); - - for (IAlleleGrowth alleleGrowth : growthAlleles) { - AlleleManager.alleleRegistry.registerAllele(alleleGrowth, EnumTreeChromosome.GROWTH); - } - } - - private final IGrowthProvider provider; - - public AlleleGrowth(String name, IGrowthProvider provider) { - this(name, provider, false); - } - - public AlleleGrowth(String name, IGrowthProvider provider, boolean isDominant) { - super(Constants.MOD_ID, "growth", name, isDominant); - this.provider = provider; - } - - @Override - public IGrowthProvider getProvider() { - return provider; - } - -} diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java index b8b7390a8..bdc290107 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffect.java @@ -10,25 +10,18 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; +import javax.annotation.Nullable; + import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleLeafEffect; import forestry.api.arboriculture.ITreeGenome; -import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IEffectData; import forestry.core.config.Constants; -import forestry.core.genetics.alleles.Allele; import forestry.core.genetics.alleles.AlleleCategorized; public class AlleleLeafEffect extends AlleleCategorized implements IAlleleLeafEffect { - public static Allele leavesNone; - - public static void createAlleles() { - leavesNone = new AlleleLeafEffectNone(); - AlleleManager.alleleRegistry.registerAllele(leavesNone, EnumTreeChromosome.EFFECT); - } protected AlleleLeafEffect(String valueName, boolean isDominant) { super(Constants.MOD_ID, "leaves", valueName, isDominant); diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffects.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffects.java new file mode 100644 index 000000000..b748d5193 --- /dev/null +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleLeafEffects.java @@ -0,0 +1,13 @@ +package forestry.arboriculture.genetics.alleles; + +import forestry.api.arboriculture.EnumTreeChromosome; +import forestry.api.genetics.AlleleManager; +import forestry.core.genetics.alleles.Allele; + +public class AlleleLeafEffects { + public static final Allele leavesNone = new AlleleLeafEffectNone(); + + public static void registerAlleles() { + AlleleManager.alleleRegistry.registerAllele(leavesNone, EnumTreeChromosome.EFFECT); + } +} diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java index 9e04e0ecc..0eadb9b73 100644 --- a/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java +++ b/src/main/java/forestry/arboriculture/genetics/alleles/AlleleTreeSpecies.java @@ -10,17 +10,9 @@ ******************************************************************************/ package forestry.arboriculture.genetics.alleles; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.item.Item; - -import net.minecraftforge.common.EnumPlantType; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.arboriculture.IAlleleTreeSpecies; @@ -36,43 +28,41 @@ import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IClassification; import forestry.api.genetics.IFruitFamily; import forestry.core.genetics.alleles.AlleleSpecies; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.Item; +import net.minecraftforge.common.EnumPlantType; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeciesBuilder, IAlleleTreeSpecies { - @Nonnull private final ITreeGenerator generator; - @Nonnull private final IWoodProvider woodProvider; - @Nonnull private final IGermlingModelProvider germlingModelProvider; - @Nonnull private final ILeafSpriteProvider leafSpriteProvider; - @Nonnull private final List fruits = new ArrayList<>(); - @Nonnull private final String modID; - @Nonnull private EnumPlantType nativeType = EnumPlantType.Plains; public AlleleTreeSpecies( - @Nonnull String uid, - @Nonnull String unlocalizedName, - @Nonnull String authority, - @Nonnull String unlocalizedDescription, + String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, boolean isDominant, - @Nonnull IClassification branch, - @Nonnull String binomial, - @Nonnull String modID, - @Nonnull ILeafSpriteProvider leafIconProvider, - @Nonnull IGermlingModelProvider germlingModelProvider, - @Nonnull IWoodProvider woodProvider, - @Nonnull ITreeGenerator generator) { + IClassification branch, + String binomial, + String modID, + ILeafSpriteProvider leafIconProvider, + IGermlingModelProvider germlingModelProvider, + IWoodProvider woodProvider, + ITreeGenerator generator) { super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); this.generator = generator; this.germlingModelProvider = germlingModelProvider; this.woodProvider = woodProvider; this.leafSpriteProvider = leafIconProvider; - + this.modID = modID; } @@ -82,7 +72,6 @@ public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeci return this; } - @Nonnull @Override public ITreeRoot getRoot() { return TreeManager.treeRoot; @@ -101,25 +90,21 @@ public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeci } /* OTHER */ - @Nonnull @Override public EnumPlantType getPlantType() { return nativeType; } - @Nonnull @Override public List getSuitableFruit() { return fruits; } - @Nonnull @Override public ITreeGenerator getGenerator() { return generator; } - @Nonnull @Override public ILeafSpriteProvider getLeafSpriteProvider() { return leafSpriteProvider; @@ -129,8 +114,7 @@ public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeci public int getSpriteColour(int renderPass) { return leafSpriteProvider.getColor(false); } - - @Nonnull + @SideOnly(Side.CLIENT) @Override public ModelResourceLocation getGermlingModel(EnumGermlingType type) { @@ -142,28 +126,25 @@ public class AlleleTreeSpecies extends AlleleSpecies implements IAlleleTreeSpeci public int getGermlingColour(EnumGermlingType type, int renderPass) { return germlingModelProvider.getSpriteColor(type, renderPass); } - + @SideOnly(Side.CLIENT) @Override public void registerModels(Item item, IModelManager manager, EnumGermlingType type) { germlingModelProvider.registerModels(item, manager, type); } - + @Override - @Nonnull public IWoodProvider getWoodProvider() { return woodProvider; } - @Nonnull @Override public String getModID() { return modID; } - + @Override - public int compareTo(@Nonnull IAlleleTreeSpecies o) { + public int compareTo(IAlleleTreeSpecies o) { return 0; } - } diff --git a/src/main/java/forestry/arboriculture/genetics/alleles/package-info.java b/src/main/java/forestry/arboriculture/genetics/alleles/package-info.java new file mode 100644 index 000000000..0d2fda458 --- /dev/null +++ b/src/main/java/forestry/arboriculture/genetics/alleles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.genetics.alleles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/genetics/package-info.java b/src/main/java/forestry/arboriculture/genetics/package-info.java new file mode 100644 index 000000000..07ee79aab --- /dev/null +++ b/src/main/java/forestry/arboriculture/genetics/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.genetics; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java b/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java index ec59ec0a6..1ff30036e 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockDecorativeLeaves.java @@ -1,16 +1,13 @@ package forestry.arboriculture.items; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - import forestry.api.arboriculture.IFruitProvider; import forestry.api.arboriculture.ITreeGenome; -import forestry.arboriculture.PluginArboriculture; import forestry.arboriculture.blocks.BlockDecorativeLeaves; import forestry.arboriculture.genetics.TreeDefinition; import forestry.core.items.IColoredItem; import forestry.core.items.ItemBlockForestry; -import forestry.core.utils.Translator; +import net.minecraft.block.Block; +import net.minecraft.item.ItemStack; public class ItemBlockDecorativeLeaves extends ItemBlockForestry implements IColoredItem { public ItemBlockDecorativeLeaves(Block block) { @@ -22,9 +19,6 @@ public class ItemBlockDecorativeLeaves extends ItemBlockForestry impl @Override public String getItemStackDisplayName(ItemStack itemstack) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return Translator.translateToLocal("trees.grammar.leaves.type"); } @@ -60,7 +60,7 @@ public class ItemBlockLeaves extends ItemBlockForestry impl @Override public int getColorFromItemstack(ItemStack itemStack, int renderPass) { - if (!itemStack.hasTagCompound()) { + if (itemStack.getTagCompound() == null) { return PluginArboriculture.proxy.getFoliageColorBasic(); } diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockPile.java b/src/main/java/forestry/arboriculture/items/ItemBlockPile.java index 268a95e4f..0735daa7c 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockPile.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockPile.java @@ -48,7 +48,7 @@ public class ItemBlockPile extends ItemBlockForestry { @Override public String getItemStackDisplayName(ItemStack itemstack) { if(block == PluginArboriculture.blocks.piles.get(EnumPileType.WOOD)){ - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return "Unknown"; } IAlleleTreeSpecies species = BlockPile.getTreeSpecies(itemstack); @@ -74,7 +74,7 @@ public class ItemBlockPile extends ItemBlockForestry { if (placed) { if (block == PluginArboriculture.blocks.piles.get(EnumPileType.WOOD)) { if (block.hasTileEntity(newState)) { - if (stack.hasTagCompound()) { + if (stack.getTagCompound() != null) { TilePile tile = TileUtil.getTile(world, pos, TilePile.class); if (tile != null) { tile.readFromNBT(stack.getTagCompound()); diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java b/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java index ec24c6ccf..11c056779 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWoodDoor.java @@ -1,5 +1,6 @@ package forestry.arboriculture.items; +import forestry.arboriculture.blocks.BlockArbDoor; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; @@ -13,17 +14,17 @@ import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.arboriculture.blocks.BlockArbDoor; - public class ItemBlockWoodDoor extends ItemBlockWood { public ItemBlockWoodDoor(Block block) { super(block); } - /** Copy of {@link ItemDoor#onItemUse} */ + /** + * Copy of {@link ItemDoor#onItemUse} + */ @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (facing != EnumFacing.UP) { return EnumActionResult.FAIL; } else { @@ -34,15 +35,17 @@ public class ItemBlockWoodDoor extends ItemBlockWood { pos = pos.offset(facing); } - if (playerIn.canPlayerEdit(pos, facing, stack) && this.block.canPlaceBlockAt(worldIn, pos)) { - EnumFacing enumfacing = EnumFacing.fromAngle(playerIn.rotationYaw); - int x = enumfacing.getFrontOffsetX(); - int z = enumfacing.getFrontOffsetZ(); - boolean isRightHinge = x < 0 && hitZ < 0.5F || x > 0 && hitZ > 0.5F || z < 0 && hitX > 0.5F || z > 0 && hitX < 0.5F; - ItemDoor.placeDoor(worldIn, pos, enumfacing, this.block, isRightHinge); - SoundType soundtype = this.block.getSoundType(); - worldIn.playSound(playerIn, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); - --stack.stackSize; + ItemStack itemstack = player.getHeldItem(hand); + + if (player.canPlayerEdit(pos, facing, itemstack) && this.block.canPlaceBlockAt(worldIn, pos)) { + EnumFacing enumfacing = EnumFacing.fromAngle((double) player.rotationYaw); + int i = enumfacing.getFrontOffsetX(); + int j = enumfacing.getFrontOffsetZ(); + boolean flag = i < 0 && hitZ < 0.5F || i > 0 && hitZ > 0.5F || j < 0 && hitX > 0.5F || j > 0 && hitX < 0.5F; + ItemDoor.placeDoor(worldIn, pos, enumfacing, this.block, flag); + SoundType soundtype = worldIn.getBlockState(pos).getBlock().getSoundType(worldIn.getBlockState(pos), worldIn, pos, player); + worldIn.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); + itemstack.shrink(1); return EnumActionResult.SUCCESS; } else { return EnumActionResult.FAIL; diff --git a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java index a82b3eaba..61e928749 100644 --- a/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java +++ b/src/main/java/forestry/arboriculture/items/ItemBlockWoodSlab.java @@ -5,7 +5,7 @@ import net.minecraft.item.ItemStack; import forestry.api.arboriculture.IWoodType; import forestry.arboriculture.WoodHelper; -import forestry.arboriculture.blocks.slab.BlockForestrySlab; +import forestry.arboriculture.blocks.BlockForestrySlab; public class ItemBlockWoodSlab extends ItemSlab { public ItemBlockWoodSlab(BlockForestrySlab block, BlockForestrySlab slab, BlockForestrySlab doubleSlab) { diff --git a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java index 08db30bfa..e99671a62 100755 --- a/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java +++ b/src/main/java/forestry/arboriculture/items/ItemGermlingGE.java @@ -10,26 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.items; -import javax.annotation.Nonnull; -import java.util.List; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.ItemMeshDefinition; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ActionResult; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.RayTraceResult; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - +import com.google.common.base.Preconditions; import forestry.api.arboriculture.EnumGermlingType; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ITree; @@ -44,7 +25,6 @@ import forestry.api.genetics.IIndividual; import forestry.api.genetics.IPollinatable; import forestry.api.recipes.IVariableFermentable; import forestry.arboriculture.genetics.Tree; -import forestry.arboriculture.genetics.TreeDefinition; import forestry.arboriculture.genetics.TreeGenome; import forestry.core.config.Config; import forestry.core.genetics.ItemGE; @@ -53,6 +33,23 @@ import forestry.core.network.packets.PacketFXSignal; import forestry.core.proxy.Proxies; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.Translator; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.ItemMeshDefinition; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.ActionResult; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class ItemGermlingGE extends ItemGE implements IVariableFermentable, IColoredItem { @@ -65,7 +62,9 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol @Override public ITree getIndividual(ItemStack itemstack) { - return new Tree(itemstack.getTagCompound()); + NBTTagCompound tagCompound = itemstack.getTagCompound(); + Preconditions.checkArgument(tagCompound != null, "Itemstack must have a tag compound."); + return new Tree(tagCompound); } @Override @@ -73,18 +72,9 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol return TreeGenome.getSpecies(itemStack); } - private static IAlleleTreeSpecies getSpeciesOrDefault(ItemStack itemstack) { - IAlleleTreeSpecies treeSpecies = TreeGenome.getSpecies(itemstack); - if (treeSpecies == null) { - treeSpecies = TreeDefinition.Oak.getGenome().getPrimary(); - } - - return treeSpecies; - } - @Override public String getItemStackDisplayName(ItemStack itemstack) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return "Unknown"; } IAlleleSpecies species = getSpecies(itemstack); @@ -98,25 +88,25 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { + addCreativeItems(subItems, true); } - public void addCreativeItems(List itemList, boolean hideSecrets) { + public void addCreativeItems(NonNullList subItems, boolean hideSecrets) { for (IIndividual individual : TreeManager.treeRoot.getIndividualTemplates()) { // Don't show secrets unless ordered to. if (hideSecrets && individual.isSecret() && !Config.isDebug) { continue; } - itemList.add(TreeManager.treeRoot.getMemberStack(individual, type)); + subItems.add(TreeManager.treeRoot.getMemberStack(individual, type)); } } @Override @SideOnly(Side.CLIENT) public int getColorFromItemstack(ItemStack itemstack, int renderPass) { - return getSpeciesOrDefault(itemstack).getGermlingColour(type, renderPass); + return TreeGenome.getSpecies(itemstack).getGermlingColour(type, renderPass); } /* MODELS */ @@ -136,34 +126,30 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol @Override public ModelResourceLocation getModelLocation(ItemStack stack) { IAlleleTreeSpecies treeSpecies = getSpecies(stack); - if (treeSpecies == null) { - treeSpecies = TreeDefinition.Oak.getGenome().getPrimary(); - } return treeSpecies.getGermlingModel(type); } - } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { RayTraceResult raytraceresult = this.rayTrace(worldIn, playerIn, true); + ItemStack itemStack = playerIn.getHeldItem(handIn); + if (raytraceresult != null && raytraceresult.typeOfHit == RayTraceResult.Type.BLOCK) { BlockPos pos = raytraceresult.getBlockPos(); - ITree tree = TreeManager.treeRoot.getMember(itemStackIn); - if (tree != null) { - if (type == EnumGermlingType.SAPLING) { - return onItemRightClickSapling(itemStackIn, worldIn, playerIn, pos, tree); - } else if (type == EnumGermlingType.POLLEN) { - return onItemRightClickPollen(itemStackIn, worldIn, playerIn, pos, tree); - } + ITree tree = TreeManager.treeRoot.getMember(itemStack); + if (type == EnumGermlingType.SAPLING) { + return onItemRightClickSapling(itemStack, worldIn, playerIn, pos, tree); + } else if (type == EnumGermlingType.POLLEN) { + return onItemRightClickPollen(itemStack, worldIn, playerIn, pos, tree); } } - return new ActionResult<>(EnumActionResult.PASS, itemStackIn); + return new ActionResult<>(EnumActionResult.PASS, itemStack); } - @Nonnull + private static ActionResult onItemRightClickPollen(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, BlockPos pos, ITree tree) { ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(worldIn, pos); if (checkPollinatable == null || !checkPollinatable.canMateWith(tree)) { @@ -174,7 +160,7 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol if (pollinatable == null || !pollinatable.canMateWith(tree)) { return new ActionResult<>(EnumActionResult.FAIL, itemStackIn); } - + if (worldIn.isRemote) { return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); } else { @@ -182,16 +168,16 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol IBlockState blockState = worldIn.getBlockState(pos); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, worldIn); + Proxies.net.sendNetworkPacket(packet, pos, worldIn); if (!playerIn.capabilities.isCreativeMode) { - itemStackIn.stackSize--; + itemStackIn.shrink(1); } return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); } } - @Nonnull + private static ActionResult onItemRightClickSapling(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, BlockPos pos, ITree tree) { // x, y, z are the coordinates of the block "hit", can thus either be the soil or tall grass, etc. IBlockState hitBlock = worldIn.getBlockState(pos); @@ -205,7 +191,7 @@ public class ItemGermlingGE extends ItemGE implements IVariableFermentable, ICol if (tree.canStay(worldIn, pos)) { if (TreeManager.treeRoot.plantSapling(worldIn, tree, playerIn.getGameProfile(), pos)) { if (!playerIn.capabilities.isCreativeMode) { - itemStackIn.stackSize--; + itemStackIn.shrink(1); } return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); } diff --git a/src/main/java/forestry/arboriculture/items/ItemGrafter.java b/src/main/java/forestry/arboriculture/items/ItemGrafter.java index 2985e1d97..03ed48523 100755 --- a/src/main/java/forestry/arboriculture/items/ItemGrafter.java +++ b/src/main/java/forestry/arboriculture/items/ItemGrafter.java @@ -29,7 +29,7 @@ import forestry.core.items.ItemForestryTool; public class ItemGrafter extends ItemForestryTool implements IToolGrafter { public ItemGrafter(int maxDamage) { - super(null); + super(ItemStack.EMPTY); setMaxDamage(maxDamage); setMaxStackSize(1); setCreativeTab(Tabs.tabArboriculture); @@ -48,10 +48,9 @@ public class ItemGrafter extends ItemForestryTool implements IToolGrafter { @Override public boolean canHarvestBlock(IBlockState state, ItemStack stack) { Block block = state.getBlock(); - if (block instanceof BlockLeaves || block.getMaterial(state) == Material.LEAVES) { - return true; - } - return super.canHarvestBlock(state, stack); + return block instanceof BlockLeaves || + state.getMaterial() == Material.LEAVES || + super.canHarvestBlock(state, stack); } @Override diff --git a/src/main/java/forestry/arboriculture/items/package-info.java b/src/main/java/forestry/arboriculture/items/package-info.java new file mode 100644 index 000000000..be02077e3 --- /dev/null +++ b/src/main/java/forestry/arboriculture/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java b/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java index 491ea9b95..9a07d4adb 100644 --- a/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java +++ b/src/main/java/forestry/arboriculture/models/ModelDecorativeLeaves.java @@ -10,9 +10,7 @@ ******************************************************************************/ package forestry.arboriculture.models; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - +import com.google.common.base.Preconditions; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.arboriculture.ILeafSpriteProvider; import forestry.api.arboriculture.ITreeGenome; @@ -36,27 +34,23 @@ public class ModelDecorativeLeaves extends ModelBlockCached { public static class Key { - public final TextureAtlasSprite leafSprite, fruitSprite; + public final TextureAtlasSprite leafSprite; + @Nullable + public final TextureAtlasSprite fruitSprite; public final boolean fancy; private final int hashCode; - public Key(TextureAtlasSprite leafSprite, TextureAtlasSprite fruitSprite, boolean fancy) { + public Key(TextureAtlasSprite leafSprite, @Nullable TextureAtlasSprite fruitSprite, boolean fancy) { this.leafSprite = leafSprite; this.fruitSprite = fruitSprite; this.fancy = fancy; @@ -64,11 +66,11 @@ public class ModelLeaves extends ModelBlockCached textureGetter = new DefaultTextureGetter(); + @Nullable private static IModel modelWoodPileItem; + @Nullable private static IModel modelWoodPileBlock; private static final Cache blockCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); private static final Cache itemCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); - + /** * Init the model with datas from the ModelBakeEvent. */ - public static void onModelBake(ModelBakeEvent event){ + public static void onModelBake(ModelBakeEvent event) { blockCache.invalidateAll(); itemCache.invalidateAll(); } - + @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { - if(state instanceof IExtendedBlockState){ + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + if (state instanceof IExtendedBlockState) { IExtendedBlockState stateExtended = (IExtendedBlockState) state; - + IBlockAccess world = stateExtended.getValue(UnlistedBlockAccess.BLOCKACCESS); BlockPos pos = stateExtended.getValue(UnlistedBlockPos.POS); - + TilePile pile = TileUtil.getTile(world, pos, TilePile.class); - - if(pile == null){ + + if (pile == null) { return Collections.emptyList(); } IAlleleTreeSpecies treeSpecies = pile.getTreeSpecies(); - if (treeSpecies == null) { - treeSpecies = (IAlleleTreeSpecies) TreeManager.treeRoot.getDefaultTemplate()[TreeManager.treeRoot.getSpeciesChromosomeType().ordinal()]; - } - + if (modelWoodPileBlock == null) { try { modelWoodPileBlock = ModelLoaderRegistry.getModel(new ResourceLocation("forestry:block/woodPile")); @@ -106,43 +106,42 @@ public class ModelWoodPile extends BlankModel{ public TextureAtlasSprite getParticleTexture() { return TreeDefinition.Oak.getGenome().getPrimary().getWoodProvider().getSprite(false); } - + @Override protected ItemOverrideList createOverrides() { return new PileItemOverrideList(); } private IBakedModel bakeModel(IAlleleTreeSpecies treeSpecies, boolean isItem) { - if(treeSpecies == null || treeSpecies.getWoodProvider() == null || treeSpecies.getWoodProvider().getSprite(false) == null){ - return null; - } ImmutableMap.Builder textures = ImmutableMap.builder(); String treeUID = treeSpecies.getUID(); Cache map = isItem ? itemCache : blockCache; - if(map.getIfPresent(treeUID) == null){ + IBakedModel model = map.getIfPresent(treeUID); + if (model == null) { textures.put("woodBark", treeSpecies.getWoodProvider().getSprite(false).getIconName()); textures.put("woodTop", treeSpecies.getWoodProvider().getSprite(true).getIconName()); IModel retextureWoodPile = ModelProcessingHelper.retexture(isItem ? modelWoodPileItem : modelWoodPileBlock, textures.build()); - map.put(treeUID, retextureWoodPile.bake(ModelRotation.X0_Y0, isItem ? DefaultVertexFormats.ITEM : DefaultVertexFormats.BLOCK, textureGetter)); + model = retextureWoodPile.bake(ModelRotation.X0_Y0, isItem ? DefaultVertexFormats.ITEM : DefaultVertexFormats.BLOCK, textureGetter); + map.put(treeUID, model); } - return map.getIfPresent(treeUID); + return model; } - + private class PileItemOverrideList extends ItemOverrideList { public PileItemOverrideList() { super(Collections.emptyList()); } @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { if (modelWoodPileItem == null) { try { modelWoodPileItem = ModelLoaderRegistry.getModel(new ResourceLocation("forestry:item/woodPile")); } catch (Exception e) { - return null; + return originalModel; } if (modelWoodPileItem == null) { - return null; + return originalModel; } } IAlleleTreeSpecies treeSpecies = BlockPile.getTreeSpecies(stack); diff --git a/src/main/java/forestry/arboriculture/models/SpriteProviderLeaves.java b/src/main/java/forestry/arboriculture/models/SpriteProviderLeaves.java index 2f306af28..62d85caa6 100644 --- a/src/main/java/forestry/arboriculture/models/SpriteProviderLeaves.java +++ b/src/main/java/forestry/arboriculture/models/SpriteProviderLeaves.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.arboriculture.models; -import javax.annotation.Nonnull; import java.awt.Color; -import net.minecraft.util.ResourceLocation; - import forestry.api.arboriculture.EnumLeafType; import forestry.api.arboriculture.ILeafSpriteProvider; +import net.minecraft.util.ResourceLocation; public class SpriteProviderLeaves implements ILeafSpriteProvider { @@ -40,10 +38,8 @@ public class SpriteProviderLeaves implements ILeafSpriteProvider { } @Override - @Nonnull public ResourceLocation getSprite(boolean pollinated, boolean fancy) { return leafTexture.getSprite(pollinated, fancy); } - } diff --git a/src/main/java/forestry/arboriculture/models/TextureLeaves.java b/src/main/java/forestry/arboriculture/models/TextureLeaves.java index cf5889dce..51d92f39d 100644 --- a/src/main/java/forestry/arboriculture/models/TextureLeaves.java +++ b/src/main/java/forestry/arboriculture/models/TextureLeaves.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.models; -import javax.annotation.Nonnull; import java.util.EnumMap; import java.util.Locale; import java.util.Map; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.util.ResourceLocation; - import forestry.api.arboriculture.EnumLeafType; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.util.ResourceLocation; public class TextureLeaves { private static final Map leafTextures = new EnumMap<>(EnumLeafType.class); @@ -62,7 +60,6 @@ public class TextureLeaves { textureMapBlocks.registerSprite(pollinatedFancy); } - @Nonnull public ResourceLocation getSprite(boolean pollinated, boolean fancy) { if (pollinated) { if (fancy) { diff --git a/src/main/java/forestry/arboriculture/models/WoodModelLoader.java b/src/main/java/forestry/arboriculture/models/WoodModelLoader.java index c1c3eceb2..57bb78fc9 100644 --- a/src/main/java/forestry/arboriculture/models/WoodModelLoader.java +++ b/src/main/java/forestry/arboriculture/models/WoodModelLoader.java @@ -7,31 +7,28 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.tuple.Pair; +import java.util.Set; import com.google.common.base.Charsets; import com.google.common.base.Function; +import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import forestry.core.config.Constants; import forestry.core.utils.Log; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelBlockDefinition; +import net.minecraft.client.renderer.block.model.ModelBlockDefinition.MissingVariantException; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.model.Variant; import net.minecraft.client.renderer.block.model.VariantList; import net.minecraft.client.renderer.block.model.WeightedBakedModel; -import net.minecraft.client.renderer.block.model.ModelBlockDefinition.MissingVariantException; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.resources.IResource; @@ -47,246 +44,243 @@ import net.minecraftforge.client.model.MultiModelState; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.tuple.Pair; -public enum WoodModelLoader implements ICustomModelLoader{ - INSTANCE; +public enum WoodModelLoader implements ICustomModelLoader { + INSTANCE; - public static Map loadingExceptions = Maps.newHashMap(); - private final Map blockDefinitions = Maps.newHashMap(); - public static final List validFiles = new ArrayList<>(); - public boolean isRegistered = false; - - static{ - validFiles.add("door"); - validFiles.add("double_slab"); - validFiles.add("fence"); - validFiles.add("fence_gate"); - validFiles.add("log"); - validFiles.add("planks"); - validFiles.add("slab"); - validFiles.add("stairs"); - } + public static final Map loadingExceptions = Maps.newHashMap(); + private final Map blockDefinitions = Maps.newHashMap(); + public static final List validFiles = new ArrayList<>(); + public boolean isRegistered = false; - // NOOP, handled in loader - @Override - public void onResourceManagerReload(IResourceManager resourceManager) {} + static { + validFiles.add("door"); + validFiles.add("double_slab"); + validFiles.add("fence"); + validFiles.add("fence_gate"); + validFiles.add("log"); + validFiles.add("planks"); + validFiles.add("slab"); + validFiles.add("stairs"); + } - @Override - public boolean accepts(ResourceLocation modelLocation){ - if(!(modelLocation instanceof ModelResourceLocation) || !modelLocation.getResourceDomain().equals(Constants.MOD_ID) || !modelLocation.getResourcePath().contains("arboriculture")){ - return false; - } - String path = modelLocation.getResourcePath(); - for(String validFile : validFiles){ - if(path.endsWith(validFile)){ - return true; - } - } - return false; - } + // NOOP, handled in loader + @Override + public void onResourceManagerReload(IResourceManager resourceManager) { + } - @Override - public IModel loadModel(ResourceLocation modelLocation) throws Exception{ - ModelResourceLocation variant = (ModelResourceLocation) modelLocation; - ModelBlockDefinition definition = getModelBlockDefinition(variant); - try{ - VariantList variants = definition.getVariant(variant.getVariant()); - return new WeightedRandomModel(variant, variants); - }catch(MissingVariantException e){ - if(definition.hasMultipartData()){ - Log.error("The forestry model loader can't load the model with the location: %s, because it dons't support multipart models.", modelLocation.toString()); - } - throw e; - } - } - - /* MODEL LOADER PRIVATE METHODS */ - private ModelBlockDefinition getModelBlockDefinition(ResourceLocation location){ - try{ - ResourceLocation resourcelocation = this.getBlockstateLocation(location); - ModelBlockDefinition modelblockdefinition = this.blockDefinitions.get(resourcelocation); + @Override + public boolean accepts(ResourceLocation modelLocation) { + if (!(modelLocation instanceof ModelResourceLocation) || !modelLocation.getResourceDomain().equals(Constants.MOD_ID) || !modelLocation.getResourcePath().contains("arboriculture")) { + return false; + } + String path = modelLocation.getResourcePath(); + for (String validFile : validFiles) { + if (path.endsWith(validFile)) { + return true; + } + } + return false; + } - if (modelblockdefinition == null){ - modelblockdefinition = this.loadMultipartMBD(location, resourcelocation); - this.blockDefinitions.put(resourcelocation, modelblockdefinition); - } + @Override + public IModel loadModel(ResourceLocation modelLocation) throws Exception { + ModelResourceLocation variant = (ModelResourceLocation) modelLocation; + ModelBlockDefinition definition = getModelBlockDefinition(variant); + try { + VariantList variants = definition.getVariant(variant.getVariant()); + return new WeightedRandomModel(variant, variants); + } catch (MissingVariantException e) { + if (definition.hasMultipartData()) { + Log.error("The forestry model loader can't load the model with the location: %s, because it dons't support multipart models.", modelLocation.toString()); + } + throw e; + } + } - return modelblockdefinition; - } - catch (Exception exception){ - loadingExceptions.put(location, new Exception("Could not load model definition for variant " + location, exception)); - } - return new ModelBlockDefinition(new ArrayList()); - } - - private ResourceLocation getBlockstateLocation(ResourceLocation location){ - return new ResourceLocation(location.getResourceDomain(), "blockstates/" + location.getResourcePath() + ".json"); - } - - private ModelBlockDefinition loadMultipartMBD(ResourceLocation location, ResourceLocation fileIn){ - List list = Lists.newArrayList(); + /* MODEL LOADER PRIVATE METHODS */ + private ModelBlockDefinition getModelBlockDefinition(ResourceLocation location) { + try { + ResourceLocation resourcelocation = this.getBlockstateLocation(location); + return this.blockDefinitions.computeIfAbsent(resourcelocation, k -> this.loadMultipartMBD(location, resourcelocation)); + } catch (Exception exception) { + loadingExceptions.put(location, new Exception("Could not load model definition for variant " + location, exception)); + } + return new ModelBlockDefinition(new ArrayList<>()); + } - try{ - for (IResource iresource : Minecraft.getMinecraft().getResourceManager().getAllResources(fileIn)){ - list.add(this.loadModelBlockDefinition(location, iresource)); - } - }catch (IOException ioexception){ - throw new RuntimeException("Encountered an exception when loading model definition of model " + fileIn, ioexception); - } + private ResourceLocation getBlockstateLocation(ResourceLocation location) { + return new ResourceLocation(location.getResourceDomain(), "blockstates/" + location.getResourcePath() + ".json"); + } - return new ModelBlockDefinition(list); - } - - private ModelBlockDefinition loadModelBlockDefinition(ResourceLocation location, IResource iresource){ - InputStream inputstream = null; - ModelBlockDefinition definition; + private ModelBlockDefinition loadMultipartMBD(ResourceLocation location, ResourceLocation fileIn) { + List list = Lists.newArrayList(); - try{ - inputstream = iresource.getInputStream(); - definition = ModelBlockDefinition.parseFromReader(new InputStreamReader(inputstream, Charsets.UTF_8)); - }catch (Exception exception){ - throw new RuntimeException("Encountered an exception when loading model definition of \'" + location + "\' from: \'" + iresource.getResourceLocation() + "\' in resourcepack: \'" + iresource.getResourcePackName() + "\'", exception); - }finally{ - IOUtils.closeQuietly(inputstream); - } + try { + for (IResource iresource : Minecraft.getMinecraft().getResourceManager().getAllResources(fileIn)) { + list.add(this.loadModelBlockDefinition(location, iresource)); + } + } catch (IOException ioexception) { + throw new RuntimeException("Encountered an exception when loading model definition of model " + fileIn, ioexception); + } - return definition; - } - - private class WeightedRandomModel implements IRetexturableModel { - private final List variants; - private final List locations = new ArrayList(); - private final Set textures = Sets.newHashSet(); - private final List models = new ArrayList(); - private final IModelState defaultState; + return new ModelBlockDefinition(list); + } - public WeightedRandomModel(List locations, List models, List variants, IModelState defaultState){ - this.locations.addAll(locations); - this.models.addAll(models); - this.variants = variants; - this.defaultState = defaultState; - for(IModel model : models){ - textures.addAll(model.getTextures()); - } - } - - public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception{ - this.variants = variants.getVariantList(); - ImmutableList.Builder> builder = ImmutableList.builder(); - for (Variant v : this.variants){ - ResourceLocation loc = v.getModelLocation(); - locations.add(loc); + private ModelBlockDefinition loadModelBlockDefinition(ResourceLocation location, IResource iresource) { + InputStream inputstream = null; + ModelBlockDefinition definition; + + try { + inputstream = iresource.getInputStream(); + definition = ModelBlockDefinition.parseFromReader(new InputStreamReader(inputstream, Charsets.UTF_8)); + } catch (Exception exception) { + throw new RuntimeException("Encountered an exception when loading model definition of \'" + location + "\' from: \'" + iresource.getResourceLocation() + "\' in resourcepack: \'" + iresource.getResourcePackName() + "\'", exception); + } finally { + IOUtils.closeQuietly(inputstream); + } + + return definition; + } + + private class WeightedRandomModel implements IRetexturableModel { + private final List variants; + private final List locations = new ArrayList<>(); + private final Set textures = Sets.newHashSet(); + private final List models = new ArrayList<>(); + private final IModelState defaultState; + + public WeightedRandomModel(List locations, List models, List variants, IModelState defaultState) { + this.locations.addAll(locations); + this.models.addAll(models); + this.variants = variants; + this.defaultState = defaultState; + for (IModel model : models) { + textures.addAll(model.getTextures()); + } + } + + public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception { + this.variants = variants.getVariantList(); + ImmutableList.Builder> builder = ImmutableList.builder(); + for (Variant v : this.variants) { + ResourceLocation loc = v.getModelLocation(); + locations.add(loc); /* - * Vanilla eats this, which makes it only show variants that have models. + * Vanilla eats this, which makes it only show variants that have models. * But that doesn't help debugging, so throw the exception */ - IModel model; - if(loc.equals(new ModelResourceLocation("builtin/missing", "missing"))){ - // explicit missing location, happens if blockstate has "model"=null - model = ModelLoaderRegistry.getMissingModel(); - }else{ - model = ModelLoaderRegistry.getModel(loc); - } + IModel model; + if (loc.equals(new ModelResourceLocation("builtin/missing", "missing"))) { + // explicit missing location, happens if blockstate has "model"=null + model = ModelLoaderRegistry.getMissingModel(); + } else { + model = ModelLoaderRegistry.getModel(loc); + } - // FIXME: is this the place? messes up dependency and texture resolution - model = v.process(model); - for(ResourceLocation location : model.getDependencies()){ - ModelLoaderRegistry.getModelOrMissing(location); - } - //FMLLog.getLogger().error("Exception resolving indirect dependencies for model" + loc, e); - textures.addAll(model.getTextures()); // Kick this, just in case. + // FIXME: is this the place? messes up dependency and texture resolution + model = v.process(model); + for (ResourceLocation location : model.getDependencies()) { + ModelLoaderRegistry.getModelOrMissing(location); + } + //FMLLog.getLogger().error("Exception resolving indirect dependencies for model" + loc, e); + textures.addAll(model.getTextures()); // Kick this, just in case. - models.add(model); - builder.add(Pair.of(model, v.getState())); - } + models.add(model); + builder.add(Pair.of(model, v.getState())); + } - if (models.size() == 0){ //If all variants are missing, add one with the missing model and default rotation. - // FIXME: log this? - IModel missing = ModelLoaderRegistry.getMissingModel(); - models.add(missing); - builder.add(Pair.of(missing, TRSRTransformation.identity())); - } + if (models.size() == 0) { //If all variants are missing, add one with the missing model and default rotation. + // FIXME: log this? + IModel missing = ModelLoaderRegistry.getMissingModel(); + models.add(missing); + builder.add(Pair.of(missing, TRSRTransformation.identity())); + } - defaultState = new MultiModelState(builder.build()); - } + defaultState = new MultiModelState(builder.build()); + } - @Override - public Collection getDependencies(){ - return ImmutableList.copyOf(locations); - } + @Override + public Collection getDependencies() { + return ImmutableList.copyOf(locations); + } - @Override - public Collection getTextures(){ - return ImmutableSet.copyOf(textures); - } + @Override + public Collection getTextures() { + return ImmutableSet.copyOf(textures); + } - @Override - public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter){ - if(variants.size() == 1){ - IModel model = models.get(0); - return model.bake(MultiModelState.getPartState(state, model, 0), format, bakedTextureGetter); - } - WeightedBakedModel.Builder builder = new WeightedBakedModel.Builder(); - for(int i = 0; i < variants.size(); i++){ - IModel model = models.get(i); - builder.add(model.bake(MultiModelState.getPartState(state, model, i), format, bakedTextureGetter), variants.get(i).getWeight()); - } - return builder.build(); - } + @Override + public IBakedModel bake(IModelState state, VertexFormat format, Function bakedTextureGetter) { + if (variants.size() == 1) { + IModel model = models.get(0); + return model.bake(MultiModelState.getPartState(state, model, 0), format, bakedTextureGetter); + } + WeightedBakedModel.Builder builder = new WeightedBakedModel.Builder(); + for (int i = 0; i < variants.size(); i++) { + IModel model = models.get(i); + builder.add(model.bake(MultiModelState.getPartState(state, model, i), format, bakedTextureGetter), variants.get(i).getWeight()); + } + return builder.build(); + } - @Override - public IModelState getDefaultState(){ - return defaultState; - } + @Override + public IModelState getDefaultState() { + return defaultState; + } @Override public IModel retexture(ImmutableMap textures) { - List models = new ArrayList(); - ImmutableList.Builder> builder = ImmutableList.builder(); - for (Variant v : this.variants){ - try{ - ResourceLocation loc = v.getModelLocation(); - locations.add(loc); - - IModel model; - if(loc.equals(new ModelResourceLocation("builtin/missing", "missing"))){ - model = ModelLoaderRegistry.getMissingModel(); - }else{ - model = ModelLoaderRegistry.getModel(loc); - } - - model = v.process(model); - for(ResourceLocation location : model.getDependencies()){ - ModelLoaderRegistry.getModelOrMissing(location); - } - - if(model instanceof MultiModel){ - IModel base = ObfuscationReflectionHelper.getPrivateValue(MultiModel.class, (MultiModel)model, 1); - Map> parts = ObfuscationReflectionHelper.getPrivateValue(MultiModel.class, (MultiModel)model, 3); - - ImmutableMap.Builder> partBuilder = new ImmutableMap.Builder<>(); - IModel retexturedModel = ModelProcessingHelper.retexture(base, textures); - for(Entry> part : parts.entrySet()){ - partBuilder.put(part.getKey(), Pair.of(ModelProcessingHelper.retexture(part.getValue().getLeft(), textures), part.getValue().getRight())); - } - - ObfuscationReflectionHelper.setPrivateValue(MultiModel.class, (MultiModel)model, retexturedModel, 1); - ObfuscationReflectionHelper.setPrivateValue(MultiModel.class, (MultiModel)model, partBuilder.build(), 3); - } - model = ModelProcessingHelper.retexture(model, textures); - - models.add(model); - builder.add(Pair.of(model, v.getState())); - }catch(Exception e){} - } + List models = new ArrayList<>(); + ImmutableList.Builder> builder = ImmutableList.builder(); + for (Variant v : this.variants) { + ResourceLocation loc = v.getModelLocation(); + locations.add(loc); - if (models.size() == 0){ - IModel missing = ModelLoaderRegistry.getMissingModel(); - models.add(missing); - builder.add(Pair.of(missing, TRSRTransformation.identity())); - } + IModel model; + if (loc.equals(new ModelResourceLocation("builtin/missing", "missing"))) { + model = ModelLoaderRegistry.getMissingModel(); + } else { + try { + model = ModelLoaderRegistry.getModel(loc); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } + + model = v.process(model); + for (ResourceLocation location : model.getDependencies()) { + ModelLoaderRegistry.getModelOrMissing(location); + } + + if (model instanceof MultiModel) { + IModel base = ObfuscationReflectionHelper.getPrivateValue(MultiModel.class, (MultiModel) model, 1); + Map> parts = ObfuscationReflectionHelper.getPrivateValue(MultiModel.class, (MultiModel) model, 3); + + ImmutableMap.Builder> partBuilder = new ImmutableMap.Builder<>(); + IModel retexturedModel = ModelProcessingHelper.retexture(base, textures); + for (Entry> part : parts.entrySet()) { + partBuilder.put(part.getKey(), Pair.of(ModelProcessingHelper.retexture(part.getValue().getLeft(), textures), part.getValue().getRight())); + } + + ObfuscationReflectionHelper.setPrivateValue(MultiModel.class, (MultiModel) model, retexturedModel, 1); + ObfuscationReflectionHelper.setPrivateValue(MultiModel.class, (MultiModel) model, partBuilder.build(), 3); + } + model = ModelProcessingHelper.retexture(model, textures); + + models.add(model); + builder.add(Pair.of(model, v.getState())); + } + + if (models.size() == 0) { + IModel missing = ModelLoaderRegistry.getMissingModel(); + models.add(missing); + builder.add(Pair.of(missing, TRSRTransformation.identity())); + } return new WeightedRandomModel(locations, models, variants, new MultiModelState(builder.build())); } - } + } } diff --git a/src/main/java/forestry/arboriculture/models/WoodTextures.java b/src/main/java/forestry/arboriculture/models/WoodTextures.java index 870d18516..0aeb96c80 100644 --- a/src/main/java/forestry/arboriculture/models/WoodTextures.java +++ b/src/main/java/forestry/arboriculture/models/WoodTextures.java @@ -11,13 +11,10 @@ import java.util.Map; import java.util.Map.Entry; import com.google.common.collect.ImmutableMap; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.internal.Streams; import com.google.gson.stream.JsonReader; - import forestry.api.arboriculture.IWoodType; import forestry.api.arboriculture.WoodBlockKind; import net.minecraft.client.resources.IResourceManager; @@ -27,119 +24,118 @@ import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class WoodTextures { - - public static final Gson GSON = new GsonBuilder().create(); protected static final Map textures = new HashMap<>(); - - public static void deserializeFile(IResourceManager resourceManager){ + + public static void deserializeFile(IResourceManager resourceManager) { try { InputStream stream = resourceManager.getResource(new ResourceLocation("forestry:textures/woodTextures.json")).getInputStream(); - if(stream != null){ - JsonReader reader = null; - try { - reader = new JsonReader(new BufferedReader(new InputStreamReader(stream))); - JsonElement json = Streams.parse(reader); - if(json.isJsonObject()){ - for(Entry entry : json.getAsJsonObject().entrySet()){ - JsonElement ele = entry.getValue(); - if(ele.isJsonObject()){ - textures.put(entry.getKey(), loadTexture(ele.getAsJsonObject())); - }else if(ele.isJsonArray()){ - ImmutableMap.Builder locations = new ImmutableMap.Builder<>(); - for(JsonElement eleEntry : ele.getAsJsonArray()){ - if(eleEntry.isJsonObject()){ - JsonObject obj = eleEntry.getAsJsonObject(); - if(!obj.has("kind") || !obj.get("kind").isJsonPrimitive() || !obj.get("kind").getAsJsonPrimitive().isString()){ - continue; - } - String kind = obj.get("kind").getAsString(); - locations.put(kind, loadTexture(obj)); + JsonReader reader = null; + try { + reader = new JsonReader(new BufferedReader(new InputStreamReader(stream))); + JsonElement json = Streams.parse(reader); + if (json.isJsonObject()) { + for (Entry entry : json.getAsJsonObject().entrySet()) { + JsonElement ele = entry.getValue(); + if (ele.isJsonObject()) { + textures.put(entry.getKey(), loadTexture(ele.getAsJsonObject())); + } else if (ele.isJsonArray()) { + ImmutableMap.Builder locations = new ImmutableMap.Builder<>(); + for (JsonElement eleEntry : ele.getAsJsonArray()) { + if (eleEntry.isJsonObject()) { + JsonObject obj = eleEntry.getAsJsonObject(); + if (!obj.has("kind") || !obj.get("kind").isJsonPrimitive() || !obj.get("kind").getAsJsonPrimitive().isString()) { + continue; } + String kind = obj.get("kind").getAsString(); + locations.put(kind, loadTexture(obj)); } - textures.put(entry.getKey(), new KindTexture(locations.build())); } + textures.put(entry.getKey(), new KindTexture(locations.build())); } } - }finally{ - if(reader != null){ - reader.close(); - } + } + } finally { + if (reader != null) { + reader.close(); } } } catch (IOException e) { - if(!(e instanceof FileNotFoundException)){ + if (!(e instanceof FileNotFoundException)) { e.printStackTrace(); } - } + } } - - private static SimpleTexture loadTexture(JsonObject obj){ + + private static SimpleTexture loadTexture(JsonObject obj) { ImmutableMap.Builder locations = new ImmutableMap.Builder<>(); - for(Entry eleEntry : obj.entrySet()){ + for (Entry eleEntry : obj.entrySet()) { JsonElement e = eleEntry.getValue(); - if(e.isJsonPrimitive() && e.getAsJsonPrimitive().isString()){ + if (e.isJsonPrimitive() && e.getAsJsonPrimitive().isString()) { locations.put(eleEntry.getKey(), e.getAsString()); } } return new SimpleTexture(locations.build()); } - - public static ImmutableMap getLocations(IWoodType woodType, WoodBlockKind blockKind){ - if(woodType != null && blockKind != null && woodType.getName() != null){ - String kindName = blockKind.toString(); - Texture kindTex = textures.get(blockKind); - Texture tex = textures.get(woodType.getName().toLowerCase(Locale.ENGLISH)); - Map locations = new HashMap<>(); - if(kindTex != null && kindTex instanceof SimpleTexture){ - locations.putAll(((SimpleTexture)kindTex).locations); + + public static ImmutableMap getLocations(IWoodType woodType, WoodBlockKind blockKind) { + String kindName = blockKind.toString(); + Texture kindTex = textures.get(kindName); + Texture tex = textures.get(woodType.getName().toLowerCase(Locale.ENGLISH)); + Map locations = new HashMap<>(); + if (kindTex != null && kindTex instanceof SimpleTexture) { + locations.putAll(((SimpleTexture) kindTex).locations); + } + if (tex != null) { + if (tex instanceof SimpleTexture) { + locations.putAll(((SimpleTexture) tex).locations); + } else { + SimpleTexture kind = ((KindTexture) tex).kindLocations.get(kindName); + locations.putAll(kind.locations); } - if(tex != null){ - if(tex instanceof SimpleTexture){ - locations.putAll(((SimpleTexture) tex).locations); - }else{ - SimpleTexture kind = ((KindTexture)tex).kindLocations.get(kindName); - locations.putAll(kind.locations); - } - } - ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); - for(Entry location : locations.entrySet()){ - String texture = location.getValue(); - if(texture.equals("plank")){ + } + ImmutableMap.Builder builder = new ImmutableMap.Builder<>(); + for (Entry location : locations.entrySet()) { + String texture = location.getValue(); + switch (texture) { + case "plank": texture = woodType.getPlankTexture(); - }else if(texture.equals("bark")){ + break; + case "bark": texture = woodType.getBarkTexture(); - }else if(texture.equals("heart")){ + break; + case "heart": texture = woodType.getHeartTexture(); - }else if(texture.equals("doorUp")){ + break; + case "doorUp": texture = woodType.getDoorUpperTexture(); - }else if(texture.equals("doorLow")){ + break; + case "doorLow": texture = woodType.getDoorLowerTexture(); - }else{ + break; + default: builder.put(location.getKey(), texture.replace("%woodType", woodType.getName().toLowerCase(Locale.ENGLISH))); continue; - } - builder.put(location.getKey(), texture); } - return builder.build(); + builder.put(location.getKey(), texture); } - return ImmutableMap.of(); + return builder.build(); } - - private static class Texture{ - + + private static class Texture { + } - - private static class SimpleTexture extends Texture{ + + private static class SimpleTexture extends Texture { public final ImmutableMap locations; - + public SimpleTexture(ImmutableMap locations) { this.locations = locations; } } - - private static class KindTexture extends Texture{ + + private static class KindTexture extends Texture { public final ImmutableMap kindLocations; - + public KindTexture(ImmutableMap kindLocations) { this.kindLocations = kindLocations; } diff --git a/src/main/java/forestry/arboriculture/models/package-info.java b/src/main/java/forestry/arboriculture/models/package-info.java new file mode 100644 index 000000000..ae47832f8 --- /dev/null +++ b/src/main/java/forestry/arboriculture/models/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.models; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/multiblock/CharcoalPileController.java b/src/main/java/forestry/arboriculture/multiblock/CharcoalPileController.java index 3eb36c519..eaf7840b6 100644 --- a/src/main/java/forestry/arboriculture/multiblock/CharcoalPileController.java +++ b/src/main/java/forestry/arboriculture/multiblock/CharcoalPileController.java @@ -17,8 +17,7 @@ import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.multiblock.MultiblockRegistry; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.proxy.Proxies; import forestry.core.utils.Log; import forestry.core.utils.Translator; @@ -39,7 +38,7 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase active = false; burnTime = 0; } - + @Override public void setActive(boolean active) { if (this.active == active) { @@ -48,12 +47,10 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase this.active = active; - if (worldObj != null) { - if (worldObj.isRemote) { - worldObj.markBlockRangeForRenderUpdate(getMinimumCoord(), getMaximumCoord()); - } else { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); - } + if (world.isRemote) { + world.markBlockRangeForRenderUpdate(getMinimumCoord(), getMaximumCoord()); + } else { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), getCoordinates(), world); } } @@ -62,10 +59,6 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase return active; } - public int getBurnTime() { - return burnTime; - } - @Override public void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data) { readFromNBT(data); @@ -102,17 +95,16 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase protected void onAssimilate(IMultiblockControllerInternal assimilated) { if (!(assimilated instanceof CharcoalPileController)) { Log.warning("[%s] Charcoal Kiln @ %s is attempting to assimilate a non-Charcoal Kiln machine! That machine's data will be lost!", - worldObj.isRemote ? "CLIENT" : "SERVER", getReferenceCoord()); - return; + world.isRemote ? "CLIENT" : "SERVER", getReferenceCoord()); } } - + @Override protected boolean updateServer(int tickCount) { if (!isActive()) { return false; } - if(woodBurnTime == 0){ + if (woodBurnTime == 0) { int validComps = 0; int newBurnTime = 0; for (IMultiblockComponent part : connectedParts) { @@ -121,33 +113,33 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase validComps++; IWoodProvider woodProvider = comp.getTreeSpecies().getWoodProvider(); int charcoalAmount = woodProvider.getCarbonization(); - while(worldObj.rand.nextFloat() < woodProvider.getCharcoalChance(charcoalAmount)){ + while (world.rand.nextFloat() < woodProvider.getCharcoalChance(charcoalAmount)) { charcoalAmount++; } newBurnTime += charcoalAmount * 500; } } - if(validComps > 0){ + if (validComps > 0) { woodBurnTime = newBurnTime; - }else{ + } else { woodBurnTime = 0; } } if (burnTime >= woodBurnTime) { - for(IMultiblockComponent part : connectedParts) { + for (IMultiblockComponent part : connectedParts) { BlockPos pos = part.getCoordinates(); - IBlockState state = worldObj.getBlockState(pos); + IBlockState state = world.getBlockState(pos); IBlockState ashPileState = PluginArboriculture.blocks.piles.get(EnumPileType.ASH).getDefaultState().withProperty(BlockPile.PILE_POSITION, state.getValue(BlockPile.PILE_POSITION)); - - worldObj.setBlockState(pos, ashPileState); + + world.setBlockState(pos, ashPileState); } - MultiblockRegistry.addDirtyController(worldObj, this); + MultiblockRegistry.addDirtyController(world, this); } else { burnTime++; } return true; } - + @Override public String getUnlocalizedType() { return "for.multiblock.charcoal.pile.type"; @@ -155,10 +147,9 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase @Override public BlockPos getCoordinates() { - BlockPos coord = getReferenceCoord(); - return new BlockPos(coord); + return getReferenceCoord(); } - + @Override protected void updateClient(int tickCount) { } @@ -168,13 +159,13 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase int minX = getSizeLimits().getMinimumXSize(); int minY = getSizeLimits().getMinimumYSize(); int minZ = getSizeLimits().getMinimumZSize(); - + if (connectedParts.size() < getSizeLimits().getMinimumNumberOfBlocksForAssembledMachine()) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.small", minX, minY, minZ)); } BlockPos maximumCoord = getMaximumCoord(); BlockPos minimumCoord = getMinimumCoord(); - + int deltaX = maximumCoord.getX() - minimumCoord.getX() + 1; int deltaY = maximumCoord.getY() - minimumCoord.getY() + 1; int deltaZ = maximumCoord.getZ() - minimumCoord.getZ() + 1; @@ -199,7 +190,7 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase if (deltaZ < minZ) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.small.z", minZ)); } - + TileEntity te; IMultiblockComponent part; Class myClass = this.getClass(); @@ -207,18 +198,18 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase for (int y = minimumCoord.getY(); y <= maximumCoord.getY(); y++) { int partsOnLayer = 0; int layer = y - getMinimumCoord().getY(); - + BlockPos currentMaximumCoord = maximumCoord.add(-layer, 0, -layer); BlockPos currentMinimumCoord = minimumCoord.add(layer, 0, layer); - + for (int z = currentMinimumCoord.getZ(); z <= currentMaximumCoord.getZ(); z++) { for (int x = currentMinimumCoord.getX(); x <= currentMaximumCoord.getX(); x++) { // Okay, figure out what sort of block this should be. BlockPos pos = new BlockPos(x, y, z); - te = this.worldObj.getTileEntity(pos); + te = this.world.getTileEntity(pos); if (te instanceof IMultiblockComponent) { part = (IMultiblockComponent) te; - + // Ensure this part should actually be allowed within a cube of this controller's type if (!myClass.equals(part.getMultiblockLogic().getController().getClass())) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.invalid.part", Translator.translateToLocal(getUnlocalizedType()))); @@ -227,7 +218,7 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase // This is permitted so that we can incorporate certain non-multiblock parts inside interiors part = null; } - + // Validate block type against both part-level and material-level validators. int extremes = 0; @@ -237,7 +228,7 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase if (z == currentMinimumCoord.getZ()) { extremes++; } - + if (x == currentMaximumCoord.getX()) { extremes++; } @@ -247,33 +238,33 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase if (z == currentMaximumCoord.getZ()) { extremes++; } - + if (extremes >= 1) { // Side int exteriorLevel = y - currentMinimumCoord.getY(); if (part != null) { isGoodForExteriorLevel(part, exteriorLevel); } else { - isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, pos); + isBlockGoodForExteriorLevel(exteriorLevel, this.world, pos); } } else { if (part != null) { isGoodForInterior(part); } else { - isBlockGoodForInterior(this.worldObj, pos); + isBlockGoodForInterior(this.world, pos); } } components.add(pos); partsOnLayer++; } } - + if (partsOnLayer < 4) { throw new MultiblockValidationException(Translator.translateToLocal("for.multiblock.charcoal.pile.error.small")); } } - for(IMultiblockComponent comp : connectedParts){ - if(!components.contains(comp.getCoordinates())){ + for (IMultiblockComponent comp : connectedParts) { + if (!components.contains(comp.getCoordinates())) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.charcoal.pile.error.large", comp.getCoordinates().getX(), comp.getCoordinates().getY(), comp.getCoordinates().getZ())); } } @@ -303,27 +294,27 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase public void decodeDescriptionPacket(NBTTagCompound data) { readFromNBT(data); } - + @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { data.writeInt(burnTime); data.writeBoolean(active); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { burnTime = data.readInt(); active = data.readBoolean(); } @Override public EnumTemperature getTemperature() { - return null; + return EnumTemperature.NORMAL; } @Override public EnumHumidity getHumidity() { - return null; + return EnumHumidity.NORMAL; } @Override @@ -338,22 +329,22 @@ public class CharcoalPileController extends RectangularMultiblockControllerBase @Override protected void isGoodForExteriorLevel(IMultiblockComponent part, int level) throws MultiblockValidationException { - if(!(part instanceof ICharcoalPileComponent)){ + if (!(part instanceof ICharcoalPileComponent)) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.charcoal.pile.error.invalid.exterior", part.getCoordinates().getX(), part.getCoordinates().getY(), part.getCoordinates().getZ())); } ICharcoalPileComponent component = (ICharcoalPileComponent) part; - if(component.getPileType() != EnumPileType.DIRT){ + if (component.getPileType() != EnumPileType.DIRT) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.charcoal.pile.error.invalid.exterior", part.getCoordinates().getX(), part.getCoordinates().getY(), part.getCoordinates().getZ())); } } @Override protected void isGoodForInterior(IMultiblockComponent part) throws MultiblockValidationException { - if(!(part instanceof ICharcoalPileComponent)){ + if (!(part instanceof ICharcoalPileComponent)) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.charcoal.pile.error.invalid.interior", part.getCoordinates().getX(), part.getCoordinates().getY(), part.getCoordinates().getZ())); } ICharcoalPileComponent component = (ICharcoalPileComponent) part; - if(component.getPileType() != EnumPileType.WOOD){ + if (component.getPileType() != EnumPileType.WOOD) { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.charcoal.pile.error.invalid.interior", part.getCoordinates().getX(), part.getCoordinates().getY(), part.getCoordinates().getZ())); } } diff --git a/src/main/java/forestry/arboriculture/multiblock/FakeCharcoalPileController.java b/src/main/java/forestry/arboriculture/multiblock/FakeCharcoalPileController.java index dee4c3eba..49ec8486a 100644 --- a/src/main/java/forestry/arboriculture/multiblock/FakeCharcoalPileController.java +++ b/src/main/java/forestry/arboriculture/multiblock/FakeCharcoalPileController.java @@ -26,17 +26,17 @@ public class FakeCharcoalPileController extends FakeMultiblockController impleme @Override public BlockPos getMinimumCoord() { - return null; + return BlockPos.ORIGIN; } @Override public BlockPos getMaximumCoord() { - return null; + return BlockPos.ORIGIN; } @Override public BlockPos getCoordinates() { - return null; + return BlockPos.ORIGIN; } } diff --git a/src/main/java/forestry/arboriculture/multiblock/package-info.java b/src/main/java/forestry/arboriculture/multiblock/package-info.java new file mode 100644 index 000000000..0181a94f0 --- /dev/null +++ b/src/main/java/forestry/arboriculture/multiblock/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.multiblock; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java b/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java index a217bf55a..bb0a2deb7 100644 --- a/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java +++ b/src/main/java/forestry/arboriculture/network/PacketRegistryArboriculture.java @@ -10,12 +10,12 @@ ******************************************************************************/ package forestry.arboriculture.network; -import forestry.arboriculture.network.packets.PacketRipeningUpdate; -import forestry.core.network.PacketRegistry; +import forestry.core.network.IPacketRegistry; +import forestry.core.network.PacketIdClient; -public class PacketRegistryArboriculture extends PacketRegistry { +public class PacketRegistryArboriculture implements IPacketRegistry { @Override public void registerPackets() { - registerClientPacket(new PacketRipeningUpdate()); + PacketIdClient.RIPENING_UPDATE.setPacketHandler(new PacketRipeningUpdate.Handler()); } } diff --git a/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java new file mode 100644 index 000000000..dd654b516 --- /dev/null +++ b/src/main/java/forestry/arboriculture/network/PacketRipeningUpdate.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.arboriculture.network; + +import java.io.IOException; + +import forestry.arboriculture.tiles.TileLeaves; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; + +public class PacketRipeningUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final int value; + + public PacketRipeningUpdate(TileLeaves leaves) { + this.pos = leaves.getPos(); + this.value = leaves.getFruitColour(); + } + + @Override + public PacketIdClient getPacketId() { + return PacketIdClient.RIPENING_UPDATE; + } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeVarInt(value); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + int value = data.readVarInt(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof IRipeningPacketReceiver) { + ((IRipeningPacketReceiver) tile).fromRipeningPacket(value); + } + } + } +} diff --git a/src/main/java/forestry/arboriculture/network/package-info.java b/src/main/java/forestry/arboriculture/network/package-info.java new file mode 100644 index 000000000..2db8f4db0 --- /dev/null +++ b/src/main/java/forestry/arboriculture/network/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.network; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java b/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java deleted file mode 100644 index 5ee201794..000000000 --- a/src/main/java/forestry/arboriculture/network/packets/PacketRipeningUpdate.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.arboriculture.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.arboriculture.network.IRipeningPacketReceiver; -import forestry.arboriculture.tiles.TileLeaves; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; - -public class PacketRipeningUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int value; - - public PacketRipeningUpdate() { - } - - public PacketRipeningUpdate(TileLeaves leaves) { - super(leaves); - value = leaves.getFruitColour(); - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.RIPENING_UPDATE; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(value); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - value = data.readVarInt(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IRipeningPacketReceiver) { - ((IRipeningPacketReceiver) tile).fromRipeningPacket(value); - } - } -} diff --git a/src/main/java/forestry/arboriculture/package-info.java b/src/main/java/forestry/arboriculture/package-info.java new file mode 100644 index 000000000..acec3935a --- /dev/null +++ b/src/main/java/forestry/arboriculture/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java b/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java index 914f0969b..d3450eb14 100644 --- a/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java +++ b/src/main/java/forestry/arboriculture/proxy/ProxyArboricultureClient.java @@ -10,6 +10,31 @@ ******************************************************************************/ package forestry.arboriculture.proxy; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.google.common.collect.ImmutableMap; +import forestry.api.arboriculture.EnumPileType; +import forestry.api.arboriculture.IWoodItemMeshDefinition; +import forestry.api.arboriculture.IWoodStateMapper; +import forestry.api.arboriculture.IWoodType; +import forestry.api.arboriculture.WoodBlockKind; +import forestry.arboriculture.IWoodTyped; +import forestry.arboriculture.PluginArboriculture; +import forestry.arboriculture.blocks.BlockArbSlab; +import forestry.arboriculture.blocks.BlockDecorativeLeaves; +import forestry.arboriculture.models.ModelDecorativeLeaves; +import forestry.arboriculture.models.ModelLeaves; +import forestry.arboriculture.models.ModelWoodPile; +import forestry.arboriculture.models.WoodModelLoader; +import forestry.arboriculture.models.WoodTextures; +import forestry.arboriculture.render.CharcoalPileRenderer; +import forestry.arboriculture.tiles.TilePile; +import forestry.core.models.BlockModelEntry; +import forestry.core.models.SimpleRetexturedModel; +import forestry.core.models.WoodModelEntry; +import forestry.core.proxy.Proxies; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -32,36 +57,9 @@ import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import com.google.common.collect.ImmutableMap; - -import forestry.api.arboriculture.EnumPileType; -import forestry.api.arboriculture.IWoodItemMeshDefinition; -import forestry.api.arboriculture.IWoodStateMapper; -import forestry.api.arboriculture.IWoodType; -import forestry.api.arboriculture.WoodBlockKind; -import forestry.arboriculture.IWoodTyped; -import forestry.arboriculture.PluginArboriculture; -import forestry.arboriculture.blocks.BlockDecorativeLeaves; -import forestry.arboriculture.blocks.slab.BlockArbSlab; -import forestry.arboriculture.models.ModelDecorativeLeaves; -import forestry.arboriculture.models.ModelLeaves; -import forestry.arboriculture.models.ModelWoodPile; -import forestry.arboriculture.models.WoodModelLoader; -import forestry.arboriculture.models.WoodTextures; -import forestry.arboriculture.render.CharcoalPileRenderer; -import forestry.arboriculture.tiles.TilePile; -import forestry.core.models.BlockModelEntry; -import forestry.core.models.SimpleRetexturedModel; -import forestry.core.models.WoodModelEntry; -import forestry.core.proxy.Proxies; - public class ProxyArboricultureClient extends ProxyArboriculture { - private static Set woodModelEntrys = new HashSet<>(); - + private static final Set woodModelEntrys = new HashSet<>(); + @Override public void initializeModels() { { @@ -78,87 +76,87 @@ public class ProxyArboricultureClient extends ProxyArboriculture { BlockModelEntry blockModelIndex = new BlockModelEntry(blockModelLocation, itemModeLocation, new ModelDecorativeLeaves(), leaves); Proxies.render.registerBlockModel(blockModelIndex); } - + { ModelResourceLocation blockModelLocation = new ModelResourceLocation("forestry:pile", "type=wood"); ModelResourceLocation itemModelLocation = new ModelResourceLocation("forestry:woodPile", "inventory"); BlockModelEntry blockModelIndex = new BlockModelEntry(blockModelLocation, itemModelLocation, new ModelWoodPile(), PluginArboriculture.blocks.piles.get(EnumPileType.WOOD)); Proxies.render.registerBlockModel(blockModelIndex); } - + ClientRegistry.bindTileEntitySpecialRenderer(TilePile.class, new CharcoalPileRenderer()); ModelLoaderRegistry.registerLoader(WoodModelLoader.INSTANCE); - for(BlockArbSlab slab : PluginArboriculture.blocks.slabsDouble){ + for (BlockArbSlab slab : PluginArboriculture.blocks.slabsDouble) { registerWoodModel(slab, true); } - for(BlockArbSlab slab : PluginArboriculture.blocks.slabsDoubleFireproof){ + for (BlockArbSlab slab : PluginArboriculture.blocks.slabsDoubleFireproof) { registerWoodModel(slab, true); } } - + @SubscribeEvent - public void onModelBake(ModelBakeEvent event){ + public void onModelBake(ModelBakeEvent event) { WoodModelLoader.INSTANCE.isRegistered = true; IRegistry registry = event.getModelRegistry(); Minecraft minecraft = Proxies.common.getClientInstance(); Map loadingExceptions = ObfuscationReflectionHelper.getPrivateValue(ModelLoader.class, event.getModelLoader(), 2); - - if(minecraft.getBlockRendererDispatcher() != null){ + + if (minecraft.getBlockRendererDispatcher() != null) { BlockStateMapper stateMapper = minecraft.getBlockRendererDispatcher().getBlockModelShapes().getBlockStateMapper(); Map definitions = ObfuscationReflectionHelper.getPrivateValue(ItemModelMesher.class, minecraft.getRenderItem().getItemModelMesher(), 2); Map blockStateMap = ObfuscationReflectionHelper.getPrivateValue(BlockStateMapper.class, stateMapper, 0); - - for(WoodModelEntry entry : woodModelEntrys){ + + for (WoodModelEntry entry : woodModelEntrys) { T woodTyped = entry.woodTyped; WoodBlockKind woodKind = woodTyped.getBlockKind(); - + IStateMapper mapper = blockStateMap.get(woodTyped); - if(mapper instanceof IWoodStateMapper){ + if (mapper instanceof IWoodStateMapper) { IWoodStateMapper woodMapper = (IWoodStateMapper) mapper; - try{ - for(IBlockState state : woodTyped.getBlockState().getValidStates()) { + try { + for (IBlockState state : woodTyped.getBlockState().getValidStates()) { IWoodType woodType; ItemStack itemStack; - if(entry.withVariants){ + if (entry.withVariants) { int meta = woodTyped.getMetaFromState(state); woodType = woodTyped.getWoodType(meta); itemStack = new ItemStack(woodTyped, 1, meta); - }else{ + } else { woodType = woodTyped.getWoodType(0); itemStack = new ItemStack(woodTyped); } ImmutableMap customTextures = WoodTextures.getLocations(woodType, woodKind); - if(woodKind.retextureItem){ + if (woodKind.retextureItem) { ItemMeshDefinition definition = definitions.get(itemStack.getItem()); - if(definition instanceof IWoodItemMeshDefinition){ + if (definition instanceof IWoodItemMeshDefinition) { IWoodItemMeshDefinition woodDefinition = (IWoodItemMeshDefinition) definition; IModel basicItemModel = ModelLoaderRegistry.getModel(woodDefinition.getDefaultModelLocation(itemStack)); ModelResourceLocation basicItemLocation = definition.getModelLocation(itemStack); - + registry.putObject(basicItemLocation, new SimpleRetexturedModel(woodKind.retextureModel(basicItemModel, woodType, customTextures))); } } IModel basicModel = ModelLoaderRegistry.getModel(woodMapper.getDefaultModelResourceLocation(state)); ModelResourceLocation basicLocation = woodMapper.getModelLocation(state); - if(loadingExceptions.containsKey(basicLocation)){ + if (loadingExceptions.containsKey(basicLocation)) { loadingExceptions.remove(basicLocation); } registry.putObject(basicLocation, new SimpleRetexturedModel(woodKind.retextureModel(basicModel, woodType, customTextures))); } - }catch(Exception e){ + } catch (Exception e) { e.printStackTrace(); } } } } - + loadingExceptions.putAll(WoodModelLoader.loadingExceptions); ModelWoodPile.onModelBake(event); } - + @Override - public void registerWoodModel(T woodTyped, boolean withVariants){ - woodModelEntrys.add(new WoodModelEntry(woodTyped, withVariants)); + public void registerWoodModel(T woodTyped, boolean withVariants) { + woodModelEntrys.add(new WoodModelEntry<>(woodTyped, withVariants)); } @Override diff --git a/src/main/java/forestry/arboriculture/proxy/package-info.java b/src/main/java/forestry/arboriculture/proxy/package-info.java new file mode 100644 index 000000000..501843616 --- /dev/null +++ b/src/main/java/forestry/arboriculture/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/render/CharcoalPileRenderer.java b/src/main/java/forestry/arboriculture/render/CharcoalPileRenderer.java index bdd6f7c6d..a0ac439c2 100644 --- a/src/main/java/forestry/arboriculture/render/CharcoalPileRenderer.java +++ b/src/main/java/forestry/arboriculture/render/CharcoalPileRenderer.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.render; -import javax.annotation.Nonnull; - import static forestry.arboriculture.multiblock.EnumPilePosition.*; import forestry.api.arboriculture.EnumPileType; @@ -35,12 +33,11 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; public class CharcoalPileRenderer extends TileEntitySpecialRenderer { - public CharcoalPileRenderer() { } - + @Override - public void renderTileEntityAt(@Nonnull TilePile pile, double x, double y, double z, float p_147500_8_, int destroyStage) { + public void renderTileEntityAt(TilePile pile, double x, double y, double z, float p_147500_8_, int destroyStage) { IBlockState state = pile.getWorld().getBlockState(pile.getPos()); if (!(state.getBlock() instanceof BlockPile)) { return; @@ -54,7 +51,7 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { GlStateManager.pushMatrix(); GlStateManager.disableLighting(); Proxies.common.getClientInstance().renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); - + boolean withWood = pile.getPileType() != EnumPileType.ASH; boolean isOnTop = logic.getController().getMaximumCoord().getY() == pile.getPos().getY(); // TODO Add brightness to the textures. @@ -64,9 +61,9 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { treeSpecies = (IAlleleTreeSpecies) TreeManager.treeRoot.getDefaultTemplate()[TreeManager.treeRoot.getSpeciesChromosomeType().ordinal()]; } TextureAtlasSprite dirtSprite; - if(pile.getPileType() == EnumPileType.ASH){ + if (pile.getPileType() == EnumPileType.ASH) { dirtSprite = TextureManager.registerSprite(new ResourceLocation("forestry:blocks/ash")); - }else{ + } else { dirtSprite = TextureManager.registerSprite(new ResourceLocation("forestry:blocks/loam")); } TextureAtlasSprite woodSprite = treeSpecies.getWoodProvider().getSprite(false); @@ -76,35 +73,35 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { } else if (pilePosition == FRONT) { GlStateManager.rotate(180, 0F, 0F, 1F); GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); - + renderPileSide(withWood, dirtSprite, woodSprite, woodTopSprite, brightness); } else if (pilePosition == SIDE_LEFT) { GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileSide(withWood, dirtSprite, woodSprite, woodTopSprite, brightness); } else if (pilePosition == SIDE_RIGHT) { GlStateManager.rotate(180, 0F, 1F, 0F); GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileSide(withWood, dirtSprite, woodSprite, woodTopSprite, brightness); } else if (pilePosition == CORNER_BACK_RIGHT) { GlStateManager.rotate(180, 0F, 1F, 0F); GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileCorner(withWood, dirtSprite, woodSprite, woodTopSprite, brightness, isOnTop); } else if (pilePosition == CORNER_BACK_LEFT) { GlStateManager.rotate(90, 0F, 1F, 0F); GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileCorner(withWood, dirtSprite, woodSprite, woodTopSprite, brightness, isOnTop); } else if (pilePosition == CORNER_FRONT_LEFT) { GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileCorner(withWood, dirtSprite, woodSprite, woodTopSprite, brightness, isOnTop); } else if (pilePosition == CORNER_FRONT_RIGHT) { GlStateManager.rotate(270, 0F, 1F, 0F); GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - + renderPileCorner(withWood, dirtSprite, woodSprite, woodTopSprite, brightness, isOnTop); } GlStateManager.enableLighting(); @@ -116,64 +113,64 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { public static void renderPileSide(boolean withWood, TextureAtlasSprite dirtSprite, TextureAtlasSprite woodSprite, TextureAtlasSprite woodTopSprite, int brightness) { Tessellator t = Tessellator.getInstance(); VertexBuffer buffer = t.getBuffer(); - buffer.begin(7, DefaultVertexFormats.POSITION_TEX); - + buffer.begin(7, DefaultVertexFormats.POSITION_TEX); + buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); - + buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); - + buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); - + buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); - + buffer.pos(0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); - - if(withWood){ + + if (withWood) { buffer.pos(0.1, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.1, -0.5, -0.5).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.1, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.1, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.1, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.1, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.1, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.1, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(-0.1, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.1, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.1, -0.5, -0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.1, 0.3, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(-0.1, -0.5, -0.7).tex(woodTopSprite.getMinU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.1, -0.5, -0.7).tex(woodTopSprite.getMaxU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.1, -0.5, -0.5).tex(woodTopSprite.getMaxU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(-0.1, -0.5, -0.5).tex(woodTopSprite.getMinU(), woodTopSprite.getMaxV()).endVertex(); - + buffer.pos(-0.5, 0.3, 0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.5, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.5, 0.3, 0.5).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(-0.5, 0.5, 0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.5, 0.5).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.5, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.5, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); @@ -185,62 +182,62 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { public static void renderPileCorner(boolean withWood, TextureAtlasSprite dirtSprite, TextureAtlasSprite woodSprite, TextureAtlasSprite woodTopSprite, int brightness, boolean isTop) { Tessellator t = Tessellator.getInstance(); VertexBuffer buffer = t.getBuffer(); - buffer.begin(7, DefaultVertexFormats.POSITION_TEX); - + buffer.begin(7, DefaultVertexFormats.POSITION_TEX); + buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); - + buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); - + buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); - + buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); - + buffer.pos(-0.5, 0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMinU(), dirtSprite.getMaxV()).endVertex(); buffer.pos(0.5, -0.5, 0.5).tex(dirtSprite.getMaxU(), dirtSprite.getMaxV()).endVertex(); - + if (isTop && withWood) { - + buffer.pos(-0.3, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.3, -0.5, -0.5).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.3, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.3, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(-0.3, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.3, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.5, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); - + buffer.pos(-0.5, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(-0.5, 0.3, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(-0.5, -0.5, -0.7).tex(woodTopSprite.getMinU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(-0.3, -0.5, -0.7).tex(woodTopSprite.getMaxU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(-0.3, -0.5, -0.5).tex(woodTopSprite.getMaxU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(-0.5, -0.5, -0.5).tex(woodTopSprite.getMinU(), woodTopSprite.getMaxV()).endVertex(); } - t.draw(); - + t.draw(); + GlStateManager.rotate(270.0F, 0.0F, 1.0F, 0.0F); - if(withWood){ - buffer.begin(7, DefaultVertexFormats.POSITION_TEX); + if (withWood) { + buffer.begin(7, DefaultVertexFormats.POSITION_TEX); if (isTop) { - + buffer.pos(0.5, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); @@ -250,40 +247,40 @@ public class CharcoalPileRenderer extends TileEntitySpecialRenderer { buffer.pos(0.5, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.3, -0.5, -0.7).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.3, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.3, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.3, -0.5, -0.7).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.3, -0.5, -0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.3, 0.3, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.3, -0.5, -0.7).tex(woodTopSprite.getMinU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.7).tex(woodTopSprite.getMaxU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.5, -0.5, -0.5).tex(woodTopSprite.getMaxU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(0.3, -0.5, -0.5).tex(woodTopSprite.getMinU(), woodTopSprite.getMaxV()).endVertex(); } - + buffer.pos(0.3, 0.5, 0.5).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.5, 0.5).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.5, 0.3).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.5, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.3, 0.3, 0.5).tex(woodSprite.getMaxU(), woodSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.3, 0.3).tex(woodSprite.getMaxU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.3, 0.3).tex(woodSprite.getMinU(), woodSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.3, 0.5).tex(woodSprite.getMinU(), woodSprite.getMaxV()).endVertex(); - + buffer.pos(0.5, 0.5, 0.3).tex(woodTopSprite.getMinU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.5, 0.3, 0.3).tex(woodTopSprite.getMinU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.3, 0.3).tex(woodTopSprite.getMaxU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.5, 0.3).tex(woodTopSprite.getMaxU(), woodTopSprite.getMinV()).endVertex(); - + buffer.pos(0.3, 0.5, 0.3).tex(woodTopSprite.getMinU(), woodTopSprite.getMinV()).endVertex(); buffer.pos(0.3, 0.3, 0.3).tex(woodTopSprite.getMinU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.3, 0.5).tex(woodTopSprite.getMaxU(), woodTopSprite.getMaxV()).endVertex(); buffer.pos(0.3, 0.5, 0.5).tex(woodTopSprite.getMaxU(), woodTopSprite.getMinV()).endVertex(); t.draw(); } - + GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); } } diff --git a/src/main/java/forestry/arboriculture/render/FruitPodStateMapper.java b/src/main/java/forestry/arboriculture/render/FruitPodStateMapper.java index 4eefe6d60..44ad2d5f6 100644 --- a/src/main/java/forestry/arboriculture/render/FruitPodStateMapper.java +++ b/src/main/java/forestry/arboriculture/render/FruitPodStateMapper.java @@ -2,17 +2,15 @@ package forestry.arboriculture.render; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.IAlleleFruit; import forestry.arboriculture.blocks.BlockFruitPod; import forestry.core.config.Constants; import forestry.core.render.ForestryStateMapper; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class FruitPodStateMapper extends ForestryStateMapper { @@ -34,5 +32,5 @@ public class FruitPodStateMapper extends ForestryStateMapper { } return mapStateModelLocations; } - + } diff --git a/src/main/java/forestry/arboriculture/render/PileParticleCallback.java b/src/main/java/forestry/arboriculture/render/PileParticleCallback.java index 2a76bf0c4..de57d9a1a 100644 --- a/src/main/java/forestry/arboriculture/render/PileParticleCallback.java +++ b/src/main/java/forestry/arboriculture/render/PileParticleCallback.java @@ -13,12 +13,12 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -public class PileParticleCallback extends ParticleHelper.DefaultCallback{ +public class PileParticleCallback extends ParticleHelper.DefaultCallback { public PileParticleCallback(BlockPile block) { super(block); } - + @Override protected void setTexture(ParticleDigging fx, World world, BlockPos pos, IBlockState state) { EnumPileType type = block.getPileType(); @@ -32,7 +32,7 @@ public class PileParticleCallback extends ParticleHelper.DefaultCallback putStateModelLocations(Block block) { String location = Constants.MOD_ID + ":pile"; - + IBlockState woodPileState = PluginArboriculture.blocks.piles.get(EnumPileType.WOOD).getDefaultState(); mapStateModelLocations.put(woodPileState, new ModelResourceLocation(location, "type=wood")); - + IBlockState dirtPileState = PluginArboriculture.blocks.piles.get(EnumPileType.DIRT).getDefaultState(); mapStateModelLocations.put(dirtPileState, new ModelResourceLocation(location, "type=dirt")); - + IBlockState ashPileState = PluginArboriculture.blocks.piles.get(EnumPileType.ASH).getDefaultState(); mapStateModelLocations.put(ashPileState, new ModelResourceLocation(location, "type=ash")); - + return this.mapStateModelLocations; } diff --git a/src/main/java/forestry/arboriculture/render/SaplingStateMapper.java b/src/main/java/forestry/arboriculture/render/SaplingStateMapper.java index d542b1f04..dc8c42cdc 100644 --- a/src/main/java/forestry/arboriculture/render/SaplingStateMapper.java +++ b/src/main/java/forestry/arboriculture/render/SaplingStateMapper.java @@ -1,28 +1,24 @@ package forestry.arboriculture.render; -import com.google.common.collect.Maps; - import java.util.LinkedHashMap; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.block.properties.IProperty; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - +import com.google.common.collect.Maps; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.arboriculture.blocks.BlockSapling; -import forestry.core.config.Constants; import forestry.core.render.ForestryStateMapper; +import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class SaplingStateMapper extends ForestryStateMapper { - + @Override public Map putStateModelLocations(Block block) { for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { @@ -31,9 +27,6 @@ public class SaplingStateMapper extends ForestryStateMapper { IBlockState state = block.getDefaultState().withProperty(BlockSapling.TREE, tree); LinkedHashMap, Comparable> linkedhashmap = Maps.newLinkedHashMap(state.getProperties()); String modID = tree.getModID(); - if (modID == null) { - modID = Constants.MOD_ID; - } String s = String.format("%s:%s", modID, "germlings"); mapStateModelLocations.put(state, new ModelResourceLocation(s, getPropertyString(linkedhashmap))); } diff --git a/src/main/java/forestry/arboriculture/render/package-info.java b/src/main/java/forestry/arboriculture/render/package-info.java new file mode 100644 index 000000000..71bd83eca --- /dev/null +++ b/src/main/java/forestry/arboriculture/render/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.render; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java index 5618524d5..9c3c67236 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java +++ b/src/main/java/forestry/arboriculture/tiles/TileFruitPod.java @@ -10,14 +10,23 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import java.util.Collection; -import java.util.List; import java.util.Map; import java.util.Random; +import forestry.api.arboriculture.IAlleleFruit; +import forestry.api.arboriculture.ITreeGenome; +import forestry.api.arboriculture.TreeManager; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IFruitBearer; +import forestry.api.genetics.IFruitFamily; +import forestry.core.config.Constants; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.NBTUtilForestry; import net.minecraft.block.BlockCocoa; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; @@ -25,38 +34,27 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.api.arboriculture.IAlleleFruit; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IFruitBearer; -import forestry.api.genetics.IFruitFamily; -import forestry.core.config.Constants; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.Log; -import forestry.core.utils.NBTUtilForestry; - public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamable { private static final short MAX_MATURITY = 2; + private static final ITreeGenome defaultGenome = TreeManager.treeRoot.templateAsGenome(TreeManager.treeRoot.getDefaultTemplate()); private static final IAlleleFruit defaultAllele = (IAlleleFruit) AlleleManager.alleleRegistry.getAllele(Constants.MOD_ID + ".fruitCocoa"); - @Nonnull + private ITreeGenome genome = defaultGenome; private IAlleleFruit allele = defaultAllele; - private short maturity; private float sappiness; public TileFruitPod() { - Log.debug("Made a fruit pod"); + } - public void setProperties(@Nonnull IAlleleFruit allele, float sappiness) { + public void setProperties(ITreeGenome genome, IAlleleFruit allele, float sappiness) { + this.genome = genome; this.allele = allele; this.sappiness = sappiness; markDirty(); @@ -78,7 +76,6 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl sappiness = nbttagcompound.getFloat("SP"); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -103,11 +100,10 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl return maturity; } - @Nullable public ItemStack getPickBlock() { Map products = allele.getProvider().getProducts(); - ItemStack pickBlock = null; + ItemStack pickBlock = ItemStack.EMPTY; Float maxChance = 0.0f; for (Map.Entry product : products.entrySet()) { if (maxChance < product.getValue()) { @@ -116,16 +112,12 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl } } - if (pickBlock == null) { - return null; - } else { - pickBlock.stackSize = 1; - return pickBlock; - } + pickBlock.setCount(1); + return pickBlock; } - public List getDrops() { - return allele.getProvider().getFruits(null, worldObj, getPos(), maturity); + public NonNullList getDrops() { + return allele.getProvider().getFruits(genome, world, getPos(), maturity); } /* NETWORK */ @@ -135,7 +127,6 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl return new SPacketUpdateTileEntity(this.getPos(), 0, getUpdateTag()); } - @Nonnull @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = super.getUpdateTag(); @@ -143,7 +134,7 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); NBTUtilForestry.readStreamableFromNbt(this, tag); } @@ -167,13 +158,13 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl } @Override - public Collection pickFruit(ItemStack tool) { - Collection fruits = getDrops(); + public NonNullList pickFruit(ItemStack tool) { + NonNullList fruits = getDrops(); maturity = 0; - IBlockState oldState = worldObj.getBlockState(getPos()); + IBlockState oldState = world.getBlockState(getPos()); IBlockState newState = oldState.withProperty(BlockCocoa.AGE, 0); - BlockUtil.setBlockWithBreakSound(worldObj, getPos(), newState, oldState); + BlockUtil.setBlockWithBreakSound(world, getPos(), newState, oldState); return fruits; } @@ -194,8 +185,8 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl int age = (int) Math.floor(maturity); if (age - previousAge > 0) { - IBlockState state = worldObj.getBlockState(getPos()).withProperty(BlockCocoa.AGE, age); - worldObj.setBlockState(getPos(), state); + IBlockState state = world.getBlockState(getPos()).withProperty(BlockCocoa.AGE, age); + world.setBlockState(getPos(), state); } } @@ -205,22 +196,22 @@ public class TileFruitPod extends TileEntity implements IFruitBearer, IStreamabl } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { if (allele != defaultAllele) { - data.writeUTF(allele.getUID()); + data.writeString(allele.getUID()); } else { - data.writeUTF(""); + data.writeString(""); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { - IAllele stored = AlleleManager.alleleRegistry.getAllele(data.readUTF()); + public void readData(PacketBufferForestry data) throws IOException { + IAllele stored = AlleleManager.alleleRegistry.getAllele(data.readString()); if (stored instanceof IAlleleFruit) { allele = (IAlleleFruit) stored; } else { allele = defaultAllele; } - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } } diff --git a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java index f985ff9e4..514448d84 100644 --- a/src/main/java/forestry/arboriculture/tiles/TileLeaves.java +++ b/src/main/java/forestry/arboriculture/tiles/TileLeaves.java @@ -10,12 +10,8 @@ ******************************************************************************/ package forestry.arboriculture.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.List; import java.util.Random; import forestry.api.arboriculture.EnumTreeChromosome; @@ -42,11 +38,10 @@ import forestry.api.lepidopterology.IButterfly; import forestry.api.lepidopterology.IButterflyGenome; import forestry.api.lepidopterology.IButterflyNursery; import forestry.arboriculture.genetics.TreeDefinition; -import forestry.arboriculture.genetics.alleles.AlleleFruit; +import forestry.arboriculture.genetics.alleles.AlleleFruits; import forestry.arboriculture.network.IRipeningPacketReceiver; -import forestry.arboriculture.network.packets.PacketRipeningUpdate; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.arboriculture.network.PacketRipeningUpdate; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.utils.ColourUtil; @@ -55,6 +50,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -67,7 +63,10 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru @Nullable private ResourceLocation fruitSprite; + @Nullable private IAlleleTreeSpecies species; + @Nullable + private IButterfly caterpillar; private boolean isFruitLeaf; private boolean isPollinatedState; @@ -98,7 +97,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound = super.writeToNBT(nbtTagCompound); @@ -127,7 +126,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru boolean isDestroyed = isDestroyed(tree, damage); for (ILeafTickHandler tickHandler : genome.getPrimary().getRoot().getLeafTickHandlers()) { - if (tickHandler.onRandomLeafTick(tree, worldObj, rand, getPos(), isDestroyed)) { + if (tickHandler.onRandomLeafTick(tree, world, rand, getPos(), isDestroyed)) { return; } } @@ -141,7 +140,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } if (hasFruit() && getRipeningTime() < ripeningPeriod) { - ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(worldObj); + ITreekeepingMode treekeepingMode = TreeManager.treeRoot.getTreekeepingMode(world); float sappinessModifier = treekeepingMode.getSappinessModifier(genome, 1f); float sappiness = genome.getSappiness() * sappinessModifier; @@ -155,7 +154,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru matureCaterpillar(); } - effectData = tree.doEffect(effectData, worldObj, getPos()); + effectData = tree.doEffect(effectData, world, getPos()); } @Override @@ -168,13 +167,13 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru if (tree.canBearFruit()) { IFruitProvider fruitProvider = genome.getFruitProvider(); - isFruitLeaf = fruitProvider.isFruitLeaf(genome, worldObj, getPos()); + isFruitLeaf = fruitProvider.isFruitLeaf(genome, world, getPos()); if (isFruitLeaf) { // Hardcoded because vanilla oak trees don't show fruits. - if (species == TreeDefinition.Oak.getGenome().getPrimary() && fruitProvider == AlleleFruit.fruitApple.getProvider()) { + if (species == TreeDefinition.Oak.getGenome().getPrimary() && fruitProvider == AlleleFruits.fruitApple.getProvider()) { fruitSprite = null; } else { - fruitSprite = fruitProvider.getSprite(genome, worldObj, getPos(), getRipeningTime()); + fruitSprite = fruitProvider.getSprite(genome, world, getPos(), getRipeningTime()); } ripeningPeriod = (short) tree.getGenome().getFruitProvider().getRipeningPeriod(); @@ -188,11 +187,8 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } /* INFORMATION */ - private static boolean isDestroyed(ITree tree, int damage) { - if (tree == null) { - return false; - } - return damage > tree.getResilience(); + private static boolean isDestroyed(@Nullable ITree tree, int damage) { + return tree != null && damage > tree.getResilience(); } @Override @@ -229,16 +225,16 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } ITreeGenome genome = tree.getGenome(); IFruitProvider fruit = genome.getFruitProvider(); - return fruit.getColour(genome, worldObj, getPos(), getRipeningTime()); + return fruit.getColour(genome, world, getPos(), getRipeningTime()); } - @Nonnull + public ResourceLocation getLeaveSprite(boolean fancy) { final ILeafSpriteProvider leafSpriteProvider = getLeafSpriteProvider(); return leafSpriteProvider.getSprite(isPollinatedState, fancy); } - @Nonnull + private ILeafSpriteProvider getLeafSpriteProvider() { if (species != null) { return species.getLeafSpriteProvider(); @@ -270,30 +266,25 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru @Override public boolean canMateWith(IIndividual individual) { - if(individual instanceof ITree){ + if (individual instanceof ITree) { ITree tree = getTree(); - if (tree == null) { - return false; - } - if (tree.getMate() != null) { - return false; - } - - return !tree.isGeneticEqual(individual); + return tree != null && + tree.getMate() == null && + !tree.isGeneticEqual(individual); } return false; } @Override public void mateWith(IIndividual individual) { - if(individual instanceof ITree){ + if (individual instanceof ITree) { ITree tree = getTree(); - if (tree == null || worldObj == null) { + if (tree == null || world == null) { return; } - + tree.mate((ITree) individual); - if (!worldObj.isRemote) { + if (!world.isRemote) { sendNetworkUpdate(); } } @@ -314,7 +305,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru /* NETWORK */ private void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(new PacketTileStream(this), worldObj); + Proxies.net.sendNetworkPacket(new PacketTileStream(this), pos, world); } private void sendNetworkUpdateRipening() { @@ -325,16 +316,14 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru colourFruits = newColourFruits; PacketRipeningUpdate ripeningUpdate = new PacketRipeningUpdate(this); - Proxies.net.sendNetworkPacket(ripeningUpdate, worldObj); + Proxies.net.sendNetworkPacket(ripeningUpdate, pos, world); } private static final short hasFruitFlag = 1; private static final short isPollinatedFlag = 1 << 1; @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - + public void writeData(PacketBufferForestry data) { byte leafState = 0; boolean hasFruit = hasFruit(); @@ -352,15 +341,15 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru String fruitAlleleUID = getTree().getGenome().getActiveAllele(EnumTreeChromosome.FRUITS).getUID(); int colourFruits = getFruitColour(); - data.writeUTF(fruitAlleleUID); + data.writeString(fruitAlleleUID); data.writeInt(colourFruits); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { - String speciesUID = data.readUTF(); // this is called instead of super.readData, be careful! + String speciesUID = data.readString(); // this is called instead of super.readData, be careful! byte leafState = data.readByte(); isFruitLeaf = (leafState & hasFruitFlag) > 0; @@ -368,7 +357,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru String fruitAlleleUID = null; if (isFruitLeaf) { - fruitAlleleUID = data.readUTF(); + fruitAlleleUID = data.readString(); colourFruits = data.readInt(); } @@ -388,7 +377,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru setTree(tree); - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } } @@ -398,18 +387,18 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru return; } colourFruits = newColourFruits; - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } /* IFRUITBEARER */ @Override - public Collection pickFruit(ItemStack tool) { + public NonNullList pickFruit(ItemStack tool) { ITree tree = getTree(); if (tree == null || !hasFruit()) { - return Collections.emptyList(); + return NonNullList.create(); } - List produceStacks = tree.produceStacks(worldObj, getPos(), getRipeningTime()); + NonNullList produceStacks = tree.produceStacks(world, getPos(), getRipeningTime()); ripeningTime = 0; sendNetworkUpdateRipening(); return produceStacks; @@ -449,6 +438,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru sendNetworkUpdateRipening(); } + @Nullable public String getSpeciesUID() { if (species == null) { return null; @@ -457,9 +447,11 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } /* IBUTTERFLYNURSERY */ - private IButterfly caterpillar; private void matureCaterpillar() { + if (caterpillar == null) { + return; + } maturationTime++; ITree tree = getTree(); @@ -470,7 +462,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru int caterpillarMatureTime = Math.round((float) caterpillarGenome.getLifespan() / (caterpillarGenome.getFertility() * 2)); if (maturationTime >= caterpillarMatureTime) { - ButterflyManager.butterflyRoot.plantCocoon(worldObj, this, getOwnerHandler().getOwner(), 0); + ButterflyManager.butterflyRoot.plantCocoon(world, this, getOwnerHandler().getOwner(), 0); setCaterpillar(null); } else if (!wasDestroyed && isDestroyed(tree, damage)) { sendNetworkUpdate(); @@ -483,6 +475,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } @Override + @Nullable public IButterfly getCaterpillar() { return caterpillar; } @@ -493,7 +486,7 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru } @Override - public void setCaterpillar(IButterfly butterfly) { + public void setCaterpillar(@Nullable IButterfly butterfly) { maturationTime = 0; caterpillar = butterfly; sendNetworkUpdate(); @@ -507,16 +500,16 @@ public class TileLeaves extends TileTreeContainer implements IPollinatable, IFru @Override public Biome getBiome() { - return worldObj.getBiome(pos); + return world.getBiome(pos); } @Override public EnumTemperature getTemperature() { - return EnumTemperature.getFromBiome(worldObj.getBiome(pos), worldObj, pos); + return EnumTemperature.getFromBiome(world.getBiome(pos), world, pos); } @Override public EnumHumidity getHumidity() { - return EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(worldObj, pos)); + return EnumHumidity.getFromValue(ForestryAPI.climateManager.getHumidity(world, pos)); } } diff --git a/src/main/java/forestry/arboriculture/tiles/TilePile.java b/src/main/java/forestry/arboriculture/tiles/TilePile.java index bcb03c216..10eef6b50 100644 --- a/src/main/java/forestry/arboriculture/tiles/TilePile.java +++ b/src/main/java/forestry/arboriculture/tiles/TilePile.java @@ -1,6 +1,6 @@ package forestry.arboriculture.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import forestry.api.arboriculture.EnumPileType; import forestry.api.arboriculture.IAlleleTreeSpecies; @@ -23,10 +23,11 @@ import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -public class TilePile extends MultiblockTileEntityForestry implements ICharcoalPileComponent{ - +public class TilePile extends MultiblockTileEntityForestry implements ICharcoalPileComponent { + @Nullable private IAlleleTreeSpecies treeSpecies; @SideOnly(Side.CLIENT) + @Nullable private BlockPos woodPos; public TilePile() { @@ -36,13 +37,13 @@ public class TilePile extends MultiblockTileEntityForestry 0 ) { + + if (facesMatching > 0) { if (levelMaxX == pos.getX()) { if (levelMaxZ == pos.getZ()) { pileType = EnumPilePosition.CORNER_BACK_RIGHT; @@ -126,7 +127,7 @@ public class TilePile extends MultiblockTileEntityForestry generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.Direction leanDirection = WorldGenHelper.Direction.getRandom(rand); @@ -49,7 +46,7 @@ public class WorldGenAcacia extends WorldGenTree { int zOffset = treeTop.getZ(); float canopyMultiplier = (1.5f * height - yOffset + 2) / 4.0f; int canopyThickness = Math.max(1, Math.round(yOffset / 10.0f)); - + branchEnds.add(new BlockPos(xOffset, startPos.getY() + yOffset--, zOffset)); yOffset--; @@ -65,7 +62,7 @@ public class WorldGenAcacia extends WorldGenTree { @Override protected void generateLeaves(World world, Random rand, TreeBlockTypeLeaf leaf, List branchEnds, BlockPos startPos) { for (BlockPos branchEnd : branchEnds) { - int leafSpawn = branchEnd.getY() - startPos.getY(); + int leafSpawn = branchEnd.getY() - startPos.getY(); int canopyThickness = Math.max(1, Math.round(leafSpawn / 10.0f)); float canopyMultiplier = (1.5f * height - leafSpawn + 2) / 4.0f; float canopyWidth = rand.nextBoolean() ? 1.0f : 1.5f; diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java index fd9a109b0..1718df052 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenArboriculture.java @@ -10,27 +10,22 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Set; -import forestry.arboriculture.blocks.BlockSapling; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.event.terraingen.TerrainGen; - import forestry.api.world.ITreeGenData; +import forestry.arboriculture.blocks.BlockSapling; import forestry.arboriculture.tiles.TileTreeContainer; import forestry.core.tiles.TileUtil; import forestry.core.utils.TopDownBlockPosComparator; import forestry.core.worldgen.WorldGenBase; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.event.terraingen.TerrainGen; public abstract class WorldGenArboriculture extends WorldGenBase { @@ -64,7 +59,7 @@ public abstract class WorldGenArboriculture extends WorldGenBase { if (genPos != null) { clearSaplings(world, genPos); List branchEnds = new ArrayList<>(generateTrunk(world, rand, wood, genPos)); - Collections.sort(branchEnds, TopDownBlockPosComparator.INSTANCE); + branchEnds.sort(TopDownBlockPosComparator.INSTANCE); generateLeaves(world, rand, leaf, branchEnds, genPos); generateExtras(world, rand, genPos); return true; @@ -73,6 +68,7 @@ public abstract class WorldGenArboriculture extends WorldGenBase { return false; } + @Nullable private static GameProfile getOwner(World world, BlockPos pos) { TileTreeContainer tile = TileUtil.getTile(world, pos, TileTreeContainer.class); if (tile == null) { @@ -88,7 +84,7 @@ public abstract class WorldGenArboriculture extends WorldGenBase { /** * Generate the tree's trunk. Returns a list of positions of branch ends for leaves to generate at. */ - @Nonnull + protected abstract Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos); protected abstract void generateLeaves(World world, Random rand, TreeBlockTypeLeaf leaf, List branchEnds, BlockPos startPos); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java index f793cfeb5..16e485ea8 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenBaobab.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class WorldGenBaobab extends WorldGenTree { @@ -27,7 +25,6 @@ public class WorldGenBaobab extends WorldGenTree { super(tree, 6, 6); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height - 1, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java index 6b0d749e5..ff42aa05c 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenCherry.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class WorldGenCherry extends WorldGenTree { @@ -28,7 +26,6 @@ public class WorldGenCherry extends WorldGenTree { super(tree, 4, 4); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java index 0b852a66c..19dd0a315 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenChestnut.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenChestnut extends WorldGenTree { super(tree, 7, 3); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java index a99724d15..f66bca1cd 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenCocobolo.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenCocobolo extends WorldGenTree { super(tree, 8, 8); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { return WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java index 4e701a091..819770e95 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenEbony.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class WorldGenEbony extends WorldGenTree { @@ -28,7 +26,6 @@ public class WorldGenEbony extends WorldGenTree { super(tree, 10, 4); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { int trunksGenerated = 0; diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java index 513b14774..20d3609c5 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenGreenheart.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class WorldGenGreenheart extends WorldGenTree { @@ -28,7 +26,6 @@ public class WorldGenGreenheart extends WorldGenTree { super(tree, 10, 8); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0.4f, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java index 6529f175b..c8d095005 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenIpe.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class WorldGenIpe extends WorldGenTree { @@ -28,7 +26,6 @@ public class WorldGenIpe extends WorldGenTree { super(tree, 6, 4); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java index 32ab96963..3a19445a2 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenJungle.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.world.ITreeGenData; import forestry.core.worldgen.WorldGenHelper; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; /** * This is a dummy and needs to be replaced with something proper. @@ -31,7 +29,6 @@ public class WorldGenJungle extends WorldGenTreeVanilla { super(tree); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { int height = this.height; diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java index 8e11bbd0d..da1729df2 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenKapok.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenKapok extends WorldGenTree { super(tree, 10, 8); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0.6f, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java index 3f72c1d07..1ae07b45b 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahoe.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenMahoe extends WorldGenTree { super(tree, 6, 3); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { Set branchCoords = new HashSet<>(); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java index 3fee91fbc..4349cca82 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMahogany.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenMahogany extends WorldGenTree { super(tree, 12, 6); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0.6f, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java index b8923cf43..8903b90e6 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenMaple.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenMaple extends WorldGenTree { super(tree, 7, 5); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java index 3f92d9bb1..095b9ebc6 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPadauk.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; import java.util.Random; @@ -29,7 +28,6 @@ public class WorldGenPadauk extends WorldGenTree { super(tree, 6, 6); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java index c5d07cb50..1e72b9e4c 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPapaya.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenPapaya extends WorldGenTree { super(tree, 7, 2); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java index 5a51a46da..c0540c21b 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenPine.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenPine extends WorldGenTree { super(tree, 6, 4); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java index 3b94fc446..6d02d49f3 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSequoia.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -32,7 +31,6 @@ public class WorldGenSequoia extends WorldGenTree { super(tree, baseHeight, heightVariation); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java index e4c83d36f..97d21415b 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSilverLime.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenSilverLime extends WorldGenTree { super(tree, 6, 4); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java index f2e1da88e..c488c8ad8 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenSpruce.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenSpruce extends WorldGenTree { super(tree, 5, 3); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java index 52df4dc3b..5d3ab9238 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenTeak.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenTeak extends WorldGenTree { super(tree, 6, 3); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java index 4cb75077e..95af9c16f 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenTree.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; @@ -41,7 +40,6 @@ public abstract class WorldGenTree extends WorldGenArboriculture { this.heightVariation = heightVariation; } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java index 7fa2de442..ef82df270 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWalnut.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenWalnut extends WorldGenTree { super(tree, 7, 3); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java index a07e99975..28e986335 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWenge.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenWenge extends WorldGenTree { super(tree, 6, 2); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java index 916894820..9d69cbdc8 100755 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenWillow.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; import java.util.Random; @@ -28,7 +27,6 @@ public class WorldGenWillow extends WorldGenTree { super(tree, 5, 2); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0.8f, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java b/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java index 692538436..9b54b093d 100644 --- a/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java +++ b/src/main/java/forestry/arboriculture/worldgen/WorldGenZebrawood.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.arboriculture.worldgen; -import javax.annotation.Nonnull; import java.util.List; import java.util.Random; import java.util.Set; @@ -27,7 +26,6 @@ public class WorldGenZebrawood extends WorldGenTree { super(tree, 8, 8); } - @Nonnull @Override public Set generateTrunk(World world, Random rand, TreeBlockTypeLog wood, BlockPos startPos) { WorldGenHelper.generateTreeTrunk(world, rand, wood, startPos, height, girth, 0, 0, null, 0); diff --git a/src/main/java/forestry/arboriculture/worldgen/package-info.java b/src/main/java/forestry/arboriculture/worldgen/package-info.java new file mode 100644 index 000000000..f56f7b03d --- /dev/null +++ b/src/main/java/forestry/arboriculture/worldgen/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.arboriculture.worldgen; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/CamouflageAccess.java b/src/main/java/forestry/core/CamouflageAccess.java index fe459a955..d398ec484 100644 --- a/src/main/java/forestry/core/CamouflageAccess.java +++ b/src/main/java/forestry/core/CamouflageAccess.java @@ -10,75 +10,69 @@ ******************************************************************************/ package forestry.core; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fml.common.Loader; import forestry.api.core.ICamouflageAccess; import forestry.api.core.ICamouflageItemHandler; import forestry.core.utils.Log; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.common.Loader; public class CamouflageAccess implements ICamouflageAccess { private static final Map> camouflageItemHandlers = new HashMap<>(); private static final Map> camouflageItemBlacklist = new HashMap<>(); private static final Map> blacklistedMods = new HashMap<>(); - + @Override - public void registerCamouflageItemHandler(@Nonnull ICamouflageItemHandler itemHandler) { - if(itemHandler == null){ - Log.error("Fail to register a camouflage item handler, because the handler is null. The handler is form the mod with the ID: " + Loader.instance().activeModContainer().getModId() + "."); - return; - } + public void registerCamouflageItemHandler(ICamouflageItemHandler itemHandler) { String type = itemHandler.getType(); - if(!camouflageItemHandlers.containsKey(type)){ + if (!camouflageItemHandlers.containsKey(type)) { camouflageItemHandlers.put(type, new ArrayList<>()); } - if(!camouflageItemHandlers.containsValue(itemHandler)){ - camouflageItemHandlers.get(type).add(itemHandler); - }else{ + + List handlers = camouflageItemHandlers.get(type); + if (!handlers.contains(itemHandler)) { + handlers.add(itemHandler); + } else { Log.error("Fail to register a camouflage item handler, because the handler is already registered. The handler is form the mod with the ID: " + Loader.instance().activeModContainer().getModId() + "."); } } - + @Override + @Nullable public List getCamouflageItemHandler(String type) { - if(type == null){ + if (type == null) { List handlers = new ArrayList<>(); - for(List handler : camouflageItemHandlers.values()){ + for (List handler : camouflageItemHandlers.values()) { handlers.addAll(handler); } return handlers; } - if(!camouflageItemHandlers.containsKey(type)){ - return null; - } + return camouflageItemHandlers.get(type); } - + @Override public void addModIdToBlackList(String type, String modID) { - if(!blacklistedMods.containsKey(type)){ + if (!blacklistedMods.containsKey(type)) { blacklistedMods.put(type, new ArrayList<>()); } - if(!blacklistedMods.get(type).contains(modID)){ + if (!blacklistedMods.get(type).contains(modID)) { blacklistedMods.get(type).add(modID); } } - + @Override public void addItemToBlackList(String type, ItemStack camouflageBlock) { - if (camouflageBlock == null || camouflageBlock.getItem() == null) { - Log.error("Fail to add camouflage block item to the black list, because it is null"); - return; - } Block block = Block.getBlockFromItem(camouflageBlock.getItem()); - if (block == null) { + if (block == Blocks.AIR) { Log.error("Fail to add camouflage block item to the black list: because it has no block."); return; } @@ -88,28 +82,28 @@ public class CamouflageAccess implements ICamouflageAccess { return; } } - if(!camouflageItemBlacklist.containsKey(type)){ + if (!camouflageItemBlacklist.containsKey(type)) { camouflageItemBlacklist.put(type, new ArrayList<>()); } camouflageItemBlacklist.get(type).add(camouflageBlock); } - + @Override public boolean isItemBlackListed(String type, ItemStack camouflageBlock) { - if (camouflageBlock == null || camouflageBlock.getItem() == null || Block.getBlockFromItem(camouflageBlock.getItem()) == null || type != null && !camouflageItemBlacklist.containsKey(type)) { + if (camouflageBlock.isEmpty() || Block.getBlockFromItem(camouflageBlock.getItem()) == Blocks.AIR || type != null && !camouflageItemBlacklist.containsKey(type)) { return false; } String modId = camouflageBlock.getItem().getRegistryName().getResourceDomain(); - if(blacklistedMods.get(type) != null && blacklistedMods.get(type).contains(modId)){ + if (blacklistedMods.get(type) != null && blacklistedMods.get(type).contains(modId)) { return true; } List camouflageItemBlacklisted; - if(type == null){ + if (type == null) { camouflageItemBlacklisted = new ArrayList<>(); - for(List stacks : camouflageItemBlacklist.values()){ + for (List stacks : camouflageItemBlacklist.values()) { camouflageItemBlacklisted.addAll(stacks); } - }else{ + } else { camouflageItemBlacklisted = camouflageItemBlacklist.get(type); } for (ItemStack camouflageBlacklisted : camouflageItemBlacklisted) { @@ -117,15 +111,19 @@ public class CamouflageAccess implements ICamouflageAccess { return true; } } - + return false; } @Override + @Nullable public ICamouflageItemHandler getHandlerFromItem(ItemStack stack) { - for(List handlers : camouflageItemHandlers.values()){ - for(ICamouflageItemHandler handler : handlers){ - if(handler.canHandle(stack)){ + if (stack.isEmpty()) { + return null; + } + for (List handlers : camouflageItemHandlers.values()) { + for (ICamouflageItemHandler handler : handlers) { + if (handler.canHandle(stack)) { return handler; } } diff --git a/src/main/java/forestry/core/CamouflageHandlerDefault.java b/src/main/java/forestry/core/CamouflageHandlerDefault.java index b1698d2df..cecb30c39 100644 --- a/src/main/java/forestry/core/CamouflageHandlerDefault.java +++ b/src/main/java/forestry/core/CamouflageHandlerDefault.java @@ -10,32 +10,34 @@ ******************************************************************************/ package forestry.core; +import javax.annotation.Nonnull; + +import com.google.common.base.Preconditions; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; import forestry.api.core.ICamouflagedTile; -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockModelShapes; import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; public class CamouflageHandlerDefault implements ICamouflageItemHandler { @Override - public boolean canHandle(ItemStack stack) { - if(stack == null || stack.getItem() == null || stack.stackSize <= 0 || Block.getBlockFromItem(stack.getItem()) == null){ + public boolean canHandle(@Nonnull ItemStack stack) { + if (stack.isEmpty() || Block.getBlockFromItem(stack.getItem()) == Blocks.AIR) { return false; } Block block = Block.getBlockFromItem(stack.getItem()); IBlockState stateFromMeta = block.getStateFromMeta(stack.getItemDamage()); - + return stateFromMeta.isOpaqueCube() && !block.hasTileEntity(stateFromMeta) && block.isNormalCube(stateFromMeta) && block.isFullCube(stateFromMeta) && block.isBlockNormalCube(stateFromMeta); } @@ -51,12 +53,14 @@ public class CamouflageHandlerDefault implements ICamouflageItemHandler { @SideOnly(Side.CLIENT) @Override - public Pair getModel(ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile) { - if(camouflageHandler == null || stack == null || stack.getItem() == null || stack.stackSize <= 0 || Block.getBlockFromItem(stack.getItem()) == null){ - return null; - } + public Pair getModel(@Nonnull ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile) { + Preconditions.checkNotNull(camouflageHandler); + Preconditions.checkArgument(!stack.isEmpty(), "Stack cannot be empty"); + BlockModelShapes modelShapes = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes(); Block block = Block.getBlockFromItem(stack.getItem()); + Preconditions.checkArgument(block != Blocks.AIR, "Block cannot be AIR"); + IBlockState state = block.getStateFromMeta(stack.getItemDamage()); return Pair.of(state, modelShapes.getModelForState(state)); diff --git a/src/main/java/forestry/core/CamouflageHandlerDoor.java b/src/main/java/forestry/core/CamouflageHandlerDoor.java index 6594dd5ac..f277b1cfc 100644 --- a/src/main/java/forestry/core/CamouflageHandlerDoor.java +++ b/src/main/java/forestry/core/CamouflageHandlerDoor.java @@ -10,14 +10,11 @@ ******************************************************************************/ package forestry.core; +import com.google.common.base.Preconditions; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; import forestry.api.core.ICamouflagedTile; -import jline.internal.Log; - -import org.apache.commons.lang3.tuple.Pair; - import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.block.state.IBlockState; @@ -28,22 +25,16 @@ import net.minecraft.item.ItemDoor; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; public class CamouflageHandlerDoor implements ICamouflageItemHandler { @Override public boolean canHandle(ItemStack stack) { - if(stack == null || stack.getItem() == null || stack.stackSize <= 0){ - return false; - } - if(stack.getItem() instanceof ItemDoor){ - return true; - } - return false; + return stack.getItem() instanceof ItemDoor; } @Override @@ -59,9 +50,9 @@ public class CamouflageHandlerDoor implements ICamouflageItemHandler { @SideOnly(Side.CLIENT) @Override public Pair getModel(ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile) { - if(camouflageHandler == null || stack == null || stack.getItem() == null || stack.stackSize <= 0 || !(stack.getItem() instanceof ItemDoor)){ - return null; - } + Preconditions.checkNotNull(camouflageHandler); + Preconditions.checkArgument(stack.getItem() instanceof ItemDoor, "Item must be a door"); + World world = camouflageHandler.getWorldObj(); BlockPos pos = camouflageTile.getCoordinates(); IBlockState blockState = world.getBlockState(pos); @@ -70,9 +61,8 @@ public class CamouflageHandlerDoor implements ICamouflageItemHandler { ItemDoor itemDoor = (ItemDoor) stack.getItem(); Block doorBlock = ObfuscationReflectionHelper.getPrivateValue(ItemDoor.class, itemDoor, 0); - if(doorBlock == null){ - Log.error("Can't render Door : block is null for" + stack); - return null; + if (doorBlock == null) { + throw new IllegalStateException("Can't render Door : block is null for" + stack); } IBlockState doorState = doorBlock.getDefaultState() .withProperty(BlockDoor.FACING, currentState.getValue(BlockDoor.FACING)) diff --git a/src/main/java/forestry/core/CamouflageHandlerGlass.java b/src/main/java/forestry/core/CamouflageHandlerGlass.java index 62c1bdab1..eeed80327 100644 --- a/src/main/java/forestry/core/CamouflageHandlerGlass.java +++ b/src/main/java/forestry/core/CamouflageHandlerGlass.java @@ -10,8 +10,7 @@ ******************************************************************************/ package forestry.core; -import org.apache.commons.lang3.tuple.Pair; - +import com.google.common.base.Preconditions; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; @@ -21,20 +20,22 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockModelShapes; import net.minecraft.client.renderer.block.model.IBakedModel; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; public class CamouflageHandlerGlass implements ICamouflageItemHandler { @Override public boolean canHandle(ItemStack stack) { - if(stack == null || stack.getItem() == null || stack.stackSize <= 0 || Block.getBlockFromItem(stack.getItem()) == null){ + if (stack.isEmpty() || Block.getBlockFromItem(stack.getItem()) == Blocks.AIR) { return false; } Block block = Block.getBlockFromItem(stack.getItem()); IBlockState stateFromMeta = block.getStateFromMeta(stack.getItemDamage()); - + return !stateFromMeta.isOpaqueCube() && !block.hasTileEntity(stateFromMeta) && !block.isBlockNormalCube(stateFromMeta); } @@ -51,13 +52,12 @@ public class CamouflageHandlerGlass implements ICamouflageItemHandler { @SideOnly(Side.CLIENT) @Override public Pair getModel(ItemStack stack, ICamouflageHandler camouflageHandler, ICamouflagedTile camouflageTile) { - if(camouflageHandler == null || stack == null || stack.getItem() == null || stack.stackSize <= 0 || Block.getBlockFromItem(stack.getItem()) == null){ - return null; - } BlockModelShapes modelShapes = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes(); Block block = Block.getBlockFromItem(stack.getItem()); + Preconditions.checkArgument(block != Blocks.AIR, "stack has no block"); + IBlockState state = block.getStateFromMeta(stack.getItemDamage()); - + return Pair.of(state, modelShapes.getModelForState(state)); } diff --git a/src/main/java/forestry/core/CreativeTabForestry.java b/src/main/java/forestry/core/CreativeTabForestry.java index a3913aaaf..7a8fb2f17 100755 --- a/src/main/java/forestry/core/CreativeTabForestry.java +++ b/src/main/java/forestry/core/CreativeTabForestry.java @@ -10,24 +10,23 @@ ******************************************************************************/ package forestry.core; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.common.registry.GameRegistry; - import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; import forestry.core.config.Constants; import forestry.plugins.ForestryPluginUids; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.ForgeRegistries; public class CreativeTabForestry extends CreativeTabs { static { if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)) { - Tabs.tabAgriculture= new CreativeTabForestry(1, "agriculture"); + Tabs.tabAgriculture = new CreativeTabForestry(1, "agriculture"); } - + if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.APICULTURE)) { Tabs.tabApiculture = new CreativeTabForestry(2, "apiculture"); } @@ -55,19 +54,19 @@ public class CreativeTabForestry extends CreativeTabs { Item iconItem; switch (icon) { case 1: - iconItem = GameRegistry.findItem(Constants.MOD_ID, "ffarm"); + iconItem = ForgeRegistries.ITEMS.getValue(new ResourceLocation(Constants.MOD_ID, "ffarm")); break; case 2: - iconItem = GameRegistry.findItem(Constants.MOD_ID, "beeDroneGE"); + iconItem = ForgeRegistries.ITEMS.getValue(new ResourceLocation(Constants.MOD_ID, "beeDroneGE")); break; case 3: - iconItem = GameRegistry.findItem(Constants.MOD_ID, "sapling"); + iconItem = ForgeRegistries.ITEMS.getValue(new ResourceLocation(Constants.MOD_ID, "sapling")); break; case 4: - iconItem = GameRegistry.findItem(Constants.MOD_ID, "butterflyGE"); + iconItem = ForgeRegistries.ITEMS.getValue(new ResourceLocation(Constants.MOD_ID, "butterflyGE")); break; default: - iconItem = GameRegistry.findItem(Constants.MOD_ID, "fertilizerCompound"); + iconItem = ForgeRegistries.ITEMS.getValue(new ResourceLocation(Constants.MOD_ID, "fertilizerCompound")); break; } if (iconItem == null) { @@ -77,7 +76,7 @@ public class CreativeTabForestry extends CreativeTabs { } @Override - public Item getTabIconItem() { - return null; // not used due to overridden getIconItemStack + public ItemStack getTabIconItem() { + return getIconItemStack(); } } diff --git a/src/main/java/forestry/core/DefaultClimateProvider.java b/src/main/java/forestry/core/DefaultClimateProvider.java index 904f74d93..38f5bfd3a 100644 --- a/src/main/java/forestry/core/DefaultClimateProvider.java +++ b/src/main/java/forestry/core/DefaultClimateProvider.java @@ -19,8 +19,8 @@ import net.minecraft.world.World; import net.minecraft.world.biome.Biome; public class DefaultClimateProvider implements IClimateProvider { - private World world; - private BlockPos pos; + private final World world; + private final BlockPos pos; public DefaultClimateProvider(World world, BlockPos pos) { this.world = world; diff --git a/src/main/java/forestry/core/PickupHandlerCore.java b/src/main/java/forestry/core/PickupHandlerCore.java index 53374a6de..963b8787c 100755 --- a/src/main/java/forestry/core/PickupHandlerCore.java +++ b/src/main/java/forestry/core/PickupHandlerCore.java @@ -24,17 +24,15 @@ public class PickupHandlerCore implements IPickupHandler { @Override public boolean onItemPickup(EntityPlayer entityPlayer, EntityItem entityitem) { ItemStack itemstack = entityitem.getEntityItem(); - if (itemstack == null || itemstack.stackSize <= 0) { + if (itemstack.isEmpty()) { return false; } ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(itemstack); if (root != null) { IIndividual individual = root.getMember(itemstack); - if (individual != null) { - IBreedingTracker tracker = root.getBreedingTracker(entityitem.worldObj, entityPlayer.getGameProfile()); - tracker.registerPickup(individual); - } + IBreedingTracker tracker = root.getBreedingTracker(entityitem.world, entityPlayer.getGameProfile()); + tracker.registerPickup(individual); } return false; diff --git a/src/main/java/forestry/core/PluginCore.java b/src/main/java/forestry/core/PluginCore.java index c13544fe2..4d1b0daf9 100644 --- a/src/main/java/forestry/core/PluginCore.java +++ b/src/main/java/forestry/core/PluginCore.java @@ -10,33 +10,13 @@ ******************************************************************************/ package forestry.core; -import com.google.common.collect.ImmutableMap; - -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Set; -import forestry.core.owner.GameProfileDataSerializer; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.command.ICommand; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.world.storage.loot.functions.LootFunctionManager; - -import net.minecraftforge.client.event.ModelBakeEvent; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fml.common.IFuelHandler; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.RecipeSorter; - +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; import forestry.api.circuits.ChipsetManager; import forestry.api.core.CamouflageManager; import forestry.api.core.ForestryAPI; @@ -61,13 +41,14 @@ import forestry.core.genetics.alleles.AlleleHelper; import forestry.core.genetics.alleles.AlleleRegistry; import forestry.core.items.EnumContainerType; import forestry.core.items.ItemRegistryCore; -import forestry.core.loot.functions.SetSpeciesNBT; +import forestry.core.loot.SetSpeciesNBT; import forestry.core.models.ModelCamouflageSprayCan; import forestry.core.models.ModelEntry; import forestry.core.models.ModelManager; import forestry.core.multiblock.MultiblockLogicFactory; import forestry.core.network.IPacketRegistry; import forestry.core.network.PacketRegistryCore; +import forestry.core.owner.GameProfileDataSerializer; import forestry.core.proxy.Proxies; import forestry.core.recipes.RecipeUtil; import forestry.core.recipes.ShapedRecipeCustom; @@ -78,11 +59,30 @@ import forestry.core.utils.OreDictUtil; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.command.ICommand; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.world.storage.loot.functions.LootFunctionManager; +import net.minecraftforge.client.event.ModelBakeEvent; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fml.common.IFuelHandler; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.RecipeSorter; @ForestryPlugin(pluginID = ForestryPluginUids.CORE, name = "Core", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.core.description") public class PluginCore extends BlankForestryPlugin { public static final RootCommand rootCommand = new RootCommand(); + @Nullable public static ItemRegistryCore items; + @Nullable public static BlockRegistryCore blocks; @Override @@ -90,7 +90,6 @@ public class PluginCore extends BlankForestryPlugin { return false; } - @Nonnull @Override public Set getDependencyUids() { return Collections.emptySet(); @@ -108,13 +107,11 @@ public class PluginCore extends BlankForestryPlugin { AlleleManager.alleleFactory = new AlleleFactory(); alleleRegistry.initialize(); - AlleleHelper.instance = new AlleleHelper(); - LootFunctionManager.registerFunction(new SetSpeciesNBT.Serializer()); MultiblockManager.logicFactory = new MultiblockLogicFactory(); ForestryAPI.climateManager = new ClimateManager(); - + CamouflageManager.camouflageAccess = new CamouflageAccess(); } @@ -127,13 +124,13 @@ public class PluginCore extends BlankForestryPlugin { @Override public void preInit() { super.preInit(); - + GameProfileDataSerializer.register(); MinecraftForge.EVENT_BUS.register(this); rootCommand.addChildCommand(new CommandPlugins()); - + CamouflageManager.camouflageAccess.registerCamouflageItemHandler(new CamouflageHandlerDefault()); CamouflageManager.camouflageAccess.registerCamouflageItemHandler(new CamouflageHandlerGlass()); CamouflageManager.camouflageAccess.registerCamouflageItemHandler(new CamouflageHandlerDoor()); @@ -143,12 +140,16 @@ public class PluginCore extends BlankForestryPlugin { public void doInit() { super.doInit(); + AlleleHelper alleleHelper = AlleleHelper.getInstance(); + Preconditions.checkState(blocks != null); + Preconditions.checkState(alleleHelper != null); + blocks.analyzer.init(); blocks.escritoire.init(); ForestryModEnvWarningCallable.register(); - AlleleHelper.instance.init(); + alleleHelper.init(); Proxies.render.initRendering(); @@ -163,6 +164,8 @@ public class PluginCore extends BlankForestryPlugin { @Override public void registerCrates() { ICrateRegistry crateRegistry = StorageManager.crateRegistry; + Preconditions.checkState(items != null); + Preconditions.checkState(blocks != null); // forestry items crateRegistry.registerCrate(items.peat); @@ -233,6 +236,8 @@ public class PluginCore extends BlankForestryPlugin { @Override public void registerRecipes() { + Preconditions.checkState(blocks != null); + Preconditions.checkState(items != null); /* SMELTING RECIPES */ RecipeUtil.addSmelting(blocks.resources.get(EnumResourceType.APATITE, 1), items.apatite, 0.5f); @@ -243,7 +248,7 @@ public class PluginCore extends BlankForestryPlugin { /* BRONZE INGOTS */ if (Config.isCraftingBronzeEnabled()) { ItemStack ingotBronze = items.ingotBronze.copy(); - ingotBronze.stackSize = 4; + ingotBronze.setCount(4); RecipeUtil.addShapelessRecipe(ingotBronze, OreDictUtil.INGOT_TIN, OreDictUtil.INGOT_COPPER, OreDictUtil.INGOT_COPPER, OreDictUtil.INGOT_COPPER); } @@ -278,21 +283,21 @@ public class PluginCore extends BlankForestryPlugin { // / WRENCH RecipeUtil.addRecipe(items.wrench, "# #", " # ", " # ", '#', OreDictUtil.INGOT_BRONZE); - + // / CAMOUFLAGE SPRAY CAN RecipeUtil.addRecipe(items.camouflageSprayCan, "TTT", "TCT", "TCT", 'T', OreDictUtil.INGOT_TIN, 'C', items.craftingMaterial.getCamouflagedPaneling()); - + if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FACTORY)) { // / CARPENTER // Portable ANALYZER - RecipeManagers.carpenterManager.addRecipe(100, new FluidStack(FluidRegistry.WATER, 2000), null, PluginCore.items.portableAlyzer.getItemStack(), + RecipeManagers.carpenterManager.addRecipe(100, new FluidStack(FluidRegistry.WATER, 2000), ItemStack.EMPTY, items.portableAlyzer.getItemStack(), "X#X", "X#X", "RDR", '#', OreDictUtil.PANE_GLASS, 'X', OreDictUtil.INGOT_TIN, 'R', OreDictUtil.DUST_REDSTONE, 'D', OreDictUtil.GEM_DIAMOND); // Camouflaged Paneling - RecipeManagers.carpenterManager.addRecipe(50, Fluids.BIOMASS.getFluid(500), null, PluginCore.items.craftingMaterial.getCamouflagedPaneling(4), + RecipeManagers.carpenterManager.addRecipe(50, Fluids.BIOMASS.getFluid(500), ItemStack.EMPTY, items.craftingMaterial.getCamouflagedPaneling(4), "YAR", "B#B", "RPY", '#', OreDictUtil.PLANK_WOOD, 'A', OreDictUtil.DUST_ASH, @@ -301,9 +306,9 @@ public class PluginCore extends BlankForestryPlugin { 'R', OreDictUtil.DYE_RED, 'B', OreDictUtil.DYE_BLUE, 'Y', OreDictUtil.DYE_YELLOW); - }else{ + } else { // Portable ANALYZER - RecipeUtil.addRecipe(PluginCore.items.portableAlyzer.getItemStack(), + RecipeUtil.addRecipe(items.portableAlyzer.getItemStack(), "X#X", "X#X", "RDR", @@ -312,24 +317,24 @@ public class PluginCore extends BlankForestryPlugin { 'R', OreDictUtil.DUST_REDSTONE, 'D', OreDictUtil.GEM_DIAMOND); // Camouflaged Paneling - RecipeUtil.addRecipe(PluginCore.items.craftingMaterial.getCamouflagedPaneling(4), - "WWW", - "YBR", - "WWW", - 'W', OreDictUtil.PLANK_WOOD, - 'D', OreDictUtil.DUST_REDSTONE, + RecipeUtil.addRecipe(items.craftingMaterial.getCamouflagedPaneling(4), + "WWW", + "YBR", + "WWW", + 'W', OreDictUtil.PLANK_WOOD, + 'D', OreDictUtil.DUST_REDSTONE, 'Y', OreDictUtil.DYE_YELLOW, 'B', OreDictUtil.DYE_BLUE, 'R', OreDictUtil.DYE_RED); } - + // ANALYZER - RecipeUtil.addRecipe(PluginCore.blocks.analyzer, + RecipeUtil.addRecipe(blocks.analyzer, "XTX", " Y ", "X X", - 'Y', PluginCore.items.sturdyCasing, - 'T', PluginCore.items.portableAlyzer, + 'Y', items.sturdyCasing, + 'T', items.portableAlyzer, 'X', OreDictUtil.INGOT_BRONZE); // Manure and Fertilizer @@ -405,7 +410,7 @@ public class PluginCore extends BlankForestryPlugin { RecipeUtil.addRecipe(blocks.resourceStorageCopper, "###", "###", "###", '#', OreDictUtil.INGOT_COPPER); ItemStack ingotCopper = items.ingotCopper.copy(); - ingotCopper.stackSize = 9; + ingotCopper.setCount(9); RecipeUtil.addShapelessRecipe(ingotCopper, OreDictUtil.BLOCK_COPPER); } @@ -413,7 +418,7 @@ public class PluginCore extends BlankForestryPlugin { RecipeUtil.addRecipe(blocks.resourceStorageTin, "###", "###", "###", '#', OreDictUtil.INGOT_TIN); ItemStack ingotTin = items.ingotTin.copy(); - ingotTin.stackSize = 9; + ingotTin.setCount(9); RecipeUtil.addShapelessRecipe(ingotTin, OreDictUtil.BLOCK_TIN); } @@ -421,7 +426,7 @@ public class PluginCore extends BlankForestryPlugin { RecipeUtil.addRecipe(blocks.resourceStorageBronze, "###", "###", "###", '#', OreDictUtil.INGOT_BRONZE); ItemStack ingotBronze = items.ingotBronze.copy(); - ingotBronze.stackSize = 9; + ingotBronze.setCount(9); RecipeUtil.addShapelessRecipe(ingotBronze, OreDictUtil.BLOCK_BRONZE); } @@ -450,16 +455,23 @@ public class PluginCore extends BlankForestryPlugin { @Override public IFuelHandler getFuelHandler() { - return new FuelHandler(); + Preconditions.checkState(items != null); + return new FuelHandler(items); } @Override public void getHiddenItems(List hiddenItems) { + Preconditions.checkState(items != null); // research note items are not useful without actually having completed research - hiddenItems.add(new ItemStack(PluginCore.items.researchNote)); + hiddenItems.add(new ItemStack(items.researchNote)); } private static class FuelHandler implements IFuelHandler { + private final ItemRegistryCore items; + + public FuelHandler(ItemRegistryCore items) { + this.items = items; + } @Override public int getBurnTime(ItemStack fuel) { @@ -473,7 +485,7 @@ public class PluginCore extends BlankForestryPlugin { return 0; } } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void onBakeModel(ModelBakeEvent event) { @@ -482,7 +494,7 @@ public class PluginCore extends BlankForestryPlugin { Proxies.render.registerModel(blockModelIndex); ModelManager.getInstance().registerCustomModels(event); } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void registerSprites(TextureStitchEvent.Pre event) { diff --git a/src/main/java/forestry/core/PluginFluids.java b/src/main/java/forestry/core/PluginFluids.java index b367d46b5..3cfb6887f 100644 --- a/src/main/java/forestry/core/PluginFluids.java +++ b/src/main/java/forestry/core/PluginFluids.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.core; +import javax.annotation.Nullable; + +import com.google.common.base.Preconditions; +import forestry.core.items.ItemRegistryCore; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.util.ResourceLocation; @@ -36,7 +40,7 @@ import forestry.plugins.ForestryPluginUids; @ForestryPlugin(pluginID = ForestryPluginUids.FLUIDS, name = "Fluids", author = "mezz", url = Constants.URL, unlocalizedDescription = "for.plugin.fluids.description") public class PluginFluids extends BlankForestryPlugin { - + @Nullable public static ItemRegistryFluids items; private static void createFluid(Fluids fluidDefinition) { @@ -56,6 +60,7 @@ public class PluginFluids extends BlankForestryPlugin { private static void createBlock(Fluids forestryFluid) { Fluid fluid = forestryFluid.getFluid(); + Preconditions.checkState(fluid != null); Block fluidBlock = fluid.getBlock(); if (Config.isBlockEnabled(forestryFluid.getTag())) { @@ -101,10 +106,14 @@ public class PluginFluids extends BlankForestryPlugin { @Override public void doInit() { + Preconditions.checkState(items != null); + if (RecipeManagers.squeezerManager != null) { - RecipeManagers.squeezerManager.addContainerRecipe(10, items.canEmpty.getItemStack(), PluginCore.items.ingotTin.copy(), 0.05f); - RecipeManagers.squeezerManager.addContainerRecipe(10, items.waxCapsuleEmpty.getItemStack(), PluginCore.items.beeswax.getItemStack(), 0.10f); - RecipeManagers.squeezerManager.addContainerRecipe(10, items.refractoryEmpty.getItemStack(), PluginCore.items.refractoryWax.getItemStack(), 0.10f); + ItemRegistryCore itemRegistryCore = PluginCore.items; + Preconditions.checkState(itemRegistryCore != null); + RecipeManagers.squeezerManager.addContainerRecipe(10, items.canEmpty.getItemStack(), itemRegistryCore.ingotTin.copy(), 0.05f); + RecipeManagers.squeezerManager.addContainerRecipe(10, items.waxCapsuleEmpty.getItemStack(), itemRegistryCore.beeswax.getItemStack(), 0.10f); + RecipeManagers.squeezerManager.addContainerRecipe(10, items.refractoryEmpty.getItemStack(), itemRegistryCore.refractoryWax.getItemStack(), 0.10f); } FluidStack ethanol = Fluids.BIO_ETHANOL.getFluid(1); diff --git a/src/main/java/forestry/core/TickHandlerCoreClient.java b/src/main/java/forestry/core/TickHandlerCoreClient.java index 6db551dc3..dbea461e3 100755 --- a/src/main/java/forestry/core/TickHandlerCoreClient.java +++ b/src/main/java/forestry/core/TickHandlerCoreClient.java @@ -26,28 +26,22 @@ public class TickHandlerCoreClient { @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { - if (event.phase != Phase.END) { - return; - } - - Minecraft minecraft = Minecraft.getMinecraft(); - if (minecraft == null) { - return; - } - - EntityPlayer player = minecraft.thePlayer; - if (player == null) { - return; - } - - boolean hasNaturalistEye = GeneticsUtil.hasNaturalistEye(player); - if (this.hasNaturalistEye != hasNaturalistEye) { - this.hasNaturalistEye = hasNaturalistEye; - RenderGlobal renderGlobal = minecraft.renderGlobal; - if (renderGlobal != null) { - renderGlobal.markBlockRangeForRenderUpdate( - (int) player.posX - 32, (int) player.posY - 32, (int) player.posZ - 32, - (int) player.posX + 32, (int) player.posY + 32, (int) player.posZ + 32); + if (event.phase == Phase.END) { + Minecraft minecraft = Minecraft.getMinecraft(); + if (minecraft != null) { + EntityPlayer player = minecraft.player; + if (player != null) { + boolean hasNaturalistEye = GeneticsUtil.hasNaturalistEye(player); + if (this.hasNaturalistEye != hasNaturalistEye) { + this.hasNaturalistEye = hasNaturalistEye; + RenderGlobal renderGlobal = minecraft.renderGlobal; + if (renderGlobal != null) { + renderGlobal.markBlockRangeForRenderUpdate( + (int) player.posX - 32, (int) player.posY - 32, (int) player.posZ - 32, + (int) player.posX + 32, (int) player.posY + 32, (int) player.posZ + 32); + } + } + } } } } diff --git a/src/main/java/forestry/core/TickHandlerCoreServer.java b/src/main/java/forestry/core/TickHandlerCoreServer.java index c216a8c0f..7509bd364 100755 --- a/src/main/java/forestry/core/TickHandlerCoreServer.java +++ b/src/main/java/forestry/core/TickHandlerCoreServer.java @@ -88,10 +88,13 @@ public class TickHandlerCoreServer { @SubscribeEvent public void chunkLoadEventHandler(ChunkDataEvent.Load event) { if (Config.doRetrogen) { - NBTTagCompound tag = (NBTTagCompound) event.getData().getTag(Constants.MOD_ID); - if (tag == null || !tag.hasKey("retrogen") || Config.forceRetrogen) { - ChunkCoords coords = new ChunkCoords(event.getChunk()); - chunkRegenList.put(coords.dimension, coords); + NBTTagCompound eventData = event.getData(); + if (eventData.hasKey(Constants.MOD_ID)) { + NBTTagCompound tag = (NBTTagCompound) eventData.getTag(Constants.MOD_ID); + if (!tag.hasKey("retrogen") || Config.forceRetrogen) { + ChunkCoords coords = new ChunkCoords(event.getChunk()); + chunkRegenList.put(coords.dimension, coords); + } } } } diff --git a/src/main/java/forestry/core/blocks/BlockBase.java b/src/main/java/forestry/core/blocks/BlockBase.java index 0b889332a..e4082e1d2 100644 --- a/src/main/java/forestry/core/blocks/BlockBase.java +++ b/src/main/java/forestry/core/blocks/BlockBase.java @@ -10,8 +10,22 @@ ******************************************************************************/ package forestry.core.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.ISpriteRegister; +import forestry.api.core.IStateMapperRegister; +import forestry.api.core.ITextureManager; +import forestry.core.circuits.ISocketable; +import forestry.core.proxy.Proxies; +import forestry.core.render.MachineParticleCallback; +import forestry.core.render.MachineStateMapper; +import forestry.core.render.ParticleHelper; +import forestry.core.tiles.TileBase; +import forestry.core.tiles.TileForestry; +import forestry.core.tiles.TileUtil; +import forestry.core.utils.InventoryUtil; import net.minecraft.block.BlockHorizontal; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; @@ -36,45 +50,29 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; +import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - +import net.minecraftforge.fluids.FluidActionResult; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.ISpriteRegister; -import forestry.api.core.IStateMapperRegister; -import forestry.api.core.ITextureManager; -import forestry.core.circuits.ISocketable; -import forestry.core.proxy.Proxies; -import forestry.core.render.MachineParticleCallback; -import forestry.core.render.MachineStateMapper; -import forestry.core.render.ParticleHelper; -import forestry.core.tiles.TileBase; -import forestry.core.tiles.TileForestry; -import forestry.core.tiles.TileUtil; -import forestry.core.utils.InventoryUtil; - public class BlockBase

& IBlockType & IStringSerializable> extends BlockForestry implements IItemModelRegister, ISpriteRegister, IStateMapperRegister, IBlockRotatable { - /** use this instead of {@link BlockHorizontal#FACING} so the blocks rotate in a circle instead of NSWE order. */ + /** + * use this instead of {@link BlockHorizontal#FACING} so the blocks rotate in a circle instead of NSWE order. + */ public static final PropertyEnum FACING = PropertyEnum.create("facing", EnumFacing.class, EnumFacing.NORTH, EnumFacing.EAST, EnumFacing.SOUTH, EnumFacing.WEST, EnumFacing.DOWN, EnumFacing.UP); private final boolean hasTESR; private final boolean hasCustom; - @Nonnull public final P blockType; - /* PROPERTIES */ - private final ParticleHelper.Callback particleCallback; - protected final BlockStateContainer blockState; - public BlockBase(@Nonnull P blockType, Material material) { + public BlockBase(P blockType, Material material) { super(material); this.blockType = blockType; @@ -87,11 +85,11 @@ public class BlockBase

& IBlockType & IStringSerializable> ext this.blockState = this.createBlockState(); IBlockState state = this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH); this.setDefaultState(state); - + particleCallback = new MachineParticleCallback<>(this, blockType); } - - public BlockBase(@Nonnull P blockType) { + + public BlockBase(P blockType) { this(blockType, Material.IRON); } @@ -114,18 +112,19 @@ public class BlockBase

& IBlockType & IStringSerializable> ext } } - @Nonnull + private IMachineProperties getDefinition() { return blockType.getMachineProperties(); } + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { IMachineProperties definition = getDefinition(); return definition.getBoundingBox(pos, blockState); } - @Nonnull + @Override @SideOnly(Side.CLIENT) public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) { @@ -147,16 +146,20 @@ public class BlockBase

& IBlockType & IStringSerializable> ext } /* INTERACTION */ + @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { TileBase tile = TileUtil.getTile(worldIn, pos, TileBase.class); if (tile != null) { if (TileUtil.isUsableByPlayer(playerIn, tile)) { + ItemStack heldItem = playerIn.getHeldItem(hand); if (!playerIn.isSneaking()) { - if (tile.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side)) { - IFluidHandler tileFluidHandler = tile.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side); - if (FluidUtil.interactWithFluidHandler(heldItem, tileFluidHandler, playerIn)) { + if (tile.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, facing)) { + IFluidHandler tileFluidHandler = tile.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, facing); + FluidActionResult fluidActionResult = FluidUtil.interactWithFluidHandler(heldItem, tileFluidHandler, playerIn); + if (fluidActionResult.isSuccess()) { + playerIn.setHeldItem(hand, fluidActionResult.getResult()); return true; } } @@ -180,7 +183,7 @@ public class BlockBase

& IBlockType & IStringSerializable> ext } protected EnumFacing getPlacementRotation(EntityPlayer player, World world, BlockPos pos, EnumFacing side) { - int l = MathHelper.floor_double(player.rotationYaw * 4F / 360F + 0.5D) & 3; + int l = MathHelper.floor(player.rotationYaw * 4F / 360F + 0.5D) & 3; if (l == 1) { return EnumFacing.EAST; } @@ -224,19 +227,19 @@ public class BlockBase

& IBlockType & IStringSerializable> ext public void registerModel(Item item, IModelManager manager) { blockType.getMachineProperties().registerModel(item, manager); } - + /* STATES */ @Override @SideOnly(Side.CLIENT) public void registerStateMapper() { Proxies.render.registerStateMapper(this, new MachineStateMapper<>(blockType)); } - + @Override - public boolean isFullCube(IBlockState state){ + public boolean isFullCube(IBlockState state) { IMachineProperties definition = getDefinition(); - return definition.isFullCube(state); - } + return definition.isFullCube(state); + } @Override protected BlockStateContainer createBlockState() { @@ -252,7 +255,7 @@ public class BlockBase

& IBlockType & IStringSerializable> ext public int getMetaFromState(IBlockState state) { return state.getValue(FACING).getIndex(); } - + @Override public BlockStateContainer getBlockState() { return this.blockState; @@ -277,9 +280,9 @@ public class BlockBase

& IBlockType & IStringSerializable> ext /* Particles */ @SideOnly(Side.CLIENT) @Override - public boolean addHitEffects(IBlockState state, World worldObj, RayTraceResult target, ParticleManager effectRenderer) { + public boolean addHitEffects(IBlockState state, World world, RayTraceResult target, ParticleManager effectRenderer) { if (blockType.getMachineProperties() instanceof IMachinePropertiesTesr) { - return ParticleHelper.addBlockHitEffects(worldObj, target.getBlockPos(), target.sideHit, effectRenderer, particleCallback); + return ParticleHelper.addBlockHitEffects(world, target.getBlockPos(), target.sideHit, effectRenderer, particleCallback); } return false; } diff --git a/src/main/java/forestry/core/blocks/BlockBogEarth.java b/src/main/java/forestry/core/blocks/BlockBogEarth.java index dafc3309f..131acd3d8 100644 --- a/src/main/java/forestry/core/blocks/BlockBogEarth.java +++ b/src/main/java/forestry/core/blocks/BlockBogEarth.java @@ -10,11 +10,15 @@ ******************************************************************************/ package forestry.core.blocks; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Random; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; +import forestry.core.PluginCore; +import forestry.core.config.Constants; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; @@ -28,20 +32,14 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; -import forestry.core.PluginCore; -import forestry.core.config.Constants; - /** * bog earth, which becomes peat */ @@ -53,14 +51,13 @@ public class BlockBogEarth extends Block implements IItemModelRegister, IBlockWi BOG_EARTH("bog_earth"), PEAT("peat"); - @Nonnull + private final String name; - SoilType(@Nonnull String name) { + SoilType(String name) { this.name = name; } - - @Nonnull + @Override public String getName() { return name; @@ -84,7 +81,7 @@ public class BlockBogEarth extends Block implements IItemModelRegister, IBlockWi setDefaultState(this.blockState.getBaseState().withProperty(MATURITY, 0)); } - + @Override public int getMetaFromState(IBlockState state) { return state.getValue(MATURITY); @@ -166,8 +163,8 @@ public class BlockBogEarth extends Block implements IItemModelRegister, IBlockWi } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this, 1, 0)); + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { + list.add(new ItemStack(this, 1, 0)); } /* MODELS */ diff --git a/src/main/java/forestry/core/blocks/BlockForestry.java b/src/main/java/forestry/core/blocks/BlockForestry.java index 471db69e9..f1f571575 100644 --- a/src/main/java/forestry/core/blocks/BlockForestry.java +++ b/src/main/java/forestry/core/blocks/BlockForestry.java @@ -59,14 +59,16 @@ public abstract class BlockForestry extends Block implements IItemModelRegister, public void onNeighborChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { super.onNeighborChange(world, pos, neighbor); - try { - TileEntity tile = world.getTileEntity(pos); - if (tile instanceof TileForestry) { - ((TileForestry) tile).onNeighborTileChange(world, pos, neighbor); + if (world instanceof World) { + try { + TileEntity tile = world.getTileEntity(pos); + if (tile instanceof TileForestry) { + ((TileForestry) tile).onNeighborTileChange((World) world, pos, neighbor); + } + } catch (StackOverflowError error) { + Log.error("Stack Overflow Error in BlockForestry.onNeighborChange()", error); + throw error; } - } catch (StackOverflowError error) { - Log.error("Stack Overflow Error in BlockForestry.onNeighborChange()", error); - throw error; } } } diff --git a/src/main/java/forestry/core/blocks/BlockHumus.java b/src/main/java/forestry/core/blocks/BlockHumus.java index 33f2c8f27..fd2347706 100644 --- a/src/main/java/forestry/core/blocks/BlockHumus.java +++ b/src/main/java/forestry/core/blocks/BlockHumus.java @@ -4,6 +4,10 @@ import java.util.Collections; import java.util.List; import java.util.Random; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; +import forestry.core.config.Constants; import net.minecraft.block.Block; import net.minecraft.block.BlockLog; import net.minecraft.block.IGrowable; @@ -18,20 +22,15 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.EnumPlantType; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; -import forestry.core.config.Constants; - public class BlockHumus extends Block implements IItemModelRegister { private static final int degradeDelimiter = 3; public static final PropertyInteger DEGRADE = PropertyInteger.create("degrade", 0, degradeDelimiter); // degradation level of humus @@ -125,11 +124,7 @@ public class BlockHumus extends Block implements IItemModelRegister { @Override public boolean canSustainPlant(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing direction, IPlantable plantable) { EnumPlantType plantType = plantable.getPlantType(world, pos); - if (plantType != EnumPlantType.Crop && plantType != EnumPlantType.Plains) { - return false; - } - - return true; + return plantType == EnumPlantType.Crop || plantType == EnumPlantType.Plains; } @Override @@ -138,8 +133,8 @@ public class BlockHumus extends Block implements IItemModelRegister { } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { - itemList.add(new ItemStack(this)); + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { + list.add(new ItemStack(this)); } /* MODELS */ diff --git a/src/main/java/forestry/core/blocks/BlockRegistry.java b/src/main/java/forestry/core/blocks/BlockRegistry.java index 989136a76..cf03694f6 100644 --- a/src/main/java/forestry/core/blocks/BlockRegistry.java +++ b/src/main/java/forestry/core/blocks/BlockRegistry.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.blocks; +import javax.annotation.Nullable; + import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; @@ -21,7 +23,7 @@ import forestry.core.proxy.Proxies; import forestry.plugins.PluginManager; public abstract class BlockRegistry { - protected void registerBlock(T block, ItemBlock itemBlock, String name) { + protected void registerBlock(T block, @Nullable ItemBlock itemBlock, String name) { if (PluginManager.getStage() != PluginManager.Stage.REGISTER) { throw new RuntimeException("Tried to register Block outside of REGISTER"); } diff --git a/src/main/java/forestry/core/blocks/BlockResourceOre.java b/src/main/java/forestry/core/blocks/BlockResourceOre.java index e324b2d7e..27cc170c7 100644 --- a/src/main/java/forestry/core/blocks/BlockResourceOre.java +++ b/src/main/java/forestry/core/blocks/BlockResourceOre.java @@ -10,11 +10,13 @@ ******************************************************************************/ package forestry.core.blocks; -import com.google.common.base.Predicate; - import java.util.ArrayList; import java.util.List; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; +import forestry.core.PluginCore; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; @@ -23,27 +25,17 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; -import forestry.core.PluginCore; - public class BlockResourceOre extends Block implements IItemModelRegister, IBlockWithMeta { - public static final PropertyEnum ORE_RESOURCES = PropertyEnum.create("resource", EnumResourceType.class, new Predicate(){ - @Override - public boolean apply(EnumResourceType input) { - return input.hasOre(); - } - }); - + public static final PropertyEnum ORE_RESOURCES = PropertyEnum.create("resource", EnumResourceType.class, input -> input != null && input.hasOre()); + public BlockResourceOre() { super(Material.ROCK); setHardness(3F); @@ -70,9 +62,9 @@ public class BlockResourceOre extends Block implements IItemModelRegister, IBloc @Override public void dropBlockAsItemWithChance(World world, BlockPos pos, IBlockState state, float chance, int fortune) { super.dropBlockAsItemWithChance(world, pos, state, chance, fortune); - + if (state.getValue(ORE_RESOURCES) == EnumResourceType.APATITE) { - this.dropXpOnBlockBreak(world, pos, MathHelper.getRandomIntegerInRange(world.rand, 1, 4)); + this.dropXpOnBlockBreak(world, pos, MathHelper.getInt(world.rand, 1, 4)); } } @@ -112,9 +104,9 @@ public class BlockResourceOre extends Block implements IItemModelRegister, IBloc } @Override - public void getSubBlocks(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (EnumResourceType resourceType : ORE_RESOURCES.getAllowedValues()) { - itemList.add(get(resourceType, 1)); + list.add(get(resourceType, 1)); } } diff --git a/src/main/java/forestry/core/blocks/BlockResourceStorage.java b/src/main/java/forestry/core/blocks/BlockResourceStorage.java index ee6d07725..84293d18e 100644 --- a/src/main/java/forestry/core/blocks/BlockResourceStorage.java +++ b/src/main/java/forestry/core/blocks/BlockResourceStorage.java @@ -1,6 +1,8 @@ package forestry.core.blocks; -import java.util.List; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; @@ -9,13 +11,10 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; - public class BlockResourceStorage extends Block implements IItemModelRegister, IBlockWithMeta { public static final PropertyEnum STORAGE_RESOURCES = PropertyEnum.create("resource", EnumResourceType.class); @@ -26,7 +25,7 @@ public class BlockResourceStorage extends Block implements IItemModelRegister, I setCreativeTab(CreativeTabForestry.tabForestry); setDefaultState(this.blockState.getBaseState().withProperty(STORAGE_RESOURCES, EnumResourceType.APATITE)); } - + @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, STORAGE_RESOURCES); @@ -41,11 +40,11 @@ public class BlockResourceStorage extends Block implements IItemModelRegister, I public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(STORAGE_RESOURCES, EnumResourceType.VALUES[meta]); } - + @Override - public void getSubBlocks(Item item, CreativeTabs creativeTabs, List itemList) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (EnumResourceType resourceType : EnumResourceType.VALUES) { - itemList.add(get(resourceType)); + list.add(get(resourceType)); } } @@ -53,11 +52,11 @@ public class BlockResourceStorage extends Block implements IItemModelRegister, I public int damageDropped(IBlockState state) { return getMetaFromState(state); } - + @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { - for(EnumResourceType resourceType : EnumResourceType.VALUES){ + for (EnumResourceType resourceType : EnumResourceType.VALUES) { manager.registerItemModel(item, resourceType.getMeta(), "storage/" + resourceType.getName()); } } diff --git a/src/main/java/forestry/core/blocks/BlockStructure.java b/src/main/java/forestry/core/blocks/BlockStructure.java index d3ae8c686..547866bec 100644 --- a/src/main/java/forestry/core/blocks/BlockStructure.java +++ b/src/main/java/forestry/core/blocks/BlockStructure.java @@ -48,7 +48,7 @@ public abstract class BlockStructure extends BlockForestry { protected long previousMessageTick = 0; @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (playerIn.isSneaking()) { return false; } @@ -61,23 +61,24 @@ public abstract class BlockStructure extends BlockForestry { MultiblockTileEntityForestry part = (MultiblockTileEntityForestry) tile; IMultiblockController controller = part.getMultiblockLogic().getController(); + ItemStack heldItem = playerIn.getHeldItem(hand); // If the player's hands are empty and they right-click on a multiblock, they get a // multiblock-debugging message if the machine is not assembled. - if (heldItem == null) { + if (heldItem.isEmpty()) { if (controller != null) { if (!controller.isAssembled()) { String validationError = controller.getLastValidationError(); if (validationError != null) { long tick = worldIn.getTotalWorldTime(); if (tick > previousMessageTick + 20) { - playerIn.addChatMessage(new TextComponentString(validationError)); + playerIn.sendMessage(new TextComponentString(validationError)); previousMessageTick = tick; } return true; } } } else { - playerIn.addChatMessage(new TextComponentTranslation("for.multiblock.error.notConnected")); + playerIn.sendMessage(new TextComponentTranslation("for.multiblock.error.notConnected")); return true; } } diff --git a/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java b/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java index 7480bfa73..d11c9e636 100644 --- a/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java +++ b/src/main/java/forestry/core/blocks/BlockTypeCoreTesr.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.core.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; - import forestry.core.config.Constants; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileAnalyzer; import forestry.core.tiles.TileEscritoire; import forestry.core.tiles.TileForestry; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; public enum BlockTypeCoreTesr implements IBlockTypeTesr { ANALYZER(TileAnalyzer.class, "analyzer", Proxies.render.getRendererAnalyzer()), @@ -27,14 +25,12 @@ public enum BlockTypeCoreTesr implements IBlockTypeTesr { public static final BlockTypeCoreTesr[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeCoreTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer) { + BlockTypeCoreTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer) { this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, Constants.MOD_ID + ":blocks/" + name + ".0"); } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/core/blocks/IBlockType.java b/src/main/java/forestry/core/blocks/IBlockType.java index 375bebd64..b2dd1a4fc 100644 --- a/src/main/java/forestry/core/blocks/IBlockType.java +++ b/src/main/java/forestry/core/blocks/IBlockType.java @@ -1,10 +1,7 @@ package forestry.core.blocks; -import javax.annotation.Nonnull; - import net.minecraft.util.IStringSerializable; public interface IBlockType extends IStringSerializable { - @Nonnull IMachineProperties getMachineProperties(); } diff --git a/src/main/java/forestry/core/blocks/IBlockTypeTesr.java b/src/main/java/forestry/core/blocks/IBlockTypeTesr.java index 1bbcef9ef..b44ee61ad 100644 --- a/src/main/java/forestry/core/blocks/IBlockTypeTesr.java +++ b/src/main/java/forestry/core/blocks/IBlockTypeTesr.java @@ -1,9 +1,6 @@ package forestry.core.blocks; -import javax.annotation.Nonnull; - public interface IBlockTypeTesr extends IBlockType { @Override - @Nonnull IMachineProperties getMachineProperties(); } diff --git a/src/main/java/forestry/core/blocks/IColoredBlock.java b/src/main/java/forestry/core/blocks/IColoredBlock.java index 984701a4e..e1de53b34 100644 --- a/src/main/java/forestry/core/blocks/IColoredBlock.java +++ b/src/main/java/forestry/core/blocks/IColoredBlock.java @@ -1,9 +1,11 @@ package forestry.core.blocks; +import javax.annotation.Nullable; + import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; public interface IColoredBlock { - int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex); + int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex); } diff --git a/src/main/java/forestry/core/blocks/IMachineProperties.java b/src/main/java/forestry/core/blocks/IMachineProperties.java index d0b30495b..bd1e90ef0 100644 --- a/src/main/java/forestry/core/blocks/IMachineProperties.java +++ b/src/main/java/forestry/core/blocks/IMachineProperties.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.core.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; @@ -27,10 +27,8 @@ import forestry.api.core.IModelManager; import forestry.core.tiles.TileForestry; public interface IMachineProperties extends IStringSerializable { - @Nonnull String getTeIdent(); - - @Nonnull + Class getTeClass(); /** @@ -40,18 +38,16 @@ public interface IMachineProperties extends IStringSeria void registerModel(Item item, IModelManager manager); - @Nonnull TileEntity createTileEntity(); - void setBlock(@Nonnull Block block); + void setBlock( Block block); + @Nullable Block getBlock(); boolean isFullCube(IBlockState state); - @Nonnull - AxisAlignedBB getBoundingBox(@Nonnull BlockPos pos, @Nonnull IBlockState state); - - @Nonnull - RayTraceResult collisionRayTrace(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Vec3d startVec, @Nonnull Vec3d endVec); + AxisAlignedBB getBoundingBox( BlockPos pos, IBlockState state); + + RayTraceResult collisionRayTrace( World world, BlockPos pos, Vec3d startVec, Vec3d endVec); } diff --git a/src/main/java/forestry/core/blocks/IMachinePropertiesTesr.java b/src/main/java/forestry/core/blocks/IMachinePropertiesTesr.java index 143c9ec87..c61b3eea1 100644 --- a/src/main/java/forestry/core/blocks/IMachinePropertiesTesr.java +++ b/src/main/java/forestry/core/blocks/IMachinePropertiesTesr.java @@ -10,9 +10,9 @@ ******************************************************************************/ package forestry.core.blocks; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import javax.annotation.Nullable; -import javax.annotation.Nonnull; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import forestry.core.tiles.TileForestry; @@ -21,8 +21,8 @@ public interface IMachinePropertiesTesr extends IMachine /** * @return The renderer from the machine */ + @Nullable TileEntitySpecialRenderer getRenderer(); - @Nonnull String getParticleTextureLocation(); } diff --git a/src/main/java/forestry/core/blocks/MachineProperties.java b/src/main/java/forestry/core/blocks/MachineProperties.java index 76dcde25f..fcf9d4ac8 100644 --- a/src/main/java/forestry/core/blocks/MachineProperties.java +++ b/src/main/java/forestry/core/blocks/MachineProperties.java @@ -1,8 +1,11 @@ package forestry.core.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; +import forestry.api.core.IModelManager; +import forestry.core.tiles.TileForestry; +import forestry.core.utils.BlockUtil; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; @@ -12,35 +15,25 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; - import net.minecraftforge.fml.common.registry.GameRegistry; -import forestry.api.core.IModelManager; -import forestry.core.tiles.TileForestry; -import forestry.core.utils.BlockUtil; -import forestry.core.utils.ItemStackUtil; - public class MachineProperties implements IMachineProperties { - @Nonnull private final String name; - @Nonnull private final String teIdent; - @Nonnull private final Class teClass; - @Nonnull private final AxisAlignedBB boundingBox; @Nullable private Block block; - public MachineProperties(@Nonnull Class teClass, @Nonnull String name) { + public MachineProperties(Class teClass, String name) { this("forestry." + name, teClass, name, new AxisAlignedBB(0, 0, 0, 1, 1, 1)); } - public MachineProperties(@Nonnull Class teClass, @Nonnull String name, @Nonnull AxisAlignedBB boundingBox) { + public MachineProperties(Class teClass, String name, AxisAlignedBB boundingBox) { this("forestry." + name, teClass, name, boundingBox); } - private MachineProperties(@Nonnull String teIdent, @Nonnull Class teClass, @Nonnull String name, @Nonnull AxisAlignedBB boundingBox) { + private MachineProperties(String teIdent, Class teClass, String name, AxisAlignedBB boundingBox) { this.teIdent = teIdent; this.teClass = teClass; this.name = name; @@ -48,7 +41,7 @@ public class MachineProperties implements IMachineProper } @Override - public void setBlock(@Nonnull Block block) { + public void setBlock(Block block) { this.block = block; } @@ -58,15 +51,13 @@ public class MachineProperties implements IMachineProper return block; } - @Nonnull @Override - public AxisAlignedBB getBoundingBox(@Nonnull BlockPos pos, @Nonnull IBlockState state) { + public AxisAlignedBB getBoundingBox(BlockPos pos, IBlockState state) { return boundingBox; } - @Nonnull @Override - public RayTraceResult collisionRayTrace(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull Vec3d startVec, @Nonnull Vec3d endVec) { + public RayTraceResult collisionRayTrace(World world, BlockPos pos, Vec3d startVec, Vec3d endVec) { return BlockUtil.collisionRayTrace(pos, startVec, endVec, boundingBox); } @@ -76,12 +67,11 @@ public class MachineProperties implements IMachineProper } @Override - public void registerModel(@Nonnull Item item, @Nonnull IModelManager manager) { + public void registerModel(Item item, IModelManager manager) { String identifier = ItemStackUtil.getItemNameFromRegistry(item).getResourcePath(); manager.registerItemModel(item, 0, identifier); } - @Nonnull @Override public TileEntity createTileEntity() { try { @@ -91,19 +81,16 @@ public class MachineProperties implements IMachineProper } } - @Nonnull @Override public String getTeIdent() { return teIdent; } - @Nonnull @Override public Class getTeClass() { return teClass; } - @Nonnull @Override public String getName() { return name; diff --git a/src/main/java/forestry/core/blocks/MachinePropertiesTesr.java b/src/main/java/forestry/core/blocks/MachinePropertiesTesr.java index 61d1ae716..b4d54b7a4 100644 --- a/src/main/java/forestry/core/blocks/MachinePropertiesTesr.java +++ b/src/main/java/forestry/core/blocks/MachinePropertiesTesr.java @@ -1,43 +1,42 @@ package forestry.core.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; +import forestry.core.tiles.TileForestry; +import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.math.AxisAlignedBB; - import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; -import forestry.core.tiles.TileForestry; - public class MachinePropertiesTesr extends MachineProperties implements IMachinePropertiesTesr { @Nullable private final TileEntitySpecialRenderer renderer; - @Nonnull + private final String particleTextureLocation; private final boolean isFullCube; - public MachinePropertiesTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nonnull String particleTextureLocation) { + public MachinePropertiesTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, String particleTextureLocation) { this(teClass, name, renderer, particleTextureLocation, true); } - public MachinePropertiesTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nonnull AxisAlignedBB boundingBox, @Nonnull String particleTextureLocation) { + public MachinePropertiesTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, AxisAlignedBB boundingBox, String particleTextureLocation) { this(teClass, name, renderer, boundingBox, particleTextureLocation, true); } - - public MachinePropertiesTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nonnull String particleTextureLocation, boolean isFullCube) { + + public MachinePropertiesTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, String particleTextureLocation, boolean isFullCube) { super(teClass, name); this.renderer = renderer; this.particleTextureLocation = particleTextureLocation; this.isFullCube = isFullCube; } - public MachinePropertiesTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nonnull AxisAlignedBB boundingBox, @Nonnull String particleTextureLocation, boolean isFullCube) { + public MachinePropertiesTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, AxisAlignedBB boundingBox, String particleTextureLocation, boolean isFullCube) { super(teClass, name, boundingBox); this.renderer = renderer; this.particleTextureLocation = particleTextureLocation; @@ -53,21 +52,21 @@ public class MachinePropertiesTesr extends MachineProper @Override public void registerTileEntity() { super.registerTileEntity(); - if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { + Block block = getBlock(); + if (FMLCommonHandler.instance().getSide() == Side.CLIENT && renderer != null && block != null) { ClientRegistry.bindTileEntitySpecialRenderer(getTeClass(), renderer); - Item item = Item.getItemFromBlock(getBlock()); - if (item != null) { + Item item = Item.getItemFromBlock(block); + if (item != Items.AIR) { ForgeHooksClient.registerTESRItemStack(item, 0, getTeClass()); } } } - - @Nonnull + @Override public String getParticleTextureLocation() { return particleTextureLocation; } - + @Override public boolean isFullCube(IBlockState state) { return isFullCube; diff --git a/src/main/java/forestry/core/blocks/package-info.java b/src/main/java/forestry/core/blocks/package-info.java new file mode 100644 index 000000000..7624a90a5 --- /dev/null +++ b/src/main/java/forestry/core/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/blocks/propertys/PropertyAllele.java b/src/main/java/forestry/core/blocks/properties/PropertyAllele.java similarity index 97% rename from src/main/java/forestry/core/blocks/propertys/PropertyAllele.java rename to src/main/java/forestry/core/blocks/properties/PropertyAllele.java index 2b9256e85..c0a3f32ab 100644 --- a/src/main/java/forestry/core/blocks/propertys/PropertyAllele.java +++ b/src/main/java/forestry/core/blocks/properties/PropertyAllele.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.blocks.propertys; +package forestry.core.blocks.properties; import com.google.common.base.Optional; diff --git a/src/main/java/forestry/core/blocks/propertys/UnlistedBlockAccess.java b/src/main/java/forestry/core/blocks/properties/UnlistedBlockAccess.java similarity index 87% rename from src/main/java/forestry/core/blocks/propertys/UnlistedBlockAccess.java rename to src/main/java/forestry/core/blocks/properties/UnlistedBlockAccess.java index 52a408c37..8df4f1d7a 100644 --- a/src/main/java/forestry/core/blocks/propertys/UnlistedBlockAccess.java +++ b/src/main/java/forestry/core/blocks/properties/UnlistedBlockAccess.java @@ -8,14 +8,14 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.blocks.propertys; +package forestry.core.blocks.properties; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.property.IUnlistedProperty; public final class UnlistedBlockAccess implements IUnlistedProperty { - public static UnlistedBlockAccess BLOCKACCESS = new UnlistedBlockAccess(); + public static final UnlistedBlockAccess BLOCKACCESS = new UnlistedBlockAccess(); @Override public String getName() { @@ -34,6 +34,6 @@ public final class UnlistedBlockAccess implements IUnlistedProperty { - public static UnlistedBlockPos POS = new UnlistedBlockPos(); + public static final UnlistedBlockPos POS = new UnlistedBlockPos(); @Override public String getName() { @@ -34,6 +34,6 @@ public final class UnlistedBlockPos implements IUnlistedProperty { @Override public String valueToString(final BlockPos value) { - return null; + return value.toString(); } } \ No newline at end of file diff --git a/src/main/java/forestry/core/blocks/properties/package-info.java b/src/main/java/forestry/core/blocks/properties/package-info.java new file mode 100644 index 000000000..f948838c8 --- /dev/null +++ b/src/main/java/forestry/core/blocks/properties/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.blocks.properties; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/capabilities/NullStorage.java b/src/main/java/forestry/core/capabilities/NullStorage.java index a755ef119..c71a6a4b1 100644 --- a/src/main/java/forestry/core/capabilities/NullStorage.java +++ b/src/main/java/forestry/core/capabilities/NullStorage.java @@ -1,11 +1,14 @@ package forestry.core.capabilities; +import javax.annotation.Nullable; + import net.minecraft.nbt.NBTBase; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; public class NullStorage implements Capability.IStorage { @Override + @Nullable public NBTBase writeNBT(Capability capability, T instance, EnumFacing side) { return null; } diff --git a/src/main/java/forestry/core/capabilities/package-info.java b/src/main/java/forestry/core/capabilities/package-info.java new file mode 100644 index 000000000..e151a385e --- /dev/null +++ b/src/main/java/forestry/core/capabilities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.capabilities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/circuits/Circuit.java b/src/main/java/forestry/core/circuits/Circuit.java index bdb8c7566..88396319b 100755 --- a/src/main/java/forestry/core/circuits/Circuit.java +++ b/src/main/java/forestry/core/circuits/Circuit.java @@ -17,7 +17,6 @@ import forestry.api.circuits.ICircuit; import forestry.core.utils.Translator; public abstract class Circuit implements ICircuit { - private final String uid; protected Circuit(String uid) { @@ -51,37 +50,4 @@ public abstract class Circuit implements ICircuit { i++; } } - - public static ICircuit energyElectricChoke1; - public static ICircuit energyElectricEfficiency1; - public static ICircuit energyElectricBoost1; - public static ICircuit energyElectricBoost2; - - public static ICircuit farmArborealManaged; - public static ICircuit farmShroomManaged; - public static ICircuit farmCerealManaged; - public static ICircuit farmVegetableManaged; - public static ICircuit farmPeatManaged; - public static ICircuit farmSucculentManaged; - public static ICircuit farmPoaleManaged; - public static ICircuit farmFungal; - public static ICircuit farmInfernalManaged; - public static ICircuit farmGourdManaged; - - public static ICircuit farmShroomManual; - public static ICircuit farmCerealManual; - public static ICircuit farmVegetableManual; - public static ICircuit farmPeatManual; - public static ICircuit farmSucculentManual; - public static ICircuit farmPoalesManual; - public static ICircuit farmGourdManual; - public static ICircuit farmCocoaManual; - - public static ICircuit farmOrchardManual; - public static ICircuit farmRubberManual; - public static ICircuit farmEnderManaged; - - public static ICircuit machineSpeedUpgrade1; - public static ICircuit machineSpeedUpgrade2; - public static ICircuit machineEfficiencyUpgrade1; } diff --git a/src/main/java/forestry/core/circuits/CircuitRegistry.java b/src/main/java/forestry/core/circuits/CircuitRegistry.java index e6c4da321..75b86b87f 100755 --- a/src/main/java/forestry/core/circuits/CircuitRegistry.java +++ b/src/main/java/forestry/core/circuits/CircuitRegistry.java @@ -38,11 +38,11 @@ public class CircuitRegistry implements ICircuitRegistry { @Override public ICircuitLibrary getCircuitLibrary(World world, String playerName) { - CircuitLibrary library = (CircuitLibrary) world.loadItemData(CircuitLibrary.class, "CircuitLibrary_" + playerName); + CircuitLibrary library = (CircuitLibrary) world.loadData(CircuitLibrary.class, "CircuitLibrary_" + playerName); if (library == null) { library = new CircuitLibrary(playerName); - world.setItemData("CircuitLibrary_" + playerName, library); + world.setData("CircuitLibrary_" + playerName, library); } return library; @@ -100,7 +100,7 @@ public class CircuitRegistry implements ICircuitRegistry { @Override public boolean isChipset(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == PluginCore.items.circuitboards; + return itemstack.getItem() == PluginCore.items.circuitboards; } @Override diff --git a/src/main/java/forestry/core/circuits/Circuits.java b/src/main/java/forestry/core/circuits/Circuits.java new file mode 100644 index 000000000..8ae064869 --- /dev/null +++ b/src/main/java/forestry/core/circuits/Circuits.java @@ -0,0 +1,34 @@ +package forestry.core.circuits; + +import forestry.api.circuits.ICircuit; + +public class Circuits { + public static ICircuit energyElectricChoke1; + public static ICircuit energyElectricEfficiency1; + public static ICircuit energyElectricBoost1; + public static ICircuit energyElectricBoost2; + public static ICircuit farmArborealManaged; + public static ICircuit farmShroomManaged; + public static ICircuit farmCerealManaged; + public static ICircuit farmVegetableManaged; + public static ICircuit farmPeatManaged; + public static ICircuit farmSucculentManaged; + public static ICircuit farmPoaleManaged; + public static ICircuit farmFungal; + public static ICircuit farmInfernalManaged; + public static ICircuit farmGourdManaged; + public static ICircuit farmShroomManual; + public static ICircuit farmCerealManual; + public static ICircuit farmVegetableManual; + public static ICircuit farmPeatManual; + public static ICircuit farmSucculentManual; + public static ICircuit farmPoalesManual; + public static ICircuit farmGourdManual; + public static ICircuit farmCocoaManual; + public static ICircuit farmOrchardManual; + public static ICircuit farmRubberManual; + public static ICircuit farmEnderManaged; + public static ICircuit machineSpeedUpgrade1; + public static ICircuit machineSpeedUpgrade2; + public static ICircuit machineEfficiencyUpgrade1; +} diff --git a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java index fca543ad1..40807b65c 100755 --- a/src/main/java/forestry/core/circuits/ContainerSolderingIron.java +++ b/src/main/java/forestry/core/circuits/ContainerSolderingIron.java @@ -61,13 +61,13 @@ public class ContainerSolderingIron extends ContainerItemInventory itemList) { - itemList.add(createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.ENHANCED, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{})); - itemList.add(createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[]{})); + public void getSubItems(Item itemIn, CreativeTabs tab, NonNullList subItems) { + subItems.add(createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[]{})); + subItems.add(createCircuitboard(EnumCircuitBoardType.ENHANCED, null, new ICircuit[]{})); + subItems.add(createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{})); + subItems.add(createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[]{})); } /* MODELS*/ @@ -85,21 +87,12 @@ public class ItemCircuitBoard extends ItemForestry implements IColoredItem { } } - public static ItemStack createCircuitboard(EnumCircuitBoardType type, ICircuitLayout layout, ICircuit[] circuits) { + public static ItemStack createCircuitboard(EnumCircuitBoardType type, @Nullable ICircuitLayout layout, ICircuit[] circuits) { ItemStack chipset = PluginCore.items.circuitboards.get(type); - saveChipset(chipset, new CircuitBoard(type, layout, circuits)); - return chipset; - } - - private static void saveChipset(ItemStack itemstack, ICircuitBoard circuitboard) { - if (circuitboard == null) { - itemstack.setTagCompound(null); - return; - } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - circuitboard.writeToNBT(nbttagcompound); - itemstack.setTagCompound(nbttagcompound); + new CircuitBoard(type, layout, circuits).writeToNBT(nbttagcompound); + chipset.setTagCompound(nbttagcompound); + return chipset; } public ItemStack get(EnumCircuitBoardType type) { diff --git a/src/main/java/forestry/core/circuits/SolderManager.java b/src/main/java/forestry/core/circuits/SolderManager.java index e07215e61..ae6571aa2 100644 --- a/src/main/java/forestry/core/circuits/SolderManager.java +++ b/src/main/java/forestry/core/circuits/SolderManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.circuits; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -36,6 +37,7 @@ public class SolderManager implements ISolderManager { recipes.add(new CircuitRecipe(layout, resource, circuit)); } + @Nullable public static ICircuit getCircuit(ICircuitLayout layout, ItemStack resource) { CircuitRecipe circuitRecipe = getMatchingRecipe(layout, resource); if (circuitRecipe == null) { @@ -44,11 +46,8 @@ public class SolderManager implements ISolderManager { return circuitRecipe.getCircuit(); } + @Nullable public static CircuitRecipe getMatchingRecipe(ICircuitLayout layout, ItemStack resource) { - if (layout == null || resource == null) { - return null; - } - for (CircuitRecipe recipe : recipes) { if (recipe.matches(layout, resource)) { return recipe; diff --git a/src/main/java/forestry/core/circuits/package-info.java b/src/main/java/forestry/core/circuits/package-info.java new file mode 100644 index 000000000..889a8c961 --- /dev/null +++ b/src/main/java/forestry/core/circuits/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.circuits; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/climate/ClimateControl.java b/src/main/java/forestry/core/climate/ClimateControl.java index 73d08edb9..b153c5430 100644 --- a/src/main/java/forestry/core/climate/ClimateControl.java +++ b/src/main/java/forestry/core/climate/ClimateControl.java @@ -10,27 +10,25 @@ ******************************************************************************/ package forestry.core.climate; -import forestry.api.core.INbtReadable; -import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import net.minecraft.nbt.NBTTagCompound; - import java.io.IOException; import forestry.api.climate.IClimateControl; +import forestry.api.core.INbtReadable; +import forestry.api.core.INbtWritable; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.nbt.NBTTagCompound; public class ClimateControl implements IClimateControl, INbtWritable, INbtReadable, IStreamable { private float temperature; private float humidity; - + public ClimateControl() { temperature = 2.0F; humidity = 2.0F; } - + @Override public float getControlTemperature() { return temperature; @@ -43,30 +41,30 @@ public class ClimateControl implements IClimateControl, INbtWritable, INbtReadab @Override public void setControlTemperature(float temperature) { - if(temperature > 2.0F){ - temperature = 2.0F; - }else{ + if (temperature > 2.0F) { + this.temperature = 2.0F; + } else { this.temperature = temperature; } } @Override public void setControlHumidity(float humidity) { - if(humidity > 2.0F){ - humidity = 2.0F; - }else{ + if (humidity > 2.0F) { + this.humidity = 2.0F; + } else { this.humidity = humidity; } } - + @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeFloat(temperature); data.writeFloat(humidity); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { temperature = data.readFloat(); humidity = data.readFloat(); } diff --git a/src/main/java/forestry/core/climate/ClimateEventHandler.java b/src/main/java/forestry/core/climate/ClimateEventHandler.java index fbf917532..2eadd8977 100644 --- a/src/main/java/forestry/core/climate/ClimateEventHandler.java +++ b/src/main/java/forestry/core/climate/ClimateEventHandler.java @@ -13,6 +13,7 @@ package forestry.core.climate; import java.util.HashMap; import java.util.List; import java.util.Map; + import forestry.api.climate.IClimateRegion; import forestry.api.core.ForestryAPI; import net.minecraft.server.MinecraftServer; @@ -22,12 +23,12 @@ import net.minecraftforge.fml.common.gameevent.TickEvent; public class ClimateEventHandler { - Map serverTicks; + private final Map serverTicks; public ClimateEventHandler() { serverTicks = new HashMap<>(); } - + //Climate test mode /*public static Pair recalculateMinMaxCoords(Collection positions) { BlockPos minimumCoord = new BlockPos(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE); @@ -70,7 +71,7 @@ public class ClimateEventHandler { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer buffer = tessellator.getBuffer(); float partialTicks = event.getPartialTicks(); - EntityPlayer entityplayer = Minecraft.getMinecraft().thePlayer; + EntityPlayer entityplayer = Minecraft.getMinecraft().player; double d0 = entityplayer.lastTickPosX + (entityplayer.posX - entityplayer.lastTickPosX) * partialTicks; double d1 = entityplayer.lastTickPosY + (entityplayer.posY - entityplayer.lastTickPosY) * partialTicks; double d2 = entityplayer.lastTickPosZ + (entityplayer.posZ - entityplayer.lastTickPosZ) * partialTicks; @@ -79,7 +80,7 @@ public class ClimateEventHandler { GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.disableTexture2D(); GlStateManager.glLineWidth(5.0F); - World world = Minecraft.getMinecraft().theWorld; + World world = Minecraft.getMinecraft().world; List regions = ForestryAPI.climateManager.getRegions().get(Integer.valueOf(world.provider.getDimension())); for(IClimateRegion region : regions){ if(region != null){ @@ -153,23 +154,20 @@ public class ClimateEventHandler { World world = event.world; if (event.phase == TickEvent.Phase.END) { MinecraftServer server = world.getMinecraftServer(); - if(server != null){ - server.addScheduledTask(new Runnable() { - @Override - public void run() { - Integer dim = Integer.valueOf(event.world.provider.getDimension()); - if(!serverTicks.containsKey(dim)){ - serverTicks.put(dim, 1); - } - int ticks = serverTicks.get(dim); - Map> regions = ForestryAPI.climateManager.getRegions(); - if(regions != null && regions.containsKey(dim)){ - for(IClimateRegion region : regions.get(dim)){ - region.updateClimate(ticks); - } - } - serverTicks.put(dim, ticks+1); + if (server != null) { + server.addScheduledTask(() -> { + Integer dim = event.world.provider.getDimension(); + if (!serverTicks.containsKey(dim)) { + serverTicks.put(dim, 1); } + int ticks = serverTicks.get(dim); + Map> regions = ForestryAPI.climateManager.getRegions(); + if (regions.containsKey(dim)) { + for (IClimateRegion region : regions.get(dim)) { + region.updateClimate(ticks); + } + } + serverTicks.put(dim, ticks + 1); }); } } diff --git a/src/main/java/forestry/core/climate/ClimateManager.java b/src/main/java/forestry/core/climate/ClimateManager.java index 61f4dd57f..2b506f1ba 100644 --- a/src/main/java/forestry/core/climate/ClimateManager.java +++ b/src/main/java/forestry/core/climate/ClimateManager.java @@ -22,13 +22,12 @@ import forestry.api.climate.IClimateRegion; import forestry.api.climate.IClimateSourceProvider; import forestry.api.core.ForestryAPI; import forestry.core.DefaultClimateProvider; - import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -public class ClimateManager implements IClimateManager{ +public class ClimateManager implements IClimateManager { - protected Map> regions; + protected final Map> regions; private final Object regionsMutex; public ClimateManager() { @@ -38,18 +37,15 @@ public class ClimateManager implements IClimateManager{ @Override public void addRegion(IClimateRegion region) { - if(region == null){ - return; - } synchronized (regionsMutex) { - Integer dimensionID = Integer.valueOf(region.getWorld().provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + Integer dimensionID = region.getWorld().provider.getDimension(); + if (!regions.containsKey(dimensionID)) { this.regions.put(dimensionID, new ArrayList<>()); } List regions = this.regions.get(dimensionID); - if(!regions.contains(region)){ - for(BlockPos pos : region.getPositions().keySet()){ - if(getRegionForPos(region.getWorld(), pos) != null){ + if (!regions.contains(region)) { + for (BlockPos pos : region.getPositions().keySet()) { + if (getRegionForPos(region.getWorld(), pos) != null) { return; } } @@ -60,16 +56,13 @@ public class ClimateManager implements IClimateManager{ @Override public void removeRegion(IClimateRegion region) { - if(region == null){ - return; - } synchronized (regionsMutex) { - Integer dimensionID = Integer.valueOf(region.getWorld().provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + Integer dimensionID = region.getWorld().provider.getDimension(); + if (!regions.containsKey(dimensionID)) { this.regions.put(dimensionID, new ArrayList<>()); } List regions = this.regions.get(dimensionID); - if(regions.contains(region)){ + if (regions.contains(region)) { regions.remove(region); } } @@ -77,17 +70,14 @@ public class ClimateManager implements IClimateManager{ @Override public void removeSource(IClimateSourceProvider source) { - if(source == null){ - return; - } synchronized (regionsMutex) { - Integer dimensionID = Integer.valueOf(source.getWorldObj().provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + Integer dimensionID = source.getWorldObj().provider.getDimension(); + if (!regions.containsKey(dimensionID)) { regions.put(dimensionID, new ArrayList<>()); } IClimateRegion region = getRegionForPos(source.getWorldObj(), source.getCoordinates()); - if(region != null){ - if(region.getSources().contains(source.getClimateSource())){ + if (region != null) { + if (region.getSources().contains(source.getClimateSource())) { region.removeSource(source.getClimateSource()); } } @@ -96,17 +86,14 @@ public class ClimateManager implements IClimateManager{ @Override public void addSource(IClimateSourceProvider source) { - if(source == null){ - return; - } synchronized (regionsMutex) { - Integer dimensionID = Integer.valueOf(source.getWorldObj().provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + Integer dimensionID = source.getWorldObj().provider.getDimension(); + if (!regions.containsKey(dimensionID)) { regions.put(dimensionID, new ArrayList<>()); } IClimateRegion region = getRegionForPos(source.getWorldObj(), source.getCoordinates()); - if(region != null){ - if(!region.getSources().contains(source.getClimateSource())){ + if (region != null) { + if (!region.getSources().contains(source.getClimateSource())) { region.addSource(source.getClimateSource()); } } @@ -117,7 +104,7 @@ public class ClimateManager implements IClimateManager{ public float getTemperature(World world, BlockPos pos) { IClimatePosition position = ForestryAPI.climateManager.getPosition(world, pos); - if(position != null){ + if (position != null) { return position.getTemperature(); } return world.getBiome(pos).getTemperature(); @@ -127,7 +114,7 @@ public class ClimateManager implements IClimateManager{ public float getHumidity(World world, BlockPos pos) { IClimatePosition position = ForestryAPI.climateManager.getPosition(world, pos); - if(position != null){ + if (position != null) { return position.getHumidity(); } return world.getBiome(pos).getRainfall(); @@ -137,16 +124,16 @@ public class ClimateManager implements IClimateManager{ public Map> getRegions() { return regions; } - + @Override - public IClimatePosition getPosition(World world, BlockPos pos){ - Integer dimensionID = Integer.valueOf(world.provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + public IClimatePosition getPosition(World world, BlockPos pos) { + Integer dimensionID = world.provider.getDimension(); + if (!regions.containsKey(dimensionID)) { regions.put(dimensionID, new ArrayList<>()); return null; } - for(IClimateRegion region : regions.get(dimensionID)){ - if(region.getPositions().keySet().contains(pos)){ + for (IClimateRegion region : regions.get(dimensionID)) { + if (region.getPositions().keySet().contains(pos)) { return region.getPositions().get(pos); } } @@ -154,16 +141,16 @@ public class ClimateManager implements IClimateManager{ } @Override - public IClimateRegion getRegionForPos(World world, BlockPos pos){ - Integer dimensionID = Integer.valueOf(world.provider.getDimension()); - if(!regions.containsKey(dimensionID)){ + public IClimateRegion getRegionForPos(World world, BlockPos pos) { + Integer dimensionID = world.provider.getDimension(); + if (!regions.containsKey(dimensionID)) { this.regions.put(dimensionID, new ArrayList<>()); } List regions = this.regions.get(dimensionID); - for(IClimateRegion region : regions){ - if(region.getPositions().keySet().contains(pos)){ + for (IClimateRegion region : regions) { + if (region.getPositions().keySet().contains(pos)) { return region; - }else if(region.getOtherPositions().contains(pos)){ + } else if (region.getOtherPositions().contains(pos)) { return region; } } diff --git a/src/main/java/forestry/core/climate/ClimatePosition.java b/src/main/java/forestry/core/climate/ClimatePosition.java index 638a7ae6f..477d8d209 100644 --- a/src/main/java/forestry/core/climate/ClimatePosition.java +++ b/src/main/java/forestry/core/climate/ClimatePosition.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.climate; -import javax.annotation.Nonnull; - import forestry.api.climate.IClimatePosition; import forestry.api.climate.IClimateRegion; import net.minecraft.nbt.NBTTagCompound; @@ -19,20 +17,18 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.biome.Biome; public class ClimatePosition implements IClimatePosition { - - @Nonnull protected final IClimateRegion climateRegion; - @Nonnull + protected final BlockPos pos; protected float temperature; protected float humidity; - + public ClimatePosition(IClimateRegion climateRegion, BlockPos pos, NBTTagCompound nbtTag) { this.climateRegion = climateRegion; this.pos = pos; readFromNBT(nbtTag); } - + public ClimatePosition(IClimateRegion climateRegion, BlockPos pos) { Biome biome = climateRegion.getWorld().getBiome(pos); this.climateRegion = climateRegion; @@ -40,26 +36,25 @@ public class ClimatePosition implements IClimatePosition { this.temperature = biome.getTemperature(); this.humidity = biome.getRainfall(); } - - public ClimatePosition(@Nonnull IClimateRegion climateRegion, @Nonnull BlockPos pos, float temperature, float humidity) { + + public ClimatePosition(IClimateRegion climateRegion, BlockPos pos, float temperature, float humidity) { this.climateRegion = climateRegion; this.pos = pos; this.temperature = temperature; this.humidity = humidity; } - - @Nonnull + + @Override public IClimateRegion getClimateRegion() { return climateRegion; } - - @Nonnull + @Override public BlockPos getPos() { return pos; } - + @Override public void setTemperature(float temperature) { this.temperature = temperature; @@ -69,17 +64,17 @@ public class ClimatePosition implements IClimatePosition { public float getTemperature() { return temperature; } - + @Override public void addTemperature(float temperature) { setTemperature(getTemperature() + temperature); } - + @Override public void addHumidity(float humidity) { setHumidity(getHumidity() + humidity); } - + @Override public void setHumidity(float humidity) { this.humidity = humidity; @@ -102,5 +97,4 @@ public class ClimatePosition implements IClimatePosition { nbt.setFloat("Humidity", humidity); return nbt; } - } diff --git a/src/main/java/forestry/core/climate/ClimateRoom.java b/src/main/java/forestry/core/climate/ClimateRoom.java index aab4d7124..dedf48b6b 100644 --- a/src/main/java/forestry/core/climate/ClimateRoom.java +++ b/src/main/java/forestry/core/climate/ClimateRoom.java @@ -22,9 +22,8 @@ import forestry.api.climate.IClimateControl; import forestry.api.climate.IClimatePosition; import forestry.api.climate.IClimateRegion; import forestry.api.climate.IClimateSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.utils.ClimateUtil; import forestry.greenhouse.multiblock.IGreenhouseControllerInternal; import net.minecraft.nbt.NBTTagCompound; @@ -34,7 +33,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ClimateRoom implements IClimateRegion, IStreamable { - + protected final World world; protected final IGreenhouseControllerInternal controller; protected final Map positions; @@ -42,20 +41,20 @@ public class ClimateRoom implements IClimateRegion, IStreamable { protected final List sources; protected float temperature; protected float humidity; - + public ClimateRoom(ClimateRoom oldRoom, Map newPositions, List newWallPositions) { this.world = oldRoom.getWorld(); this.controller = oldRoom.controller; this.positions = new HashMap<>(); this.wallPositions = newWallPositions; this.sources = new ArrayList<>(); - for(Entry positionEntry : newPositions.entrySet()){ + for (Entry positionEntry : newPositions.entrySet()) { BlockPos pos = positionEntry.getKey(); IClimatePosition position = positionEntry.getValue(); IClimatePosition oldPosition = oldRoom.getPositions().get(pos); float temperature = position.getTemperature(); float humidity = position.getHumidity(); - if(oldPosition != null){ + if (oldPosition != null) { temperature = oldPosition.getTemperature(); humidity = oldPosition.getHumidity(); } @@ -64,7 +63,7 @@ public class ClimateRoom implements IClimateRegion, IStreamable { this.temperature = getExactTemperature(); this.humidity = getExactHumidity(); } - + public ClimateRoom(IGreenhouseControllerInternal controller, Map innerPositions, List wallPositions) { this.world = controller.getWorldObj(); this.controller = controller; @@ -74,7 +73,7 @@ public class ClimateRoom implements IClimateRegion, IStreamable { this.temperature = getExactTemperature(); this.humidity = getExactHumidity(); } - + public ClimateRoom(IGreenhouseControllerInternal controller, List wallPositions, NBTTagCompound nbtTag) { this.world = controller.getWorldObj(); this.controller = controller; @@ -85,15 +84,15 @@ public class ClimateRoom implements IClimateRegion, IStreamable { this.temperature = getExactTemperature(); this.humidity = getExactHumidity(); } - + private float getExactTemperature() { float temperature = 0.0F; int positions = 0; - - for(IClimatePosition position : this.positions.values()){ - if(position != null){ + + for (IClimatePosition position : this.positions.values()) { + if (position != null) { positions++; - temperature+=position.getTemperature(); + temperature += position.getTemperature(); } } return temperature / positions; @@ -102,50 +101,51 @@ public class ClimateRoom implements IClimateRegion, IStreamable { private float getExactHumidity() { float humidity = 0.0F; int positions = 0; - - for(IClimatePosition position : this.positions.values()){ - if(position != null){ + + for (IClimatePosition position : this.positions.values()) { + if (position != null) { positions++; - humidity+=position.getHumidity(); + humidity += position.getHumidity(); } } return humidity / positions; } - + @Override public void updateClimate(int ticks) { - boolean hasChange = false;; - for(IClimateSource source : sources){ - if(source != null){ - if(ticks % source.getTicksForChange(this) == 0){ + boolean hasChange = false; + ; + for (IClimateSource source : sources) { + if (source != null) { + if (ticks % source.getTicksForChange(this) == 0) { hasChange |= source.changeClimate(ticks, this); } } } - if(ticks % getTicksPerUpdate() == 0){ - for(Entry position : positions.entrySet()){ + if (ticks % getTicksPerUpdate() == 0) { + for (Entry position : positions.entrySet()) { BlockPos pos = position.getKey(); - if(world.isBlockLoaded(pos)){ + if (world.isBlockLoaded(pos)) { hasChange |= updateSides(pos); - - if(!controller.isAssembled()){ + + if (!controller.isAssembled()) { IClimateControl climateControl = getControl(pos); IClimatePosition climatedInfo = positions.get(pos); - - if(climatedInfo.getTemperature() != climateControl.getControlTemperature()){ - if(climatedInfo.getTemperature() > climateControl.getControlTemperature()){ + + if (climatedInfo.getTemperature() != climateControl.getControlTemperature()) { + if (climatedInfo.getTemperature() > climateControl.getControlTemperature()) { climatedInfo.addTemperature(-Math.min(0.01F, climatedInfo.getTemperature() - climateControl.getControlTemperature())); hasChange = true; - }else{ + } else { climatedInfo.addTemperature(Math.min(0.01F, climateControl.getControlTemperature() - climatedInfo.getTemperature())); hasChange = true; } } - if(climatedInfo.getHumidity() != climateControl.getControlHumidity()){ - if(climatedInfo.getHumidity() > climateControl.getControlHumidity()){ + if (climatedInfo.getHumidity() != climateControl.getControlHumidity()) { + if (climatedInfo.getHumidity() > climateControl.getControlHumidity()) { climatedInfo.addHumidity(-Math.min(0.01F, climatedInfo.getHumidity() - climateControl.getControlHumidity())); hasChange = true; - }else{ + } else { climatedInfo.addHumidity(Math.min(0.01F, climateControl.getControlHumidity() - climatedInfo.getHumidity())); hasChange = true; } @@ -154,27 +154,27 @@ public class ClimateRoom implements IClimateRegion, IStreamable { } } } - if(hasChange){ + if (hasChange) { temperature = getExactTemperature(); humidity = getExactHumidity(); } } - - protected boolean updateSides(BlockPos pos){ + + protected boolean updateSides(BlockPos pos) { IClimatePosition climatedInfo = positions.get(pos); IClimateControl climateControl = getControl(pos); boolean hasChange = false; - if(climateControl.getControlTemperature() != temperature || climateControl.getControlHumidity() != humidity) { - for(EnumFacing facing : EnumFacing.VALUES){ + if (climateControl.getControlTemperature() != temperature || climateControl.getControlHumidity() != humidity) { + for (EnumFacing facing : EnumFacing.VALUES) { IClimatePosition climatedInfoFace = positions.get(pos.offset(facing)); - if(climatedInfoFace != null){ - if(climatedInfo.getTemperature() > climatedInfoFace.getTemperature() + 0.01F){ + if (climatedInfoFace != null) { + if (climatedInfo.getTemperature() > climatedInfoFace.getTemperature() + 0.01F) { float change = Math.min(0.01F, climatedInfo.getTemperature() - climatedInfoFace.getTemperature()); climatedInfo.addTemperature(-change); climatedInfoFace.addTemperature(change); hasChange = true; } - if(climatedInfo.getHumidity() > climatedInfoFace.getHumidity() + 0.01F){ + if (climatedInfo.getHumidity() > climatedInfoFace.getHumidity() + 0.01F) { float change = Math.min(0.01F, climatedInfo.getHumidity() - climatedInfoFace.getHumidity()); climatedInfo.addHumidity(-change); climatedInfoFace.addHumidity(change); @@ -185,20 +185,20 @@ public class ClimateRoom implements IClimateRegion, IStreamable { } return hasChange; } - - protected IClimateControl getControl(BlockPos pos){ - if(world.isBlockLoaded(pos)){ - if(!controller.isAssembled()){ + + protected IClimateControl getControl(BlockPos pos) { + if (world.isBlockLoaded(pos)) { + if (!controller.isAssembled()) { return BiomeClimateControl.getControl(world.getBiome(pos)); } } return controller.getClimateControl(); } - + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { NBTTagList positionList = new NBTTagList(); - for(Entry entry : positions.entrySet()){ + for (Entry entry : positions.entrySet()) { BlockPos pos = entry.getKey(); NBTTagCompound tag = new NBTTagCompound(); tag.setInteger("X", pos.getX()); @@ -209,106 +209,107 @@ public class ClimateRoom implements IClimateRegion, IStreamable { nbt.setTag("Positions", positionList); return nbt; } - + @Override public void readFromNBT(NBTTagCompound nbt) { NBTTagList positionList = nbt.getTagList("Positions", 10); - for(int i = 0;i < positionList.tagCount();i++){ + for (int i = 0; i < positionList.tagCount(); i++) { NBTTagCompound positionTag = positionList.getCompoundTagAt(i); int xPos = positionTag.getInteger("X"); int yPos = positionTag.getInteger("Y"); int zPos = positionTag.getInteger("Z"); BlockPos pos = new BlockPos(xPos, yPos, zPos); IClimatePosition position = positions.get(pos); - if(position != null){ + if (position != null) { position.readFromNBT(positionTag); - }else{ + } else { positions.put(pos, new ClimatePosition(this, pos, positionTag)); } } } - + @Override public int getTicksPerUpdate() { return 20; } - + @Override public World getWorld() { return world; } - + @Override public Map getPositions() { return positions; } - - public synchronized void addPosition(BlockPos pos, float temperature, float humidity){ + + public synchronized void addPosition(BlockPos pos, float temperature, float humidity) { IClimatePosition otherPosition = positions.get(pos); - if(otherPosition != null){ + if (otherPosition != null) { otherPosition.setHumidity(humidity); otherPosition.setTemperature(temperature); - }else{ + } else { positions.put(pos, new ClimatePosition(this, pos, temperature, humidity)); } } - + @Override public synchronized void addSource(IClimateSource source) { - if(!sources.contains(source)){ + if (!sources.contains(source)) { sources.add(source); } } - + @Override public synchronized void removeSource(IClimateSource source) { - if(sources.contains(source)){ + if (sources.contains(source)) { sources.remove(source); } } - + @Override public Collection getSources() { return sources; } - + @Override public List getOtherPositions() { return wallPositions; } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - if(!positions.isEmpty()){ + public void writeData(PacketBufferForestry data) { + if (!positions.isEmpty()) { data.writeInt(positions.size()); - for(IClimatePosition pos : positions.values()){ + for (IClimatePosition pos : positions.values()) { ClimateUtil.writeRoomPositionData(pos, data); } data.writeFloat(temperature); data.writeFloat(humidity); - }else{ + } else { data.writeInt(0); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { int size = data.readInt(); - if(size != 0){ - positions.clear();; - for(int index = 0;index < size;index++){ + if (size != 0) { + positions.clear(); + ; + for (int index = 0; index < size; index++) { ClimateUtil.readRoomPositionData(this, data); } temperature = data.readFloat(); humidity = data.readFloat(); } } - + @Override public float getTemperature() { return temperature; } - + @Override public float getHumidity() { return humidity; diff --git a/src/main/java/forestry/core/climate/ClimateSource.java b/src/main/java/forestry/core/climate/ClimateSource.java index a09b9b49e..d46f669a7 100644 --- a/src/main/java/forestry/core/climate/ClimateSource.java +++ b/src/main/java/forestry/core/climate/ClimateSource.java @@ -10,12 +10,14 @@ ******************************************************************************/ package forestry.core.climate; +import javax.annotation.Nullable; + import forestry.api.climate.IClimateRegion; import forestry.api.climate.IClimateSource; import forestry.api.climate.IClimateSourceProvider; public abstract class ClimateSource

implements IClimateSource { - + @Nullable protected P provider; protected final int ticksForChange; @@ -38,6 +40,7 @@ public abstract class ClimateSource

implements } @Override + @Nullable public IClimateSourceProvider getProvider() { return provider; } diff --git a/src/main/java/forestry/core/climate/package-info.java b/src/main/java/forestry/core/climate/package-info.java new file mode 100644 index 000000000..0b98471d5 --- /dev/null +++ b/src/main/java/forestry/core/climate/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.climate; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/commands/CommandHelpers.java b/src/main/java/forestry/core/commands/CommandHelpers.java index b0ad5d988..a1777a013 100644 --- a/src/main/java/forestry/core/commands/CommandHelpers.java +++ b/src/main/java/forestry/core/commands/CommandHelpers.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -33,13 +34,13 @@ import forestry.core.utils.Translator; public class CommandHelpers { public static void sendLocalizedChatMessage(ICommandSender sender, String locTag, Object... args) { - sender.addChatMessage(new TextComponentTranslation(locTag, args)); + sender.sendMessage(new TextComponentTranslation(locTag, args)); } public static void sendLocalizedChatMessage(ICommandSender sender, Style chatStyle, String locTag, Object... args) { TextComponentTranslation chat = new TextComponentTranslation(locTag, args); chat.setStyle(chatStyle); - sender.addChatMessage(chat); + sender.sendMessage(chat); } /** @@ -50,15 +51,15 @@ public class CommandHelpers { * Messages will not be localized properly if you use StringUtil.localize(). */ public static void sendChatMessage(ICommandSender sender, String message) { - sender.addChatMessage(new TextComponentString(message)); + sender.sendMessage(new TextComponentString(message)); } public static void throwWrongUsage(ICommandSender sender, IForestryCommand command) throws WrongUsageException { - throw new WrongUsageException(Translator.translateToLocalFormatted("for.chat.help", command.getCommandUsage(sender))); + throw new WrongUsageException(Translator.translateToLocalFormatted("for.chat.help", command.getUsage(sender))); } public static void processChildCommand(MinecraftServer server, ICommandSender sender, SubCommand child, String[] args) throws CommandException { - if (!sender.canCommandSenderUseCommand(child.getPermissionLevel(), child.getFullCommandString())) { + if (!sender.canUseCommand(child.getPermissionLevel(), child.getFullCommandString())) { throw new WrongUsageException(Translator.translateToLocal("for.chat.command.noperms")); } String[] newargs = new String[args.length - 1]; @@ -77,7 +78,7 @@ public class CommandHelpers { Style body = new Style(); body.setColor(TextFormatting.GRAY); - List commandAliases = command.getCommandAliases(); + List commandAliases = command.getAliases(); if (!commandAliases.isEmpty()) { sendLocalizedChatMessage(sender, body, "for.chat.command.aliases", commandAliases.toString().replace("[", "").replace("]", "")); } @@ -92,7 +93,7 @@ public class CommandHelpers { if (!command.getChildren().isEmpty()) { sendLocalizedChatMessage(sender, "for.chat.command.list"); for (SubCommand child : command.getChildren()) { - sendLocalizedChatMessage(sender, "for.chat.command." + child.getFullCommandString().replace(" ", ".") + ".desc", child.getCommandName()); + sendLocalizedChatMessage(sender, "for.chat.command." + child.getFullCommandString().replace(" ", ".") + ".desc", child.getName()); } } } @@ -114,10 +115,10 @@ public class CommandHelpers { } public static boolean matches(String commandName, IForestryCommand command) { - if (commandName.equals(command.getCommandName())) { + if (commandName.equals(command.getName())) { return true; - } else if (command.getCommandAliases() != null) { - for (String alias : command.getCommandAliases()) { + } else { + for (String alias : command.getAliases()) { if (commandName.equals(alias)) { return true; } @@ -130,20 +131,20 @@ public class CommandHelpers { return CommandBase.getListOfStringsMatchingLastWord(strings, lastWords); } - public static List addStandardTabCompletionOptions(MinecraftServer server, IForestryCommand command, ICommandSender sender, String[] incomplete, BlockPos pos) { + public static List addStandardTabCompletionOptions(MinecraftServer server, IForestryCommand command, ICommandSender sender, String[] incomplete, @Nullable BlockPos pos) { if (incomplete.length > 1) { String commandName = incomplete[0]; for (SubCommand child : command.getChildren()) { if (CommandHelpers.matches(commandName, child)) { String[] incompleteRemaining = Arrays.copyOfRange(incomplete, 1, incomplete.length); - return child.getTabCompletionOptions(server, sender, incompleteRemaining, pos); + return child.getTabCompletions(server, sender, incompleteRemaining, pos); } } } List commandNames = new ArrayList<>(); for (SubCommand child : command.getChildren()) { - commandNames.add(child.getCommandName()); + commandNames.add(child.getName()); } commandNames.add("help"); diff --git a/src/main/java/forestry/core/commands/CommandModeInfo.java b/src/main/java/forestry/core/commands/CommandModeInfo.java index 3351395be..1214b1e25 100644 --- a/src/main/java/forestry/core/commands/CommandModeInfo.java +++ b/src/main/java/forestry/core/commands/CommandModeInfo.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; import java.util.List; import org.apache.commons.lang3.StringUtils; @@ -73,7 +74,7 @@ public class CommandModeInfo extends SubCommand { } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { return CommandHelpers.getListOfStringsMatchingLastWord(args, modeStringArr); } } diff --git a/src/main/java/forestry/core/commands/CommandModeSet.java b/src/main/java/forestry/core/commands/CommandModeSet.java index c5bfb5534..2d8d77cbb 100644 --- a/src/main/java/forestry/core/commands/CommandModeSet.java +++ b/src/main/java/forestry/core/commands/CommandModeSet.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.command.ICommandSender; @@ -54,7 +55,7 @@ public final class CommandModeSet extends SubCommand { } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { return CommandHelpers.getListOfStringsMatchingLastWord(args, modeStringArr); } } diff --git a/src/main/java/forestry/core/commands/CommandSaveStats.java b/src/main/java/forestry/core/commands/CommandSaveStats.java index 3c7f99abb..a8c7414df 100644 --- a/src/main/java/forestry/core/commands/CommandSaveStats.java +++ b/src/main/java/forestry/core/commands/CommandSaveStats.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; @@ -59,10 +60,9 @@ public final class CommandSaveStats extends SubCommand { this.modeHelper = modeHelper; } - @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { - return CommandHelpers.getListOfStringsMatchingLastWord(args, server.getAllUsernames()); + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { + return CommandHelpers.getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames()); } @Override @@ -91,32 +91,28 @@ public final class CommandSaveStats extends SubCommand { statistics.add(""); IBreedingTracker tracker = saveHelper.getBreedingTracker(world, player.getGameProfile()); - if (tracker == null) { - statistics.add(Translator.translateToLocal("for.chat.command.forestry.stats.save.error4")); - } else { - saveHelper.addExtraInfo(statistics, tracker); + saveHelper.addExtraInfo(statistics, tracker); - Collection species = saveHelper.getSpecies(); + Collection species = saveHelper.getSpecies(); - String speciesCount = Translator.translateToLocal("for.gui.speciescount"); - String speciesCountLine = String.format("%s (%s):", speciesCount, species.size()); - statistics.add(speciesCountLine); - statistics.add(StringUtil.line(speciesCountLine.length())); + String speciesCount = Translator.translateToLocal("for.gui.speciescount"); + String speciesCountLine = String.format("%s (%s):", speciesCount, species.size()); + statistics.add(speciesCountLine); + statistics.add(StringUtil.line(speciesCountLine.length())); - statistics.add(discoveredSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.discovered")); - statistics.add(blacklistedSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted")); - statistics.add(notCountedSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted")); - statistics.add(""); + statistics.add(discoveredSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.discovered")); + statistics.add(blacklistedSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.blacklisted")); + statistics.add(notCountedSymbol + ": " + Translator.translateToLocal("for.chat.command.forestry.stats.save.key.notCounted")); + statistics.add(""); - String header = generateSpeciesListHeader(); - statistics.add(header); + String header = generateSpeciesListHeader(); + statistics.add(header); - statistics.add(StringUtil.line(header.length())); - statistics.add(""); + statistics.add(StringUtil.line(header.length())); + statistics.add(""); - for (IAlleleSpecies allele : species) { - statistics.add(generateSpeciesListEntry(allele, tracker)); - } + for (IAlleleSpecies allele : species) { + statistics.add(generateSpeciesListEntry(allele, tracker)); } File file = new File(Proxies.common.getForestryRoot(), "config/" + Constants.MOD_ID + "/stats/" + player.getDisplayNameString() + '-' + saveHelper.getFileSuffix() + ".log"); diff --git a/src/main/java/forestry/core/commands/ICommandModeHelper.java b/src/main/java/forestry/core/commands/ICommandModeHelper.java index a2b9e6569..70574e258 100644 --- a/src/main/java/forestry/core/commands/ICommandModeHelper.java +++ b/src/main/java/forestry/core/commands/ICommandModeHelper.java @@ -10,11 +10,14 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; + import net.minecraft.world.World; public interface ICommandModeHelper { String[] getModeNames(); + @Nullable String getModeNameMatching(String desired); String getModeName(World world); diff --git a/src/main/java/forestry/core/commands/IForestryCommand.java b/src/main/java/forestry/core/commands/IForestryCommand.java index 81238313a..eff0a829d 100644 --- a/src/main/java/forestry/core/commands/IForestryCommand.java +++ b/src/main/java/forestry/core/commands/IForestryCommand.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.commands; -import java.util.List; import java.util.SortedSet; import net.minecraft.command.ICommand; @@ -23,9 +22,6 @@ public interface IForestryCommand extends ICommand { String getFullCommandString(); - @Override - List getCommandAliases(); - int getPermissionLevel(); SortedSet getChildren(); diff --git a/src/main/java/forestry/core/commands/RootCommand.java b/src/main/java/forestry/core/commands/RootCommand.java index 98291a588..0e418e99b 100644 --- a/src/main/java/forestry/core/commands/RootCommand.java +++ b/src/main/java/forestry/core/commands/RootCommand.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.commands; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; @@ -41,13 +42,13 @@ public class RootCommand extends CommandBase implements IForestryCommand { /* CommandBase */ @Override - public String getCommandName() { + public String getName() { return ROOT_COMMAND_NAME; } @Override - public String getCommandUsage(ICommandSender sender) { - return "/" + this.getCommandName() + " help"; + public String getUsage(ICommandSender sender) { + return "/" + this.getName() + " help"; } @Override @@ -67,22 +68,22 @@ public class RootCommand extends CommandBase implements IForestryCommand { } @Override - public List getCommandAliases() { + public List getAliases() { List aliases = new ArrayList<>(); aliases.add(ROOT_COMMAND_ALIAS); return aliases; } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { - return CommandHelpers.addStandardTabCompletionOptions(server, this, sender, args, pos); + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { + return CommandHelpers.addStandardTabCompletionOptions(server, this, sender, args, targetPos); } /* IForestryCommand */ @Override public String getFullCommandString() { - return getCommandName(); + return getName(); } @Override diff --git a/src/main/java/forestry/core/commands/SubCommand.java b/src/main/java/forestry/core/commands/SubCommand.java index 1bcd74395..54b6fea4e 100644 --- a/src/main/java/forestry/core/commands/SubCommand.java +++ b/src/main/java/forestry/core/commands/SubCommand.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.core.commands; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; @@ -42,6 +42,7 @@ public abstract class SubCommand implements IForestryCommand { private final String name; private final List aliases = new ArrayList<>(); private PermLevel permLevel = PermLevel.EVERYONE; + @Nullable private IForestryCommand parent; private final SortedSet children = new TreeSet<>(); @@ -50,7 +51,7 @@ public abstract class SubCommand implements IForestryCommand { } @Override - public final String getCommandName() { + public String getName() { return name; } @@ -74,13 +75,13 @@ public abstract class SubCommand implements IForestryCommand { } @Override - public List getCommandAliases() { + public List getAliases() { return aliases; } @Override - public List getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) { - return CommandHelpers.addStandardTabCompletionOptions(server, this, sender, args, pos); + public List getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { + return CommandHelpers.addStandardTabCompletionOptions(server, this, sender, args, targetPos); } @Override @@ -90,7 +91,7 @@ public abstract class SubCommand implements IForestryCommand { } } - public void executeSubCommand(MinecraftServer server, ICommandSender sender, String[] args) throws WrongUsageException, CommandException { + public void executeSubCommand(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { printHelp(sender); } @@ -106,7 +107,7 @@ public abstract class SubCommand implements IForestryCommand { @Override public boolean checkPermission(MinecraftServer server, ICommandSender sender) { - return sender.canCommandSenderUseCommand(getPermissionLevel(), getCommandName()); + return sender.canUseCommand(getPermissionLevel(), getName()); } @Override @@ -115,7 +116,7 @@ public abstract class SubCommand implements IForestryCommand { } @Override - public String getCommandUsage(ICommandSender sender) { + public String getUsage(ICommandSender sender) { return "/" + getFullCommandString() + " help"; } @@ -126,12 +127,15 @@ public abstract class SubCommand implements IForestryCommand { @Override public String getFullCommandString() { - return parent.getFullCommandString() + " " + getCommandName(); + if (parent == null) { + return getName(); + } + return parent.getFullCommandString() + " " + getName(); } @Override - public int compareTo(@Nonnull ICommand command) { - return this.getCommandName().compareTo(command.getCommandName()); + public int compareTo(ICommand command) { + return this.getName().compareTo(command.getName()); } } diff --git a/src/main/java/forestry/core/commands/package-info.java b/src/main/java/forestry/core/commands/package-info.java new file mode 100644 index 000000000..0ca8327f0 --- /dev/null +++ b/src/main/java/forestry/core/commands/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.commands; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/config/Config.java b/src/main/java/forestry/core/config/Config.java index e16f564f5..ef03803e5 100755 --- a/src/main/java/forestry/core/config/Config.java +++ b/src/main/java/forestry/core/config/Config.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.config; +import javax.annotation.Nullable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; @@ -36,9 +37,11 @@ public class Config { public static final String CATEGORY_FLUIDS = "fluids"; public static final String CATEGORY_FARM = "farm"; + @Nullable public static LocalizedConfiguration configCommon; + @Nullable public static LocalizedConfiguration configFluid; - + @Nullable public static String gameMode; private static final Set disabledStructures = new HashSet<>(); @@ -300,10 +303,8 @@ public class Config { for (String key : prop.stringPropertyNames()) { String[] parsedHints = parseHints(prop.getProperty(key)); - if (parsedHints != null) { - for (String parsedHint : parsedHints) { - hints.put(key, parsedHint); - } + for (String parsedHint : parsedHints) { + hints.put(key, parsedHint); } } } diff --git a/src/main/java/forestry/core/config/ForestryGuiConfig.java b/src/main/java/forestry/core/config/ForestryGuiConfig.java index 31bd44c74..814862e02 100644 --- a/src/main/java/forestry/core/config/ForestryGuiConfig.java +++ b/src/main/java/forestry/core/config/ForestryGuiConfig.java @@ -30,16 +30,22 @@ public class ForestryGuiConfig extends GuiConfig { private static List getConfigCategories() { List configElements = new ArrayList<>(); - List commonCategoryNames = Arrays.asList("crafting", "difficulty", "genetics", "performance", "structures", "tweaks", "world"); - for (String categoryName : commonCategoryNames) { - ConfigCategory category = Config.configCommon.getCategory(categoryName); - configElements.add(new ConfigElement(category)); + LocalizedConfiguration configCommon = Config.configCommon; + if (configCommon != null) { + List commonCategoryNames = Arrays.asList("crafting", "difficulty", "genetics", "performance", "structures", "tweaks", "world"); + for (String categoryName : commonCategoryNames) { + ConfigCategory category = configCommon.getCategory(categoryName); + configElements.add(new ConfigElement(category)); + } } - List fluidCategoryNames = Arrays.asList("enableFluid", "enableFluidBlock"); - for (String categoryName : fluidCategoryNames) { - ConfigCategory category = Config.configFluid.getCategory(categoryName); - configElements.add(new ConfigElement(category)); + LocalizedConfiguration configFluid = Config.configFluid; + if (configFluid != null) { + List fluidCategoryNames = Arrays.asList("enableFluid", "enableFluidBlock"); + for (String categoryName : fluidCategoryNames) { + ConfigCategory category = configFluid.getCategory(categoryName); + configElements.add(new ConfigElement(category)); + } } return configElements; diff --git a/src/main/java/forestry/core/config/GameMode.java b/src/main/java/forestry/core/config/GameMode.java index b31288d10..871ff4968 100644 --- a/src/main/java/forestry/core/config/GameMode.java +++ b/src/main/java/forestry/core/config/GameMode.java @@ -21,7 +21,6 @@ import forestry.core.utils.Log; public class GameMode implements IGameMode { private static final String GAMEMODE_KEY = "gamemode"; private String identifier = "EASY"; - private final String category; private final Map booleanSettings = new HashMap<>(); private final Map integerSettings = new HashMap<>(); @@ -66,7 +65,7 @@ public class GameMode implements IGameMode { public GameMode(String identifier) { this.identifier = identifier; - this.category = "gamemodes/" + identifier; + String category = "gamemodes/" + identifier; File configFile = new File(Forestry.instance.getConfigFolder(), category + ".cfg"); diff --git a/src/main/java/forestry/core/config/SessionVars.java b/src/main/java/forestry/core/config/SessionVars.java index 623d41872..c5fc599d5 100755 --- a/src/main/java/forestry/core/config/SessionVars.java +++ b/src/main/java/forestry/core/config/SessionVars.java @@ -10,18 +10,22 @@ ******************************************************************************/ package forestry.core.config; +import javax.annotation.Nullable; import java.util.HashMap; +import java.util.Map; public class SessionVars { - private static final HashMap stringVars = new HashMap<>(); - + private static final Map stringVars = new HashMap<>(); + + @Nullable private static Class openedLedger; - public static void setOpenedLedger(Class ledgerClass) { + public static void setOpenedLedger(@Nullable Class ledgerClass) { openedLedger = ledgerClass; } + @Nullable public static Class getOpenedLedger() { return openedLedger; } @@ -29,13 +33,10 @@ public class SessionVars { public static void setStringVar(String ident, String val) { stringVars.put(ident, val); } - + + @Nullable public static String getStringVar(String ident) { - if (stringVars.containsKey(ident)) { - return stringVars.get(ident); - } - - return null; + return stringVars.get(ident); } public static void clearStringVar(String ident) { diff --git a/src/main/java/forestry/core/config/package-info.java b/src/main/java/forestry/core/config/package-info.java new file mode 100644 index 000000000..0073b0082 --- /dev/null +++ b/src/main/java/forestry/core/config/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.config; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java b/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java index 989e2fa0e..70e9ebc88 100644 --- a/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java +++ b/src/main/java/forestry/core/entities/EntityMinecartContainerForestry.java @@ -54,8 +54,8 @@ public abstract class EntityMinecartContainerForestry extends EntityMinecartFore @Override public void setDead() { - if (dropContentsWhenDead && !worldObj.isRemote) { - InventoryUtil.dropInventory(getInternalInventory(), worldObj, posX, posY, posZ); + if (dropContentsWhenDead && !world.isRemote) { + InventoryUtil.dropInventory(getInternalInventory(), world, posX, posY, posZ); } super.setDead(); } @@ -76,8 +76,14 @@ public abstract class EntityMinecartContainerForestry extends EntityMinecartFore } /* IInventory */ + @Override - public boolean isUseableByPlayer(EntityPlayer player) { + public boolean isEmpty() { + return getInternalInventory().isEmpty(); + } + + @Override + public boolean isUsableByPlayer(EntityPlayer player) { return !isDead && player.getDistanceSqToEntity(this) <= 64.0D; } diff --git a/src/main/java/forestry/core/entities/EntityMinecartForestry.java b/src/main/java/forestry/core/entities/EntityMinecartForestry.java index 0f3946a8f..2c353a820 100644 --- a/src/main/java/forestry/core/entities/EntityMinecartForestry.java +++ b/src/main/java/forestry/core/entities/EntityMinecartForestry.java @@ -40,12 +40,12 @@ public abstract class EntityMinecartForestry extends EntityMinecart implements I } @Override - public boolean processInitialInteract(EntityPlayer player, ItemStack stack, EnumHand hand) { - if (MinecraftForge.EVENT_BUS.post(new MinecartInteractEvent(this, player, stack, hand))) { + public boolean processInitialInteract(EntityPlayer player, EnumHand hand) { + if (MinecraftForge.EVENT_BUS.post(new MinecartInteractEvent(this, player, hand))) { return true; } - if (!worldObj.isRemote) { + if (!world.isRemote) { GuiHandler.openGui(player, this); } return true; @@ -53,7 +53,7 @@ public abstract class EntityMinecartForestry extends EntityMinecart implements I @Override public Type getType() { - return null; + return Type.CHEST; } /* EntityMinecart */ @@ -78,7 +78,7 @@ public abstract class EntityMinecartForestry extends EntityMinecart implements I @Override public void killMinecart(DamageSource damageSource) { super.killMinecart(damageSource); - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + if (this.world.getGameRules().getBoolean("doEntityDrops")) { Block block = getDisplayTile().getBlock(); entityDropItem(new ItemStack(block), 0.0F); } diff --git a/src/main/java/forestry/core/entities/ParticleColoredDripParticle.java b/src/main/java/forestry/core/entities/ParticleColoredDripParticle.java index 19953010a..9ed1dc91d 100644 --- a/src/main/java/forestry/core/entities/ParticleColoredDripParticle.java +++ b/src/main/java/forestry/core/entities/ParticleColoredDripParticle.java @@ -61,7 +61,7 @@ public class ParticleColoredDripParticle extends Particle { this.setParticleTextureIndex(112); } - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.9800000190734863D; this.motionY *= 0.9800000190734863D; this.motionZ *= 0.9800000190734863D; @@ -70,7 +70,7 @@ public class ParticleColoredDripParticle extends Particle { this.setExpired(); } - if (this.isCollided) { + if (this.onGround) { this.setParticleTextureIndex(114); this.motionX *= 0.699999988079071D; @@ -78,7 +78,7 @@ public class ParticleColoredDripParticle extends Particle { } BlockPos blockpos = new BlockPos(this.posX, this.posY, this.posZ); - IBlockState iblockstate = this.worldObj.getBlockState(blockpos); + IBlockState iblockstate = this.world.getBlockState(blockpos); Material material = iblockstate.getMaterial(); if (material.isLiquid() || material.isSolid()) { @@ -88,7 +88,7 @@ public class ParticleColoredDripParticle extends Particle { d0 = BlockLiquid.getLiquidHeightPercent(iblockstate.getValue(BlockLiquid.LEVEL)); } - double d1 = MathHelper.floor_double(this.posY) + 1 - d0; + double d1 = MathHelper.floor(this.posY) + 1 - d0; if (this.posY < d1) { this.setExpired(); diff --git a/src/main/java/forestry/core/entities/ParticleIgnition.java b/src/main/java/forestry/core/entities/ParticleIgnition.java index 8985556eb..f332a61ac 100644 --- a/src/main/java/forestry/core/entities/ParticleIgnition.java +++ b/src/main/java/forestry/core/entities/ParticleIgnition.java @@ -67,16 +67,16 @@ public class ParticleIgnition extends Particle { float f = (float) this.particleAge / (float) this.particleMaxAge; if (this.rand.nextFloat() > f * 2) { - this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); + this.world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); } this.motionY -= 0.03D; - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.999D; this.motionY *= 0.999D; this.motionZ *= 0.999D; - if (this.isCollided) { + if (this.onGround) { this.motionX *= 0.7; this.motionZ *= 0.7; } diff --git a/src/main/java/forestry/core/entities/ParticleSmoke.java b/src/main/java/forestry/core/entities/ParticleSmoke.java index c91041669..ffa2d1c46 100644 --- a/src/main/java/forestry/core/entities/ParticleSmoke.java +++ b/src/main/java/forestry/core/entities/ParticleSmoke.java @@ -66,16 +66,16 @@ public class ParticleSmoke extends Particle { float f = (float) this.particleAge / (float) this.particleMaxAge; if (this.rand.nextFloat() > f * 2) { - this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); + this.world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ); } this.motionY -= 0.03D; - this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.move(this.motionX, this.motionY, this.motionZ); this.motionX *= 0.999D; this.motionY *= 0.999D; this.motionZ *= 0.999D; - if (this.isCollided) { + if (this.onGround) { this.motionX *= 0.7; this.motionZ *= 0.7; } diff --git a/src/main/java/forestry/core/entities/ParticleSnow.java b/src/main/java/forestry/core/entities/ParticleSnow.java index 426152a0f..9eb6240be 100644 --- a/src/main/java/forestry/core/entities/ParticleSnow.java +++ b/src/main/java/forestry/core/entities/ParticleSnow.java @@ -17,8 +17,7 @@ import net.minecraft.entity.Entity; import net.minecraft.world.World; public class ParticleSnow extends Particle { - - public static TextureAtlasSprite sprites[]; + public static final TextureAtlasSprite sprites[] = new TextureAtlasSprite[3]; public ParticleSnow(World world, double x, double y, double z) { super(world, x, y, z, 0.0D, 0.0D, 0.0D); diff --git a/src/main/java/forestry/core/entities/package-info.java b/src/main/java/forestry/core/entities/package-info.java new file mode 100644 index 000000000..3d480c208 --- /dev/null +++ b/src/main/java/forestry/core/entities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.entities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/errors/ErrorLogic.java b/src/main/java/forestry/core/errors/ErrorLogic.java index 8dde26678..b06595358 100644 --- a/src/main/java/forestry/core/errors/ErrorLogic.java +++ b/src/main/java/forestry/core/errors/ErrorLogic.java @@ -12,8 +12,6 @@ package forestry.core.errors; import com.google.common.collect.ImmutableSet; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import java.util.HashSet; import java.util.Set; @@ -21,6 +19,7 @@ import java.util.Set; import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorState; +import net.minecraft.network.PacketBuffer; public class ErrorLogic implements IErrorLogic { private final Set errorStates = new HashSet<>(); @@ -56,7 +55,7 @@ public class ErrorLogic implements IErrorLogic { } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(PacketBuffer data) { data.writeShort(errorStates.size()); for (IErrorState errorState : errorStates) { data.writeShort(errorState.getID()); @@ -64,7 +63,7 @@ public class ErrorLogic implements IErrorLogic { } @Override - public void readData(DataInputStream data) throws IOException { + public void readData(PacketBuffer data) { clearErrors(); short errorStateCount = data.readShort(); diff --git a/src/main/java/forestry/core/errors/FakeErrorLogic.java b/src/main/java/forestry/core/errors/FakeErrorLogic.java index b1982801c..86b72060d 100644 --- a/src/main/java/forestry/core/errors/FakeErrorLogic.java +++ b/src/main/java/forestry/core/errors/FakeErrorLogic.java @@ -12,12 +12,11 @@ package forestry.core.errors; import com.google.common.collect.ImmutableSet; -import java.io.DataInputStream; -import java.io.DataOutputStream; import java.io.IOException; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorState; +import net.minecraft.network.PacketBuffer; public class FakeErrorLogic implements IErrorLogic { @@ -48,12 +47,12 @@ public class FakeErrorLogic implements IErrorLogic { } @Override - public void writeData(DataOutputStream data) throws IOException { + public void writeData(PacketBuffer data) { } @Override - public void readData(DataInputStream data) throws IOException { + public void readData(PacketBuffer data) { } diff --git a/src/main/java/forestry/core/errors/package-info.java b/src/main/java/forestry/core/errors/package-info.java new file mode 100644 index 000000000..1336eff52 --- /dev/null +++ b/src/main/java/forestry/core/errors/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.errors; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/fluids/BlockForestryFluid.java b/src/main/java/forestry/core/fluids/BlockForestryFluid.java index 1787a9aee..fb697d8bd 100644 --- a/src/main/java/forestry/core/fluids/BlockForestryFluid.java +++ b/src/main/java/forestry/core/fluids/BlockForestryFluid.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.fluids; +import javax.annotation.Nullable; import java.awt.Color; import java.util.Random; @@ -129,19 +130,15 @@ public class BlockForestryFluid extends BlockFluidClassic implements IItemModelR @Override public boolean canDisplace(IBlockAccess world, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); - if (blockState.getBlock().getMaterial(blockState).isLiquid()) { - return false; - } - return super.canDisplace(world, pos); + return !blockState.getMaterial().isLiquid() && + super.canDisplace(world, pos); } @Override public boolean displaceIfPossible(World world, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); - if (blockState.getBlock().getMaterial(blockState).isLiquid()) { - return false; - } - return super.displaceIfPossible(world, pos); + return !blockState.getMaterial().isLiquid() && + super.displaceIfPossible(world, pos); } @Override @@ -150,14 +147,14 @@ public class BlockForestryFluid extends BlockFluidClassic implements IItemModelR } @Override - public int getFlammability(IBlockAccess world, BlockPos pos, EnumFacing face) { + public int getFlammability(IBlockAccess world, BlockPos pos, @Nullable EnumFacing face) { return flammability; } private static boolean isFlammable(IBlockAccess world, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); - return block.isFlammable(world, pos, null); + return block.isFlammable(world, pos, EnumFacing.UP); } @Override @@ -208,14 +205,12 @@ public class BlockForestryFluid extends BlockFluidClassic implements IItemModelR ++y; z += rand.nextInt(3) - 1; IBlockState blockState = world.getBlockState(new BlockPos(x, y, z)); - Block block = blockState.getBlock(); - - if (block.getMaterial(blockState) == Material.AIR) { + if (blockState.getMaterial() == Material.AIR) { if (isNeighborFlammable(world, x, y, z)) { world.setBlockState(new BlockPos(x, y, z), Blocks.FIRE.getDefaultState()); return; } - } else if (block.getMaterial(blockState).blocksMovement()) { + } else if (blockState.getMaterial().blocksMovement()) { return; } } diff --git a/src/main/java/forestry/core/fluids/ContainerFiller.java b/src/main/java/forestry/core/fluids/ContainerFiller.java index f9bb813f8..226fcfb63 100644 --- a/src/main/java/forestry/core/fluids/ContainerFiller.java +++ b/src/main/java/forestry/core/fluids/ContainerFiller.java @@ -1,5 +1,7 @@ package forestry.core.fluids; +import javax.annotation.Nullable; + import forestry.core.utils.ItemStackUtil; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -18,6 +20,7 @@ public class ContainerFiller { private final int inputSlot; private final int outputSlot; + @Nullable private ItemStack usedInput; private int fillingProgress; diff --git a/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java b/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java index e3f99071c..dc44796db 100644 --- a/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java +++ b/src/main/java/forestry/core/fluids/DrainOnlyFluidHandlerWrapper.java @@ -1,6 +1,5 @@ package forestry.core.fluids; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraftforge.fluids.FluidStack; @@ -8,10 +7,9 @@ import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; public class DrainOnlyFluidHandlerWrapper implements IFluidHandler { - @Nonnull private final IFluidHandler internalFluidHandler; - public DrainOnlyFluidHandlerWrapper(@Nonnull IFluidHandler internalFluidHandler) { + public DrainOnlyFluidHandlerWrapper(IFluidHandler internalFluidHandler) { this.internalFluidHandler = internalFluidHandler; } @@ -44,10 +42,10 @@ public class DrainOnlyFluidHandlerWrapper implements IFluidHandler { } private static class DrainOnlyFluidPropertiesWrapper implements IFluidTankProperties { - @Nonnull + private final IFluidTankProperties internalTankProperties; - public DrainOnlyFluidPropertiesWrapper(@Nonnull IFluidTankProperties internalTankProperties) { + public DrainOnlyFluidPropertiesWrapper(IFluidTankProperties internalTankProperties) { this.internalTankProperties = internalTankProperties; } diff --git a/src/main/java/forestry/core/fluids/FakeTankManager.java b/src/main/java/forestry/core/fluids/FakeTankManager.java index f34b122c7..0e0da346b 100644 --- a/src/main/java/forestry/core/fluids/FakeTankManager.java +++ b/src/main/java/forestry/core/fluids/FakeTankManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.fluids; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.inventory.Container; @@ -57,7 +58,7 @@ public class FakeTankManager extends EmptyFluidHandler implements ITankManager { } @Override - public void processTankUpdate(int tankIndex, FluidStack contents) { + public void processTankUpdate(int tankIndex, @Nullable FluidStack contents) { } } diff --git a/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java b/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java index b474deb01..264a5f187 100644 --- a/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java +++ b/src/main/java/forestry/core/fluids/FakeTankUpdateHandler.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.fluids; -import forestry.core.fluids.tanks.StandardTank; - public class FakeTankUpdateHandler implements ITankUpdateHandler { public static final FakeTankUpdateHandler instance = new FakeTankUpdateHandler(); diff --git a/src/main/java/forestry/core/fluids/tanks/FilteredTank.java b/src/main/java/forestry/core/fluids/FilteredTank.java similarity index 94% rename from src/main/java/forestry/core/fluids/tanks/FilteredTank.java rename to src/main/java/forestry/core/fluids/FilteredTank.java index 7bf09d74b..0cb63ebc0 100644 --- a/src/main/java/forestry/core/fluids/tanks/FilteredTank.java +++ b/src/main/java/forestry/core/fluids/FilteredTank.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.fluids.tanks; +package forestry.core.fluids; import java.util.Arrays; import java.util.Collection; @@ -63,10 +63,8 @@ public class FilteredTank extends StandardTank { } private boolean fluidMatchesFilter(FluidStack resource) { - if (resource == null || resource.getFluid() == null) { - return false; - } - return filters.contains(resource.getFluid().getName()); + return resource.getFluid() != null && + filters.contains(resource.getFluid().getName()); } @Override diff --git a/src/main/java/forestry/core/fluids/FluidHelper.java b/src/main/java/forestry/core/fluids/FluidHelper.java index f99ba5101..6b6bf7546 100644 --- a/src/main/java/forestry/core/fluids/FluidHelper.java +++ b/src/main/java/forestry/core/fluids/FluidHelper.java @@ -11,6 +11,7 @@ package forestry.core.fluids; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; @@ -20,9 +21,11 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidActionResult; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fluids.capability.IFluidTankProperties; public final class FluidHelper { @@ -30,7 +33,7 @@ public final class FluidHelper { private FluidHelper() { } - public static boolean areFluidStacksEqual(FluidStack fluidStack1, FluidStack fluidStack2) { + public static boolean areFluidStacksEqual(@Nullable FluidStack fluidStack1, @Nullable FluidStack fluidStack2) { if (fluidStack1 == null) { return fluidStack2 == null; } else { @@ -41,7 +44,7 @@ public final class FluidHelper { public static boolean canAcceptFluid(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull EnumFacing facing, @Nonnull FluidStack fluid) { IFluidHandler capability = FluidUtil.getFluidHandler(world, pos, facing); if (capability != null) { - if(capability.getTankProperties() == null){ + if (capability.getTankProperties() == null) { throw new NullPointerException("The fluid handler " + capability.toString() + " returns null in the method getTankProperties, this is not allowed, please report that to the author of the mod from that the handler is."); } for (IFluidTankProperties tankProperties : capability.getTankProperties()) { @@ -56,32 +59,25 @@ public final class FluidHelper { public enum FillStatus { SUCCESS, INVALID_INPUT, NO_FLUID, NO_SPACE, NO_SPACE_FLUID } - + public static FillStatus fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill, boolean doFill) { return fillContainers(fluidHandler, inv, inputSlot, outputSlot, fluidToFill, getEmptyContainer(inv.getStackInSlot(inputSlot)), doFill); } - + public static FillStatus fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, Fluid fluidToFill, ItemStack emptyStack, boolean doFill) { - if (fluidToFill == null) { - return FillStatus.INVALID_INPUT; - } ItemStack input = inv.getStackInSlot(inputSlot); - if (input == null) { + if (input.isEmpty()) { return FillStatus.INVALID_INPUT; } ItemStack output = inv.getStackInSlot(outputSlot); ItemStack filled = input.copy(); - filled.stackSize = 1; + filled.setCount(1); - if(emptyStack == null){ - emptyStack = filled; - } - - IFluidHandler fluidFilledHandler = FluidUtil.getFluidHandler(filled); - IFluidHandler fluidEmptyHandler = FluidUtil.getFluidHandler(emptyStack); - if (fluidFilledHandler == null || emptyStack != null && fluidEmptyHandler == null) { + IFluidHandlerItem fluidFilledHandler = FluidUtil.getFluidHandler(filled); + IFluidHandlerItem fluidEmptyHandler = FluidUtil.getFluidHandler(emptyStack); + if (fluidFilledHandler == null || fluidEmptyHandler == null) { return FillStatus.INVALID_INPUT; } @@ -105,13 +101,15 @@ public final class FluidHelper { return FillStatus.INVALID_INPUT; } - boolean moveToOutput = fluidInContainer.amount >= containerEmptyCapacity; + filled = fluidFilledHandler.getContainer(); + + boolean moveToOutput = fluidInContainer.amount >= containerCapacity; if (moveToOutput) { - if (output != null && (output.stackSize >= output.getMaxStackSize() || !InventoryUtil.isItemEqual(filled, output))) { + if (!output.isEmpty() && (output.getCount() >= output.getMaxStackSize() || !InventoryUtil.isItemEqual(filled, output))) { return FillStatus.NO_SPACE; } } else { - if (input.stackSize > 1) { + if (input.getCount() > 1) { return FillStatus.NO_SPACE; } } @@ -119,38 +117,39 @@ public final class FluidHelper { if (doFill) { fluidHandler.drain(canDrain, true); if (moveToOutput) { - if (output == null) { + if (output.isEmpty()) { inv.setInventorySlotContents(outputSlot, filled); } else { - output.stackSize++; + output.grow(1); } inv.decrStackSize(inputSlot, 1); - }else{ + } else { inv.setInventorySlotContents(inputSlot, filled); } } return FillStatus.SUCCESS; } - + public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot) { ItemStack input = inv.getStackInSlot(inputSlot); - if (input == null) { + if (input.isEmpty()) { return false; } - ItemStack drainedItemSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); - if (drainedItemSimulated == null) { + FluidActionResult fluidActionSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); + if (!fluidActionSimulated.isSuccess()) { return false; } - if (input.stackSize == 1 || drainedItemSimulated.stackSize == 0) { - ItemStack drainedItem = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); - - if (drainedItem != null) { - if(drainedItem.stackSize > 0){ + ItemStack drainedItemSimulated = fluidActionSimulated.getResult(); + if (input.getCount() == 1 || drainedItemSimulated.isEmpty()) { + FluidActionResult fluidActionResult = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); + if (fluidActionResult.isSuccess()) { + ItemStack drainedItem = fluidActionResult.getResult(); + if (!drainedItem.isEmpty()) { inv.setInventorySlotContents(inputSlot, drainedItem); - }else { + } else { inv.decrStackSize(inputSlot, 1); } return true; @@ -162,31 +161,33 @@ public final class FluidHelper { public static FillStatus drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot, boolean doDrain) { ItemStack input = inv.getStackInSlot(inputSlot); - if (input == null) { + if (input.isEmpty()) { return FillStatus.INVALID_INPUT; } ItemStack outputStack = inv.getStackInSlot(outputSlot); - - ItemStack drainedItemSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); - if (drainedItemSimulated == null) { + + FluidActionResult drainedResultSimulated = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, false); + if (!drainedResultSimulated.isSuccess()) { return FillStatus.INVALID_INPUT; } - if (outputStack == null || drainedItemSimulated.stackSize == 0 || ItemStackUtil.isIdenticalItem(outputStack, drainedItemSimulated) && outputStack.stackSize + drainedItemSimulated.stackSize < outputStack.getMaxStackSize()) { - if(doDrain){ - ItemStack drainedItem = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); - - if (drainedItem != null) { - if(drainedItem.stackSize > 0){ + ItemStack drainedItemSimulated = drainedResultSimulated.getResult(); + + if (outputStack.isEmpty() || drainedItemSimulated.isEmpty() || ItemStackUtil.isIdenticalItem(outputStack, drainedItemSimulated) && outputStack.getCount() + drainedItemSimulated.getCount() < outputStack.getMaxStackSize()) { + if (doDrain) { + FluidActionResult drainedResult = FluidUtil.tryEmptyContainer(input, fluidHandler, Fluid.BUCKET_VOLUME, null, true); + if (drainedResult.isSuccess()) { + ItemStack drainedItem = drainedResult.getResult(); + if (!drainedItem.isEmpty()) { ItemStack newStack = drainedItem.copy(); - if(outputStack != null){ - newStack.stackSize+=outputStack.stackSize; + if (!outputStack.isEmpty()) { + newStack.grow(outputStack.getCount()); } if (isFillableContainerAndEmpty(newStack)) { inv.setInventorySlotContents(outputSlot, newStack); inv.decrStackSize(inputSlot, 1); } - }else { + } else { inv.decrStackSize(inputSlot, 1); } return FillStatus.SUCCESS; @@ -197,7 +198,7 @@ public final class FluidHelper { return FillStatus.NO_SPACE; } - + public static boolean isFillableContainerAndEmpty(ItemStack container) { IFluidHandler fluidHandler = FluidUtil.getFluidHandler(container); if (fluidHandler == null) { @@ -218,23 +219,20 @@ public final class FluidHelper { return false; } - - public static ItemStack getEmptyContainer(ItemStack container){ - if(container == null){ - return null; - } + + public static ItemStack getEmptyContainer(ItemStack container) { ItemStack empty = container.copy(); - empty.stackSize = 1; + empty.setCount(1); IFluidHandler fluidHandler = FluidUtil.getFluidHandler(empty); if (fluidHandler == null) { - return null; + return ItemStack.EMPTY; } - if(fluidHandler.drain(Integer.MAX_VALUE, true) != null){ + if (fluidHandler.drain(Integer.MAX_VALUE, true) != null) { return empty; } - return null; + return ItemStack.EMPTY; } - + public static boolean isFillableContainerWithRoom(ItemStack container) { IFluidHandler fluidHandler = FluidUtil.getFluidHandler(container); if (fluidHandler == null) { @@ -297,48 +295,4 @@ public final class FluidHelper { return true; } - - public static ItemStack getDrainedContainer(ItemStack container, int drainAmount) { - if (container == null) { - return null; - } - - if (drainAmount == 0) { - return container; - } - - container = container.copy(); - container.stackSize = 1; - - IFluidHandler fluidHandler = FluidUtil.getFluidHandler(container); - if (fluidHandler == null) { - return null; - } - - fluidHandler.drain(drainAmount, true); - if (container.stackSize <= 0) { - return null; - } - - return container; - } - - public static ItemStack getFilledContainer(FluidStack liquid, ItemStack stack) { - if (liquid == null || stack == null) { - return null; - } - - stack = stack.copy(); - stack.stackSize = 1; - - IFluidHandler fluidHandler = FluidUtil.getFluidHandler(stack); - if (fluidHandler == null) { - return null; - } - - if (fluidHandler.fill(liquid, true) > 0) { - return stack; - } - return null; - } } diff --git a/src/main/java/forestry/core/fluids/Fluids.java b/src/main/java/forestry/core/fluids/Fluids.java index c4592efa2..71bfd99ef 100644 --- a/src/main/java/forestry/core/fluids/Fluids.java +++ b/src/main/java/forestry/core/fluids/Fluids.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.fluids; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.Color; import java.io.IOException; @@ -20,24 +19,21 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import forestry.core.items.DrinkProperties; +import forestry.core.proxy.Proxies; +import forestry.core.render.ForestryResource; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.IResourceManager; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.relauncher.Side; -import forestry.core.items.DrinkProperties; -import forestry.core.proxy.Proxies; -import forestry.core.render.ForestryResource; - public enum Fluids { BIO_ETHANOL(new Color(255, 111, 0), 790, 1000) { @@ -102,7 +98,7 @@ public enum Fluids { return new BlockForestryFluid(this); } - @Nonnull + @Override public List getOtherContainers() { return Collections.singletonList( @@ -122,7 +118,7 @@ public enum Fluids { return new BlockForestryFluid(this, 4, true); } }; - + private static final Map tagToFluid = new HashMap<>(); static { @@ -133,16 +129,16 @@ public enum Fluids { private final String tag; private final int density, viscosity; - @Nonnull + private final Color particleColor; private final ResourceLocation[] resources = new ResourceLocation[2]; - - Fluids(@Nonnull Color particleColor) { + + Fluids(Color particleColor) { this(particleColor, 1000, 1000); } - - Fluids(@Nonnull Color particleColor, int density, int viscosity) { + + Fluids(Color particleColor, int density, int viscosity) { this.tag = name().toLowerCase(Locale.ENGLISH).replace('_', '.'); this.particleColor = particleColor; this.density = density; @@ -170,6 +166,7 @@ public enum Fluids { return viscosity; } + @Nullable public final Fluid getFluid() { return FluidRegistry.getFluid(getTag()); } @@ -178,15 +175,6 @@ public enum Fluids { return FluidRegistry.getFluidStack(getTag(), mb); } - public final Block getBlock() { - Fluid fluid = getFluid(); - if (fluid == null) { - return null; - } - return fluid.getBlock(); - } - - @Nonnull public final Color getParticleColor() { return particleColor; } @@ -196,29 +184,11 @@ public enum Fluids { } public final boolean is(FluidStack fluidStack) { - return fluidStack != null && getFluid() == fluidStack.getFluid(); + return getFluid() == fluidStack.getFluid(); } - public final boolean isContained(ItemStack containerStack) { - FluidStack fluidStackInContainer = FluidUtil.getFluidContained(containerStack); - return fluidStackInContainer != null && fluidStackInContainer.getFluid() == getFluid(); - } - - public static boolean areEqual(Fluid fluid, FluidStack fluidStack) { - if (fluidStack != null && fluid == fluidStack.getFluid()) { - return true; - } - return fluid == null && fluidStack == null; - } - - public static boolean areEqual(FluidStack a, FluidStack b) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - return a.isFluidEqual(b); + public static boolean areEqual(@Nullable Fluid fluid, FluidStack fluidStack) { + return fluid == fluidStack.getFluid(); } @Nullable @@ -239,7 +209,6 @@ public enum Fluids { /** * Add non-forestry containers for this fluid. */ - @Nonnull public List getOtherContainers() { return Collections.emptyList(); } @@ -259,7 +228,7 @@ public enum Fluids { public DrinkProperties getDrinkProperties() { return null; } - + public boolean flowTextureExists() { if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { return true; @@ -267,13 +236,14 @@ public enum Fluids { try { ResourceLocation resourceLocation = new ForestryResource("blocks/liquid/" + getTag() + "_flow"); Minecraft minecraft = Proxies.common.getClientInstance(); - if(minecraft != null){ + if (minecraft != null) { IResourceManager resourceManager = minecraft.getResourceManager(); return resourceManager.getResource(resourceLocation) != null; } + return false; } catch (IOException e) { + return false; } - return false; } public ResourceLocation[] getResources() { diff --git a/src/main/java/forestry/core/fluids/ITankManager.java b/src/main/java/forestry/core/fluids/ITankManager.java index e28364b90..233037c87 100644 --- a/src/main/java/forestry/core/fluids/ITankManager.java +++ b/src/main/java/forestry/core/fluids/ITankManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.fluids; +import javax.annotation.Nullable; import java.util.List; import net.minecraft.inventory.Container; @@ -35,5 +36,5 @@ public interface ITankManager extends IFluidHandler { /** * For updating tanks on the client */ - void processTankUpdate(int tankIndex, FluidStack contents); + void processTankUpdate(int tankIndex, @Nullable FluidStack contents); } diff --git a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java index babbfec69..cbf4b8202 100644 --- a/src/main/java/forestry/core/fluids/ITankUpdateHandler.java +++ b/src/main/java/forestry/core/fluids/ITankUpdateHandler.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.fluids; -import forestry.core.fluids.tanks.StandardTank; - public interface ITankUpdateHandler { void updateTankLevels(StandardTank tank); } diff --git a/src/main/java/forestry/core/fluids/PipetteContents.java b/src/main/java/forestry/core/fluids/PipetteContents.java index bcdf36e38..63c715c46 100644 --- a/src/main/java/forestry/core/fluids/PipetteContents.java +++ b/src/main/java/forestry/core/fluids/PipetteContents.java @@ -10,40 +10,31 @@ ******************************************************************************/ package forestry.core.fluids; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; -import forestry.api.core.INbtWritable; +public class PipetteContents { -public class PipetteContents implements INbtWritable { - @Nonnull private final FluidStack contents; @Nullable - public static PipetteContents create(@Nullable ItemStack itemStack) { - if (itemStack == null) { - return null; - } - NBTTagCompound nbt = itemStack.getTagCompound(); - FluidStack contents = FluidStack.loadFluidStackFromNBT(nbt); + public static PipetteContents create(ItemStack itemStack) { + FluidStack contents = FluidUtil.getFluidContained(itemStack); if (contents == null) { return null; } return new PipetteContents(contents); } - public PipetteContents(@Nonnull FluidStack contents) { + public PipetteContents(FluidStack contents) { this.contents = contents; } - @Nonnull public FluidStack getContents() { return contents; } @@ -58,10 +49,4 @@ public class PipetteContents implements INbtWritable { list.add(descr); } - - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - contents.writeToNBT(nbttagcompound); - return nbttagcompound; - } } diff --git a/src/main/java/forestry/core/fluids/tanks/StandardTank.java b/src/main/java/forestry/core/fluids/StandardTank.java similarity index 85% rename from src/main/java/forestry/core/fluids/tanks/StandardTank.java rename to src/main/java/forestry/core/fluids/StandardTank.java index 9811fd556..49ecf2ec1 100644 --- a/src/main/java/forestry/core/fluids/tanks/StandardTank.java +++ b/src/main/java/forestry/core/fluids/StandardTank.java @@ -8,32 +8,26 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.fluids.tanks; +package forestry.core.fluids; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import forestry.core.utils.Translator; import net.minecraft.item.EnumRarity; - import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; -import forestry.core.fluids.FakeTankUpdateHandler; -import forestry.core.fluids.ITankUpdateHandler; -import forestry.core.fluids.TankManager; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.utils.Translator; - /** * @author CovertJaguar */ public class StandardTank extends FluidTank implements IStreamable { private static final int DEFAULT_COLOR = 0xFFFFFF; - @Nonnull + private ITankUpdateHandler tankUpdateHandler = FakeTankUpdateHandler.instance; private int tankIndex; @@ -51,7 +45,7 @@ public class StandardTank extends FluidTank implements IStreamable { this.tankIndex = index; } - public void setTankUpdateHandler(@Nonnull TankManager tankUpdateHandler) { + public void setTankUpdateHandler(TankManager tankUpdateHandler) { this.tankUpdateHandler = tankUpdateHandler; } @@ -79,6 +73,7 @@ public class StandardTank extends FluidTank implements IStreamable { return capacity - getFluidAmount(); } + @Nullable public Fluid getFluidType() { return getFluid() != null ? getFluid().getFluid() : null; } @@ -93,6 +88,7 @@ public class StandardTank extends FluidTank implements IStreamable { } @Override + @Nullable public FluidStack drainInternal(int maxDrain, boolean doDrain) { FluidStack drained = super.drainInternal(maxDrain, doDrain); if (doDrain && drained != null && drained.amount > 0) { @@ -118,8 +114,9 @@ public class StandardTank extends FluidTank implements IStreamable { protected void refreshTooltip() { toolTip.clear(); int amount = 0; - if (hasFluid()) { - Fluid fluidType = getFluidType(); + FluidStack fluidStack = getFluid(); + if (fluidStack != null) { + Fluid fluidType = fluidStack.getFluid(); EnumRarity rarity = fluidType.getRarity(); if (rarity == null) { rarity = EnumRarity.COMMON; @@ -136,17 +133,15 @@ public class StandardTank extends FluidTank implements IStreamable { public void refresh() { refreshTooltip(); } - }; - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeFluidStack(fluid); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { fluid = data.readFluidStack(); } } diff --git a/src/main/java/forestry/core/fluids/TankManager.java b/src/main/java/forestry/core/fluids/TankManager.java index 88ed94f97..7171a9bce 100644 --- a/src/main/java/forestry/core/fluids/TankManager.java +++ b/src/main/java/forestry/core/fluids/TankManager.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.core.fluids; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Table; - -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; @@ -22,26 +18,13 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidTank; -import net.minecraftforge.fluids.capability.FluidTankPropertiesWrapper; -import net.minecraftforge.fluids.capability.IFluidTankProperties; -import net.minecraftforge.fluids.capability.templates.EmptyFluidHandler; - +import com.google.common.collect.HashBasedTable; +import com.google.common.collect.Table; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.fluids.tanks.StandardTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.PacketTankLevelUpdate; import forestry.core.proxy.Proxies; import forestry.core.render.EnumTankLevel; @@ -49,6 +32,17 @@ import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.IRenderableTile; import forestry.core.utils.NBTUtilForestry; import forestry.core.utils.NBTUtilForestry.NBTList; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidTank; +import net.minecraftforge.fluids.capability.FluidTankPropertiesWrapper; +import net.minecraftforge.fluids.capability.IFluidTankProperties; +import net.minecraftforge.fluids.capability.templates.EmptyFluidHandler; /** * @author CovertJaguar @@ -61,6 +55,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl private final Table prevFluidStacks = HashBasedTable.create(); // tank tile updates, for blocks that show fluid levels on the outside + @Nullable private final ILiquidTankTile tile; private final List tankLevels = new ArrayList<>(); @@ -73,7 +68,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl addAll(Arrays.asList(tanks)); } - public final boolean addAll(@Nonnull Collection collection) { + public final boolean addAll(Collection collection) { boolean addedAll = true; for (StandardTank tank : collection) { addedAll &= add(tank); @@ -81,7 +76,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl return addedAll; } - public boolean add(@Nonnull StandardTank tank) { + public boolean add(StandardTank tank) { boolean added = tanks.add(tank); int index = tanks.indexOf(tank); tank.setTankUpdateHandler(this); @@ -120,14 +115,14 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { for (StandardTank tank : tanks) { tank.writeData(data); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { for (StandardTank tank : tanks) { tank.readData(data); } @@ -176,24 +171,26 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl } private void sendTankUpdate(Container container, StandardTank tank, Iterable crafters) { - int tankIndex = tank.getTankIndex(); - FluidStack fluid = tank.getFluid(); - IForestryPacketClient packet = new PacketTankLevelUpdate(tile, tankIndex, fluid); - for (IContainerListener crafter : crafters) { - if (crafter instanceof EntityPlayerMP) { - Proxies.net.sendToPlayer(packet, (EntityPlayerMP) crafter); + if (tile != null) { + int tankIndex = tank.getTankIndex(); + FluidStack fluid = tank.getFluid(); + IForestryPacketClient packet = new PacketTankLevelUpdate(tile, tankIndex, fluid); + for (IContainerListener crafter : crafters) { + if (crafter instanceof EntityPlayerMP) { + Proxies.net.sendToPlayer(packet, (EntityPlayerMP) crafter); + } } - } - if (fluid == null) { - prevFluidStacks.remove(container, tankIndex); - } else { - prevFluidStacks.put(container, tankIndex, fluid.copy()); + if (fluid == null) { + prevFluidStacks.remove(container, tankIndex); + } else { + prevFluidStacks.put(container, tankIndex, fluid.copy()); + } } } @Override - public void processTankUpdate(int tankIndex, FluidStack contents) { + public void processTankUpdate(int tankIndex, @Nullable FluidStack contents) { if (tankIndex < 0 || tankIndex > tanks.size()) { return; } @@ -218,7 +215,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl } public int fill(int tankIndex, FluidStack resource, boolean doFill) { - if (tankIndex < 0 || tankIndex >= tanks.size() || resource == null) { + if (tankIndex < 0 || tankIndex >= tanks.size()) { return 0; } @@ -246,7 +243,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl tankLevels.set(tankIndex, tankLevel); if (sendUpdate) { PacketTankLevelUpdate tankLevelUpdate = new PacketTankLevelUpdate(tile, tankIndex, tank.getFluid()); - Proxies.net.sendNetworkPacket(tankLevelUpdate, tile.getWorldObj()); + Proxies.net.sendNetworkPacket(tankLevelUpdate, tile.getCoordinates(), tile.getWorldObj()); } } } @@ -262,6 +259,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl return EmptyFluidHandler.INSTANCE.drain(maxDrain, doDrain); } + @Nullable public FluidStack drain(int tankIndex, int maxDrain, boolean doDrain) { if (tankIndex < 0 || tankIndex >= tanks.size()) { return null; @@ -309,10 +307,6 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl @Override public boolean canFillFluidType(FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - for (StandardTank tank : tanks) { if (tank.canFillFluidType(fluidStack)) { return true; @@ -324,10 +318,6 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl @Override public boolean canDrainFluidType(FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - for (StandardTank tank : tanks) { if (tank.canDrainFluidType(fluidStack)) { return true; @@ -338,13 +328,8 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl } private static boolean tankAcceptsFluid(StandardTank tank, FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - if (!tank.canFill()) { - return false; - } - return tank.fill(fluidStack, false) > 0; + return tank.canFill() && + tank.fill(fluidStack, false) > 0; } private static boolean tankCanDrain(StandardTank tank) { @@ -356,12 +341,7 @@ public class TankManager implements ITankManager, ITankUpdateHandler, IStreamabl } private static boolean tankCanDrainFluid(StandardTank tank, FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - if (!Fluids.areEqual(tank.getFluidType(), fluidStack)) { - return false; - } - return tankCanDrain(tank); + return Fluids.areEqual(tank.getFluidType(), fluidStack) && + tankCanDrain(tank); } } diff --git a/src/main/java/forestry/core/fluids/package-info.java b/src/main/java/forestry/core/fluids/package-info.java new file mode 100644 index 000000000..85a95a24b --- /dev/null +++ b/src/main/java/forestry/core/fluids/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.fluids; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/genetics/BreedingTracker.java b/src/main/java/forestry/core/genetics/BreedingTracker.java index 339a61a05..d0732e0ac 100755 --- a/src/main/java/forestry/core/genetics/BreedingTracker.java +++ b/src/main/java/forestry/core/genetics/BreedingTracker.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; @@ -18,17 +17,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; -import net.minecraft.world.WorldSavedData; - import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.util.FakePlayer; - import forestry.api.core.ForestryEvent; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; @@ -38,6 +27,13 @@ import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; import forestry.core.network.packets.PacketGenomeTrackerSync; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; +import net.minecraft.world.WorldSavedData; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.util.FakePlayer; public abstract class BreedingTracker extends WorldSavedData implements IBreedingTracker { @@ -56,6 +52,7 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin private final Set discoveredSpecies = new HashSet<>(); private final Set discoveredMutations = new HashSet<>(); private final Set researchedMutations = new HashSet<>(); + @Nullable private String modeName; @Nullable @@ -76,6 +73,7 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin } @Override + @Nullable public String getModeName() { return modeName; } @@ -89,7 +87,7 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin /** * Returns the common tracker * - * @param player used to get worldObj + * @param player used to get world * @return common tracker for this breeding system */ protected abstract IBreedingTracker getBreedingTracker(EntityPlayer player); @@ -141,7 +139,7 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin } @Override - public void readFromNBT(@Nonnull NBTTagCompound nbttagcompound) { + public void readFromNBT(NBTTagCompound nbttagcompound) { if (nbttagcompound.hasKey(MODE_NAME_KEY)) { modeName = nbttagcompound.getString(MODE_NAME_KEY); @@ -152,9 +150,9 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin readValuesFromNBT(nbttagcompound, researchedMutations, RESEARCHED_COUNT_KEY, RESEARCHED_KEY); } - @Nonnull + @Override - public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound nbttagcompound) { + public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { writeToNBT(nbttagcompound, discoveredSpecies, discoveredMutations, researchedMutations); return nbttagcompound; } @@ -175,9 +173,11 @@ public abstract class BreedingTracker extends WorldSavedData implements IBreedin if (nbttagcompound.hasKey(countKey)) { final int count = nbttagcompound.getInteger(countKey); for (int i = 0; i < count; i++) { - String value = nbttagcompound.getString(key + i); - if (value != null && !value.isEmpty()) { - values.add(value); + if (nbttagcompound.hasKey(key + i)) { + String value = nbttagcompound.getString(key + i); + if (!value.isEmpty()) { + values.add(value); + } } } } diff --git a/src/main/java/forestry/core/genetics/Chromosome.java b/src/main/java/forestry/core/genetics/Chromosome.java index eae2deaf4..9cc846e5b 100755 --- a/src/main/java/forestry/core/genetics/Chromosome.java +++ b/src/main/java/forestry/core/genetics/Chromosome.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Random; @@ -22,17 +21,13 @@ import forestry.api.genetics.ISpeciesRoot; import net.minecraft.nbt.NBTTagCompound; public class Chromosome implements IChromosome { - private static final String UID0_TAG = "UID0"; private static final String UID1_TAG = "UID1"; - @Nonnull private final IAllele primary; - @Nonnull private final IAllele secondary; - @Nonnull - public static Chromosome create(@Nullable String primarySpeciesUid, @Nullable String secondarySpeciesUid, @Nonnull IChromosomeType chromosomeType, @Nonnull NBTTagCompound nbt) { + public static Chromosome create(@Nullable String primarySpeciesUid, @Nullable String secondarySpeciesUid, IChromosomeType chromosomeType, NBTTagCompound nbt) { IAllele primary = AlleleManager.alleleRegistry.getAllele(nbt.getString(UID0_TAG)); IAllele secondary = AlleleManager.alleleRegistry.getAllele(nbt.getString(UID1_TAG)); @@ -42,8 +37,7 @@ public class Chromosome implements IChromosome { return new Chromosome(primary, secondary); } - @Nonnull - private static IAllele validateAllele(@Nullable String speciesUid, @Nonnull IChromosomeType chromosomeType, @Nullable IAllele allele) { + private static IAllele validateAllele(@Nullable String speciesUid, IChromosomeType chromosomeType, @Nullable IAllele allele) { if (!chromosomeType.getAlleleClass().isInstance(allele)) { ISpeciesRoot speciesRoot = chromosomeType.getSpeciesRoot(); @@ -62,11 +56,11 @@ public class Chromosome implements IChromosome { return allele; } - public Chromosome(@Nonnull IAllele allele) { + public Chromosome(IAllele allele) { primary = secondary = allele; } - public Chromosome(@Nonnull IAllele primary, @Nonnull IAllele secondary) { + public Chromosome(IAllele primary, IAllele secondary) { this.primary = primary; this.secondary = secondary; } diff --git a/src/main/java/forestry/core/genetics/Classification.java b/src/main/java/forestry/core/genetics/Classification.java index 8b6cc029f..156898f95 100755 --- a/src/main/java/forestry/core/genetics/Classification.java +++ b/src/main/java/forestry/core/genetics/Classification.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.genetics; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Locale; @@ -23,7 +24,7 @@ public class Classification implements IClassification { private final EnumClassLevel level; private final String uid; private final String scientific; - + @Nullable private IClassification parent; private final ArrayList members = new ArrayList<>(); @@ -47,6 +48,7 @@ public class Classification implements IClassification { } @Override + @Nullable public IClassification getParent() { return parent; } diff --git a/src/main/java/forestry/core/genetics/EffectData.java b/src/main/java/forestry/core/genetics/EffectData.java index 0e14cf15a..b6c0e02cb 100755 --- a/src/main/java/forestry/core/genetics/EffectData.java +++ b/src/main/java/forestry/core/genetics/EffectData.java @@ -17,7 +17,6 @@ import forestry.api.genetics.IEffectData; public class EffectData implements IEffectData { private final int[] intData; - private float[] floatData; private final boolean[] boolData; public EffectData(int intSize, int boolSize) { @@ -49,16 +48,6 @@ public class EffectData implements IEffectData { return intData.length; } - @Override - public void setFloat(int index, float val) { - floatData[index] = val; - } - - @Override - public float getFloat(int index) { - return floatData[index]; - } - @Override public void readFromNBT(NBTTagCompound nbttagcompound) { } diff --git a/src/main/java/forestry/core/genetics/Genome.java b/src/main/java/forestry/core/genetics/Genome.java index 9a3e97634..cf9c26827 100755 --- a/src/main/java/forestry/core/genetics/Genome.java +++ b/src/main/java/forestry/core/genetics/Genome.java @@ -10,11 +10,11 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; import com.google.common.base.Objects; +import com.google.common.base.Preconditions; import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IChromosome; @@ -26,23 +26,21 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; public abstract class Genome implements IGenome { - private static final String SLOT_TAG = "Slot"; - @Nonnull private final IChromosome[] chromosomes; - protected Genome(@Nonnull NBTTagCompound nbttagcompound) { + protected Genome(NBTTagCompound nbttagcompound) { this.chromosomes = getChromosomes(nbttagcompound, getSpeciesRoot()); } - protected Genome(@Nonnull IChromosome[] chromosomes) { + protected Genome(IChromosome[] chromosomes) { checkChromosomes(chromosomes); this.chromosomes = chromosomes; } private void checkChromosomes(IChromosome[] chromosomes) { - if (chromosomes == null || chromosomes.length != getDefaultTemplate().length) { + if (chromosomes.length != getDefaultTemplate().length) { String message = String.format("Tried to create a genome for '%s' from an invalid chromosome template.\n%s", getSpeciesRoot().getUID(), chromosomesToString(chromosomes)); throw new IllegalArgumentException(message); } @@ -87,10 +85,6 @@ public abstract class Genome implements IGenome { } private String chromosomesToString(IChromosome[] chromosomes) { - if (chromosomes == null) { - return "null"; - } - StringBuilder stringBuilder = new StringBuilder(); IChromosomeType[] karyotype = getSpeciesRoot().getKaryotype(); for (int i = 0; i < chromosomes.length; i++) { @@ -113,7 +107,7 @@ public abstract class Genome implements IGenome { * We need this because the client uses the species for rendering. */ @Nullable - public static IAlleleSpecies getSpeciesDirectly(@Nonnull ISpeciesRoot speciesRoot, @Nonnull ItemStack itemStack) { + public static IAlleleSpecies getSpeciesDirectly(ISpeciesRoot speciesRoot, ItemStack itemStack) { NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); if (nbtTagCompound == null) { return null; @@ -142,24 +136,18 @@ public abstract class Genome implements IGenome { private static IChromosome getChromosome(ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { NBTTagCompound nbtTagCompound = itemStack.getTagCompound(); - if (nbtTagCompound == null) { - return null; - } + Preconditions.checkArgument(nbtTagCompound != null, "itemStack must have nbt"); NBTTagCompound genome = nbtTagCompound.getCompoundTag("Genome"); - if (genome.hasNoTags()) { - return null; - } + Preconditions.checkArgument(!genome.hasNoTags(), "itemStack nbt must have a genome tag"); IChromosome[] chromosomes = getChromosomes(genome, speciesRoot); - if (chromosomes == null) { - return null; - } return chromosomes[chromosomeType.ordinal()]; } - private static IChromosome[] getChromosomes(@Nonnull NBTTagCompound genomeNBT, @Nonnull ISpeciesRoot speciesRoot) { + + private static IChromosome[] getChromosomes(NBTTagCompound genomeNBT, ISpeciesRoot speciesRoot) { NBTTagList chromosomesNBT = genomeNBT.getTagList("Chromosomes", 10); IChromosome[] chromosomes = new IChromosome[speciesRoot.getDefaultTemplate().length]; @@ -188,9 +176,6 @@ public abstract class Genome implements IGenome { protected static IAllele getActiveAllele(ItemStack itemStack, IChromosomeType chromosomeType, ISpeciesRoot speciesRoot) { IChromosome chromosome = getChromosome(itemStack, chromosomeType, speciesRoot); - if (chromosome == null) { - return null; - } return chromosome.getActiveAllele(); } @@ -212,19 +197,19 @@ public abstract class Genome implements IGenome { // / INFORMATION RETRIEVAL @Override - @Nonnull + public IChromosome[] getChromosomes() { return Arrays.copyOf(chromosomes, chromosomes.length); } @Override - @Nonnull + public IAllele getActiveAllele(IChromosomeType chromosomeType) { return chromosomes[chromosomeType.ordinal()].getActiveAllele(); } @Override - @Nonnull + public IAllele getInactiveAllele(IChromosomeType chromosomeType) { return chromosomes[chromosomeType.ordinal()].getInactiveAllele(); } diff --git a/src/main/java/forestry/core/genetics/Individual.java b/src/main/java/forestry/core/genetics/Individual.java index cd85cd0b7..9e2b6dd6c 100755 --- a/src/main/java/forestry/core/genetics/Individual.java +++ b/src/main/java/forestry/core/genetics/Individual.java @@ -10,22 +10,18 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nonnull; - -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IIndividual; +import net.minecraft.nbt.NBTTagCompound; public abstract class Individual implements IIndividual { - protected boolean isAnalyzed; protected Individual() { isAnalyzed = false; } - protected Individual(@Nonnull NBTTagCompound nbt) { + protected Individual(NBTTagCompound nbt) { isAnalyzed = nbt.getBoolean("IsAnalyzed"); } diff --git a/src/main/java/forestry/core/genetics/IndividualLiving.java b/src/main/java/forestry/core/genetics/IndividualLiving.java index 3bcaa6b0f..797d9f775 100755 --- a/src/main/java/forestry/core/genetics/IndividualLiving.java +++ b/src/main/java/forestry/core/genetics/IndividualLiving.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.core.genetics; -import javax.annotation.Nonnull; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; +import javax.annotation.Nullable; import forestry.api.genetics.IGenome; import forestry.api.genetics.IIndividualLiving; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public abstract class IndividualLiving extends Individual implements IIndividualLiving { @@ -25,12 +24,12 @@ public abstract class IndividualLiving extends Individual implements IIndividual protected IndividualLiving() { } - + protected IndividualLiving(int newHealth) { health = maxHealth = newHealth; } - protected IndividualLiving(@Nonnull NBTTagCompound nbt) { + protected IndividualLiving(NBTTagCompound nbt) { super(nbt); health = nbt.getInteger("Health"); maxHealth = nbt.getInteger("MaxH"); @@ -44,11 +43,10 @@ public abstract class IndividualLiving extends Individual implements IIndividual nbttagcompound.setInteger("Health", health); nbttagcompound.setInteger("MaxH", maxHealth); - if (getGenome() != null) { - NBTTagCompound nbtGenome = new NBTTagCompound(); - getGenome().writeToNBT(nbtGenome); - nbttagcompound.setTag("Genome", nbtGenome); - } + NBTTagCompound nbtGenome = new NBTTagCompound(); + getGenome().writeToNBT(nbtGenome); + nbttagcompound.setTag("Genome", nbtGenome); + if (getMate() != null) { NBTTagCompound nbtMate = new NBTTagCompound(); getMate().writeToNBT(nbtMate); @@ -59,6 +57,7 @@ public abstract class IndividualLiving extends Individual implements IIndividual /* GENERATION */ @Override + @Nullable public abstract IGenome getMate(); @Override diff --git a/src/main/java/forestry/core/genetics/ItemGE.java b/src/main/java/forestry/core/genetics/ItemGE.java index 060c56c9f..f881e201e 100755 --- a/src/main/java/forestry/core/genetics/ItemGE.java +++ b/src/main/java/forestry/core/genetics/ItemGE.java @@ -17,9 +17,6 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IIndividual; import forestry.core.items.ItemForestry; @@ -54,12 +51,12 @@ public abstract class ItemGE extends ItemForestry { @Override public boolean hasEffect(ItemStack stack) { IAlleleSpecies species = getSpecies(stack); - return species != null && species.hasEffect(); + return species.hasEffect(); } @Override public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return; } @@ -75,9 +72,4 @@ public abstract class ItemGE extends ItemForestry { list.add("<" + Translator.translateToLocal("for.gui.unknown") + ">"); } } - - @SideOnly(Side.CLIENT) - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - return 0xffffff; - } } diff --git a/src/main/java/forestry/core/genetics/ItemResearchNote.java b/src/main/java/forestry/core/genetics/ItemResearchNote.java index 405fa7155..ab5b9eac3 100755 --- a/src/main/java/forestry/core/genetics/ItemResearchNote.java +++ b/src/main/java/forestry/core/genetics/ItemResearchNote.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.genetics; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -44,6 +45,7 @@ public class ItemResearchNote extends ItemForestry { public static final EnumNoteType[] VALUES = values(); + @Nullable private static IMutation getEncodedMutation(ISpeciesRoot root, NBTTagCompound compound) { IAllele allele0 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL0")); IAllele allele1 = AlleleManager.alleleRegistry.getAllele(compound.getString("AL1")); @@ -70,10 +72,10 @@ public class ItemResearchNote extends ItemForestry { return encoded; } - public ArrayList getTooltip(NBTTagCompound compound) { - ArrayList tooltips = new ArrayList<>(); + public List getTooltip(NBTTagCompound compound) { + List tooltips = new ArrayList<>(); - if (compound == null || this == NONE) { + if (this == NONE) { return tooltips; } @@ -122,7 +124,7 @@ public class ItemResearchNote extends ItemForestry { } public boolean registerResults(World world, EntityPlayer player, NBTTagCompound compound) { - if (compound == null || this == NONE) { + if (this == NONE) { return false; } @@ -139,7 +141,7 @@ public class ItemResearchNote extends ItemForestry { IBreedingTracker tracker = encoded.getRoot().getBreedingTracker(world, player.getGameProfile()); if (tracker.isResearched(encoded)) { - player.addChatMessage(new TextComponentTranslation("for.chat.cannotmemorizeagain")); + player.sendMessage(new TextComponentTranslation("for.chat.cannotmemorizeagain")); return false; } @@ -152,9 +154,9 @@ public class ItemResearchNote extends ItemForestry { tracker.registerSpecies(speciesResult); tracker.researchMutation(encoded); - player.addChatMessage(new TextComponentTranslation("for.chat.memorizednote")); + player.sendMessage(new TextComponentTranslation("for.chat.memorizednote")); - player.addChatMessage(new TextComponentTranslation("for.chat.memorizednote2", + player.sendMessage(new TextComponentTranslation("for.chat.memorizednote2", TextFormatting.GRAY + species0.getName(), TextFormatting.GRAY + species1.getName(), TextFormatting.GREEN + speciesResult.getName())); @@ -203,7 +205,7 @@ public class ItemResearchNote extends ItemForestry { } public static class ResearchNote { - + @Nullable private final GameProfile researcher; private final EnumNoteType type; private final NBTTagCompound inner; @@ -214,7 +216,7 @@ public class ItemResearchNote extends ItemForestry { this.inner = inner; } - public ResearchNote(NBTTagCompound compound) { + public ResearchNote(@Nullable NBTTagCompound compound) { if (compound != null) { if (compound.hasKey("res")) { this.researcher = PlayerUtil.readGameProfileFromNBT(compound.getCompoundTag("res")); @@ -242,7 +244,7 @@ public class ItemResearchNote extends ItemForestry { } public void addTooltip(List list) { - ArrayList tooltips = type.getTooltip(inner); + List tooltips = type.getTooltip(inner); if (tooltips.size() <= 0) { list.add(TextFormatting.ITALIC + TextFormatting.RED.toString() + Translator.translateToLocal("for.researchNote.error.0")); list.add(Translator.translateToLocal("for.researchNote.error.1")); @@ -281,23 +283,19 @@ public class ItemResearchNote extends ItemForestry { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + ItemStack heldItem = playerIn.getHeldItem(handIn); if (worldIn.isRemote) { - return ActionResult.newResult(EnumActionResult.PASS, itemStackIn); + return ActionResult.newResult(EnumActionResult.PASS, heldItem); } - ResearchNote note = new ResearchNote(itemStackIn.getTagCompound()); + ResearchNote note = new ResearchNote(heldItem.getTagCompound()); if (note.registerResults(worldIn, playerIn)) { playerIn.inventory.decrStackSize(playerIn.inventory.currentItem, 1); // Notify player that his inventory has changed. Proxies.net.inventoryChangeNotify(playerIn); } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, heldItem); } - -// @Override -// public int getColorFromItemstack(ItemStack itemstack, int j) { -// return 0xffe8a5; -// } } diff --git a/src/main/java/forestry/core/genetics/SpeciesRoot.java b/src/main/java/forestry/core/genetics/SpeciesRoot.java index 9c1220ef0..4e781aa4d 100755 --- a/src/main/java/forestry/core/genetics/SpeciesRoot.java +++ b/src/main/java/forestry/core/genetics/SpeciesRoot.java @@ -29,10 +29,10 @@ import forestry.api.genetics.ISpeciesRoot; import net.minecraft.item.ItemStack; public abstract class SpeciesRoot implements ISpeciesRoot { - + /* RESEARCH */ private final LinkedHashMap researchCatalysts = new LinkedHashMap<>(); - + @Override public Map getResearchCatalysts() { return Collections.unmodifiableMap(researchCatalysts); @@ -50,7 +50,7 @@ public abstract class SpeciesRoot implements ISpeciesRoot { public Map getGenomeTemplates() { return speciesTemplates; } - + @Override public void registerTemplate(IAllele[] template) { if (template == null) { diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java index b6285bfbb..448abb6e3 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleHelper.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.genetics.alleles; +import javax.annotation.Nullable; +import java.util.Collection; import java.util.EnumMap; import java.util.HashMap; import java.util.Locale; @@ -35,21 +37,23 @@ import forestry.plugins.ForestryPluginUids; public class AlleleHelper implements IAlleleHelper { private static final String modId = Constants.MOD_ID; - public static AlleleHelper instance; + @Nullable + private static AlleleHelper instance; private final Map> alleleMaps = new HashMap<>(); + public static AlleleHelper getInstance() { + if (instance == null) { + instance = new AlleleHelper(); + } + return instance; + } + public void init() { if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.APICULTURE)) { createAlleles(EnumAllele.Fertility.class, EnumBeeChromosome.FERTILITY); createAlleles(EnumAllele.Flowering.class, EnumBeeChromosome.FLOWERING); - } - - if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.APICULTURE) || ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ARBORICULTURE)) { - createAlleles(EnumAllele.Territory.class, - EnumBeeChromosome.TERRITORY, - EnumTreeChromosome.TERRITORY - ); + createAlleles(EnumAllele.Territory.class, EnumBeeChromosome.TERRITORY); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.APICULTURE) || ForestryAPI.enabledPlugins.contains(ForestryPluginUids.LEPIDOPTEROLOGY)) { @@ -91,20 +95,11 @@ public class AlleleHelper implements IAlleleHelper { IAlleleInteger alleleInteger = new AlleleInteger(modId, "i", i + "d", i, true); AlleleManager.alleleRegistry.registerAllele(alleleInteger, EnumTreeChromosome.GIRTH, - EnumTreeChromosome.CARBONIZATION, - EnumTreeChromosome.COMBUSTIBILITY, EnumButterflyChromosome.METABOLISM, EnumButterflyChromosome.FERTILITY ); integers.put(i, alleleInteger); } - for (int i = 11; i <= 25; i++) { - IAlleleInteger alleleInteger = new AlleleInteger(modId, "i", i + "d", i, true); - AlleleManager.alleleRegistry.registerAllele(alleleInteger, - EnumTreeChromosome.COMBUSTIBILITY - ); - integers.put(i, alleleInteger); - } alleleMaps.put(Integer.class, integers); Map booleans = new HashMap<>(); @@ -139,18 +134,14 @@ public class AlleleHelper implements IAlleleHelper { @Override public & IChromosomeType> void set(IAllele[] alleles, T chromosomeType, IAllele allele) { - if (allele == null) { - throw new NullPointerException("Allele must not be null"); - } if (!chromosomeType.getAlleleClass().isInstance(allele)) { throw new IllegalArgumentException("Allele is the wrong type. Expected: " + chromosomeType + " Got: " + allele); } - // uncomment this once all addon mods are using the allele registration with IChromosomeType - // Collection validTypes = AlleleManager.alleleRegistry.getChromosomeTypes(allele); - // if (validTypes.size() > 0 && !validTypes.contains(chromosomeType)) { - // throw new IllegalArgumentException("Allele can't applied to this Chromosome type. Expected: " + validTypes + " Got: " + chromosomeType); - // } + Collection validTypes = AlleleManager.alleleRegistry.getChromosomeTypes(allele); + if (validTypes.size() > 0 && !validTypes.contains(chromosomeType)) { + throw new IllegalArgumentException("Allele can't applied to this Chromosome type. Expected: " + validTypes + " Got: " + chromosomeType); + } alleles[chromosomeType.ordinal()] = allele; } diff --git a/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java b/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java deleted file mode 100644 index d098c4097..000000000 --- a/src/main/java/forestry/core/genetics/alleles/AllelePlantType.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.genetics.alleles; - -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; -import java.util.Locale; - -import net.minecraftforge.common.EnumPlantType; - -import forestry.api.arboriculture.EnumTreeChromosome; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllelePlantType; -import forestry.core.config.Constants; - -public class AllelePlantType extends AlleleCategorized implements IAllelePlantType { - - public static IAllelePlantType plantTypeNone; - public static IAllelePlantType plantTypePlains; - public static IAllelePlantType plantTypeDesert; - public static IAllelePlantType plantTypeBeach; - public static IAllelePlantType plantTypeCave; - public static IAllelePlantType plantTypeWater; - public static IAllelePlantType plantTypeNether; - public static IAllelePlantType plantTypeCrop; - - public static void createAlleles() { - List alleles = Arrays.asList( - plantTypeNone = new AllelePlantType("none", EnumSet.noneOf(EnumPlantType.class), true), - plantTypePlains = new AllelePlantType(EnumPlantType.Plains), - plantTypeDesert = new AllelePlantType(EnumPlantType.Desert), - plantTypeBeach = new AllelePlantType(EnumPlantType.Beach), - plantTypeCave = new AllelePlantType(EnumPlantType.Cave), - plantTypeWater = new AllelePlantType(EnumPlantType.Water), - plantTypeNether = new AllelePlantType(EnumPlantType.Nether), - plantTypeCrop = new AllelePlantType(EnumPlantType.Crop) - ); - - for (IAllelePlantType allele : alleles) { - AlleleManager.alleleRegistry.registerAllele(allele, EnumTreeChromosome.PLANT); - } - } - - private final EnumSet types; - - protected AllelePlantType(EnumPlantType type) { - this(type.toString().toLowerCase(Locale.ENGLISH), EnumSet.of(type), false); - } - - protected AllelePlantType(String name, EnumSet types, boolean isDominant) { - super(Constants.MOD_ID, "plantType", name, isDominant); - this.types = types; - } - - @Override - public EnumSet getPlantTypes() { - return types; - } -} diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java index 3a8a1406c..41d82e916 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleRegistry.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.genetics.alleles; +import javax.annotation.Nullable; + import com.google.common.collect.HashMultimap; import java.util.ArrayList; @@ -18,6 +20,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; import net.minecraft.item.ItemStack; @@ -42,6 +45,19 @@ public class AlleleRegistry implements IAlleleRegistry { private static final int ALLELE_ARRAY_SIZE = 2048; + /* ALLELES */ + private final LinkedHashMap alleleMap = new LinkedHashMap<>(ALLELE_ARRAY_SIZE); + private final HashMultimap allelesByType = HashMultimap.create(); + private final HashMultimap typesByAllele = HashMultimap.create(); + private final LinkedHashMap deprecatedAlleleMap = new LinkedHashMap<>(32); + private final LinkedHashMap classificationMap = new LinkedHashMap<>(128); + private final LinkedHashMap fruitMap = new LinkedHashMap<>(64); + + /* + * Internal Set of all alleleHandlers, which trigger when an allele or branch is registered + */ + private final Set alleleHandlers = new HashSet<>(); + /* SPECIES ROOT */ private final LinkedHashMap rootMap = new LinkedHashMap<>(16); @@ -56,13 +72,15 @@ public class AlleleRegistry implements IAlleleRegistry { } @Override + @Nullable public ISpeciesRoot getSpeciesRoot(String uid) { return rootMap.get(uid); } @Override + @Nullable public ISpeciesRoot getSpeciesRoot(ItemStack stack) { - if (stack == null) { + if (stack.isEmpty()) { return null; } @@ -75,6 +93,7 @@ public class AlleleRegistry implements IAlleleRegistry { } @Override + @Nullable public ISpeciesRoot getSpeciesRoot(Class clz) { for (ISpeciesRoot root : rootMap.values()) { if (root.getMemberClass().isAssignableFrom(clz)) { @@ -84,16 +103,19 @@ public class AlleleRegistry implements IAlleleRegistry { return null; } + @Override + public ISpeciesRoot getSpeciesRoot(IIndividual individual) { + return individual.getGenome().getSpeciesRoot(); + } + /* INDIVIDUALS */ @Override public boolean isIndividual(ItemStack stack) { - if (stack == null) { - return false; - } return getSpeciesRoot(stack) != null; } @Override + @Nullable public IIndividual getIndividual(ItemStack stack) { ISpeciesRoot root = getSpeciesRoot(stack); if (root == null) { @@ -103,19 +125,6 @@ public class AlleleRegistry implements IAlleleRegistry { return root.getMember(stack); } - /* ALLELES */ - private final LinkedHashMap alleleMap = new LinkedHashMap<>(ALLELE_ARRAY_SIZE); - private final HashMultimap allelesByType = HashMultimap.create(); - private final HashMultimap typesByAllele = HashMultimap.create(); - private final LinkedHashMap deprecatedAlleleMap = new LinkedHashMap<>(32); - private final LinkedHashMap classificationMap = new LinkedHashMap<>(128); - private final LinkedHashMap fruitMap = new LinkedHashMap<>(64); - - /* - * Internal HashSet of all alleleHandlers, which trigger when an allele or branch is registered - */ - private final HashSet alleleHandlers = new HashSet<>(); - public void initialize() { createAndRegisterClassification(EnumClassLevel.DOMAIN, "archaea", "Archaea"); diff --git a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java index f5a95e68a..934ea7945 100644 --- a/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java +++ b/src/main/java/forestry/core/genetics/alleles/AlleleSpecies.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.core.genetics.alleles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -45,15 +45,16 @@ public abstract class AlleleSpecies extends Allele implements IAlleleSpeciesBuil private boolean isCounted = true; private EnumTemperature climate = EnumTemperature.NORMAL; private EnumHumidity humidity = EnumHumidity.NORMAL; + @Nullable private Integer complexityOverride = null; - protected AlleleSpecies(@Nonnull String uid, - @Nonnull String unlocalizedName, - @Nonnull String authority, - @Nonnull String unlocalizedDescription, - boolean isDominant, - @Nonnull IClassification branch, - @Nonnull String binomial) { + protected AlleleSpecies(String uid, + String unlocalizedName, + String authority, + String unlocalizedDescription, + boolean isDominant, + IClassification branch, + String binomial) { super(uid, unlocalizedName, isDominant); this.branch = branch; @@ -69,7 +70,7 @@ public abstract class AlleleSpecies extends Allele implements IAlleleSpeciesBuil @Override public float getResearchSuitability(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return 0f; } diff --git a/src/main/java/forestry/core/genetics/alleles/package-info.java b/src/main/java/forestry/core/genetics/alleles/package-info.java new file mode 100644 index 000000000..b49b19670 --- /dev/null +++ b/src/main/java/forestry/core/genetics/alleles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.genetics.alleles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java index 002a8f99c..8f5a4be4b 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionBiome.java @@ -37,7 +37,7 @@ public class MutationConditionBiome implements IMutationCondition { public float getChance(World world, BlockPos pos, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { Biome biome = climate.getBiome(); for (BiomeDictionary.Type type : validBiomeTypes) { - if (BiomeDictionary.isBiomeOfType(biome, type)) { + if (BiomeDictionary.hasType(biome, type)) { return 1; } } diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java index b08214b42..549a4a628 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionRequiresResource.java @@ -22,6 +22,7 @@ import forestry.api.genetics.IMutationCondition; import forestry.core.utils.Translator; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -37,13 +38,11 @@ public class MutationConditionRequiresResource implements IMutationCondition { public MutationConditionRequiresResource(String oreDictName) { this.displayName = oreDictName; for (ItemStack ore : OreDictionary.getOres(oreDictName)) { - if (ore != null) { + if (!ore.isEmpty()) { Item oreItem = ore.getItem(); - if (oreItem != null) { - Block oreBlock = Block.getBlockFromItem(oreItem); - if (oreBlock != null) { - this.acceptedBlockStates.addAll(oreBlock.getBlockState().getValidStates()); - } + Block oreBlock = Block.getBlockFromItem(oreItem); + if (oreBlock != Blocks.AIR) { + this.acceptedBlockStates.addAll(oreBlock.getBlockState().getValidStates()); } } } diff --git a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java index 3a890c373..b148a5032 100644 --- a/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java +++ b/src/main/java/forestry/core/genetics/mutations/MutationConditionTemperature.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.core.genetics.mutations; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; import forestry.api.climate.IClimateProvider; import forestry.api.core.EnumTemperature; import forestry.api.genetics.AlleleManager; @@ -20,6 +17,8 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IGenome; import forestry.api.genetics.IMutationCondition; import forestry.core.utils.Translator; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class MutationConditionTemperature implements IMutationCondition { @@ -33,7 +32,6 @@ public class MutationConditionTemperature implements IMutationCondition { @Override public float getChance(World world, BlockPos pos, IAllele allele0, IAllele allele1, IGenome genome0, IGenome genome1, IClimateProvider climate) { - Biome biome = world.getBiomeProvider().getBiome(pos); EnumTemperature biomeTemperature = climate.getTemperature(); if (biomeTemperature.ordinal() < minTemperature.ordinal() || biomeTemperature.ordinal() > maxTemperature.ordinal()) { diff --git a/src/main/java/forestry/core/genetics/mutations/package-info.java b/src/main/java/forestry/core/genetics/mutations/package-info.java new file mode 100644 index 000000000..bf9640684 --- /dev/null +++ b/src/main/java/forestry/core/genetics/mutations/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.genetics.mutations; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/genetics/package-info.java b/src/main/java/forestry/core/genetics/package-info.java new file mode 100644 index 000000000..43b0f9cd8 --- /dev/null +++ b/src/main/java/forestry/core/genetics/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.genetics; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/ContainerEntity.java b/src/main/java/forestry/core/gui/ContainerEntity.java index de07830c3..a4c20eb94 100644 --- a/src/main/java/forestry/core/gui/ContainerEntity.java +++ b/src/main/java/forestry/core/gui/ContainerEntity.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; + import com.google.common.collect.ImmutableSet; import forestry.api.core.IErrorLogicSource; import forestry.api.core.IErrorState; @@ -21,6 +23,7 @@ import net.minecraft.inventory.IInventory; public class ContainerEntity extends ContainerForestry { protected final T entity; + @Nullable private ImmutableSet previousErrorStates; protected ContainerEntity(T entity) { @@ -34,12 +37,12 @@ public class ContainerEntity extends ContainerFor @Override protected final boolean canAccess(EntityPlayer player) { - return player != null; + return true; } @Override public final boolean canInteractWith(EntityPlayer entityplayer) { - return entity.isUseableByPlayer(entityplayer); + return entity.isUsableByPlayer(entityplayer); } @Override diff --git a/src/main/java/forestry/core/gui/ContainerEscritoire.java b/src/main/java/forestry/core/gui/ContainerEscritoire.java index 77a73500c..a428ec706 100755 --- a/src/main/java/forestry/core/gui/ContainerEscritoire.java +++ b/src/main/java/forestry/core/gui/ContainerEscritoire.java @@ -16,7 +16,6 @@ import net.minecraft.entity.player.EntityPlayerMP; import forestry.core.gui.slots.SlotFiltered; import forestry.core.gui.slots.SlotOutput; import forestry.core.inventory.InventoryEscritoire; -import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.network.packets.PacketGuiUpdate; import forestry.core.tiles.EscritoireGame; import forestry.core.tiles.TileEscritoire; @@ -53,17 +52,16 @@ public class ContainerEscritoire extends ContainerTile implement } @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + public void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary) { EscritoireGame.Status status = tile.getGame().getStatus(); if (status != EscritoireGame.Status.PLAYING) { return; } - int index = packet.getPrimaryIndex(); - if (index == -1) { + if (primary == -1) { tile.probe(); } else { - tile.choose(player.getGameProfile(), index); + tile.choose(player.getGameProfile(), primary); } } } diff --git a/src/main/java/forestry/core/gui/ContainerForestry.java b/src/main/java/forestry/core/gui/ContainerForestry.java index a68941f79..a1298412c 100644 --- a/src/main/java/forestry/core/gui/ContainerForestry.java +++ b/src/main/java/forestry/core/gui/ContainerForestry.java @@ -10,12 +10,19 @@ ******************************************************************************/ package forestry.core.gui; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimaps; - import java.util.List; import java.util.Map; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimaps; +import forestry.core.gui.slots.SlotFilteredInventory; +import forestry.core.gui.slots.SlotForestry; +import forestry.core.gui.slots.SlotLocked; +import forestry.core.network.IForestryPacketClient; +import forestry.core.proxy.Proxies; +import forestry.core.utils.SlotUtil; +import invtweaks.api.container.ContainerSection; +import invtweaks.api.container.ContainerSectionCallback; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ClickType; @@ -24,16 +31,6 @@ import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import forestry.core.gui.slots.SlotFilteredInventory; -import forestry.core.gui.slots.SlotForestry; -import forestry.core.gui.slots.SlotLocked; -import forestry.core.network.IForestryPacketClient; -import forestry.core.proxy.Proxies; -import forestry.core.utils.SlotUtil; - -import invtweaks.api.container.ContainerSection; -import invtweaks.api.container.ContainerSectionCallback; - @invtweaks.api.container.ChestContainer(showButtons = false) public abstract class ContainerForestry extends Container { protected final void addPlayerInventory(InventoryPlayer playerInventory, int xInv, int yInv) { @@ -61,7 +58,7 @@ public abstract class ContainerForestry extends Container { @Override public ItemStack slotClick(int slotId, int dragType_or_button, ClickType clickTypeIn, EntityPlayer player) { if (!canAccess(player)) { - return null; + return ItemStack.EMPTY; } if (clickTypeIn == ClickType.SWAP && dragType_or_button >= 0 && dragType_or_button < 9) { @@ -69,7 +66,7 @@ public abstract class ContainerForestry extends Container { int hotbarSlotIndex = 27 + dragType_or_button; Slot hotbarSlot = getSlot(hotbarSlotIndex); if (hotbarSlot instanceof SlotLocked) { - return null; + return ItemStack.EMPTY; } } @@ -87,7 +84,7 @@ public abstract class ContainerForestry extends Container { @Override public final ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { if (!canAccess(player)) { - return null; + return ItemStack.EMPTY; } return SlotUtil.transferStackInSlot(inventorySlots, player, slotIndex); @@ -129,7 +126,7 @@ public abstract class ContainerForestry extends Container { } } } - + return Multimaps.asMap(map); } } diff --git a/src/main/java/forestry/core/gui/ContainerItemInventory.java b/src/main/java/forestry/core/gui/ContainerItemInventory.java index 297e2c67d..6e4639b55 100755 --- a/src/main/java/forestry/core/gui/ContainerItemInventory.java +++ b/src/main/java/forestry/core/gui/ContainerItemInventory.java @@ -47,7 +47,7 @@ public abstract class ContainerItemInventory extends Co @Override public final boolean canInteractWith(EntityPlayer entityplayer) { - return inventory.isUseableByPlayer(entityplayer); + return inventory.isUsableByPlayer(entityplayer); } @Override diff --git a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java index cd033b8b4..45c8232dc 100644 --- a/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java +++ b/src/main/java/forestry/core/gui/ContainerLiquidTanksHelper.java @@ -19,12 +19,14 @@ import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; +import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.IFluidTank; import forestry.api.core.IToolPipette; import forestry.core.network.packets.PacketPipetteClick; import forestry.core.proxy.Proxies; import forestry.core.tiles.ILiquidTankTile; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; public class ContainerLiquidTanksHelper implements IContainerLiquidTanks { @@ -37,20 +39,14 @@ public class ContainerLiquidTanksHelper @Override public void handlePipetteClickClient(int slot, EntityPlayer player) { ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null || !(itemstack.getItem() instanceof IToolPipette)) { - return; + if (itemstack.getItem() instanceof IToolPipette) { + Proxies.net.sendToServer(new PacketPipetteClick(slot)); } - - Proxies.net.sendToServer(new PacketPipetteClick(tile, slot)); } @Override public void handlePipetteClick(int slot, EntityPlayerMP player) { ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null) { - return; - } - Item held = itemstack.getItem(); if (!(held instanceof IToolPipette)) { return; @@ -60,22 +56,27 @@ public class ContainerLiquidTanksHelper IFluidTank tank = tile.getTankManager().getTank(slot); int liquidAmount = tank.getFluidAmount(); - if (pipette.canPipette(itemstack) && liquidAmount > 0) { - if (liquidAmount > 0) { - if (tank instanceof FluidTank) { - FluidStack fillAmount = ((FluidTank) tank).drainInternal(Fluid.BUCKET_VOLUME, false); - int filled = pipette.fill(itemstack, fillAmount, true); - tank.drain(filled, true); - player.updateHeldItem(); + IFluidHandlerItem fluidHandlerItem = FluidUtil.getFluidHandler(itemstack); + if (fluidHandlerItem != null) { + if (pipette.canPipette(itemstack) && liquidAmount > 0) { + if (liquidAmount > 0) { + if (tank instanceof FluidTank) { + FluidStack fillAmount = ((FluidTank) tank).drainInternal(Fluid.BUCKET_VOLUME, false); + int filled = fluidHandlerItem.fill(fillAmount, true); + tank.drain(filled, true); + player.inventory.setItemStack(fluidHandlerItem.getContainer()); + player.updateHeldItem(); + } } - } - } else { - FluidStack potential = pipette.drain(itemstack, pipette.getCapacity(itemstack), false); - if (potential != null) { - if (tank instanceof FluidTank) { - int fill = ((FluidTank) tank).fillInternal(potential, true); - pipette.drain(itemstack, fill, true); - player.updateHeldItem(); + } else { + FluidStack potential = fluidHandlerItem.drain(Integer.MAX_VALUE, false); + if (potential != null) { + if (tank instanceof FluidTank) { + int fill = ((FluidTank) tank).fillInternal(potential, true); + fluidHandlerItem.drain(fill, true); + player.inventory.setItemStack(fluidHandlerItem.getContainer()); + player.updateHeldItem(); + } } } } diff --git a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java index 3c68fd006..4a8081c98 100755 --- a/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/ContainerNaturalistInventory.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.core.gui; +import forestry.core.gui.slots.SlotFilteredInventory; +import forestry.core.tiles.IFilterSlotDelegate; +import forestry.core.tiles.TileNaturalistChest; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IContainerListener; import net.minecraft.inventory.IInventory; -import forestry.core.gui.slots.SlotFilteredInventory; -import forestry.core.network.packets.PacketGuiSelectRequest; -import forestry.core.tiles.IFilterSlotDelegate; -import forestry.core.tiles.TileNaturalistChest; - public class ContainerNaturalistInventory extends ContainerTile implements IGuiSelectable { public ContainerNaturalistInventory(InventoryPlayer player, TileNaturalistChest tile, int page) { @@ -45,14 +43,14 @@ public class ContainerNaturalistInventory extends ContainerTile impleme @Override public void handleChipsetClick(int slot) { - Proxies.net.sendToServer(new PacketChipsetClick(tile, slot)); + Proxies.net.sendToServer(new PacketChipsetClick(slot)); } @Override public void handleChipsetClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { - if (tile.getSocket(slot) != null) { + if (!tile.getSocket(slot).isEmpty()) { return; } @@ -56,14 +56,11 @@ public class ContainerSocketedHelper impleme } ItemStack toSocket = itemstack.copy(); - toSocket.stackSize = 1; + toSocket.setCount(1); tile.setSocket(slot, toSocket); ItemStack stack = player.inventory.getItemStack(); - stack.stackSize--; - if (stack.stackSize <= 0) { - player.inventory.setItemStack(null); - } + stack.shrink(1); player.updateHeldItem(); PacketSocketUpdate packet = new PacketSocketUpdate(tile); @@ -72,30 +69,26 @@ public class ContainerSocketedHelper impleme @Override public void handleSolderingIronClick(int slot) { - Proxies.net.sendToServer(new PacketSolderingIronClick(tile, slot)); + Proxies.net.sendToServer(new PacketSolderingIronClick(slot)); } @Override public void handleSolderingIronClickServer(int slot, EntityPlayerMP player, ItemStack itemstack) { ItemStack socket = tile.getSocket(slot); - if (socket == null) { + if (socket.isEmpty()) { return; } InventoryUtil.stowInInventory(socket, player.inventory, true); // Not sufficient space in player's inventory. failed to stow. - if (socket.stackSize > 0) { + if (!socket.isEmpty()) { return; } - tile.setSocket(slot, null); + tile.setSocket(slot, ItemStack.EMPTY); itemstack.damageItem(1, player); - if (itemstack.stackSize <= 0) { - player.inventory.setItemStack(null); - } player.updateHeldItem(); - PacketSocketUpdate packet = new PacketSocketUpdate(tile); Proxies.net.sendToPlayer(packet, player); } diff --git a/src/main/java/forestry/core/gui/ContainerTile.java b/src/main/java/forestry/core/gui/ContainerTile.java index cb3cad4e9..f499d091b 100644 --- a/src/main/java/forestry/core/gui/ContainerTile.java +++ b/src/main/java/forestry/core/gui/ContainerTile.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; + import com.google.common.collect.ImmutableSet; import forestry.api.core.IErrorLogicSource; import forestry.api.core.IErrorState; @@ -26,6 +28,7 @@ import net.minecraft.tileentity.TileEntity; public abstract class ContainerTile extends ContainerForestry { protected final T tile; + @Nullable private ImmutableSet previousErrorStates; private int previousEnergyManagerData = 0; private int previousWorkCounter = 0; @@ -43,7 +46,7 @@ public abstract class ContainerTile extends ContainerFores @Override protected final boolean canAccess(EntityPlayer player) { - return player != null; + return true; } @Override diff --git a/src/main/java/forestry/core/gui/GuiAlyzer.java b/src/main/java/forestry/core/gui/GuiAlyzer.java index 1f025e239..ca39eeeb4 100755 --- a/src/main/java/forestry/core/gui/GuiAlyzer.java +++ b/src/main/java/forestry/core/gui/GuiAlyzer.java @@ -10,19 +10,11 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; import java.util.Locale; import java.util.Map; import java.util.Stack; -import forestry.api.genetics.IGenome; -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.EnumBeeChromosome; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.EnumTolerance; @@ -33,6 +25,7 @@ import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.IChromosomeType; import forestry.api.genetics.IClassification; import forestry.api.genetics.IClassification.EnumClassLevel; +import forestry.api.genetics.IGenome; import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; @@ -45,9 +38,15 @@ import forestry.core.inventory.ItemInventoryAlyzer; import forestry.core.proxy.Proxies; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import org.apache.commons.lang3.StringUtils; public class GuiAlyzer extends GuiForestry { - + public static final int COLUMN_0 = 12; public static final int COLUMN_1 = 90; public static final int COLUMN_2 = 155; @@ -96,7 +95,7 @@ public class GuiAlyzer extends GuiForestry { getColorCoding(inactive.isDominant())); } - public final void drawSpeciesRow(String text0, IIndividual individual, IChromosomeType chromosome, String customPrimaryName, String customSecondaryName) { + public final void drawSpeciesRow(String text0, IIndividual individual, IChromosomeType chromosome, @Nullable String customPrimaryName, @Nullable String customSecondaryName) { IAlleleSpecies primary = individual.getGenome().getPrimary(); IAlleleSpecies secondary = individual.getGenome().getSecondary(); @@ -117,6 +116,7 @@ public class GuiAlyzer extends GuiForestry { textLayout.newLine(); } + @Nullable public static String checkCustomName(String key) { if (Translator.canTranslateToLocal(key)) { return Translator.translateToLocal(key); @@ -124,7 +124,7 @@ public class GuiAlyzer extends GuiForestry { return null; } } - + @Override protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); @@ -138,6 +138,9 @@ public class GuiAlyzer extends GuiForestry { ItemStack stackInSlot = inventory.getStackInSlot(specimenSlot); ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(stackInSlot); + if (speciesRoot == null) { + return; + } switch (specimenSlot) { case ItemInventoryAlyzer.SLOT_ANALYZE_1: { @@ -171,7 +174,7 @@ public class GuiAlyzer extends GuiForestry { private int getSpecimenSlot() { for (int k = ItemInventoryAlyzer.SLOT_SPECIMEN; k <= ItemInventoryAlyzer.SLOT_ANALYZE_5; k++) { ItemStack stackInSlot = inventory.getStackInSlot(k); - if (stackInSlot == null) { + if (stackInSlot.isEmpty()) { continue; } @@ -181,7 +184,7 @@ public class GuiAlyzer extends GuiForestry { } IIndividual individual = speciesRoot.getMember(stackInSlot); - if (individual == null || !individual.isAnalyzed()) { + if (!individual.isAnalyzed()) { continue; } @@ -229,7 +232,7 @@ public class GuiAlyzer extends GuiForestry { IClassification classification = individual.getGenome().getPrimary().getBranch(); while (classification != null) { - if (classification.getScientific() != null && !classification.getScientific().isEmpty()) { + if (!classification.getScientific().isEmpty()) { hierarchy.push(classification); } classification = classification.getParent(); @@ -301,7 +304,7 @@ public class GuiAlyzer extends GuiForestry { int x = 0; EntityPlayer player = Proxies.common.getPlayer(); - IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.world, player.getGameProfile()); for (IMutation mutation : speciesRoot.getCombinations(species)) { if (breedingTracker.isDiscovered(mutation)) { @@ -328,7 +331,7 @@ public class GuiAlyzer extends GuiForestry { public void drawMutationInfo(IMutation combination, IAllele species, int x, IBreedingTracker breedingTracker) { Map iconStacks = combination.getRoot().getAlyzerPlugin().getIconStacks(); - + ItemStack partnerBee = iconStacks.get(combination.getPartner(species).getUID()); widgetManager.add(new ItemStackWidget(widgetManager, x, textLayout.getLineY(), partnerBee)); diff --git a/src/main/java/forestry/core/gui/GuiForestry.java b/src/main/java/forestry/core/gui/GuiForestry.java index 99f3093b1..32bf583db 100755 --- a/src/main/java/forestry/core/gui/GuiForestry.java +++ b/src/main/java/forestry/core/gui/GuiForestry.java @@ -47,22 +47,24 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidTank; public abstract class GuiForestry extends GuiContainer { + @Nullable protected final I inventory; protected final C container; public final ResourceLocation textureFile; protected final WidgetManager widgetManager; - protected LedgerManager ledgerManager; - protected TextLayoutHelper textLayout; + protected final LedgerManager ledgerManager; + protected final TextLayoutHelper textLayout; - protected GuiForestry(String texture, C container, I inventory) { + protected GuiForestry(String texture, C container, @Nullable I inventory) { this(new ForestryResource(texture), container, inventory); } - protected GuiForestry(ResourceLocation texture, C container, I inventory) { + protected GuiForestry(ResourceLocation texture, C container, @Nullable I inventory) { super(container); this.widgetManager = new WidgetManager(this); + this.ledgerManager = new LedgerManager(this); this.textureFile = texture; @@ -78,7 +80,8 @@ public abstract class GuiForestry ext super.initGui(); int maxLedgerWidth = (this.width - this.xSize) / 2; - this.ledgerManager = new LedgerManager(this, maxLedgerWidth); + + this.ledgerManager.setMaxWidth(maxLedgerWidth); addLedgers(); } @@ -109,7 +112,7 @@ public abstract class GuiForestry ext if (Config.enableHints && inventory instanceof IHintSource) { IHintSource hintSource = (IHintSource) inventory; List hints = hintSource.getHints(); - if (hints != null && !hints.isEmpty()) { + if (!hints.isEmpty()) { ledgerManager.add(new HintLedger(ledgerManager, hintSource)); } } @@ -141,11 +144,11 @@ public abstract class GuiForestry ext ledgerManager.handleMouseClicked(xPos, yPos, mouseButton); widgetManager.handleMouseClicked(xPos, yPos, mouseButton); } - + @Override protected void mouseReleased(int mouseX, int mouseY, int state) { super.mouseReleased(mouseX, mouseY, state); - + widgetManager.handleMouseRelease(mouseX, mouseY, state); } @@ -171,6 +174,7 @@ public abstract class GuiForestry ext return null; } + @Nullable protected Slot getSlotAtPosition(int mouseX, int mouseY) { for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { Slot slot = this.inventorySlots.inventorySlots.get(k); @@ -184,16 +188,16 @@ public abstract class GuiForestry ext } private boolean isMouseOverSlot(Slot par1Slot, int mouseX, int mouseY) { - return isPointInRegion(par1Slot.xDisplayPosition, par1Slot.yDisplayPosition, 16, 16, mouseX, mouseY); + return isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, mouseX, mouseY); } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { ledgerManager.drawTooltips(mouseX, mouseY); - InventoryPlayer playerInv = mc.thePlayer.inventory; + InventoryPlayer playerInv = mc.player.inventory; - if (playerInv.getItemStack() == null) { + if (playerInv.getItemStack().isEmpty()) { GuiUtil.drawToolTips(this, widgetManager.getWidgets(), mouseX, mouseY); GuiUtil.drawToolTips(this, buttonList, mouseX, mouseY); GuiUtil.drawToolTips(this, inventorySlots.inventorySlots, mouseX, mouseY); diff --git a/src/main/java/forestry/core/gui/GuiHandler.java b/src/main/java/forestry/core/gui/GuiHandler.java index fa9857582..8531fce7c 100644 --- a/src/main/java/forestry/core/gui/GuiHandler.java +++ b/src/main/java/forestry/core/gui/GuiHandler.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; + +import forestry.api.core.ForestryAPI; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; @@ -18,11 +21,8 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.common.network.IGuiHandler; -import forestry.api.core.ForestryAPI; - public class GuiHandler implements IGuiHandler { public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler) { openGui(entityplayer, guiHandler, (short) 0); @@ -30,7 +30,7 @@ public class GuiHandler implements IGuiHandler { public static void openGui(EntityPlayer entityplayer, IGuiHandlerEntity guiHandler, short data) { int guiData = encodeGuiData(guiHandler, data); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, guiHandler.getIdOfEntity(), 0, 0); + entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.world, guiHandler.getIdOfEntity(), 0, 0); } public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler) { @@ -39,7 +39,7 @@ public class GuiHandler implements IGuiHandler { public static void openGui(EntityPlayer entityplayer, IGuiHandlerItem guiHandler, short data) { int guiData = encodeGuiData(guiHandler, data); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, 0, 0, 0); + entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.world, 0, 0, 0); } public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler) { @@ -49,7 +49,7 @@ public class GuiHandler implements IGuiHandler { public static void openGui(EntityPlayer entityplayer, IGuiHandlerTile guiHandler, short data) { int guiData = encodeGuiData(guiHandler, data); BlockPos coordinates = guiHandler.getCoordinates(); - entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.worldObj, coordinates.getX(), coordinates.getY(), coordinates.getZ()); + entityplayer.openGui(ForestryAPI.instance, guiData, entityplayer.world, coordinates.getX(), coordinates.getY(), coordinates.getZ()); } private static int encodeGuiData(IGuiHandlerForestry guiHandler, short data) { @@ -57,6 +57,7 @@ public class GuiHandler implements IGuiHandler { return data << 16 | guiId.getId(); } + @Nullable private static GuiId decodeGuiID(int guiData) { int guiId = guiData & 0xFF; return GuiIdRegistry.getGuiId(guiId); @@ -67,6 +68,7 @@ public class GuiHandler implements IGuiHandler { } @Override + @Nullable public Object getClientGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { GuiId guiId = decodeGuiID(guiData); if (guiId == null) { @@ -79,7 +81,7 @@ public class GuiHandler implements IGuiHandler { case Item: { for (EnumHand hand : EnumHand.values()) { ItemStack heldItem = player.getHeldItem(hand); - if (heldItem != null) { + if (!heldItem.isEmpty()) { Item item = heldItem.getItem(); if (guiId.getGuiHandlerClass().isInstance(item)) { return ((IGuiHandlerItem) item).getGui(player, heldItem, data); @@ -107,6 +109,7 @@ public class GuiHandler implements IGuiHandler { } @Override + @Nullable public Object getServerGuiElement(int guiData, EntityPlayer player, World world, int x, int y, int z) { GuiId guiId = decodeGuiID(guiData); if (guiId == null) { @@ -119,7 +122,7 @@ public class GuiHandler implements IGuiHandler { case Item: { for (EnumHand hand : EnumHand.values()) { ItemStack heldItem = player.getHeldItem(hand); - if (heldItem != null) { + if (!heldItem.isEmpty()) { Item item = heldItem.getItem(); if (guiId.getGuiHandlerClass().isInstance(item)) { return ((IGuiHandlerItem) item).getContainer(player, heldItem, data); diff --git a/src/main/java/forestry/core/gui/GuiIdRegistry.java b/src/main/java/forestry/core/gui/GuiIdRegistry.java index bfe0277b1..29ee2b73b 100644 --- a/src/main/java/forestry/core/gui/GuiIdRegistry.java +++ b/src/main/java/forestry/core/gui/GuiIdRegistry.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -31,9 +32,7 @@ import forestry.core.tiles.TileAnalyzer; import forestry.core.tiles.TileEscritoire; import forestry.core.tiles.TileNaturalistChest; import forestry.energy.tiles.TileEngineBiogas; -import forestry.energy.tiles.TileEngineElectric; import forestry.energy.tiles.TileEnginePeat; -import forestry.energy.tiles.TileEuGenerator; import forestry.factory.tiles.TileBottler; import forestry.factory.tiles.TileCarpenter; import forestry.factory.tiles.TileCentrifuge; @@ -84,13 +83,13 @@ public class GuiIdRegistry { TileStill.class, TileFarm.class, - + TileGreenhouse.class, TileEngineBiogas.class, - TileEngineElectric.class, +// TileEngineElectric.class, TileEnginePeat.class, - TileEuGenerator.class, +// TileEuGenerator.class, TileMailbox.class, TileStampCollector.class, @@ -141,6 +140,7 @@ public class GuiIdRegistry { return guiId; } + @Nullable public static GuiId getGuiId(int id) { return idMap.get(id); } diff --git a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java index 856ce025a..56edbdb8b 100755 --- a/src/main/java/forestry/core/gui/GuiNaturalistInventory.java +++ b/src/main/java/forestry/core/gui/GuiNaturalistInventory.java @@ -10,17 +10,10 @@ ******************************************************************************/ package forestry.core.gui; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.HashMap; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; - import forestry.api.apiculture.IApiaristTracker; import forestry.api.arboriculture.EnumTreeChromosome; import forestry.api.genetics.IAlleleSpecies; @@ -36,15 +29,20 @@ import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.core.proxy.Proxies; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; public class GuiNaturalistInventory extends GuiForestry { - @Nonnull private final ISpeciesRoot speciesRoot; private final IBreedingTracker breedingTracker; private final HashMap iconStacks = new HashMap<>(); private final int pageCurrent, pageMax; - public GuiNaturalistInventory(@Nonnull ISpeciesRoot speciesRoot, EntityPlayer player, Container container, IPagedInventory inventory, int page, int maxPages) { + public GuiNaturalistInventory(ISpeciesRoot speciesRoot, EntityPlayer player, Container container, IPagedInventory inventory, int page, int maxPages) { super(Constants.TEXTURE_PATH_GUI + "/apiaristinventory.png", container, inventory); this.speciesRoot = speciesRoot; @@ -59,7 +57,7 @@ public class GuiNaturalistInventory extends GuiForestry lines = toolTips.getLines(); if (!lines.isEmpty()) { GlStateManager.pushMatrix(); diff --git a/src/main/java/forestry/core/gui/IGuiHandlerItem.java b/src/main/java/forestry/core/gui/IGuiHandlerItem.java index 05bf7bc89..2fc2df134 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerItem.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerItem.java @@ -10,11 +10,15 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public interface IGuiHandlerItem extends IGuiHandlerForestry { + @Nullable Object getGui(EntityPlayer player, ItemStack heldItem, int data); + @Nullable Object getContainer(EntityPlayer player, ItemStack heldItem, int data); } diff --git a/src/main/java/forestry/core/gui/IGuiHandlerTile.java b/src/main/java/forestry/core/gui/IGuiHandlerTile.java index 3032c696e..2381fd4d9 100644 --- a/src/main/java/forestry/core/gui/IGuiHandlerTile.java +++ b/src/main/java/forestry/core/gui/IGuiHandlerTile.java @@ -10,12 +10,16 @@ ******************************************************************************/ package forestry.core.gui; +import javax.annotation.Nullable; + import forestry.api.core.ILocatable; import net.minecraft.entity.player.EntityPlayer; public interface IGuiHandlerTile extends IGuiHandlerForestry, ILocatable { + @Nullable Object getGui(EntityPlayer player, int data); + @Nullable Object getContainer(EntityPlayer player, int data); } diff --git a/src/main/java/forestry/core/gui/IGuiSelectable.java b/src/main/java/forestry/core/gui/IGuiSelectable.java index 34cf95fe0..9ffa56922 100755 --- a/src/main/java/forestry/core/gui/IGuiSelectable.java +++ b/src/main/java/forestry/core/gui/IGuiSelectable.java @@ -12,9 +12,7 @@ package forestry.core.gui; import net.minecraft.entity.player.EntityPlayerMP; -import forestry.core.network.packets.PacketGuiSelectRequest; - public interface IGuiSelectable { // server - void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packetRequest); + void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary); } diff --git a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java index 752857316..7e0a84a0e 100755 --- a/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java +++ b/src/main/java/forestry/core/gui/buttons/GuiBetterButton.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.buttons; +import javax.annotation.Nullable; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; @@ -29,6 +31,7 @@ public class GuiBetterButton extends GuiButton implements IToolTipProvider { private static final ResourceLocation TEXTURE = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/buttons.png"); protected IButtonTextureSet texture; + @Nullable private ToolTip toolTip; private boolean useTexWidth = false; diff --git a/src/main/java/forestry/core/gui/buttons/package-info.java b/src/main/java/forestry/core/gui/buttons/package-info.java new file mode 100644 index 000000000..b4ea3a1ee --- /dev/null +++ b/src/main/java/forestry/core/gui/buttons/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.buttons; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java b/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java index 094d098c6..dab7b4c2b 100644 --- a/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/ErrorLedger.java @@ -72,7 +72,7 @@ public class ErrorLedger extends Ledger { @Override public String getTooltip() { - if (!isVisible()) { + if (state == null) { return ""; } return Translator.translateToLocal(state.getUnlocalizedDescription()); diff --git a/src/main/java/forestry/core/gui/ledgers/Ledger.java b/src/main/java/forestry/core/gui/ledgers/Ledger.java index 41c70b2c3..03a83ebfa 100644 --- a/src/main/java/forestry/core/gui/ledgers/Ledger.java +++ b/src/main/java/forestry/core/gui/ledgers/Ledger.java @@ -217,11 +217,9 @@ public abstract class Ledger { } protected void drawSprite(ResourceLocation textureMap, TextureAtlasSprite sprite, int x, int y) { - if (sprite != null) { - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0F); - Proxies.render.bindTexture(textureMap); - manager.gui.drawTexturedModalRect(x, y, sprite, 16, 16); - } + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(textureMap); + manager.gui.drawTexturedModalRect(x, y, sprite, 16, 16); } protected int drawHeader(String string, int x, int y) { diff --git a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java index 39e16d15f..04313c52e 100644 --- a/src/main/java/forestry/core/gui/ledgers/LedgerManager.java +++ b/src/main/java/forestry/core/gui/ledgers/LedgerManager.java @@ -10,13 +10,11 @@ ******************************************************************************/ package forestry.core.gui.ledgers; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; -import net.minecraft.client.renderer.GlStateManager; - import forestry.api.core.IErrorSource; import forestry.api.core.IErrorState; import forestry.core.config.SessionVars; @@ -24,27 +22,27 @@ import forestry.core.errors.FakeErrorSource; import forestry.core.gui.GuiForestry; import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; +import net.minecraft.client.renderer.GlStateManager; public class LedgerManager { private final List ledgers = new ArrayList<>(); private final List errorLedgers = new ArrayList<>(); private IErrorSource errorSource; - private final int maxWidth; + private int maxWidth; public final GuiForestry gui; - public LedgerManager(GuiForestry gui, int maxWidth) { + public LedgerManager(GuiForestry gui) { this.gui = gui; this.errorSource = FakeErrorSource.instance; + } + + public void setMaxWidth(int maxWidth) { this.maxWidth = maxWidth; } public void add(IErrorSource errorSource) { - if (errorSource == null) { - return; - } - this.errorSource = errorSource; int maxErrorLedgerCount = (gui.getSizeY() - 10) / Ledger.minHeight; for (int i = 0; i < maxErrorLedgerCount; i++) { @@ -72,6 +70,7 @@ public class LedgerManager { this.ledgers.add(ledgers.size() - 1, ledger); } + @Nullable private Ledger getAtPosition(int mX, int mY) { if (!ledgers.isEmpty()) { final int xShift = (gui.width - gui.getSizeX()) / 2 + gui.getSizeX(); @@ -112,7 +111,6 @@ public class LedgerManager { return null; } - @Nonnull public List getLedgerAreas() { List areas = new ArrayList<>(); for (Ledger ledger : ledgers) { diff --git a/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java b/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java index cfb3b0688..f5b12a116 100644 --- a/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java +++ b/src/main/java/forestry/core/gui/ledgers/OwnerLedger.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.ledgers; +import javax.annotation.Nullable; + import com.mojang.authlib.GameProfile; import forestry.core.owner.IOwnedTile; import forestry.core.render.TextureManager; @@ -21,7 +23,7 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; * Ledger displaying ownership information */ public class OwnerLedger extends Ledger { - + @Nullable private final GameProfile owner; public OwnerLedger(LedgerManager manager, IOwnedTile tile) { diff --git a/src/main/java/forestry/core/gui/ledgers/package-info.java b/src/main/java/forestry/core/gui/ledgers/package-info.java new file mode 100644 index 000000000..e217825f8 --- /dev/null +++ b/src/main/java/forestry/core/gui/ledgers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.ledgers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/package-info.java b/src/main/java/forestry/core/gui/package-info.java new file mode 100644 index 000000000..816cd12ac --- /dev/null +++ b/src/main/java/forestry/core/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/slots/SlotCrafter.java b/src/main/java/forestry/core/gui/slots/SlotCrafter.java index a99cb1c93..241e9751e 100755 --- a/src/main/java/forestry/core/gui/slots/SlotCrafter.java +++ b/src/main/java/forestry/core/gui/slots/SlotCrafter.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.gui.slots; +import forestry.factory.tiles.ICrafterWorktable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -23,28 +24,30 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.stats.AchievementList; -import net.minecraftforge.fml.common.FMLCommonHandler; - -import forestry.factory.tiles.ICrafterWorktable; - public class SlotCrafter extends Slot { - /** The craft matrix inventory linked to this result slot. */ + /** + * The craft matrix inventory linked to this result slot. + */ private final IInventory craftMatrix; private final ICrafterWorktable crafter; - - /** The player that is using the GUI where this slot resides. */ - private final EntityPlayer thePlayer; - /** The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. */ + + /** + * The player that is using the GUI where this slot resides. + */ + private final EntityPlayer player; + /** + * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. + */ private int amountCrafted; public SlotCrafter(EntityPlayer player, IInventory craftMatrix, ICrafterWorktable crafter, int slot, int xPos, int yPos) { super(craftMatrix, slot, xPos, yPos); this.craftMatrix = craftMatrix; this.crafter = crafter; - this.thePlayer = player; + this.player = player; } - + /** * Check if the stack is a valid item for this slot. Always true beside for the armor slots. */ @@ -70,56 +73,57 @@ public class SlotCrafter extends Slot { @Override protected void onCrafting(ItemStack stack) { if (this.amountCrafted > 0) { - stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.amountCrafted); + stack.onCrafting(this.player.world, this.player, this.amountCrafted); + net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(this.player, stack, craftMatrix); } this.amountCrafted = 0; if (stack.getItem() == Item.getItemFromBlock(Blocks.CRAFTING_TABLE)) { - this.thePlayer.addStat(AchievementList.BUILD_WORK_BENCH); + this.player.addStat(AchievementList.BUILD_WORK_BENCH); } if (stack.getItem() instanceof ItemPickaxe) { - this.thePlayer.addStat(AchievementList.BUILD_PICKAXE); + this.player.addStat(AchievementList.BUILD_PICKAXE); } if (stack.getItem() == Item.getItemFromBlock(Blocks.FURNACE)) { - this.thePlayer.addStat(AchievementList.BUILD_FURNACE); + this.player.addStat(AchievementList.BUILD_FURNACE); } if (stack.getItem() instanceof ItemHoe) { - this.thePlayer.addStat(AchievementList.BUILD_HOE); + this.player.addStat(AchievementList.BUILD_HOE); } if (stack.getItem() == Items.BREAD) { - this.thePlayer.addStat(AchievementList.MAKE_BREAD); + this.player.addStat(AchievementList.MAKE_BREAD); } if (stack.getItem() == Items.CAKE) { - this.thePlayer.addStat(AchievementList.BAKE_CAKE); + this.player.addStat(AchievementList.BAKE_CAKE); } if (stack.getItem() instanceof ItemPickaxe && ((ItemPickaxe) stack.getItem()).getToolMaterial() != Item.ToolMaterial.WOOD) { - this.thePlayer.addStat(AchievementList.BUILD_BETTER_PICKAXE); + this.player.addStat(AchievementList.BUILD_BETTER_PICKAXE); } if (stack.getItem() instanceof ItemSword) { - this.thePlayer.addStat(AchievementList.BUILD_SWORD); + this.player.addStat(AchievementList.BUILD_SWORD); } if (stack.getItem() == Item.getItemFromBlock(Blocks.ENCHANTING_TABLE)) { - this.thePlayer.addStat(AchievementList.ENCHANTMENTS); + this.player.addStat(AchievementList.ENCHANTMENTS); } if (stack.getItem() == Item.getItemFromBlock(Blocks.BOOKSHELF)) { - this.thePlayer.addStat(AchievementList.BOOKCASE); + this.player.addStat(AchievementList.BOOKCASE); } } @Override public ItemStack decrStackSize(int amount) { if (!this.getHasStack()) { - return null; + return ItemStack.EMPTY; } return this.getStack(); @@ -137,18 +141,16 @@ public class SlotCrafter extends Slot { @Override public boolean getHasStack() { - return getStack() != null && crafter.canTakeStack(getSlotIndex()); + return !getStack().isEmpty() && crafter.canTakeStack(getSlotIndex()); } @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - if (!crafter.onCraftingStart(player)) { - return; + public ItemStack onTake(EntityPlayer player, ItemStack itemStack) { + if (crafter.onCraftingStart(player)) { + this.onCrafting(itemStack); // handles crafting achievements, maps, and statistics + + crafter.onCraftingComplete(player); } - - FMLCommonHandler.instance().firePlayerCraftingEvent(player, itemStack, craftMatrix); - this.onCrafting(itemStack); // handles crafting achievements, maps, and statistics - - crafter.onCraftingComplete(player); + return itemStack; } } diff --git a/src/main/java/forestry/core/gui/slots/SlotFiltered.java b/src/main/java/forestry/core/gui/slots/SlotFiltered.java index cc41c58dd..2daf45a91 100644 --- a/src/main/java/forestry/core/gui/slots/SlotFiltered.java +++ b/src/main/java/forestry/core/gui/slots/SlotFiltered.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.slots; +import javax.annotation.Nullable; + import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -25,6 +27,7 @@ import forestry.core.tiles.IFilterSlotDelegate; */ public class SlotFiltered extends SlotWatched { private final IFilterSlotDelegate filterSlotDelegate; + @Nullable private String backgroundTexture = null; private String blockedTexture = "slots/blocked"; @@ -36,13 +39,8 @@ public class SlotFiltered extends SlotWatched { @Override public boolean isItemValid(ItemStack itemstack) { int slotIndex = getSlotIndex(); - if (filterSlotDelegate.isLocked(slotIndex)) { - return false; - } - if (itemstack != null) { - return filterSlotDelegate.canSlotAccept(slotIndex, itemstack); - } - return true; + return !filterSlotDelegate.isLocked(slotIndex) && + (itemstack == null || filterSlotDelegate.canSlotAccept(slotIndex, itemstack)); } public SlotFiltered setBlockedTexture(String ident) { @@ -57,6 +55,7 @@ public class SlotFiltered extends SlotWatched { @SideOnly(Side.CLIENT) @Override + @Nullable public TextureAtlasSprite getBackgroundSprite() { ItemStack stack = getStack(); if (!isItemValid(stack)) { diff --git a/src/main/java/forestry/core/gui/slots/SlotForestry.java b/src/main/java/forestry/core/gui/slots/SlotForestry.java index a9d54c1da..29f19ec45 100755 --- a/src/main/java/forestry/core/gui/slots/SlotForestry.java +++ b/src/main/java/forestry/core/gui/slots/SlotForestry.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.core.gui.slots; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + import forestry.core.gui.tooltips.IToolTipProvider; import forestry.core.gui.tooltips.ToolTip; import forestry.core.render.TextureManager; @@ -26,13 +29,11 @@ public class SlotForestry extends Slot implements IToolTipProvider { private boolean canAdjustPhantom = true; private boolean canShift = true; private int stackLimit; + @Nullable private ToolTip toolTips; public SlotForestry(IInventory inventory, int slotIndex, int xPos, int yPos) { super(inventory, slotIndex, xPos, yPos); - if (inventory == null) { - throw new IllegalArgumentException("Inventory must not be null"); - } if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) { setBackgroundLocation(TextureManager.getInstance().getGuiTextureMap()); } @@ -50,7 +51,7 @@ public class SlotForestry extends Slot implements IToolTipProvider { } @Override - public void putStack(ItemStack itemStack) { + public void putStack(@Nonnull ItemStack itemStack) { if (!isPhantom() || canAdjustPhantom()) { super.putStack(itemStack); } @@ -92,18 +93,10 @@ public class SlotForestry extends Slot implements IToolTipProvider { } } - /** - * @param toolTips the tooltips to set - */ public void setToolTips(ToolTip toolTips) { this.toolTips = toolTips; } - /** - * @return the toolTips - * @param mouseX - * @param mouseY - */ @Override public ToolTip getToolTip(int mouseX, int mouseY) { return toolTips; @@ -111,11 +104,11 @@ public class SlotForestry extends Slot implements IToolTipProvider { @Override public boolean isToolTipVisible() { - return getStack() == null; + return getStack().isEmpty(); } @Override public boolean isMouseOver(int mouseX, int mouseY) { - return mouseX >= xDisplayPosition && mouseX <= xDisplayPosition + 16 && mouseY >= yDisplayPosition && mouseY <= yDisplayPosition + 16; + return mouseX >= xPos && mouseX <= xPos + 16 && mouseY >= yPos && mouseY <= yPos + 16; } } diff --git a/src/main/java/forestry/core/gui/slots/SlotLocked.java b/src/main/java/forestry/core/gui/slots/SlotLocked.java index 73db9dd4f..1839a9534 100755 --- a/src/main/java/forestry/core/gui/slots/SlotLocked.java +++ b/src/main/java/forestry/core/gui/slots/SlotLocked.java @@ -24,7 +24,8 @@ public class SlotLocked extends SlotForestry { } @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { + public ItemStack onTake(EntityPlayer player, ItemStack itemStack) { + return ItemStack.EMPTY; } @Override @@ -34,6 +35,6 @@ public class SlotLocked extends SlotForestry { @Override public ItemStack decrStackSize(int i) { - return null; + return ItemStack.EMPTY; } } diff --git a/src/main/java/forestry/core/gui/slots/SlotOutput.java b/src/main/java/forestry/core/gui/slots/SlotOutput.java index 917d948c5..73c3e0bcd 100755 --- a/src/main/java/forestry/core/gui/slots/SlotOutput.java +++ b/src/main/java/forestry/core/gui/slots/SlotOutput.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.slots; +import javax.annotation.Nullable; + import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -33,6 +35,7 @@ public class SlotOutput extends SlotWatched { @SideOnly(Side.CLIENT) @Override + @Nullable public TextureAtlasSprite getBackgroundSprite() { return null; } diff --git a/src/main/java/forestry/core/gui/slots/SlotWatched.java b/src/main/java/forestry/core/gui/slots/SlotWatched.java index c98012e23..789055bcc 100644 --- a/src/main/java/forestry/core/gui/slots/SlotWatched.java +++ b/src/main/java/forestry/core/gui/slots/SlotWatched.java @@ -10,14 +10,13 @@ ******************************************************************************/ package forestry.core.gui.slots; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.core.inventory.watchers.FakeSlotChangeWatcher; import forestry.core.inventory.watchers.FakeSlotPickupWatcher; import forestry.core.inventory.watchers.ISlotChangeWatcher; import forestry.core.inventory.watchers.ISlotPickupWatcher; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; /** * Slot with a watcher callbacks. @@ -41,9 +40,10 @@ public class SlotWatched extends SlotForestry { } @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { - super.onPickupFromSlot(player, itemStack); - pickupWatcher.onPickupFromSlot(getSlotIndex(), player); + public ItemStack onTake(EntityPlayer player, ItemStack itemStack) { + itemStack = super.onTake(player, itemStack); + pickupWatcher.onTake(getSlotIndex(), player); + return itemStack; } @Override diff --git a/src/main/java/forestry/core/gui/slots/SlotWorking.java b/src/main/java/forestry/core/gui/slots/SlotWorking.java index 9855c5dd8..abfb992db 100755 --- a/src/main/java/forestry/core/gui/slots/SlotWorking.java +++ b/src/main/java/forestry/core/gui/slots/SlotWorking.java @@ -27,7 +27,8 @@ public class SlotWorking extends SlotForestry { } @Override - public void onPickupFromSlot(EntityPlayer player, ItemStack itemStack) { + public ItemStack onTake(EntityPlayer player, ItemStack itemStack) { + return ItemStack.EMPTY; } @Override @@ -37,6 +38,6 @@ public class SlotWorking extends SlotForestry { @Override public ItemStack decrStackSize(int i) { - return null; + return ItemStack.EMPTY; } } diff --git a/src/main/java/forestry/core/gui/slots/package-info.java b/src/main/java/forestry/core/gui/slots/package-info.java new file mode 100644 index 000000000..f4a562bdb --- /dev/null +++ b/src/main/java/forestry/core/gui/slots/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.slots; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/tooltips/ToolTip.java b/src/main/java/forestry/core/gui/tooltips/ToolTip.java index adbfc344c..da4cc6600 100755 --- a/src/main/java/forestry/core/gui/tooltips/ToolTip.java +++ b/src/main/java/forestry/core/gui/tooltips/ToolTip.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.gui.tooltips; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; @@ -39,11 +38,11 @@ public class ToolTip { lines.clear(); } - public boolean add(@Nonnull String line) { + public boolean add(String line) { return add(line, null); } - public boolean add(@Nonnull String line, @Nullable TextFormatting formatting) { + public boolean add(String line, @Nullable TextFormatting formatting) { if (formatting != null) { return lines.add(formatting + line); } else { @@ -79,13 +78,7 @@ public class ToolTip { } public boolean isReady() { - if (delay == 0) { - return true; - } - if (mouseOverStart == 0) { - return false; - } - return System.currentTimeMillis() - mouseOverStart >= delay; + return delay == 0 || mouseOverStart != 0 && System.currentTimeMillis() - mouseOverStart >= delay; } public void refresh() { diff --git a/src/main/java/forestry/core/gui/tooltips/package-info.java b/src/main/java/forestry/core/gui/tooltips/package-info.java new file mode 100644 index 000000000..675767fe4 --- /dev/null +++ b/src/main/java/forestry/core/gui/tooltips/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.tooltips; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java index 740ed40f5..718d1c60b 100644 --- a/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java +++ b/src/main/java/forestry/core/gui/widgets/GameTokenWidget.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.gui.widgets; +import javax.annotation.Nullable; + import forestry.core.gui.GuiUtil; import forestry.core.gui.tooltips.ToolTip; import forestry.core.network.packets.PacketGuiSelectRequest; @@ -34,6 +36,7 @@ public class GameTokenWidget extends Widget { this.index = index; } + @Nullable private EscritoireGameToken getToken() { return game.getToken(index); } diff --git a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java index 7da24f2af..e32ac7f3f 100644 --- a/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java +++ b/src/main/java/forestry/core/gui/widgets/ItemStackWidgetBase.java @@ -31,7 +31,7 @@ public abstract class ItemStackWidgetBase extends Widget { @Override public void draw(int startX, int startY) { ItemStack itemStack = getItemStack(); - if (itemStack != null) { + if (!itemStack.isEmpty()) { GuiUtil.drawItemStack(manager.gui, itemStack, xPos + startX, yPos + startY); } } @@ -40,10 +40,10 @@ public abstract class ItemStackWidgetBase extends Widget { @Override public ToolTip getToolTip(int mouseX, int mouseY) { Minecraft minecraft = Proxies.common.getClientInstance(); - EntityPlayer player = minecraft.thePlayer; + EntityPlayer player = minecraft.player; ItemStack itemStack = getItemStack(); ToolTip tip = new ToolTip(); - if (itemStack != null) { + if (!itemStack.isEmpty()) { tip.add(itemStack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips)); } return tip; diff --git a/src/main/java/forestry/core/gui/widgets/SocketWidget.java b/src/main/java/forestry/core/gui/widgets/SocketWidget.java index 93cc0cdd9..a8d8b23ec 100755 --- a/src/main/java/forestry/core/gui/widgets/SocketWidget.java +++ b/src/main/java/forestry/core/gui/widgets/SocketWidget.java @@ -42,7 +42,7 @@ public class SocketWidget extends Widget { @Override public void draw(int startX, int startY) { ItemStack socketStack = tile.getSocket(slot); - if (socketStack != null) { + if (!socketStack.isEmpty()) { Proxies.common.getClientInstance().getRenderItem().renderItemIntoGUI(socketStack, startX + xPos, startY + yPos); } } @@ -59,9 +59,9 @@ public class SocketWidget extends Widget { public void refresh() { toolTip.clear(); ItemStack stack = tile.getSocket(slot); - if (stack != null) { + if (!stack.isEmpty()) { Minecraft minecraft = Proxies.common.getClientInstance(); - EntityPlayer player = minecraft.thePlayer; + EntityPlayer player = minecraft.player; toolTip.add(stack.getTooltip(player, minecraft.gameSettings.advancedItemTooltips)); toolTip.add(TextFormatting.ITALIC + Translator.translateToLocal("for.gui.socket.remove")); } else { @@ -73,8 +73,8 @@ public class SocketWidget extends Widget { @Override public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - ItemStack itemstack = manager.minecraft.thePlayer.inventory.getItemStack(); - if (itemstack == null) { + ItemStack itemstack = manager.minecraft.player.inventory.getItemStack(); + if (itemstack.isEmpty()) { return; } diff --git a/src/main/java/forestry/core/gui/widgets/TankWidget.java b/src/main/java/forestry/core/gui/widgets/TankWidget.java index ecbbc4cfe..275f31232 100755 --- a/src/main/java/forestry/core/gui/widgets/TankWidget.java +++ b/src/main/java/forestry/core/gui/widgets/TankWidget.java @@ -13,7 +13,7 @@ package forestry.core.gui.widgets; import javax.annotation.Nullable; import forestry.api.core.IToolPipette; -import forestry.core.fluids.tanks.StandardTank; +import forestry.core.fluids.StandardTank; import forestry.core.gui.IContainerLiquidTanks; import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; @@ -64,7 +64,7 @@ public class TankWidget extends Widget { return ((IContainerLiquidTanks) container).getTank(slot); } else if (container instanceof ContainerFarm) { return ((ContainerFarm) container).getTank(slot); - }else if (container instanceof ContainerGreenhouse) { + } else if (container instanceof ContainerGreenhouse) { return ((ContainerGreenhouse) container).getTank(slot); } return null; @@ -147,7 +147,7 @@ public class TankWidget extends Widget { } return ((StandardTank) tank).getToolTip(); } - + private static void setGLColorFromInt(int color) { float red = (color >> 16 & 0xFF) / 255.0F; float green = (color >> 8 & 0xFF) / 255.0F; @@ -156,7 +156,7 @@ public class TankWidget extends Widget { GlStateManager.color(red, green, blue, 1.0F); } - + private static void drawFluidTexture(double xCoord, double yCoord, TextureAtlasSprite textureSprite, int maskTop, int maskRight, double zLevel) { double uMin = textureSprite.getMinU(); double uMax = textureSprite.getMaxU(); @@ -168,18 +168,18 @@ public class TankWidget extends Widget { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer vertexBuffer = tessellator.getBuffer(); vertexBuffer.begin(7, DefaultVertexFormats.POSITION_TEX); - vertexBuffer.pos(xCoord, yCoord + 16, zLevel).tex(uMin, vMax).endVertex(); + vertexBuffer.pos(xCoord, yCoord + 16, zLevel).tex(uMin, vMax).endVertex(); vertexBuffer.pos(xCoord + 16 - maskRight, yCoord + 16, zLevel).tex(uMax, vMax).endVertex(); vertexBuffer.pos(xCoord + 16 - maskRight, yCoord + maskTop, zLevel).tex(uMax, vMin).endVertex(); - vertexBuffer.pos(xCoord, yCoord + maskTop, zLevel).tex(uMin, vMin).endVertex(); + vertexBuffer.pos(xCoord, yCoord + maskTop, zLevel).tex(uMin, vMin).endVertex(); tessellator.draw(); } @Override public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - EntityPlayer player = manager.minecraft.thePlayer; + EntityPlayer player = manager.minecraft.player; ItemStack itemstack = player.inventory.getItemStack(); - if (itemstack == null) { + if (itemstack.isEmpty()) { return; } diff --git a/src/main/java/forestry/core/gui/widgets/Widget.java b/src/main/java/forestry/core/gui/widgets/Widget.java index 69eedc643..c10722934 100755 --- a/src/main/java/forestry/core/gui/widgets/Widget.java +++ b/src/main/java/forestry/core/gui/widgets/Widget.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.core.gui.tooltips.IToolTipProvider; @@ -20,14 +19,13 @@ import forestry.core.gui.tooltips.ToolTip; * Basic non-ItemStack slot */ public abstract class Widget implements IToolTipProvider { - @Nonnull protected final WidgetManager manager; protected final int xPos; protected final int yPos; protected int width = 16; protected int height = 16; - public Widget(@Nonnull WidgetManager manager, int xPos, int yPos) { + public Widget(WidgetManager manager, int xPos, int yPos) { this.manager = manager; this.xPos = xPos; this.yPos = yPos; diff --git a/src/main/java/forestry/core/gui/widgets/WidgetCamouflageSlot.java b/src/main/java/forestry/core/gui/widgets/WidgetCamouflageSlot.java index b2e7b26d9..f337f74fc 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetCamouflageSlot.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetCamouflageSlot.java @@ -10,16 +10,6 @@ ******************************************************************************/ package forestry.core.gui.widgets; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.renderer.RenderItem; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextFormatting; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; @@ -27,43 +17,49 @@ import forestry.api.multiblock.IMultiblockController; import forestry.core.gui.tooltips.ToolTip; import forestry.core.proxy.Proxies; import forestry.core.utils.Translator; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextFormatting; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class WidgetCamouflageSlot extends Widget { - private final ICamouflageHandler camouflageHandler; private final String type; public WidgetCamouflageSlot(WidgetManager manager, int xPos, int yPos, ICamouflageHandler camouflageHandler, String type) { super(manager, xPos, yPos); - + this.camouflageHandler = camouflageHandler; this.type = type; } @Override public void draw(int startX, int startY) { - if (camouflageHandler != null && camouflageHandler.getCamouflageBlock(type) != null) { + ItemStack camouflageBlock = camouflageHandler.getCamouflageBlock(type); + if (!camouflageBlock.isEmpty()) { Proxies.render.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE); RenderItem renderItem = Proxies.common.getClientInstance().getRenderItem(); - renderItem.renderItemIntoGUI(camouflageHandler.getCamouflageBlock(type), startX + xPos, startY + yPos); + renderItem.renderItemIntoGUI(camouflageBlock, startX + xPos, startY + yPos); } } - + @Override public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { super.handleMouseClick(mouseX, mouseY, mouseButton); - if (camouflageHandler == null) { - return; - } if (GuiScreen.isShiftKeyDown()) { camouflageHandler.setCamouflageBlock(type, camouflageHandler.getDefaultCamouflageBlock(type), true); } else { - EntityPlayer player = Minecraft.getMinecraft().thePlayer; + EntityPlayer player = Minecraft.getMinecraft().player; ItemStack stack = player.inventory.getItemStack(); - if (stack != null) { + if (!stack.isEmpty()) { if (!CamouflageManager.camouflageAccess.isItemBlackListed(type, stack)) { - for(ICamouflageItemHandler handler : CamouflageManager.camouflageAccess.getCamouflageItemHandler(type)){ - if(handler != null && handler.canHandle(stack)){ + for (ICamouflageItemHandler handler : CamouflageManager.camouflageAccess.getCamouflageItemHandler(type)) { + if (handler != null && handler.canHandle(stack)) { camouflageHandler.setCamouflageBlock(handler.getType(), stack.copy(), true); } } @@ -71,7 +67,7 @@ public class WidgetCamouflageSlot extends Widget { } } } - + @Override public ToolTip getToolTip(int mouseX, int mouseY) { if (isMouseOver(mouseX, mouseY)) { @@ -93,11 +89,11 @@ public class WidgetCamouflageSlot extends Widget { } ItemStack camouflageBlock = camouflageHandler.getCamouflageBlock(type); - if (camouflageHandler == null || camouflageBlock == null) { + if (camouflageBlock.isEmpty()) { toolTip.add(TextFormatting.ITALIC.toString() + Translator.translateToLocal("for.gui.empty")); } else { Minecraft minecraft = Proxies.common.getClientInstance(); - toolTip.add(TextFormatting.ITALIC.toString() + camouflageBlock.getTooltip(minecraft.thePlayer, minecraft.gameSettings.advancedItemTooltips)); + toolTip.add(TextFormatting.ITALIC.toString() + camouflageBlock.getTooltip(minecraft.player, minecraft.gameSettings.advancedItemTooltips)); } } }; diff --git a/src/main/java/forestry/core/gui/widgets/WidgetManager.java b/src/main/java/forestry/core/gui/widgets/WidgetManager.java index b5953a724..d86c56154 100644 --- a/src/main/java/forestry/core/gui/widgets/WidgetManager.java +++ b/src/main/java/forestry/core/gui/widgets/WidgetManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.gui.widgets; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -45,6 +46,7 @@ public class WidgetManager { return widgets; } + @Nullable public Widget getAtPosition(int mX, int mY) { for (Widget slot : widgets) { if (slot.isMouseOver(mX, mY)) { diff --git a/src/main/java/forestry/core/gui/widgets/package-info.java b/src/main/java/forestry/core/gui/widgets/package-info.java new file mode 100644 index 000000000..7e20547ef --- /dev/null +++ b/src/main/java/forestry/core/gui/widgets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.gui.widgets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java index 46da6713e..16d64d7e6 100644 --- a/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java +++ b/src/main/java/forestry/core/inventory/AdjacentInventoryCache.java @@ -10,20 +10,18 @@ ******************************************************************************/ package forestry.core.inventory; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.items.IItemHandler; - import forestry.core.tiles.AdjacentTileCache; import forestry.core.tiles.TileUtil; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.items.IItemHandler; /** * @author CovertJaguar @@ -38,18 +36,20 @@ public final class AdjacentInventoryCache implements AdjacentTileCache.ICacheLis private boolean changed = true; private final List invs = new LinkedList<>(); private final IItemHandler[] sides = new IItemHandler[6]; + @Nullable private final Comparator sorter; + @Nullable private final ITileFilter filter; public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache) { this(tile, cache, null, null); } - public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter) { + public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, @Nullable ITileFilter filter) { this(tile, cache, filter, null); } - public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, ITileFilter filter, Comparator sorter) { + public AdjacentInventoryCache(TileEntity tile, AdjacentTileCache cache, @Nullable ITileFilter filter, @Nullable Comparator sorter) { this.cache = cache; this.filter = filter; this.sorter = sorter; @@ -93,7 +93,7 @@ public final class AdjacentInventoryCache implements AdjacentTileCache.ICacheLis } } if (sorter != null) { - Collections.sort(invs, sorter); + invs.sort(sorter); } } } diff --git a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java index df0227193..9aec4f509 100644 --- a/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/FakeInventoryAdapter.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.inventory; +import javax.annotation.Nullable; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -17,9 +19,10 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.text.ITextComponent; import forestry.core.config.Constants; +import net.minecraft.util.text.TextComponentString; public class FakeInventoryAdapter implements IInventoryAdapter { - + @Nullable private static FakeInventoryAdapter instance; public static FakeInventoryAdapter instance() { @@ -33,6 +36,11 @@ public class FakeInventoryAdapter implements IInventoryAdapter { } + @Override + public boolean isEmpty() { + return true; + } + @Override public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { return false; @@ -65,17 +73,17 @@ public class FakeInventoryAdapter implements IInventoryAdapter { @Override public ItemStack getStackInSlot(int p_70301_1_) { - return null; + return ItemStack.EMPTY; } @Override public ItemStack decrStackSize(int p_70298_1_, int p_70298_2_) { - return null; + return ItemStack.EMPTY; } @Override public ItemStack removeStackFromSlot(int index) { - return null; + return ItemStack.EMPTY; } @Override @@ -85,12 +93,12 @@ public class FakeInventoryAdapter implements IInventoryAdapter { @Override public ITextComponent getDisplayName() { - return null; + return new TextComponentString(getName()); } @Override public String getName() { - return null; + return ""; } @Override @@ -109,7 +117,7 @@ public class FakeInventoryAdapter implements IInventoryAdapter { } @Override - public boolean isUseableByPlayer(EntityPlayer player) { + public boolean isUsableByPlayer(EntityPlayer player) { return false; } diff --git a/src/main/java/forestry/core/inventory/iterators/IInvSlot.java b/src/main/java/forestry/core/inventory/IInvSlot.java similarity index 96% rename from src/main/java/forestry/core/inventory/iterators/IInvSlot.java rename to src/main/java/forestry/core/inventory/IInvSlot.java index 4a5bd0568..b2ae54466 100644 --- a/src/main/java/forestry/core/inventory/iterators/IInvSlot.java +++ b/src/main/java/forestry/core/inventory/IInvSlot.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.inventory.iterators; +package forestry.core.inventory; import net.minecraft.item.ItemStack; diff --git a/src/main/java/forestry/core/inventory/iterators/InvIterator.java b/src/main/java/forestry/core/inventory/InvIterator.java similarity index 92% rename from src/main/java/forestry/core/inventory/iterators/InvIterator.java rename to src/main/java/forestry/core/inventory/InvIterator.java index 59885f603..6937bba74 100644 --- a/src/main/java/forestry/core/inventory/iterators/InvIterator.java +++ b/src/main/java/forestry/core/inventory/InvIterator.java @@ -1,4 +1,4 @@ -package forestry.core.inventory.iterators; +package forestry.core.inventory; import java.util.Iterator; import java.util.NoSuchElementException; diff --git a/src/main/java/forestry/core/inventory/iterators/InvSlot.java b/src/main/java/forestry/core/inventory/InvSlot.java similarity index 70% rename from src/main/java/forestry/core/inventory/iterators/InvSlot.java rename to src/main/java/forestry/core/inventory/InvSlot.java index 39dad1096..1ea2bd8fa 100644 --- a/src/main/java/forestry/core/inventory/iterators/InvSlot.java +++ b/src/main/java/forestry/core/inventory/InvSlot.java @@ -1,4 +1,4 @@ -package forestry.core.inventory.iterators; +package forestry.core.inventory; import net.minecraft.item.ItemStack; @@ -22,12 +22,12 @@ public class InvSlot implements IInvSlot { @Override public boolean canPutStackInSlot(ItemStack stack) { ItemStack remainder = inv.insertItem(slot, stack, true); - return remainder == null || remainder.stackSize < stack.stackSize; + return remainder.isEmpty() || remainder.getCount() < stack.getCount(); } @Override public boolean canTakeStackFromSlot(ItemStack stack) { - return inv.extractItem(slot, 1, true) != null; + return !inv.extractItem(slot, 1, true).isEmpty(); } @Override @@ -37,11 +37,7 @@ public class InvSlot implements IInvSlot { @Override public ItemStack getStackInSlot() { - ItemStack stack = inv.getStackInSlot(slot); - if (stack == null || stack.stackSize <= 0) { - return null; - } - return stack; + return inv.getStackInSlot(slot); } } diff --git a/src/main/java/forestry/core/inventory/InventoryAdapter.java b/src/main/java/forestry/core/inventory/InventoryAdapter.java index f8a2e7407..a2dd8ec74 100755 --- a/src/main/java/forestry/core/inventory/InventoryAdapter.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapter.java @@ -10,20 +10,20 @@ ******************************************************************************/ package forestry.core.inventory; +import javax.annotation.Nullable; import java.io.IOException; +import forestry.core.config.Constants; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import forestry.core.utils.InventoryUtil; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.text.ITextComponent; - -import forestry.core.config.Constants; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; -import forestry.core.utils.InventoryUtil; +import net.minecraft.util.text.TextComponentString; /** * With permission from Krapht. @@ -32,6 +32,8 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { private final IInventory inventory; private boolean allowAutomation = true; + @Nullable + private int[] slotMap; //private boolean debug = false; @@ -65,7 +67,7 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { InventoryAdapter copy = new InventoryAdapter(inventory.getSizeInventory(), inventory.getName(), inventory.getInventoryStackLimit()); for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (inventory.getStackInSlot(i) != null) { + if (!inventory.getStackInSlot(i).isEmpty()) { copy.setInventorySlotContents(i, inventory.getStackInSlot(i).copy()); } } @@ -73,8 +75,12 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { return copy; } - /* IINVENTORY */ + @Override + public boolean isEmpty() { + return inventory.isEmpty(); + } + @Override public int getSizeInventory() { return inventory.getSizeInventory(); @@ -109,25 +115,25 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { public void markDirty() { inventory.markDirty(); } - + @Override public ItemStack removeStackFromSlot(int slotIndex) { return inventory.removeStackFromSlot(slotIndex); } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { + public boolean isUsableByPlayer(EntityPlayer entityplayer) { return true; } - + @Override public boolean hasCustomName() { return false; } - + @Override public ITextComponent getDisplayName() { - return null; + return new TextComponentString(""); } @Override @@ -154,11 +160,9 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { } /* ISIDEDINVENTORY */ - private int[] slotMap; - @Override public int[] getSlotsForFace(EnumFacing side) { - if (allowAutomation) { + if (allowAutomation && slotMap != null) { return slotMap; } return Constants.SLOTS_NONE; @@ -195,30 +199,30 @@ public class InventoryAdapter implements IInventoryAdapter, IStreamable { } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeInventory(inventory); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { data.readInventory(inventory); } - + /* FIELDS */ @Override public int getField(int id) { return 0; } - + @Override public int getFieldCount() { return 0; } - + @Override public void setField(int id, int value) { } - + @Override public void clear() { } diff --git a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java index 7795f87e8..706fd0bf8 100644 --- a/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java +++ b/src/main/java/forestry/core/inventory/InventoryAdapterRestricted.java @@ -24,23 +24,16 @@ public class InventoryAdapterRestricted extends InventoryAdapter { @Override public boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { - if (itemStack == null) { - return false; - } - - return canSlotAccept(slotIndex, itemStack); + return !itemStack.isEmpty() && canSlotAccept(slotIndex, itemStack); } @Override public final boolean canInsertItem(int slotIndex, ItemStack itemStack, EnumFacing side) { - if (itemStack == null) { - return false; - } - return isItemValidForSlot(slotIndex, itemStack); + return !itemStack.isEmpty() && isItemValidForSlot(slotIndex, itemStack); } @Override public boolean canExtractItem(int slotIndex, ItemStack itemStack, EnumFacing side) { - return itemStack != null; + return !itemStack.isEmpty(); } } diff --git a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java index c048c4752..d0b50724e 100644 --- a/src/main/java/forestry/core/inventory/InventoryAnalyzer.java +++ b/src/main/java/forestry/core/inventory/InventoryAnalyzer.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.core.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import forestry.api.arboriculture.TreeManager; import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; @@ -23,6 +17,10 @@ import forestry.core.tiles.TileAnalyzer; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.SlotUtil; import forestry.plugins.ForestryPluginUids; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; public class InventoryAnalyzer extends InventoryAdapterTile { public static final short SLOT_ANALYZE = 0; @@ -42,7 +40,7 @@ public class InventoryAnalyzer extends InventoryAdapterTile { return AlleleManager.alleleRegistry.isIndividual(itemStack) || GeneticsUtil.getGeneticEquivalent(itemStack) != null; } else if (slotIndex == SLOT_CAN) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); + return fluid != null && tile.getTankManager().canFillFluidType(fluid); } return false; @@ -56,10 +54,7 @@ public class InventoryAnalyzer extends InventoryAdapterTile { @Override public void setInventorySlotContents(int slotId, ItemStack itemStack) { if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ARBORICULTURE) && !TreeManager.treeRoot.isMember(itemStack)) { - ItemStack ersatz = GeneticsUtil.convertToGeneticEquivalent(itemStack); - if (ersatz != null) { - itemStack = ersatz; - } + itemStack = GeneticsUtil.convertToGeneticEquivalent(itemStack); } super.setInventorySlotContents(slotId, itemStack); diff --git a/src/main/java/forestry/core/inventory/InventoryEscritoire.java b/src/main/java/forestry/core/inventory/InventoryEscritoire.java index d3c77795e..e59559552 100644 --- a/src/main/java/forestry/core/inventory/InventoryEscritoire.java +++ b/src/main/java/forestry/core/inventory/InventoryEscritoire.java @@ -10,14 +10,13 @@ ******************************************************************************/ package forestry.core.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.core.tiles.TileEscritoire; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.SlotUtil; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryEscritoire extends InventoryAdapterTile { public static final short SLOT_ANALYZE = 0; @@ -34,18 +33,16 @@ public class InventoryEscritoire extends InventoryAdapterTile { public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { if (slotIndex >= SLOT_INPUT_1 && slotIndex < SLOT_INPUT_1 + tile.getGame().getSampleSize(SLOTS_INPUT_COUNT)) { ItemStack specimen = getStackInSlot(SLOT_ANALYZE); - if (specimen == null) { + if (specimen.isEmpty()) { return false; } IIndividual individual = AlleleManager.alleleRegistry.getIndividual(specimen); return individual != null && individual.getGenome().getPrimary().getResearchSuitability(itemStack) > 0; } - if (slotIndex == SLOT_ANALYZE) { - return AlleleManager.alleleRegistry.isIndividual(itemStack) || GeneticsUtil.getGeneticEquivalent(itemStack) != null; - } + return slotIndex == SLOT_ANALYZE && + (AlleleManager.alleleRegistry.isIndividual(itemStack) || GeneticsUtil.getGeneticEquivalent(itemStack) != null); - return false; } @Override @@ -54,7 +51,7 @@ public class InventoryEscritoire extends InventoryAdapterTile { return false; } - if (getStackInSlot(SLOT_ANALYZE) == null) { + if (getStackInSlot(SLOT_ANALYZE).isEmpty()) { return true; } @@ -76,13 +73,13 @@ public class InventoryEscritoire extends InventoryAdapterTile { public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { super.setInventorySlotContents(slotIndex, itemstack); if (slotIndex == SLOT_ANALYZE) { - if (!AlleleManager.alleleRegistry.isIndividual(getStackInSlot(SLOT_ANALYZE)) && getStackInSlot(SLOT_ANALYZE) != null) { + if (!AlleleManager.alleleRegistry.isIndividual(getStackInSlot(SLOT_ANALYZE)) && !getStackInSlot(SLOT_ANALYZE).isEmpty()) { ItemStack ersatz = GeneticsUtil.convertToGeneticEquivalent(getStackInSlot(SLOT_ANALYZE)); - if (ersatz != null) { + if (AlleleManager.alleleRegistry.isIndividual(ersatz)) { super.setInventorySlotContents(SLOT_ANALYZE, ersatz); } } - if (tile.getWorld() != null && !tile.getWorld().isRemote) { + if (!tile.getWorld().isRemote) { tile.getGame().initialize(getStackInSlot(SLOT_ANALYZE)); } } diff --git a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java index 8fb5b515f..ede2f0d6a 100644 --- a/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java +++ b/src/main/java/forestry/core/inventory/InventoryNaturalistChest.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.core.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.api.genetics.ISpeciesRoot; import forestry.core.tiles.TileNaturalistChest; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryNaturalistChest extends InventoryAdapterTile { private final ISpeciesRoot speciesRoot; diff --git a/src/main/java/forestry/core/inventory/InventoryPlain.java b/src/main/java/forestry/core/inventory/InventoryPlain.java index 5b04f7c2e..e08528df4 100644 --- a/src/main/java/forestry/core/inventory/InventoryPlain.java +++ b/src/main/java/forestry/core/inventory/InventoryPlain.java @@ -14,6 +14,7 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; @@ -23,73 +24,56 @@ import forestry.core.utils.InventoryUtil; public class InventoryPlain implements IInventory, INbtWritable, INbtReadable { - private final ItemStack[] contents; + private final NonNullList contents; private final String name; private final int stackLimit; - public InventoryPlain(int size) { - this(size, null, 64); - } - - - public InventoryPlain(int size, String name) { - this(size, name, 64); - } - public InventoryPlain(int size, String name, int stackLimit) { - this.contents = new ItemStack[size]; + this.contents = NonNullList.withSize(size, ItemStack.EMPTY); this.name = name; this.stackLimit = stackLimit; } - public InventoryPlain(IInventory tocopy) { - this(tocopy.getSizeInventory(), tocopy.getName(), tocopy.getInventoryStackLimit()); - for (int i = 0; i < tocopy.getSizeInventory(); i++) { - if (tocopy.getStackInSlot(i) != null) { - this.setInventorySlotContents(i, tocopy.getStackInSlot(i).copy()); - } else { - this.setInventorySlotContents(i, null); + @Override + public boolean isEmpty() { + for (ItemStack stack : contents) { + if (!stack.isEmpty()) { + return false; } } + return true; } - public ItemStack[] getContents() { + public NonNullList getContents() { return contents; } @Override public int getSizeInventory() { - return contents.length; + return contents.size(); } @Override public ItemStack getStackInSlot(int slotId) { - return contents[slotId]; + return contents.get(slotId); } @Override public ItemStack decrStackSize(int slotId, int count) { - if (contents[slotId] == null) { - return null; + ItemStack itemStack = contents.get(slotId); + if (itemStack.isEmpty()) { + return ItemStack.EMPTY; } - if (contents[slotId].stackSize > count) { - return contents[slotId].splitStack(count); - } - ItemStack stack = contents[slotId]; - contents[slotId] = null; - return stack; + return itemStack.splitStack(count); } @Override public void setInventorySlotContents(int slotId, ItemStack itemstack) { - contents[slotId] = itemstack; + contents.set(slotId, itemstack); } @Override public String getName() { - if(name == null){ - return "Plain"; - } return name; } @@ -103,7 +87,7 @@ public class InventoryPlain implements IInventory, INbtWritable, INbtReadable { } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { + public boolean isUsableByPlayer(EntityPlayer entityplayer) { return false; } @@ -114,7 +98,7 @@ public class InventoryPlain implements IInventory, INbtWritable, INbtReadable { @Override public boolean hasCustomName() { - return name != null; + return true; } @Override diff --git a/src/main/java/forestry/core/inventory/manipulators/ItemHandlerInventoryManipulator.java b/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java similarity index 80% rename from src/main/java/forestry/core/inventory/manipulators/ItemHandlerInventoryManipulator.java rename to src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java index 24191cbfb..85c837816 100644 --- a/src/main/java/forestry/core/inventory/manipulators/ItemHandlerInventoryManipulator.java +++ b/src/main/java/forestry/core/inventory/ItemHandlerInventoryManipulator.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.inventory.manipulators; +package forestry.core.inventory; import javax.annotation.Nullable; import java.util.ArrayList; @@ -17,12 +17,8 @@ import java.util.List; import java.util.function.Predicate; import net.minecraft.item.ItemStack; - import net.minecraftforge.items.IItemHandler; -import forestry.core.inventory.iterators.IInvSlot; -import forestry.core.inventory.iterators.InvIterator; - /** * @author CovertJaguar */ @@ -65,11 +61,11 @@ public class ItemHandlerInventoryManipulator implements Iterable { public ItemStack removeItem(Predicate filter) { for (IInvSlot slot : this) { ItemStack stack = slot.getStackInSlot(); - if (stack != null && stack.stackSize > 0 && slot.canTakeStackFromSlot(stack) && filter.test(stack)) { + if (!stack.isEmpty() && slot.canTakeStackFromSlot(stack) && filter.test(stack)) { return slot.decreaseStackInSlot(); } } - return null; + return ItemStack.EMPTY; } public boolean transferOneStack(IItemHandler dest, Predicate filter) { @@ -85,11 +81,11 @@ public class ItemHandlerInventoryManipulator implements Iterable { boolean stacksMoved = false; for (int slotIndex = 0; slotIndex < inv.getSlots(); slotIndex++) { ItemStack targetStack = inv.extractItem(slotIndex, Integer.MAX_VALUE, true); - if (targetStack != null && targetStack.stackSize > 0 && filter.test(targetStack)) { - int extractStackSize = targetStack.stackSize; + if (!targetStack.isEmpty() && filter.test(targetStack)) { + int extractStackSize = targetStack.getCount(); ItemStack remaining = destManipulator.tryAddStack(targetStack); if (remaining != null) { - extractStackSize -= remaining.stackSize; + extractStackSize -= remaining.getCount(); } if (extractStackSize > 0) { ItemStack extracted = inv.extractItem(slotIndex, extractStackSize, false); @@ -106,7 +102,7 @@ public class ItemHandlerInventoryManipulator implements Iterable { @Nullable protected ItemStack addStack(ItemStack stack, boolean doAdd) { - if (stack == null || stack.stackSize <= 0) { + if (stack.isEmpty()) { return null; } stack = stack.copy(); @@ -114,7 +110,7 @@ public class ItemHandlerInventoryManipulator implements Iterable { List emptySlots = new ArrayList<>(inv.getSlots()); for (IInvSlot slot : new ItemHandlerInventoryManipulator(inv)) { if (slot.canPutStackInSlot(stack)) { - if (slot.getStackInSlot() == null) { + if (slot.getStackInSlot().isEmpty()) { emptySlots.add(slot); } else { filledSlots.add(slot); @@ -125,28 +121,25 @@ public class ItemHandlerInventoryManipulator implements Iterable { int injected = 0; injected = tryPut(filledSlots, stack, injected, doAdd); injected = tryPut(emptySlots, stack, injected, doAdd); - stack.stackSize -= injected; - if (stack.stackSize <= 0) { - return null; - } + stack.shrink(injected); return stack; } private int tryPut(List slots, ItemStack stack, int injected, boolean doAdd) { - if (injected >= stack.stackSize) { + if (injected >= stack.getCount()) { return injected; } for (IInvSlot slot : slots) { final ItemStack stackToInsert = stack.copy(); - final int stackToInsertSize = stack.stackSize - injected; - stackToInsert.stackSize = stackToInsertSize; + final int stackToInsertSize = stack.getCount() - injected; + stackToInsert.setCount(stackToInsertSize); final ItemStack remainder = inv.insertItem(slot.getIndex(), stackToInsert, !doAdd); - if (remainder == null) { - return stack.stackSize; + if (remainder.isEmpty()) { + return stack.getCount(); } - injected += stackToInsertSize - remainder.stackSize; - if (injected >= stack.stackSize) { + injected += stackToInsertSize - remainder.getCount(); + if (injected >= stack.getCount()) { return injected; } } diff --git a/src/main/java/forestry/core/inventory/ItemInventory.java b/src/main/java/forestry/core/inventory/ItemInventory.java index 089037f27..ac0ce3ac1 100755 --- a/src/main/java/forestry/core/inventory/ItemInventory.java +++ b/src/main/java/forestry/core/inventory/ItemInventory.java @@ -10,45 +10,63 @@ ******************************************************************************/ package forestry.core.inventory; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Random; +import com.google.common.base.Preconditions; +import forestry.core.tiles.IFilterSlotDelegate; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ItemStackHelper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; - import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.InvWrapper; -import forestry.core.tiles.IFilterSlotDelegate; - public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, ICapabilityProvider { private static final String KEY_SLOTS = "Slots"; private static final String KEY_UID = "UID"; private static final Random rand = new Random(); private final IItemHandler itemHandler = new InvWrapper(this); - @Nonnull + protected final EntityPlayer player; private final ItemStack parent; - private final ItemStack[] inventoryStacks; + private final NonNullList inventoryStacks; + + public ItemInventory(EntityPlayer player, int size, ItemStack parent) { + Preconditions.checkArgument(!parent.isEmpty(), "Parent cannot be empty."); - public ItemInventory(@Nonnull EntityPlayer player, int size, ItemStack parent) { this.player = player; this.parent = parent; - this.inventoryStacks = new ItemStack[size]; + this.inventoryStacks = NonNullList.withSize(size, ItemStack.EMPTY); - setUID(); // Set a uid to identify the itemStack on SMP + NBTTagCompound nbt = parent.getTagCompound(); + if (nbt == null) { + nbt = new NBTTagCompound(); + parent.setTagCompound(nbt); + } + setUID(nbt); // Set a uid to identify the itemStack on SMP - readFromNBT(parent.getTagCompound()); + NBTTagCompound nbtSlots = nbt.getCompoundTag(KEY_SLOTS); + for (int i = 0; i < inventoryStacks.size(); i++) { + String slotKey = getSlotNBTKey(i); + if (nbtSlots.hasKey(slotKey)) { + NBTTagCompound itemNbt = nbtSlots.getCompoundTag(slotKey); + ItemStack itemStack = new ItemStack(itemNbt); + inventoryStacks.set(i, itemStack); + } else { + inventoryStacks.set(i, ItemStack.EMPTY); + } + } } public static int getOccupiedSlotCount(ItemStack itemStack) { @@ -61,14 +79,7 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, return slotNbt.getKeySet().size(); } - private void setUID() { - ItemStack parent = getParent(); - - if (parent.getTagCompound() == null) { - parent.setTagCompound(new NBTTagCompound()); - } - - NBTTagCompound nbt = parent.getTagCompound(); + private void setUID(NBTTagCompound nbt) { if (!nbt.hasKey(KEY_UID)) { nbt.setInteger(KEY_UID, rand.nextInt()); } @@ -90,7 +101,7 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, } private static boolean isSameItemInventory(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { + if (base.isEmpty() || comparison.isEmpty()) { return false; } @@ -98,45 +109,34 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, return false; } - if (!base.hasTagCompound() || !comparison.hasTagCompound()) { + NBTTagCompound baseTagCompound = base.getTagCompound(); + NBTTagCompound comparisonTagCompound = comparison.getTagCompound(); + if (baseTagCompound == null || comparisonTagCompound == null) { return false; } - String baseUID = base.getTagCompound().getString(KEY_UID); - String comparisonUID = comparison.getTagCompound().getString(KEY_UID); - return baseUID != null && comparisonUID != null && baseUID.equals(comparisonUID); - } - - public void readFromNBT(NBTTagCompound nbt) { - - if (nbt == null) { - return; + if (!baseTagCompound.hasKey(KEY_UID) || !comparisonTagCompound.hasKey(KEY_UID)) { + return false; } - NBTTagCompound nbtSlots = nbt.getCompoundTag(KEY_SLOTS); - for (int i = 0; i < inventoryStacks.length; i++) { - String slotKey = getSlotNBTKey(i); - if (nbtSlots.hasKey(slotKey)) { - NBTTagCompound itemNbt = nbtSlots.getCompoundTag(slotKey); - ItemStack itemStack = ItemStack.loadItemStackFromNBT(itemNbt); - inventoryStacks[i] = itemStack; - } else { - inventoryStacks[i] = null; - } - } + String baseUID = baseTagCompound.getString(KEY_UID); + String comparisonUID = comparisonTagCompound.getString(KEY_UID); + return baseUID.equals(comparisonUID); } private void writeToParentNBT() { ItemStack parent = getParent(); - if (parent == null) { - return; - } NBTTagCompound nbt = parent.getTagCompound(); + if (nbt == null) { + nbt = new NBTTagCompound(); + parent.setTagCompound(nbt); + } + NBTTagCompound slotsNbt = new NBTTagCompound(); for (int i = 0; i < getSizeInventory(); i++) { ItemStack itemStack = getStackInSlot(i); - if (itemStack != null) { + if (!itemStack.isEmpty()) { String slotKey = getSlotNBTKey(i); NBTTagCompound itemNbt = new NBTTagCompound(); itemStack.writeToNBT(itemNbt); @@ -155,29 +155,31 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, } @Override - public ItemStack decrStackSize(int i, int j) { - ItemStack stack = getStackInSlot(i); - if (stack == null) { - return null; + public boolean isEmpty() { + for (ItemStack itemstack : this.inventoryStacks) { + if (!itemstack.isEmpty()) { + return false; + } } - if (stack.stackSize <= j) { - setInventorySlotContents(i, null); - return stack; - } else { - ItemStack product = stack.splitStack(j); - setInventorySlotContents(i, stack); - return product; + return true; + } + + + @Override + public ItemStack decrStackSize(int index, int count) { + ItemStack itemstack = ItemStackHelper.getAndSplit(this.inventoryStacks, index, count); + + if (!itemstack.isEmpty()) { + this.markDirty(); } + + return itemstack; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) { - if (itemstack != null && itemstack.stackSize == 0) { - itemstack = null; - } - - inventoryStacks[i] = itemstack; + public void setInventorySlotContents(int index, ItemStack itemstack) { + inventoryStacks.set(index, itemstack); ItemStack parent = getParent(); @@ -195,9 +197,9 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, slotNbt = nbt.getCompoundTag(KEY_SLOTS); } - String slotKey = getSlotNBTKey(i); + String slotKey = getSlotNBTKey(index); - if (itemstack == null) { + if (itemstack.isEmpty()) { slotNbt.removeTag(slotKey); } else { NBTTagCompound itemNbt = new NBTTagCompound(); @@ -209,19 +211,19 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, @Override public ItemStack getStackInSlot(int i) { - return inventoryStacks[i]; + return inventoryStacks.get(i); } @Override public int getSizeInventory() { - return inventoryStacks.length; + return inventoryStacks.size(); } - + @Override public String getName() { return "BeeBag"; } - + @Override public ITextComponent getDisplayName() { return new TextComponentString(getName()); @@ -238,10 +240,10 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { + public boolean isUsableByPlayer(EntityPlayer entityplayer) { return true; } - + @Override public boolean hasCustomName() { return true; @@ -259,13 +261,13 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, @Override public void closeInventory(EntityPlayer player) { } - + @Override public ItemStack removeStackFromSlot(int slot) { ItemStack toReturn = getStackInSlot(slot); - if (toReturn != null) { - setInventorySlotContents(slot, null); + if (!toReturn.isEmpty()) { + setInventorySlotContents(slot, ItemStack.EMPTY); } return toReturn; @@ -281,36 +283,37 @@ public abstract class ItemInventory implements IInventory, IFilterSlotDelegate, public boolean isLocked(int slotIndex) { return false; } - + /* Fields */ @Override public int getField(int id) { return 0; } - + @Override public int getFieldCount() { return 0; } - + @Override public void clear() { } - + @Override public void setField(int id, int value) { } - + @Override - public T getCapability(Capability capability, EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(itemHandler); } return null; } - + @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY; } diff --git a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java index 91f43abe5..c7a5443ef 100644 --- a/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java +++ b/src/main/java/forestry/core/inventory/ItemInventoryAlyzer.java @@ -10,17 +10,10 @@ ******************************************************************************/ package forestry.core.inventory; -import com.google.common.collect.ImmutableSet; - -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - +import com.google.common.collect.ImmutableSet; import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorSource; import forestry.api.core.IErrorState; @@ -35,6 +28,10 @@ import forestry.core.errors.EnumErrorCode; import forestry.core.gui.IHintSource; import forestry.core.utils.GeneticsUtil; import forestry.plugins.ForestryPluginUids; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, IHintSource { public static final int SLOT_ENERGY = 0; @@ -45,12 +42,12 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, public static final int SLOT_ANALYZE_4 = 5; public static final int SLOT_ANALYZE_5 = 6; - public ItemInventoryAlyzer(@Nonnull EntityPlayer player, ItemStack itemstack) { + public ItemInventoryAlyzer(EntityPlayer player, ItemStack itemstack) { super(player, 7, itemstack); } public static boolean isAlyzingFuel(ItemStack itemstack) { - if (itemstack == null || itemstack.stackSize <= 0) { + if (itemstack.isEmpty()) { return false; } @@ -62,7 +59,7 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, Item item = itemstack.getItem(); return beeItems.honeyDrop == item || beeItems.honeydew == item; } - + @Override public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { if (slotIndex == SLOT_ENERGY) { @@ -70,7 +67,7 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, } // only allow one slot to be used at a time - if (hasSpecimen() && getStackInSlot(slotIndex) == null) { + if (hasSpecimen() && getStackInSlot(slotIndex).isEmpty()) { return false; } @@ -87,17 +84,17 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, IIndividual individual = speciesRoot.getMember(itemStack); return individual.isAnalyzed(); } - + @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemStack) { - super.setInventorySlotContents(slotIndex, itemStack); - if (slotIndex == SLOT_SPECIMEN) { + public void setInventorySlotContents(int index, ItemStack itemStack) { + super.setInventorySlotContents(index, itemStack); + if (index == SLOT_SPECIMEN) { analyzeSpecimen(itemStack); } } private void analyzeSpecimen(ItemStack specimen) { - if (specimen == null) { + if (specimen.isEmpty()) { return; } @@ -125,9 +122,9 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, return; } } - + if (individual.analyze()) { - IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + IBreedingTracker breedingTracker = speciesRoot.getBreedingTracker(player.world, player.getGameProfile()); breedingTracker.registerSpecies(individual.getGenome().getPrimary()); breedingTracker.registerSpecies(individual.getGenome().getSecondary()); @@ -143,7 +140,7 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, } setInventorySlotContents(SLOT_ANALYZE_1, specimen); - setInventorySlotContents(SLOT_SPECIMEN, null); + setInventorySlotContents(SLOT_SPECIMEN, ItemStack.EMPTY); } @Override @@ -161,32 +158,30 @@ public class ItemInventoryAlyzer extends ItemInventory implements IErrorSource, return errorStates.build(); } - + public ItemStack getSpecimen() { for (int i = SLOT_SPECIMEN; i <= SLOT_ANALYZE_5; i++) { ItemStack itemStack = getStackInSlot(i); - if (itemStack != null) { + if (!itemStack.isEmpty()) { return itemStack; } } - return null; + return ItemStack.EMPTY; } public boolean hasSpecimen() { - return getSpecimen() != null; + return !getSpecimen().isEmpty(); } - + /* IHintSource */ @Override public List getHints() { ItemStack specimen = getSpecimen(); - if (specimen != null) { + if (!specimen.isEmpty()) { ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(specimen); if (speciesRoot != null) { IAlyzerPlugin alyzerPlugin = speciesRoot.getAlyzerPlugin(); - if (alyzerPlugin != null) { - return alyzerPlugin.getHints(); - } + return alyzerPlugin.getHints(); } } return Collections.emptyList(); diff --git a/src/main/java/forestry/core/inventory/ItemInventoryCamouflageSprayCan.java b/src/main/java/forestry/core/inventory/ItemInventoryCamouflageSprayCan.java index 5cf7ff3aa..ed4fcfa4b 100644 --- a/src/main/java/forestry/core/inventory/ItemInventoryCamouflageSprayCan.java +++ b/src/main/java/forestry/core/inventory/ItemInventoryCamouflageSprayCan.java @@ -23,7 +23,7 @@ public class ItemInventoryCamouflageSprayCan extends ItemInventory implements IC @Override public ItemStack getDefaultCamouflageBlock(String type) { - return null; + return ItemStack.EMPTY; } @Override @@ -36,7 +36,7 @@ public class ItemInventoryCamouflageSprayCan extends ItemInventory implements IC if(!ItemStackUtil.isIdenticalItem(camouflageBlock, getStackInSlot(0))){ setInventorySlotContents(0, camouflageBlock); - World world = player.worldObj; + World world = player.world; if (sendClientUpdate && world != null && world.isRemote) { Proxies.net.sendToServer(new PacketCamouflageSelectServer(this, type, CamouflageSelectionType.ITEM)); } diff --git a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java index 03d664121..537035d13 100644 --- a/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java +++ b/src/main/java/forestry/core/inventory/ItemInventorySolderingIron.java @@ -75,19 +75,15 @@ public class ItemInventorySolderingIron extends ItemInventory implements IErrorS for (short i = 0; i < ingredientSlotCount; i++) { ItemStack ingredient = getStackInSlot(ingredientSlot1 + i); - if (ingredient == null) { - continue; + if (!ingredient.isEmpty()) { + CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), ingredient); + if (recipe != null) { + if (doConsume) { + decrStackSize(ingredientSlot1 + i, recipe.getResource().getCount()); + } + circuits[i] = recipe.getCircuit(); + } } - - CircuitRecipe recipe = SolderManager.getMatchingRecipe(layouts.getCurrent(), ingredient); - if (recipe == null) { - continue; - } - - if (doConsume) { - decrStackSize(ingredientSlot1 + i, recipe.getResource().stackSize); - } - circuits[i] = recipe.getCircuit(); } return circuits; @@ -101,10 +97,10 @@ public class ItemInventorySolderingIron extends ItemInventory implements IErrorS ItemStack inputCircuitBoard = getStackInSlot(inputCircuitBoardSlot); - if (inputCircuitBoard == null || inputCircuitBoard.stackSize > 1) { + if (inputCircuitBoard.isEmpty() || inputCircuitBoard.getCount() > 1) { return; } - if (getStackInSlot(finishedCircuitBoardSlot) != null) { + if (!getStackInSlot(finishedCircuitBoardSlot).isEmpty()) { return; } @@ -128,7 +124,7 @@ public class ItemInventorySolderingIron extends ItemInventory implements IErrorS ItemStack outputCircuitBoard = ItemCircuitBoard.createCircuitboard(type, layouts.getCurrent(), circuits); setInventorySlotContents(finishedCircuitBoardSlot, outputCircuitBoard); - setInventorySlotContents(inputCircuitBoardSlot, null); + setInventorySlotContents(inputCircuitBoardSlot, ItemStack.EMPTY); } private int getCircuitCount() { @@ -152,14 +148,14 @@ public class ItemInventorySolderingIron extends ItemInventory implements IErrorS ItemStack blankCircuitBoard = getStackInSlot(inputCircuitBoardSlot); - if (blankCircuitBoard == null) { + if (blankCircuitBoard.isEmpty()) { errorStates.add(EnumErrorCode.NO_CIRCUIT_BOARD); } else { EnumCircuitBoardType type = EnumCircuitBoardType.values()[blankCircuitBoard.getItemDamage()]; int circuitCount = 0; for (short i = 0; i < type.getSockets(); i++) { - if (getStackInSlot(ingredientSlot1 + i) != null) { + if (!getStackInSlot(ingredientSlot1 + i).isEmpty()) { circuitCount++; } } @@ -179,7 +175,7 @@ public class ItemInventorySolderingIron extends ItemInventory implements IErrorS @Override public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (itemStack == null) { + if (itemStack.isEmpty()) { return false; } diff --git a/src/main/java/forestry/core/inventory/filters/StandardStackFilters.java b/src/main/java/forestry/core/inventory/StandardStackFilters.java similarity index 97% rename from src/main/java/forestry/core/inventory/filters/StandardStackFilters.java rename to src/main/java/forestry/core/inventory/StandardStackFilters.java index 8b506cae2..e7459c522 100644 --- a/src/main/java/forestry/core/inventory/filters/StandardStackFilters.java +++ b/src/main/java/forestry/core/inventory/StandardStackFilters.java @@ -8,7 +8,7 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.inventory.filters; +package forestry.core.inventory; import java.util.function.Predicate; diff --git a/src/main/java/forestry/core/inventory/package-info.java b/src/main/java/forestry/core/inventory/package-info.java new file mode 100644 index 000000000..7b9f4e459 --- /dev/null +++ b/src/main/java/forestry/core/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java b/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java index aea0999ce..f1403b1e5 100644 --- a/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/FakeSlotPickupWatcher.java @@ -21,7 +21,7 @@ public class FakeSlotPickupWatcher implements ISlotPickupWatcher { } @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + public void onTake(int slotIndex, EntityPlayer player) { } } diff --git a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java index c8d8650f9..e39fc817c 100644 --- a/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java +++ b/src/main/java/forestry/core/inventory/watchers/ISlotPickupWatcher.java @@ -13,5 +13,5 @@ package forestry.core.inventory.watchers; import net.minecraft.entity.player.EntityPlayer; public interface ISlotPickupWatcher { - void onPickupFromSlot(int slotIndex, EntityPlayer player); + void onTake(int slotIndex, EntityPlayer player); } diff --git a/src/main/java/forestry/core/inventory/watchers/package-info.java b/src/main/java/forestry/core/inventory/watchers/package-info.java new file mode 100644 index 000000000..d9fd35140 --- /dev/null +++ b/src/main/java/forestry/core/inventory/watchers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.inventory.watchers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java b/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java deleted file mode 100755 index 8cc463908..000000000 --- a/src/main/java/forestry/core/inventory/wrappers/ChestWrapper.java +++ /dev/null @@ -1,222 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.inventory.wrappers; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntityChest; -import net.minecraft.util.text.ITextComponent; - -/** - * @author CovertJaguar - */ -public class ChestWrapper implements IInventory { - - /** - * Inventory object corresponding to double chest upper part - */ - private final TileEntityChest upperChest; - /** - * Inventory object corresponding to double chest lower part - */ - private TileEntityChest lowerChest; - - public ChestWrapper(TileEntityChest tile) { - this.upperChest = tile; - checkChest(); - } - - private void checkChest() { - if (lowerChest == null || lowerChest.isInvalid()) { - if (upperChest.adjacentChestXNeg != null) { - lowerChest = upperChest.adjacentChestXNeg; - } else if (upperChest.adjacentChestXPos != null) { - lowerChest = upperChest.adjacentChestXPos; - } else if (upperChest.adjacentChestZNeg != null) { - lowerChest = upperChest.adjacentChestZNeg; - } else if (upperChest.adjacentChestZPos != null) { - lowerChest = upperChest.adjacentChestZPos; - } else { - lowerChest = null; - } - } - } - - /** - * Returns the number of slots in the inventory. - */ - @Override - public int getSizeInventory() { - checkChest(); - int size = upperChest.getSizeInventory(); - if (lowerChest != null) { - size += lowerChest.getSizeInventory(); - } - return size; - } - - /** - * Return whether the given inventory is part of this large chest. - */ - public boolean isPartOfLargeChest(IInventory inv) { - return this.upperChest == inv || this.lowerChest == inv; - } - - /** - * Returns the name of the inventory. - */ - @Override - public String getName() { - return ""; - } - - @Override - public ITextComponent getDisplayName() { - return null; - } - - /** - * If this returns false, the inventory name will be used as an unlocalized - * name, and translated into the player's language. Otherwise it will be - * used directly. - */ - @Override - public boolean hasCustomName() { - return false; - } - - /** - * Returns the stack in slot i - */ - @Override - public ItemStack getStackInSlot(int slot) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.getStackInSlot(slot - upperChest.getSizeInventory()); - } - return upperChest.getStackInSlot(slot); - } - - /** - * Removes from an inventory slot (first arg) up to a specified number - * (second arg) of items and returns them in a new stack. - */ - @Override - public ItemStack decrStackSize(int slot, int amout) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.decrStackSize(slot - upperChest.getSizeInventory(), amout); - } - return upperChest.decrStackSize(slot, amout); - } - - /** - * When some containers are closed they call this on each slot, then drop - * whatever it returns as an EntityItem - like when you close a workbench - * GUI. - */ - @Override - public ItemStack removeStackFromSlot(int slot) { - checkChest(); - if (slot >= upperChest.getSizeInventory() && lowerChest != null) { - return lowerChest.removeStackFromSlot(slot - upperChest.getSizeInventory()); - } - return upperChest.removeStackFromSlot(slot); - } - - /** - * Sets the given item stack to the specified slot in the inventory (can be - * crafting or armor sections). - */ - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - checkChest(); - if (slot >= this.upperChest.getSizeInventory() && lowerChest != null) { - lowerChest.setInventorySlotContents(slot - upperChest.getSizeInventory(), stack); - } else { - upperChest.setInventorySlotContents(slot, stack); - } - } - - /** - * Returns the maximum stack size for a inventory slot. Seems to always be - * 64, possibly will be extended. *Isn't this more of a set than a get?* - */ - @Override - public int getInventoryStackLimit() { - return this.upperChest.getInventoryStackLimit(); - } - - /** - * Called when an the contents of an Inventory change, usually - */ - @Override - public void markDirty() { - this.upperChest.markDirty(); - if (lowerChest != null) { - lowerChest.markDirty(); - } - } - - /** - * Do not make give this method the name canInteractWith because it clashes - * with Container - */ - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return this.upperChest.isUseableByPlayer(player) && (lowerChest == null || lowerChest.isUseableByPlayer(player)); - } - - @Override - public void openInventory(EntityPlayer player) { - this.upperChest.openInventory(player); - if (lowerChest != null) { - lowerChest.openInventory(player); - } - } - - @Override - public void closeInventory(EntityPlayer player) { - this.upperChest.closeInventory(player); - if (lowerChest != null) { - lowerChest.closeInventory(player); - } - } - - /** - * Returns true if automation is allowed to insert the given stack (ignoring - * stack size) into the given slot. - */ - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - return true; - } - - @Override - public int getField(int id) { - return 0; - } - - @Override - public void setField(int id, int value) { - } - - @Override - public int getFieldCount() { - return 0; - } - - @Override - public void clear() { - } - -} \ No newline at end of file diff --git a/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java b/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java index 72a758298..daeaf2faf 100644 --- a/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java +++ b/src/main/java/forestry/core/inventory/wrappers/InvWrapperBase.java @@ -82,8 +82,8 @@ public abstract class InvWrapperBase implements IInventory { } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return inv.isUseableByPlayer(entityplayer); + public boolean isUsableByPlayer(EntityPlayer entityplayer) { + return inv.isUsableByPlayer(entityplayer); } @Override diff --git a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java index a975315d0..6fc160899 100755 --- a/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/InventoryMapper.java @@ -54,6 +54,11 @@ public class InventoryMapper extends InvWrapperBase implements IInventory { this.size = size; } + @Override + public boolean isEmpty() { + return inv.isEmpty(); + } + @Override public int getSizeInventory() { return size; diff --git a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java index 4acab568c..6bddb27b3 100755 --- a/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java +++ b/src/main/java/forestry/core/inventory/wrappers/SidedInventoryMapper.java @@ -35,6 +35,17 @@ public class SidedInventoryMapper extends InvWrapperBase implements ISidedInvent this.side = side; } + @Override + public boolean isEmpty() { + int[] slotsForFace = inv.getSlotsForFace(side); + for (int slot : slotsForFace) { + if (!inv.getStackInSlot(slot).isEmpty()) { + return false; + } + } + return true; + } + @Override public int[] getSlotsForFace(EnumFacing side) { return inv.getSlotsForFace(side); diff --git a/src/main/java/forestry/core/inventory/wrappers/package-info.java b/src/main/java/forestry/core/inventory/wrappers/package-info.java new file mode 100644 index 000000000..700dda1b6 --- /dev/null +++ b/src/main/java/forestry/core/inventory/wrappers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.inventory.wrappers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/items/FluidHandlerItemForestry.java b/src/main/java/forestry/core/items/FluidHandlerItemForestry.java index a0344c6d2..693003c76 100644 --- a/src/main/java/forestry/core/items/FluidHandlerItemForestry.java +++ b/src/main/java/forestry/core/items/FluidHandlerItemForestry.java @@ -15,10 +15,6 @@ public class FluidHandlerItemForestry extends FluidHandlerItemStackSimple.Consum } private boolean contentsAllowed(FluidStack fluidStack) { - if (fluidStack == null) { - return false; - } - Fluid fluid = fluidStack.getFluid(); if (fluid == null) { return false; diff --git a/src/main/java/forestry/core/items/ItemAlyzer.java b/src/main/java/forestry/core/items/ItemAlyzer.java index a4d66cc50..c1e6a0833 100644 --- a/src/main/java/forestry/core/items/ItemAlyzer.java +++ b/src/main/java/forestry/core/items/ItemAlyzer.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.items; -import javax.annotation.Nonnull; - import forestry.api.core.Tabs; import forestry.core.gui.ContainerAlyzer; import forestry.core.gui.GuiAlyzer; @@ -23,19 +21,19 @@ public class ItemAlyzer extends ItemWithGui { public ItemAlyzer() { setCreativeTab(Tabs.tabApiculture); } - + @Override public void openGui(EntityPlayer entityplayer) { super.openGui(entityplayer); } @Override - public Object getGui(@Nonnull EntityPlayer player, ItemStack heldItem, int data) { + public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { return new GuiAlyzer(player, new ItemInventoryAlyzer(player, heldItem)); } @Override - public Object getContainer(@Nonnull EntityPlayer player, ItemStack heldItem, int data) { + public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { return new ContainerAlyzer(new ItemInventoryAlyzer(player, heldItem), player); } } diff --git a/src/main/java/forestry/core/items/ItemArmorNaturalist.java b/src/main/java/forestry/core/items/ItemArmorNaturalist.java index 03a077013..e8c0c4946 100755 --- a/src/main/java/forestry/core/items/ItemArmorNaturalist.java +++ b/src/main/java/forestry/core/items/ItemArmorNaturalist.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.items; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.api.arboriculture.ArboricultureCapabilities; @@ -38,7 +37,6 @@ public class ItemArmorNaturalist extends ItemArmor implements IItemModelRegister setCreativeTab(CreativeTabForestry.tabForestry); } - @Nonnull @Override public String getArmorTexture(ItemStack stack, Entity entity, EntityEquipmentSlot slot, String type) { return Constants.MOD_ID + ":" + Constants.TEXTURE_NATURALIST_ARMOR_PRIMARY; @@ -55,9 +53,8 @@ public class ItemArmorNaturalist extends ItemArmor implements IItemModelRegister return false; } - @Nonnull @Override - public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) { + public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return new ICapabilityProvider() { @Override public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { diff --git a/src/main/java/forestry/core/items/ItemAssemblyKit.java b/src/main/java/forestry/core/items/ItemAssemblyKit.java index 2ad433038..b870464e5 100755 --- a/src/main/java/forestry/core/items/ItemAssemblyKit.java +++ b/src/main/java/forestry/core/items/ItemAssemblyKit.java @@ -27,12 +27,13 @@ public class ItemAssemblyKit extends ItemForestry { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + ItemStack heldItem = playerIn.getHeldItem(handIn); if (!worldIn.isRemote) { - itemStackIn.stackSize--; + heldItem.shrink(1); EntityItem entity = new EntityItem(worldIn, playerIn.posX, playerIn.posY, playerIn.posZ, assembled.copy()); - worldIn.spawnEntityInWorld(entity); + worldIn.spawnEntity(entity); } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, heldItem); } } diff --git a/src/main/java/forestry/core/items/ItemBlockForestry.java b/src/main/java/forestry/core/items/ItemBlockForestry.java index 1572b7263..aa87afe96 100644 --- a/src/main/java/forestry/core/items/ItemBlockForestry.java +++ b/src/main/java/forestry/core/items/ItemBlockForestry.java @@ -68,7 +68,7 @@ public class ItemBlockForestry extends ItemBlock { if (placed) { if (block.hasTileEntity(newState)) { - if (stack.getItem() instanceof ItemBlockNBT && stack.hasTagCompound()) { + if (stack.getItem() instanceof ItemBlockNBT && stack.getTagCompound() != null) { TileForestry tile = TileUtil.getTile(world, pos, TileForestry.class); if (tile != null) { tile.readFromNBT(stack.getTagCompound()); diff --git a/src/main/java/forestry/core/items/ItemBlockNBT.java b/src/main/java/forestry/core/items/ItemBlockNBT.java index 501e1fd2e..0c8500a05 100644 --- a/src/main/java/forestry/core/items/ItemBlockNBT.java +++ b/src/main/java/forestry/core/items/ItemBlockNBT.java @@ -26,7 +26,7 @@ public class ItemBlockNBT extends ItemBlockForestry { public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean advanced) { super.addInformation(itemstack, player, info, advanced); - if (itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() != null) { info.add("There are still some scribbles on this."); } } diff --git a/src/main/java/forestry/core/items/ItemCamouflageSprayCan.java b/src/main/java/forestry/core/items/ItemCamouflageSprayCan.java index 87d00367b..5949da849 100644 --- a/src/main/java/forestry/core/items/ItemCamouflageSprayCan.java +++ b/src/main/java/forestry/core/items/ItemCamouflageSprayCan.java @@ -20,7 +20,7 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ItemCamouflageSprayCan extends ItemWithGui { - + @Override public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { return new GuiCamouflageSprayCan(player, new ItemInventoryCamouflageSprayCan(player, heldItem)); @@ -30,24 +30,25 @@ public class ItemCamouflageSprayCan extends ItemWithGui { public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { return new ContainerCamouflageSprayCan(new ItemInventoryCamouflageSprayCan(player, heldItem), player.inventory); } - + @Override public void registerModel(Item item, IModelManager manager) { super.registerModel(item, manager); ModelBakery.registerItemVariants(item, new ResourceLocation("forestry:camouflageSprayCanFilled")); } - + @Override - public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { - ItemInventoryCamouflageSprayCan inventory = new ItemInventoryCamouflageSprayCan(player, stack); + public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { + ItemStack heldItem = player.getHeldItem(hand); + ItemInventoryCamouflageSprayCan inventory = new ItemInventoryCamouflageSprayCan(player, heldItem); ItemStack camouflage = inventory.getStackInSlot(0); - if(camouflage != null){ + if (!camouflage.isEmpty()) { TileEntity tile = world.getTileEntity(pos); - if(tile instanceof ICamouflageHandler){ + if (tile instanceof ICamouflageHandler) { ICamouflageHandler handler = (ICamouflageHandler) tile; String type = CamouflageManager.camouflageAccess.getHandlerFromItem(camouflage).getType(); - if(type != null && handler.canHandleType(type)){ - if(world.isRemote){ + if (handler.canHandleType(type)) { + if (world.isRemote) { handler.setCamouflageBlock(type, camouflage, false); } return EnumActionResult.SUCCESS; @@ -56,14 +57,15 @@ public class ItemCamouflageSprayCan extends ItemWithGui { } return EnumActionResult.PASS; } - + @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { if (!worldIn.isRemote && playerIn.isSneaking()) { openGui(playerIn); } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + ItemStack heldItem = playerIn.getHeldItem(handIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, heldItem); } } diff --git a/src/main/java/forestry/core/items/ItemCraftingMaterial.java b/src/main/java/forestry/core/items/ItemCraftingMaterial.java index 970fdc0fb..3095477de 100644 --- a/src/main/java/forestry/core/items/ItemCraftingMaterial.java +++ b/src/main/java/forestry/core/items/ItemCraftingMaterial.java @@ -10,20 +10,17 @@ ******************************************************************************/ package forestry.core.items; -import java.util.List; - +import forestry.api.core.IModelManager; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - +import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; - public class ItemCraftingMaterial extends ItemForestry { - private final String[] definition = new String[]{"pulsatingDust", "pulsatingMesh", "silkWisp", "wovenSilk", "dissipationCharge", "iceShard", "scentedPaneling", "camouflagedPaneling" }; + private final String[] definition = new String[]{"pulsatingDust", "pulsatingMesh", "silkWisp", "wovenSilk", "dissipationCharge", "iceShard", "scentedPaneling", "camouflagedPaneling"}; public ItemCraftingMaterial() { setMaxDamage(0); @@ -59,9 +56,9 @@ public class ItemCraftingMaterial extends ItemForestry { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < definition.length; i++) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } @@ -92,11 +89,11 @@ public class ItemCraftingMaterial extends ItemForestry { public ItemStack getScentedPaneling() { return new ItemStack(this, 1, 6); } - + public ItemStack getCamouflagedPaneling() { return getCamouflagedPaneling(1); } - + public ItemStack getCamouflagedPaneling(int stackSize) { return new ItemStack(this, stackSize, 7); } diff --git a/src/main/java/forestry/core/items/ItemCrated.java b/src/main/java/forestry/core/items/ItemCrated.java index 63e56defd..6915e692a 100755 --- a/src/main/java/forestry/core/items/ItemCrated.java +++ b/src/main/java/forestry/core/items/ItemCrated.java @@ -12,6 +12,10 @@ package forestry.core.items; import javax.annotation.Nullable; +import forestry.api.core.IModelManager; +import forestry.core.proxy.Proxies; +import forestry.core.utils.ItemStackUtil; +import forestry.core.utils.Translator; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.color.ItemColors; @@ -22,28 +26,20 @@ import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; - import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; -import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.Translator; - public class ItemCrated extends ItemForestry implements IColoredItem { - @Nullable private final ItemStack contained; @Nullable private final String oreDictName; - public ItemCrated(@Nullable ItemStack contained, @Nullable String oreDictName) { + public ItemCrated(ItemStack contained, @Nullable String oreDictName) { this.contained = contained; this.oreDictName = oreDictName; } - @Nullable public ItemStack getContained() { return contained; } @@ -54,24 +50,25 @@ public class ItemCrated extends ItemForestry implements IColoredItem { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + ItemStack heldItem = playerIn.getHeldItem(handIn); if (!worldIn.isRemote) { - if (contained == null || itemStackIn.stackSize == 0) { - return ActionResult.newResult(EnumActionResult.PASS, itemStackIn); + if (contained.isEmpty() || heldItem.isEmpty()) { + return ActionResult.newResult(EnumActionResult.PASS, heldItem); } - itemStackIn.stackSize--; + heldItem.shrink(1); ItemStack dropStack = contained.copy(); - dropStack.stackSize = 9; + dropStack.setCount(9); ItemStackUtil.dropItemStackAsEntity(dropStack, worldIn, playerIn.posX, playerIn.posY, playerIn.posZ, 40); } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, heldItem); } @Override public String getItemStackDisplayName(ItemStack itemstack) { - if (contained == null) { + if (contained.isEmpty()) { return Translator.translateToLocal("item.for.crate.name"); } else { String containedName = Proxies.common.getDisplayName(contained); @@ -82,7 +79,7 @@ public class ItemCrated extends ItemForestry implements IColoredItem { @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { - if (contained == null) { + if (contained.isEmpty()) { manager.registerItemModel(item, 0); manager.registerItemModel(item, 1, "crate-filled"); } else { @@ -95,11 +92,11 @@ public class ItemCrated extends ItemForestry implements IColoredItem { @Override public int getColorFromItemstack(ItemStack stack, int renderPass) { ItemColors colors = Proxies.common.getClientInstance().getItemColors(); - if (getContained() == null || renderPass == 100) { + if (contained.isEmpty() || renderPass == 100) { return -1; } int color = colors.getColorFromItemstack(contained, renderPass); - if(color != -1){ + if (color != -1) { return color; } return -1; diff --git a/src/main/java/forestry/core/items/ItemElectronTube.java b/src/main/java/forestry/core/items/ItemElectronTube.java index 5a23b6984..92ef9e75b 100644 --- a/src/main/java/forestry/core/items/ItemElectronTube.java +++ b/src/main/java/forestry/core/items/ItemElectronTube.java @@ -27,6 +27,7 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.TextFormatting; public class ItemElectronTube extends ItemOverlay { @@ -57,12 +58,12 @@ public class ItemElectronTube extends ItemOverlay { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < overlays.length; i++) { if (Config.isDebug || !overlays[i].isSecret()) { ItemStack itemStack = new ItemStack(this, 1, i); if (Config.isDebug || !getCircuits(itemStack).isEmpty()) { - itemList.add(itemStack); + subItems.add(itemStack); } } } diff --git a/src/main/java/forestry/core/items/ItemFertilizer.java b/src/main/java/forestry/core/items/ItemFertilizer.java index 1883ef06f..b98f9b9d8 100644 --- a/src/main/java/forestry/core/items/ItemFertilizer.java +++ b/src/main/java/forestry/core/items/ItemFertilizer.java @@ -22,12 +22,13 @@ import net.minecraft.world.World; public class ItemFertilizer extends ItemForestry { @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { - if (!playerIn.canPlayerEdit(pos.offset(facing), facing, stack)) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + ItemStack heldItem = player.getHeldItem(hand); + if (!player.canPlayerEdit(pos.offset(facing), facing, heldItem)) { return EnumActionResult.FAIL; } - if (ItemDye.applyBonemeal(stack, worldIn, pos, playerIn)) { + if (ItemDye.applyBonemeal(heldItem, worldIn, pos, player)) { if (!worldIn.isRemote) { worldIn.playEvent(2005, pos, 0); } diff --git a/src/main/java/forestry/core/items/ItemFluidContainerForestry.java b/src/main/java/forestry/core/items/ItemFluidContainerForestry.java index 8f83ba0cf..6f673218c 100644 --- a/src/main/java/forestry/core/items/ItemFluidContainerForestry.java +++ b/src/main/java/forestry/core/items/ItemFluidContainerForestry.java @@ -10,9 +10,14 @@ ******************************************************************************/ package forestry.core.items; -import java.util.List; +import javax.annotation.Nullable; import java.util.Locale; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; +import forestry.core.config.Constants; +import forestry.core.fluids.Fluids; +import forestry.core.utils.Translator; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; @@ -27,25 +32,20 @@ import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.FoodStats; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; - import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; -import forestry.core.config.Constants; -import forestry.core.fluids.Fluids; -import forestry.core.utils.Translator; - public class ItemFluidContainerForestry extends ItemForestry { private final EnumContainerType type; @@ -65,16 +65,17 @@ public class ItemFluidContainerForestry extends ItemForestry { @SideOnly(Side.CLIENT) @Override - public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { // empty - subItems.add(new ItemStack(itemIn)); + subItems.add(new ItemStack(item)); // filled for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { - ItemStack itemStack = new ItemStack(itemIn); - IFluidHandler fluidHandler = new FluidHandlerItemForestry(itemStack, type); + ItemStack itemStack = new ItemStack(item); + IFluidHandlerItem fluidHandler = new FluidHandlerItemForestry(itemStack, type); if (fluidHandler.fill(new FluidStack(fluid, Fluid.BUCKET_VOLUME), true) == Fluid.BUCKET_VOLUME) { - subItems.add(itemStack); + ItemStack filled = fluidHandler.getContainer(); + subItems.add(filled); } } } @@ -83,10 +84,11 @@ public class ItemFluidContainerForestry extends ItemForestry { return type; } + @Nullable protected FluidStack getContained(ItemStack itemStack) { - if (itemStack.stackSize != 1) { + if (itemStack.getCount() != 1) { itemStack = itemStack.copy(); - itemStack.stackSize = 1; + itemStack.setCount(1); } IFluidHandler fluidHandler = new FluidHandlerItemForestry(itemStack, type); return fluidHandler.drain(Integer.MAX_VALUE, false); @@ -113,7 +115,9 @@ public class ItemFluidContainerForestry extends ItemForestry { return super.getItemStackDisplayName(stack); } - /** DRINKS */ + /** + * DRINKS + */ @Override public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityLivingBase entityLiving) { DrinkProperties drinkProperties = getDrinkProperties(stack); @@ -121,7 +125,7 @@ public class ItemFluidContainerForestry extends ItemForestry { if (entityLiving instanceof EntityPlayer && !((EntityPlayer) entityLiving).capabilities.isCreativeMode) { EntityPlayer player = (EntityPlayer) entityLiving; if (!player.capabilities.isCreativeMode) { - --stack.stackSize; + stack.shrink(1); } if (!worldIn.isRemote) { @@ -136,6 +140,7 @@ public class ItemFluidContainerForestry extends ItemForestry { return stack; } + @Nullable protected DrinkProperties getDrinkProperties(ItemStack itemStack) { FluidStack contained = getContained(itemStack); if (contained != null) { @@ -168,23 +173,23 @@ public class ItemFluidContainerForestry extends ItemForestry { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { - DrinkProperties drinkProperties = getDrinkProperties(itemStackIn); + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + ItemStack heldItem = playerIn.getHeldItem(handIn); + DrinkProperties drinkProperties = getDrinkProperties(heldItem); if (drinkProperties != null) { if (playerIn.canEat(false)) { - playerIn.setActiveHand(hand); - return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); + playerIn.setActiveHand(handIn); + return new ActionResult<>(EnumActionResult.SUCCESS, heldItem); } else { - return new ActionResult<>(EnumActionResult.FAIL, itemStackIn); + return new ActionResult<>(EnumActionResult.FAIL, heldItem); } } else { - return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand); + return super.onItemRightClick(worldIn, playerIn, handIn); } } @Override - public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) - { + public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { return new FluidHandlerItemForestry(stack, type); } } diff --git a/src/main/java/forestry/core/items/ItemForestryFood.java b/src/main/java/forestry/core/items/ItemForestryFood.java index 9c5509a40..9e2c659be 100755 --- a/src/main/java/forestry/core/items/ItemForestryFood.java +++ b/src/main/java/forestry/core/items/ItemForestryFood.java @@ -10,18 +10,16 @@ ******************************************************************************/ package forestry.core.items; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.core.CreativeTabForestry; import net.minecraft.item.EnumAction; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.core.CreativeTabForestry; - public class ItemForestryFood extends ItemFood implements IItemModelRegister { private boolean isDrink = false; diff --git a/src/main/java/forestry/core/items/ItemForestryTool.java b/src/main/java/forestry/core/items/ItemForestryTool.java index cd1930921..32719d0e0 100755 --- a/src/main/java/forestry/core/items/ItemForestryTool.java +++ b/src/main/java/forestry/core/items/ItemForestryTool.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.items; +import forestry.core.PluginCore; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -24,12 +26,9 @@ import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import forestry.core.PluginCore; -import forestry.core.utils.ItemStackUtil; public class ItemForestryTool extends ItemForestry { private final ItemStack remnants; @@ -40,7 +39,7 @@ public class ItemForestryTool extends ItemForestry { efficiencyOnProperMaterial = 6F; setMaxDamage(200); this.remnants = remnants; - if (remnants != null) { + if (!remnants.isEmpty()) { MinecraftForge.EVENT_BUS.register(this); } } @@ -48,12 +47,12 @@ public class ItemForestryTool extends ItemForestry { public void setEfficiencyOnProperMaterial(float efficiencyOnProperMaterial) { this.efficiencyOnProperMaterial = efficiencyOnProperMaterial; } - + @Override public boolean canHarvestBlock(IBlockState block) { - if(this == PluginCore.items.bronzePickaxe){ - Material material = block.getMaterial(); - return material == Material.ROCK ? true : (material == Material.IRON ? true : material == Material.ANVIL); + if (this == PluginCore.items.bronzePickaxe) { + Material material = block.getMaterial(); + return material == Material.ROCK || material == Material.IRON || material == Material.ANVIL; } return super.canHarvestBlock(block); } @@ -65,50 +64,51 @@ public class ItemForestryTool extends ItemForestry { return efficiencyOnProperMaterial; } } - if(this == PluginCore.items.bronzePickaxe){ - Material material = state.getMaterial(); - return material != Material.IRON && material != Material.ANVIL && material != Material.ROCK ? super.getStrVsBlock(itemstack, state) : this.efficiencyOnProperMaterial; + if (this == PluginCore.items.bronzePickaxe) { + Material material = state.getMaterial(); + return material != Material.IRON && material != Material.ANVIL && material != Material.ROCK ? super.getStrVsBlock(itemstack, state) : this.efficiencyOnProperMaterial; } return super.getStrVsBlock(itemstack, state); } - + @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ){ - if(this == PluginCore.items.bronzeShovel){ - if (!playerIn.canPlayerEdit(pos.offset(facing), facing, stack)){ - return EnumActionResult.FAIL; - }else{ - IBlockState iblockstate = worldIn.getBlockState(pos); - Block block = iblockstate.getBlock(); - - if (facing != EnumFacing.DOWN && worldIn.getBlockState(pos.up()).getMaterial() == Material.AIR && block == Blocks.GRASS){ - IBlockState iblockstate1 = Blocks.GRASS_PATH.getDefaultState(); - worldIn.playSound(playerIn, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS, 1.0F, 1.0F); - - if (!worldIn.isRemote){ - worldIn.setBlockState(pos, iblockstate1, 11); - stack.damageItem(1, playerIn); - } - - return EnumActionResult.SUCCESS; - }else{ - return EnumActionResult.PASS; - } - } - } - return EnumActionResult.PASS; - } + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + if (this == PluginCore.items.bronzeShovel) { + ItemStack heldItem = player.getHeldItem(hand); + if (!player.canPlayerEdit(pos.offset(facing), facing, heldItem)) { + return EnumActionResult.FAIL; + } else { + IBlockState iblockstate = worldIn.getBlockState(pos); + Block block = iblockstate.getBlock(); + + if (facing != EnumFacing.DOWN && worldIn.getBlockState(pos.up()).getMaterial() == Material.AIR && block == Blocks.GRASS) { + IBlockState iblockstate1 = Blocks.GRASS_PATH.getDefaultState(); + worldIn.playSound(player, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS, 1.0F, 1.0F); + + if (!worldIn.isRemote) { + worldIn.setBlockState(pos, iblockstate1, 11); + heldItem.damageItem(1, player); + } + + return EnumActionResult.SUCCESS; + } else { + return EnumActionResult.PASS; + } + } + } + return EnumActionResult.PASS; + } @SubscribeEvent public void onDestroyCurrentItem(PlayerDestroyItemEvent event) { - if (event.getOriginal() == null || event.getOriginal().getItem() != this) { + if (event.getOriginal().isEmpty() || event.getOriginal().getItem() != this) { return; } EntityPlayer player = event.getEntityPlayer(); - World world = player.worldObj; + World world = player.world; - if (!world.isRemote && remnants != null) { + if (!world.isRemote && !remnants.isEmpty()) { ItemStackUtil.dropItemStackAsEntity(remnants.copy(), world, player.posX, player.posY, player.posZ); } } diff --git a/src/main/java/forestry/core/items/ItemFruit.java b/src/main/java/forestry/core/items/ItemFruit.java index 5e903f14a..a3842bec4 100755 --- a/src/main/java/forestry/core/items/ItemFruit.java +++ b/src/main/java/forestry/core/items/ItemFruit.java @@ -10,19 +10,17 @@ ******************************************************************************/ package forestry.core.items; -import java.util.List; import java.util.Locale; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.core.IModelManager; import forestry.core.PluginCore; import forestry.core.utils.OreDictUtil; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class ItemFruit extends ItemForestryFood { @@ -87,16 +85,16 @@ public class ItemFruit extends ItemForestryFood { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < EnumFruit.values().length; i++) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } @Override public String getUnlocalizedName(ItemStack stack) { if (stack.getItemDamage() < 0 || stack.getItemDamage() >= EnumFruit.VALUES.length) { - return null; + return super.getUnlocalizedName(stack); } return super.getUnlocalizedName(stack) + "." + EnumFruit.VALUES[stack.getItemDamage()].name().toLowerCase(Locale.ENGLISH); diff --git a/src/main/java/forestry/core/items/ItemOverlay.java b/src/main/java/forestry/core/items/ItemOverlay.java index eb7dfa05b..15d896979 100755 --- a/src/main/java/forestry/core/items/ItemOverlay.java +++ b/src/main/java/forestry/core/items/ItemOverlay.java @@ -10,18 +10,15 @@ ******************************************************************************/ package forestry.core.items; -import java.util.List; - +import forestry.api.core.IModelManager; +import forestry.core.config.Config; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - +import net.minecraft.util.NonNullList; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; -import forestry.core.config.Config; - public class ItemOverlay extends ItemForestry implements IColoredItem { public interface IOverlayInfo { @@ -55,14 +52,14 @@ public class ItemOverlay extends ItemForestry implements IColoredItem { } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < overlays.length; i++) { if (Config.isDebug || !overlays[i].isSecret()) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } } - + /* Models */ @SideOnly(Side.CLIENT) @Override @@ -75,7 +72,7 @@ public class ItemOverlay extends ItemForestry implements IColoredItem { @Override public String getUnlocalizedName(ItemStack stack) { if (stack.getItemDamage() < 0 || stack.getItemDamage() >= overlays.length) { - return null; + return super.getUnlocalizedName(stack); } return super.getUnlocalizedName(stack) + "." + overlays[stack.getItemDamage()].getUid(); diff --git a/src/main/java/forestry/core/items/ItemPipette.java b/src/main/java/forestry/core/items/ItemPipette.java index 52fac6f42..5c50e3bf5 100755 --- a/src/main/java/forestry/core/items/ItemPipette.java +++ b/src/main/java/forestry/core/items/ItemPipette.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.items; +import javax.annotation.Nullable; import java.util.List; import forestry.api.core.IModelManager; @@ -23,13 +24,16 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; +import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidContainerItem; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.fluids.capability.templates.FluidHandlerItemStackSimple; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -public class ItemPipette extends ItemForestry implements IToolPipette, IFluidContainerItem { +public class ItemPipette extends ItemForestry implements IToolPipette { + @SideOnly(Side.CLIENT) + public ModelResourceLocation[] models; public ItemPipette() { setMaxStackSize(1); @@ -42,50 +46,6 @@ public class ItemPipette extends ItemForestry implements IToolPipette, IFluidCon return contained == null || !contained.isFull(); } - @Override - public int fill(ItemStack itemstack, FluidStack liquid, boolean doFill) { - PipetteContents contained = PipetteContents.create(itemstack); - - int limit = getCapacity(itemstack); - int filled; - - if (contained == null) { - if (liquid.amount > limit) { - filled = limit; - } else { - filled = liquid.amount; - } - - contained = new PipetteContents(new FluidStack(liquid, filled)); - } else { - if (contained.getContents().amount >= limit) { - return 0; - } - if (!contained.getContents().isFluidEqual(liquid)) { - return 0; - } - - int space = limit - contained.getContents().amount; - - if (liquid.amount > space) { - filled = space; - } else { - filled = liquid.amount; - } - - contained.getContents().amount += filled; - } - - if (doFill) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - contained.writeToNBT(nbttagcompound); - itemstack.setTagCompound(nbttagcompound); - itemstack.setItemDamage(1); - } - - return filled; - } - @Override public void addInformation(ItemStack itemstack, EntityPlayer player, List list, boolean flag) { super.addInformation(itemstack, player, list, flag); @@ -97,8 +57,6 @@ public class ItemPipette extends ItemForestry implements IToolPipette, IFluidCon } /* Models */ - @SideOnly(Side.CLIENT) - public ModelResourceLocation[] models; @SideOnly(Side.CLIENT) @Override @@ -112,57 +70,18 @@ public class ItemPipette extends ItemForestry implements IToolPipette, IFluidCon } public class PipetteMeshDefinition implements ItemMeshDefinition { - @Override public ModelResourceLocation getModelLocation(ItemStack stack) { - if (stack.getItemDamage() <= 0) { + if (FluidUtil.getFluidContained(stack) == null) { return models[0]; } else { return models[1]; } } - } @Override - public FluidStack drain(ItemStack pipette, int maxDrain, boolean doDrain) { - PipetteContents contained = PipetteContents.create(pipette); - if (contained == null) { - return null; - } - - int drained = maxDrain; - if (contained.getContents().amount < drained) { - drained = contained.getContents().amount; - } - - if (doDrain) { - contained.getContents().amount -= drained; - - if (contained.getContents().amount <= 0) { - pipette.setTagCompound(new NBTTagCompound()); - pipette.setItemDamage(0); - } else { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - contained.writeToNBT(nbttagcompound); - pipette.setTagCompound(nbttagcompound); - } - } - - return new FluidStack(contained.getContents(), drained); - } - - @Override - public FluidStack getFluid(ItemStack container) { - PipetteContents contained = PipetteContents.create(container); - if (contained == null) { - return null; - } - return contained.getContents(); - } - - @Override - public int getCapacity(ItemStack pipette) { - return Fluid.BUCKET_VOLUME; + public ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { + return new FluidHandlerItemStackSimple(stack, Fluid.BUCKET_VOLUME); } } diff --git a/src/main/java/forestry/core/items/ItemRegistry.java b/src/main/java/forestry/core/items/ItemRegistry.java index 062f32f71..556d70b94 100644 --- a/src/main/java/forestry/core/items/ItemRegistry.java +++ b/src/main/java/forestry/core/items/ItemRegistry.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.items; -import javax.annotation.Nonnull; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; @@ -38,11 +36,9 @@ public abstract class ItemRegistry { OreDictionary.registerOre(oreDictName, itemStack); } - @Nonnull public static ItemStack createItemForOreName(String oreName) { ItemStack oreItem = new ItemStack(registerItem(new ItemForestry(), oreName)); OreDictionary.registerOre(oreName, oreItem); return oreItem; } - } diff --git a/src/main/java/forestry/core/items/ItemRegistryFluids.java b/src/main/java/forestry/core/items/ItemRegistryFluids.java index 4eb6a4f23..0c09c5633 100644 --- a/src/main/java/forestry/core/items/ItemRegistryFluids.java +++ b/src/main/java/forestry/core/items/ItemRegistryFluids.java @@ -36,8 +36,12 @@ public class ItemRegistryFluids extends ItemRegistry { public ItemStack getContainer(EnumContainerType type, Fluid fluid) { ItemStack container = new ItemStack(containers.get(type)); IFluidHandler fluidHandler = FluidUtil.getFluidHandler(container); - fluidHandler.fill(new FluidStack(fluid, Integer.MAX_VALUE), true); - return container; + if (fluidHandler != null) { + fluidHandler.fill(new FluidStack(fluid, Integer.MAX_VALUE), true); + return container; + } else { + return ItemStack.EMPTY; + } } public ItemRegistryFluids() { diff --git a/src/main/java/forestry/core/items/ItemScoop.java b/src/main/java/forestry/core/items/ItemScoop.java index 092eeae60..c530c09bc 100755 --- a/src/main/java/forestry/core/items/ItemScoop.java +++ b/src/main/java/forestry/core/items/ItemScoop.java @@ -12,10 +12,11 @@ package forestry.core.items; import forestry.api.core.IToolScoop; import forestry.api.core.Tabs; +import net.minecraft.item.ItemStack; public class ItemScoop extends ItemForestryTool implements IToolScoop { public ItemScoop() { - super(null); + super(ItemStack.EMPTY); setEfficiencyOnProperMaterial(2.0f); setMaxDamage(10); setCreativeTab(Tabs.tabApiculture); diff --git a/src/main/java/forestry/core/items/ItemWithGui.java b/src/main/java/forestry/core/items/ItemWithGui.java index ba22dd57a..cb96cd687 100644 --- a/src/main/java/forestry/core/items/ItemWithGui.java +++ b/src/main/java/forestry/core/items/ItemWithGui.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.core.items; +import forestry.core.gui.ContainerItemInventory; +import forestry.core.gui.GuiHandler; +import forestry.core.gui.IGuiHandlerItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; @@ -18,22 +21,19 @@ import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.world.World; -import forestry.core.gui.ContainerItemInventory; -import forestry.core.gui.GuiHandler; -import forestry.core.gui.IGuiHandlerItem; - public abstract class ItemWithGui extends ItemForestry implements IGuiHandlerItem { public ItemWithGui() { setMaxStackSize(1); } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { if (!worldIn.isRemote) { openGui(playerIn); } - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + ItemStack stack = playerIn.getHeldItem(handIn); + return ActionResult.newResult(EnumActionResult.SUCCESS, stack); } protected void openGui(EntityPlayer entityplayer) { diff --git a/src/main/java/forestry/core/items/ItemWrench.java b/src/main/java/forestry/core/items/ItemWrench.java index 61cfa8d6a..d3bb05a75 100755 --- a/src/main/java/forestry/core/items/ItemWrench.java +++ b/src/main/java/forestry/core/items/ItemWrench.java @@ -12,7 +12,6 @@ package forestry.core.items; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; @@ -27,10 +26,10 @@ public class ItemWrench extends ItemForestry {//implements IToolWrench { } @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { Block block = worldIn.getBlockState(pos).getBlock(); if (block.rotateBlock(worldIn, pos, facing)) { - playerIn.swingArm(hand); + player.swingArm(hand); return EnumActionResult.SUCCESS; } return EnumActionResult.FAIL; diff --git a/src/main/java/forestry/core/items/package-info.java b/src/main/java/forestry/core/items/package-info.java new file mode 100644 index 000000000..595824e8d --- /dev/null +++ b/src/main/java/forestry/core/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/loot/LootTableLoader.java b/src/main/java/forestry/core/loot/LootTableLoader.java index 8cd4c72c8..609f6a1c7 100644 --- a/src/main/java/forestry/core/loot/LootTableLoader.java +++ b/src/main/java/forestry/core/loot/LootTableLoader.java @@ -1,5 +1,7 @@ package forestry.core.loot; +import javax.annotation.Nullable; + import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.google.gson.Gson; @@ -31,6 +33,7 @@ import forestry.core.utils.Log; public class LootTableLoader { private static final Gson GSON_INSTANCE = (new GsonBuilder()).registerTypeAdapter(RandomValueRange.class, new RandomValueRange.Serializer()).registerTypeAdapter(LootPool.class, new LootPool.Serializer()).registerTypeAdapter(LootTable.class, new LootTable.Serializer()).registerTypeHierarchyAdapter(LootEntry.class, new LootEntry.Serializer()).registerTypeHierarchyAdapter(LootFunction.class, new LootFunctionManager.Serializer()).registerTypeHierarchyAdapter(LootCondition.class, new LootConditionManager.Serializer()).registerTypeHierarchyAdapter(LootContext.EntityTarget.class, new LootContext.EntityTarget.Serializer()).create(); + @Nullable public static LootTable loadBuiltinLootTable(ResourceLocation resource) { URL url = LootTableLoader.class.getResource("/assets/" + resource.getResourceDomain() + "/loot_tables/" + resource.getResourcePath() + ".json"); diff --git a/src/main/java/forestry/core/loot/functions/SetSpeciesNBT.java b/src/main/java/forestry/core/loot/SetSpeciesNBT.java similarity index 98% rename from src/main/java/forestry/core/loot/functions/SetSpeciesNBT.java rename to src/main/java/forestry/core/loot/SetSpeciesNBT.java index d0c0ecf9d..3a65a0c9a 100644 --- a/src/main/java/forestry/core/loot/functions/SetSpeciesNBT.java +++ b/src/main/java/forestry/core/loot/SetSpeciesNBT.java @@ -1,4 +1,4 @@ -package forestry.core.loot.functions; +package forestry.core.loot; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; diff --git a/src/main/java/forestry/core/loot/package-info.java b/src/main/java/forestry/core/loot/package-info.java new file mode 100644 index 000000000..f02c3afe3 --- /dev/null +++ b/src/main/java/forestry/core/loot/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.loot; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/models/BlankModel.java b/src/main/java/forestry/core/models/BlankModel.java index da50e415a..02724f520 100644 --- a/src/main/java/forestry/core/models/BlankModel.java +++ b/src/main/java/forestry/core/models/BlankModel.java @@ -10,10 +10,12 @@ ******************************************************************************/ package forestry.core.models; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; @@ -25,20 +27,21 @@ import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public abstract class BlankModel implements IBakedModel { + @Nullable protected ItemOverrideList overrideList; - + @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { return Collections.emptyList(); } - - protected ItemOverrideList createOverrides(){ + + protected ItemOverrideList createOverrides() { return ItemOverrideList.NONE; } - + @Override public ItemOverrideList getOverrides() { - if(overrideList == null){ + if (overrideList == null) { overrideList = createOverrides(); } return overrideList; @@ -61,7 +64,7 @@ public abstract class BlankModel implements IBakedModel { @Override public TextureAtlasSprite getParticleTexture() { - return null; + return Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite(); } @Override diff --git a/src/main/java/forestry/core/models/BlockModelEntry.java b/src/main/java/forestry/core/models/BlockModelEntry.java index f99060844..ea235e8ff 100644 --- a/src/main/java/forestry/core/models/BlockModelEntry.java +++ b/src/main/java/forestry/core/models/BlockModelEntry.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.models; +import javax.annotation.Nullable; + import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ModelResourceLocation; @@ -17,6 +19,7 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; public class BlockModelEntry { public final ModelResourceLocation blockModelLocation; + @Nullable public final ModelResourceLocation itemModelLocation; public final IBakedModel model; public final boolean addStateMapper; @@ -26,7 +29,7 @@ public class BlockModelEntry { this(blockModelLocation, itemModelLocation, model, block, true); } - public BlockModelEntry(ModelResourceLocation blockModelLocation, ModelResourceLocation itemModelLocation, IBakedModel model, Block block, boolean addStateMapper) { + public BlockModelEntry(ModelResourceLocation blockModelLocation, @Nullable ModelResourceLocation itemModelLocation, IBakedModel model, Block block, boolean addStateMapper) { this.blockModelLocation = blockModelLocation; this.itemModelLocation = itemModelLocation; this.model = model; diff --git a/src/main/java/forestry/core/models/DefaultTextureGetter.java b/src/main/java/forestry/core/models/DefaultTextureGetter.java index f0fd24aa5..ad7364c99 100644 --- a/src/main/java/forestry/core/models/DefaultTextureGetter.java +++ b/src/main/java/forestry/core/models/DefaultTextureGetter.java @@ -10,8 +10,11 @@ ******************************************************************************/ package forestry.core.models; +import javax.annotation.Nullable; + import com.google.common.base.Function; +import com.google.common.base.Preconditions; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.util.ResourceLocation; @@ -22,7 +25,8 @@ import net.minecraftforge.fml.relauncher.SideOnly; public class DefaultTextureGetter implements Function { @Override - public TextureAtlasSprite apply(ResourceLocation location) { + public TextureAtlasSprite apply(@Nullable ResourceLocation location) { + Preconditions.checkNotNull(location); return Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(location.toString()); } diff --git a/src/main/java/forestry/core/models/ModelBlockCached.java b/src/main/java/forestry/core/models/ModelBlockCached.java index 8bd1cab29..ce4576322 100644 --- a/src/main/java/forestry/core/models/ModelBlockCached.java +++ b/src/main/java/forestry/core/models/ModelBlockCached.java @@ -1,6 +1,5 @@ package forestry.core.models; -import javax.annotation.Nonnull; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -14,59 +13,48 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; public abstract class ModelBlockCached extends ModelBlockDefault { - private static final Set CACHE_PROVIDERS = new HashSet<>(); + private static final Set CACHE_PROVIDERS = new HashSet<>(); - private final Cache inventoryCache; - private final Cache worldCache; + private final Cache inventoryCache; + private final Cache worldCache; - public static void clear() { - for (ModelBlockCached modelBlockCached : CACHE_PROVIDERS) { - modelBlockCached.worldCache.invalidateAll(); - modelBlockCached.inventoryCache.invalidateAll(); - } - } + public static void clear() { + for (ModelBlockCached modelBlockCached : CACHE_PROVIDERS) { + modelBlockCached.worldCache.invalidateAll(); + modelBlockCached.inventoryCache.invalidateAll(); + } + } - protected ModelBlockCached(@Nonnull Class blockClass) { - super(blockClass); + protected ModelBlockCached(Class blockClass) { + super(blockClass); - worldCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); - inventoryCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); + worldCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); + inventoryCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); - CACHE_PROVIDERS.add(this); - } + CACHE_PROVIDERS.add(this); + } - @Override - protected IBakedModel getModel(@Nonnull IBlockState state) { - if(state == null){ - return null; - } - K key = getWorldKey(state); - if (key == null) { - return null; - } + @Override + protected IBakedModel getModel(IBlockState state) { + K key = getWorldKey(state); - IBakedModel model = worldCache.getIfPresent(key); - if (model == null) { - model = bakeModel(state, key); - if (model != null) { - worldCache.put(key, model); - } - } - return model; - } + IBakedModel model = worldCache.getIfPresent(key); + if (model == null) { + model = super.getModel(state); + worldCache.put(key, model); + } + return model; + } - @Override - protected IBakedModel getModel(ItemStack stack, World world) { - K key = getInventoryKey(stack); - if (key == null) { - return null; - } + @Override + protected IBakedModel getModel(ItemStack stack, World world) { + K key = getInventoryKey(stack); - IBakedModel model = inventoryCache.getIfPresent(key); - if (model == null) { - model = bakeModel(stack, world, key); - inventoryCache.put(key, model); - } - return model; - } + IBakedModel model = inventoryCache.getIfPresent(key); + if (model == null) { + model = bakeModel(stack, world, key); + inventoryCache.put(key, model); + } + return model; + } } diff --git a/src/main/java/forestry/core/models/ModelBlockDefault.java b/src/main/java/forestry/core/models/ModelBlockDefault.java index 975e922da..45d617629 100644 --- a/src/main/java/forestry/core/models/ModelBlockDefault.java +++ b/src/main/java/forestry/core/models/ModelBlockDefault.java @@ -10,15 +10,15 @@ ******************************************************************************/ package forestry.core.models; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; +import com.google.common.base.Preconditions; import forestry.api.core.IModelBaker; import forestry.api.core.IModelBakerModel; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.models.baker.ModelBaker; import forestry.core.proxy.Proxies; import net.minecraft.block.Block; @@ -32,37 +32,30 @@ import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.property.IExtendedBlockState; public abstract class ModelBlockDefault implements IBakedModel { + @Nullable private ItemOverrideList overrideList; - @Nonnull + protected final Class blockClass; - + + @Nullable protected IModelBakerModel blockModel; + @Nullable protected IModelBakerModel itemModel; - protected ModelBlockDefault(@Nonnull Class blockClass) { + protected ModelBlockDefault(Class blockClass) { this.blockClass = blockClass; } - @Nullable - protected IBakedModel bakeModel(@Nonnull IBlockState state, @Nonnull K key) { - if (key == null) { - return null; - } - + protected IBakedModel bakeModel(IBlockState state, K key, B block) { IModelBaker baker = new ModelBaker(); - Block block = state.getBlock(); - if (!blockClass.isInstance(block)) { - return null; - } - B bBlock = blockClass.cast(block); - if (state instanceof IExtendedBlockState) { IExtendedBlockState stateExtended = (IExtendedBlockState) state; IBlockAccess world = stateExtended.getValue(UnlistedBlockAccess.BLOCKACCESS); @@ -70,7 +63,7 @@ public abstract class ModelBlockDefault implements IBakedMod baker.setRenderBounds(state.getBoundingBox(world, pos)); } - bakeBlock(bBlock, key, baker, false); + bakeBlock(block, key, baker, false); blockModel = baker.bakeModel(false); onCreateModel(blockModel); @@ -78,86 +71,69 @@ public abstract class ModelBlockDefault implements IBakedMod } protected IBakedModel getModel(IBlockState state) { - return bakeModel(state, getWorldKey(state)); + Preconditions.checkArgument(blockClass.isInstance(state.getBlock())); + + K worldKey = getWorldKey(state); + B block = blockClass.cast(state.getBlock()); + return bakeModel(state, worldKey, block); } protected IBakedModel bakeModel(ItemStack stack, World world, K key) { - if (key == null) { - return null; - } - IModelBaker baker = new ModelBaker(); Block block = Block.getBlockFromItem(stack.getItem()); - if (!blockClass.isInstance(block)) { - return null; - } + Preconditions.checkArgument(blockClass.isInstance(block)); B bBlock = blockClass.cast(block); // FIXME: This way of getting the IBlockState will probably backfire. IBlockState state = block.getStateFromMeta(stack.getItemDamage()); - baker.setRenderBounds(state.getBoundingBox(world, null)); + AxisAlignedBB boundingBox = state.getBoundingBox(world, null); + baker.setRenderBounds(boundingBox); bakeBlock(bBlock, key, baker, true); return itemModel = baker.bakeModel(true); } protected IBakedModel getModel(ItemStack stack, World world) { - if(stack == null){ - return null; - } return bakeModel(stack, world, getInventoryKey(stack)); } - @Nonnull @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { + Preconditions.checkNotNull(state); IBakedModel model = getModel(state); - - if (model != null) { - return model.getQuads(state, side, rand); - } else { - return Collections.emptyList(); - } + return model.getQuads(state, side, rand); } - - protected void onCreateModel(IModelBakerModel model){ + + protected void onCreateModel(IModelBakerModel model) { model.setAmbientOcclusion(true); } @Override public boolean isAmbientOcclusion() { - if(itemModel == null && blockModel == null) { - return false; - } - return blockModel != null ? blockModel.isAmbientOcclusion() : itemModel.isAmbientOcclusion(); + return (itemModel != null || blockModel != null) && + (blockModel != null ? blockModel.isAmbientOcclusion() : itemModel.isAmbientOcclusion()); } @Override public boolean isGui3d() { - if(itemModel == null) { - return false; - } - return itemModel.isGui3d(); + return itemModel != null && itemModel.isGui3d(); } @Override public boolean isBuiltInRenderer() { - if(itemModel == null && blockModel == null) { - return false; - } - return blockModel != null ? blockModel.isBuiltInRenderer() : itemModel.isBuiltInRenderer(); + return (itemModel != null || blockModel != null) && + (blockModel != null ? blockModel.isBuiltInRenderer() : itemModel.isBuiltInRenderer()); } - - @Nonnull + @Override public TextureAtlasSprite getParticleTexture() { - if(blockModel != null) { + if (blockModel != null) { return blockModel.getParticleTexture(); } return Minecraft.getMinecraft().getTextureMapBlocks().getMissingSprite(); } - @Nonnull + @Override public ItemCameraTransforms getItemCameraTransforms() { if (itemModel == null) { @@ -170,7 +146,6 @@ public abstract class ModelBlockDefault implements IBakedMod return new DefaultItemOverrideList(); } - @Nonnull @Override public ItemOverrideList getOverrides() { if (overrideList == null) { @@ -179,19 +154,20 @@ public abstract class ModelBlockDefault implements IBakedMod return overrideList; } - protected abstract K getInventoryKey(@Nonnull ItemStack stack); + protected abstract K getInventoryKey(ItemStack stack); - protected abstract K getWorldKey(@Nonnull IBlockState state); - protected abstract void bakeBlock(@Nonnull B block, @Nonnull K key, @Nonnull IModelBaker baker, boolean inventory); + protected abstract K getWorldKey(IBlockState state); + + protected abstract void bakeBlock(B block, K key, IModelBaker baker, boolean inventory); private class DefaultItemOverrideList extends ItemOverrideList { public DefaultItemOverrideList() { super(Collections.emptyList()); } - + @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { - if(world == null){ + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { + if (world == null) { world = Proxies.common.getRenderWorld(); } return getModel(stack, world); diff --git a/src/main/java/forestry/core/models/ModelCamouflageSprayCan.java b/src/main/java/forestry/core/models/ModelCamouflageSprayCan.java index 863040f31..a8034a00f 100644 --- a/src/main/java/forestry/core/models/ModelCamouflageSprayCan.java +++ b/src/main/java/forestry/core/models/ModelCamouflageSprayCan.java @@ -1,13 +1,11 @@ package forestry.core.models; +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import javax.vecmath.Matrix4f; - -import org.apache.commons.lang3.tuple.Pair; - import forestry.core.inventory.ItemInventoryCamouflageSprayCan; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -27,8 +25,8 @@ import net.minecraftforge.client.model.IPerspectiveAwareModel; import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.model.IModelState; import net.minecraftforge.fml.relauncher.Side; - import net.minecraftforge.fml.relauncher.SideOnly; +import org.apache.commons.lang3.tuple.Pair; @SideOnly(Side.CLIENT) public class ModelCamouflageSprayCan extends BlankModel { @@ -37,55 +35,55 @@ public class ModelCamouflageSprayCan extends BlankModel { protected ItemOverrideList createOverrides() { return new SprayCanOverrideList(); } - - private class SprayCanOverrideList extends ItemOverrideList{ + + private class SprayCanOverrideList extends ItemOverrideList { public SprayCanOverrideList() { super(Collections.emptyList()); } - + @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { IModel basicModel = ModelLoaderRegistry.getModelOrMissing(new ResourceLocation("forestry:item/camouflageSprayCan")); IBakedModel model = basicModel.bake(basicModel.getDefaultState(), DefaultVertexFormats.ITEM, new DefaultTextureGetter()); IBakedModel filledModel = basicModel.bake(basicModel.getDefaultState(), DefaultVertexFormats.ITEM, new DefaultTextureGetter()); IBakedModel camouflageModel = null; - - if(stack.hasTagCompound() && entity instanceof EntityPlayer){ + + if (stack.getTagCompound() != null && entity instanceof EntityPlayer) { ItemInventoryCamouflageSprayCan inventory = new ItemInventoryCamouflageSprayCan((EntityPlayer) entity, stack); ItemStack camouflage = inventory.getStackInSlot(0); - if(camouflage != null){ + if (!camouflage.isEmpty()) { IModel filledBasicModel = ModelLoaderRegistry.getModelOrMissing(new ResourceLocation("forestry:item/camouflageSprayCanFilled")); filledModel = filledBasicModel.bake(filledBasicModel.getDefaultState(), DefaultVertexFormats.ITEM, new DefaultTextureGetter()); - + camouflageModel = new TRSRBakedModel(Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel(camouflage), -0.0625F * 3, 0.0625F * 3, 0.0625F, 0.5F); } - } return new SprayCanModel(model, filledModel, camouflageModel, ModelManager.getInstance().DEFAULT_ITEM); } - + } - - private class SprayCanModel extends BlankModel implements IPerspectiveAwareModel{ - + + private class SprayCanModel extends BlankModel implements IPerspectiveAwareModel { + private final IBakedModel originalModel; + @Nullable private final IBakedModel camouflageModel; private final IModelState state; private final IBakedModel filledModel; - - public SprayCanModel(IBakedModel originalModel, IBakedModel filledModel, IBakedModel camouflageModel, IModelState state) { + + public SprayCanModel(IBakedModel originalModel, IBakedModel filledModel, @Nullable IBakedModel camouflageModel, IModelState state) { this.originalModel = originalModel; this.filledModel = filledModel; this.camouflageModel = camouflageModel; this.state = state; } - + @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { List quads = new ArrayList<>(); quads.addAll(filledModel.getQuads(state, side, rand)); - if(camouflageModel != null){ + if (camouflageModel != null) { quads.addAll(camouflageModel.getQuads(state, side, rand)); } return quads; @@ -93,12 +91,12 @@ public class ModelCamouflageSprayCan extends BlankModel { @Override public Pair handlePerspective(TransformType cameraTransformType) { - if(cameraTransformType == TransformType.GUI){ + if (cameraTransformType == TransformType.GUI) { return IPerspectiveAwareModel.MapWrapper.handlePerspective(this, state, cameraTransformType); } return IPerspectiveAwareModel.MapWrapper.handlePerspective(originalModel, state, cameraTransformType); } - + } - + } diff --git a/src/main/java/forestry/core/models/ModelCrate.java b/src/main/java/forestry/core/models/ModelCrate.java index 29e04366f..acfc5298c 100644 --- a/src/main/java/forestry/core/models/ModelCrate.java +++ b/src/main/java/forestry/core/models/ModelCrate.java @@ -54,9 +54,9 @@ import forestry.storage.PluginStorage; @SideOnly(Side.CLIENT) public class ModelCrate extends BlankModel { - + @Nullable private static ImmutableMap itemTransforms; - private static Map cache = new HashMap(); + private static final Map cache = new HashMap<>(); private static final String CUSTOM_CRATES = "forestry:item/crates/"; @@ -112,7 +112,7 @@ public class ModelCrate extends BlankModel { private List bakeModel(ItemCrated crateItem) { List models = new ArrayList<>(); ItemStack contained = crateItem.getContained(); - if (contained != null) { + if (!contained.isEmpty()) { IBakedModel containedModel = getModel(contained); models.add(new TRSRBakedModel(containedModel, -0.0625F, 0, 0.0625F, 0.5F)); models.add(new TRSRBakedModel(containedModel, -0.0625F, 0, -0.0625F, 0.5F)); @@ -123,21 +123,21 @@ public class ModelCrate extends BlankModel { private class CrateOverrideList extends ItemOverrideList{ public CrateOverrideList() { - super(new ArrayList()); + super(new ArrayList<>()); } /** * Bake the crated model */ @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { ItemCrated crated = (ItemCrated) stack.getItem(); String crateUID = ItemStackUtil.getItemNameFromRegistry(crated).getResourcePath(); IBakedModel model = cache.get(crateUID); if(model == null) { //Fastest list with a unknown quad size - List list = new LinkedList(); + List list = new LinkedList<>(); IBakedModel baseBaked = getModel(new ItemStack(PluginStorage.items.crate, 1, 1)); for(BakedQuad quad : ForgeHooksClient.handleCameraTransforms(baseBaked, TransformType.GROUND, false).getQuads(null, null, 0L)) { @@ -158,10 +158,10 @@ public class ModelCrate extends BlankModel { public static class BakedCrateModel extends BlankModel implements IPerspectiveAwareModel { - BakedCrateModel other; - boolean gui; - List quads = new ArrayList(); - private List emptyList = new ArrayList(); + private final BakedCrateModel other; + private final boolean gui; + private final List quads = new ArrayList<>(); + private final List emptyList = new ArrayList<>(); public BakedCrateModel(BakedCrateModel noneGui) { diff --git a/src/main/java/forestry/core/models/ModelEscritoire.java b/src/main/java/forestry/core/models/ModelEscritoire.java index 4c038a1c1..a145e70b3 100644 --- a/src/main/java/forestry/core/models/ModelEscritoire.java +++ b/src/main/java/forestry/core/models/ModelEscritoire.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.models; +import javax.annotation.Nullable; + import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; @@ -157,8 +159,7 @@ public class ModelEscritoire extends ModelBase { } @Override - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - super.render(entity, f, f1, f2, f3, f4, f5); + public void render(@Nullable Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { setRotationAngles(f, f1, f2, f3, f4, f5, entity); desk.render(f5); standRB.render(f5); diff --git a/src/main/java/forestry/core/models/ModelManager.java b/src/main/java/forestry/core/models/ModelManager.java index 959d806e1..2ee921602 100644 --- a/src/main/java/forestry/core/models/ModelManager.java +++ b/src/main/java/forestry/core/models/ModelManager.java @@ -10,13 +10,20 @@ ******************************************************************************/ package forestry.core.models; -import com.google.common.collect.ImmutableMap; - -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import javax.vecmath.Vector3f; import java.util.ArrayList; import java.util.List; +import com.google.common.collect.ImmutableMap; +import forestry.api.core.ForestryAPI; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.core.blocks.IColoredBlock; +import forestry.core.config.Constants; +import forestry.core.items.IColoredItem; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -33,7 +40,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.util.registry.IRegistry; import net.minecraft.world.IBlockAccess; - import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.SimpleModelState; @@ -42,20 +48,11 @@ import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.ForestryAPI; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.core.blocks.IColoredBlock; -import forestry.core.config.Constants; -import forestry.core.items.IColoredItem; -import forestry.core.utils.ItemStackUtil; - @SideOnly(Side.CLIENT) public class ModelManager implements IModelManager { - + private static final ModelManager instance = new ModelManager(); - + private final List customBlockModels = new ArrayList<>(); private final List customModels = new ArrayList<>(); @@ -64,41 +61,41 @@ public class ModelManager implements IModelManager { private final List blockColorList = new ArrayList<>(); private final List itemColorList = new ArrayList<>(); - private TRSRTransformation flipX = new TRSRTransformation(null, null, new Vector3f(-1, 1, 1), null); + private final TRSRTransformation flipX = new TRSRTransformation(null, null, new Vector3f(-1, 1, 1), null); public final IModelState DEFAULT_BLOCK; public final IModelState DEFAULT_ITEM; public final IModelState DEFAULT_TOOL; - + public ModelManager() { - TRSRTransformation blockThirdperson = get(0, 2.5f, 0, 75, 45, 0, 0.375f); - ImmutableMap.Builder blockBuilder = ImmutableMap.builder(); - blockBuilder.put(TransformType.GUI, get(0, 0, 0, 30, 225, 0, 0.625f)); - blockBuilder.put(TransformType.GROUND, get(0, 3, 0, 0, 0, 0, 0.25f)); - blockBuilder.put(TransformType.FIXED, get(0, 0, 0, 0, 0, 0, 0.5f)); - blockBuilder.put(TransformType.THIRD_PERSON_RIGHT_HAND, blockThirdperson); - blockBuilder.put(TransformType.THIRD_PERSON_LEFT_HAND, leftify(blockThirdperson)); - blockBuilder.put(TransformType.FIRST_PERSON_RIGHT_HAND, get(0, 0, 0, 0, 45, 0, 0.4f)); - blockBuilder.put(TransformType.FIRST_PERSON_LEFT_HAND, get(0, 0, 0, 0, 225, 0, 0.4f)); - DEFAULT_BLOCK = new SimpleModelState(blockBuilder.build()); - - TRSRTransformation itemThirdperson = get(0, 3, 1, 0, 0, 0, 0.55f); - TRSRTransformation firstperson = get(1.13f, 3.2f, 1.13f, 0, -90, 25, 0.68f); - ImmutableMap.Builder itemBuilder = ImmutableMap.builder(); - itemBuilder.put(TransformType.GROUND, get(0, 2, 0, 0, 0, 0, 0.5f)); - itemBuilder.put(TransformType.HEAD, get(0, 13, 7, 0, 180, 0, 1)); - itemBuilder.put(TransformType.THIRD_PERSON_RIGHT_HAND, itemThirdperson); - itemBuilder.put(TransformType.THIRD_PERSON_LEFT_HAND, leftify(itemThirdperson)); - itemBuilder.put(TransformType.FIRST_PERSON_RIGHT_HAND, firstperson); - itemBuilder.put(TransformType.FIRST_PERSON_LEFT_HAND, leftify(firstperson)); - DEFAULT_ITEM = new SimpleModelState(itemBuilder.build()); - - DEFAULT_TOOL = new SimpleModelState(ImmutableMap.of( - TransformType.THIRD_PERSON_RIGHT_HAND, get(0, 4, 0.5f, 0, -90, 55, 0.85f), - TransformType.THIRD_PERSON_LEFT_HAND, get(0, 4, 0.5f, 0, 90, -55, 0.85f), - TransformType.FIRST_PERSON_RIGHT_HAND, get(1.13f, 3.2f, 1.13f, 0, -90, 25, 0.68f), - TransformType.FIRST_PERSON_LEFT_HAND, get(1.13f, 3.2f, 1.13f, 0, 90, -25, 0.68f))); + TRSRTransformation blockThirdperson = get(0, 2.5f, 0, 75, 45, 0, 0.375f); + ImmutableMap.Builder blockBuilder = ImmutableMap.builder(); + blockBuilder.put(TransformType.GUI, get(0, 0, 0, 30, 225, 0, 0.625f)); + blockBuilder.put(TransformType.GROUND, get(0, 3, 0, 0, 0, 0, 0.25f)); + blockBuilder.put(TransformType.FIXED, get(0, 0, 0, 0, 0, 0, 0.5f)); + blockBuilder.put(TransformType.THIRD_PERSON_RIGHT_HAND, blockThirdperson); + blockBuilder.put(TransformType.THIRD_PERSON_LEFT_HAND, leftify(blockThirdperson)); + blockBuilder.put(TransformType.FIRST_PERSON_RIGHT_HAND, get(0, 0, 0, 0, 45, 0, 0.4f)); + blockBuilder.put(TransformType.FIRST_PERSON_LEFT_HAND, get(0, 0, 0, 0, 225, 0, 0.4f)); + DEFAULT_BLOCK = new SimpleModelState(blockBuilder.build()); + + TRSRTransformation itemThirdperson = get(0, 3, 1, 0, 0, 0, 0.55f); + TRSRTransformation firstperson = get(1.13f, 3.2f, 1.13f, 0, -90, 25, 0.68f); + ImmutableMap.Builder itemBuilder = ImmutableMap.builder(); + itemBuilder.put(TransformType.GROUND, get(0, 2, 0, 0, 0, 0, 0.5f)); + itemBuilder.put(TransformType.HEAD, get(0, 13, 7, 0, 180, 0, 1)); + itemBuilder.put(TransformType.THIRD_PERSON_RIGHT_HAND, itemThirdperson); + itemBuilder.put(TransformType.THIRD_PERSON_LEFT_HAND, leftify(itemThirdperson)); + itemBuilder.put(TransformType.FIRST_PERSON_RIGHT_HAND, firstperson); + itemBuilder.put(TransformType.FIRST_PERSON_LEFT_HAND, leftify(firstperson)); + DEFAULT_ITEM = new SimpleModelState(itemBuilder.build()); + + DEFAULT_TOOL = new SimpleModelState(ImmutableMap.of( + TransformType.THIRD_PERSON_RIGHT_HAND, get(0, 4, 0.5f, 0, -90, 55, 0.85f), + TransformType.THIRD_PERSON_LEFT_HAND, get(0, 4, 0.5f, 0, 90, -55, 0.85f), + TransformType.FIRST_PERSON_RIGHT_HAND, get(1.13f, 3.2f, 1.13f, 0, -90, 25, 0.68f), + TransformType.FIRST_PERSON_LEFT_HAND, get(1.13f, 3.2f, 1.13f, 0, 90, -25, 0.68f))); } - + static { ForestryAPI.modelManager = instance; } @@ -106,21 +103,18 @@ public class ModelManager implements IModelManager { public static ModelManager getInstance() { return instance; } - - private TRSRTransformation get(float tx, float ty, float tz, float ax, float ay, float az, float s){ - return TRSRTransformation.blockCenterToCorner(new TRSRTransformation( - new Vector3f(tx / 16, ty / 16, tz / 16), - TRSRTransformation.quatFromXYZDegrees(new Vector3f(ax, ay, az)), - new Vector3f(s, s, s), - null)); - } - private TRSRTransformation leftify(TRSRTransformation transform){ - if(flipX == null){ - flipX = new TRSRTransformation(null, null, new Vector3f(-1, 1, 1), null); - } - return TRSRTransformation.blockCenterToCorner(flipX.compose(TRSRTransformation.blockCornerToCenter(transform)).compose(flipX)); - } + private TRSRTransformation get(float tx, float ty, float tz, float ax, float ay, float az, float s) { + return TRSRTransformation.blockCenterToCorner(new TRSRTransformation( + new Vector3f(tx / 16, ty / 16, tz / 16), + TRSRTransformation.quatFromXYZDegrees(new Vector3f(ax, ay, az)), + new Vector3f(s, s, s), + null)); + } + + private TRSRTransformation leftify(TRSRTransformation transform) { + return TRSRTransformation.blockCenterToCorner(flipX.compose(TRSRTransformation.blockCornerToCenter(transform)).compose(flipX)); + } @Override public void registerItemModel(Item item, int meta, String identifier) { @@ -141,7 +135,7 @@ public class ModelManager implements IModelManager { public void registerItemModel(Item item, ItemMeshDefinition definition) { ModelLoader.setCustomMeshDefinition(item, definition); } - + @Override public ModelResourceLocation getModelLocation(Item item) { String itemName = ItemStackUtil.getItemNameFromRegistry(item).getResourcePath(); @@ -204,7 +198,7 @@ public class ModelManager implements IModelManager { @SideOnly(Side.CLIENT) public void registerItemAndBlockColors() { Minecraft minecraft = Minecraft.getMinecraft(); - + BlockColors blockColors = minecraft.getBlockColors(); for (IColoredBlock blockColor : blockColorList) { if (blockColor instanceof Block) { @@ -247,9 +241,9 @@ public class ModelManager implements IModelManager { } @Override - public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex) { + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { Block block = state.getBlock(); - if (block instanceof IColoredBlock) { + if (block instanceof IColoredBlock && worldIn != null && pos != null) { return ((IColoredBlock) block).colorMultiplier(state, worldIn, pos, tintIndex); } return 0xffffff; @@ -264,17 +258,17 @@ public class ModelManager implements IModelManager { registry.putObject(entry.itemModelLocation, entry.model); } } - + for (final ModelEntry entry : customModels) { registry.putObject(entry.modelLocation, entry.model); } } - - public void registerCustomBlockModel(@Nonnull BlockModelEntry index) { + + public void registerCustomBlockModel(BlockModelEntry index) { customBlockModels.add(index); } - - public void registerCustomModel(@Nonnull ModelEntry index) { + + public void registerCustomModel(ModelEntry index) { customModels.add(index); } diff --git a/src/main/java/forestry/core/models/SimpleRetexturedModel.java b/src/main/java/forestry/core/models/SimpleRetexturedModel.java index 4b5b0b905..97e1f4cd4 100644 --- a/src/main/java/forestry/core/models/SimpleRetexturedModel.java +++ b/src/main/java/forestry/core/models/SimpleRetexturedModel.java @@ -1,5 +1,6 @@ package forestry.core.models; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; @@ -18,6 +19,7 @@ import net.minecraftforge.client.model.IModel; public class SimpleRetexturedModel extends BlankModel { public final IModel model; + @Nullable public IBakedModel bakedModel; public SimpleRetexturedModel(IModel model) { @@ -25,7 +27,7 @@ public class SimpleRetexturedModel extends BlankModel { } @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { return getModel().getQuads(state, side, rand); } @@ -47,7 +49,7 @@ public class SimpleRetexturedModel extends BlankModel { } private static class RetexturedOverrideList extends ItemOverrideList{ - public IBakedModel bakedModel; + public final IBakedModel bakedModel; public RetexturedOverrideList(IBakedModel bakedModel) { super(Collections.emptyList()); @@ -56,7 +58,7 @@ public class SimpleRetexturedModel extends BlankModel { } @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { return bakedModel; } diff --git a/src/main/java/forestry/core/models/TRSRBakedModel.java b/src/main/java/forestry/core/models/TRSRBakedModel.java index 68d984bad..0646da764 100644 --- a/src/main/java/forestry/core/models/TRSRBakedModel.java +++ b/src/main/java/forestry/core/models/TRSRBakedModel.java @@ -16,6 +16,7 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; +import javax.annotation.Nullable; import javax.vecmath.Matrix3f; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; @@ -96,7 +97,7 @@ public class TRSRBakedModel implements IBakedModel { } @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { if (side != null) { return faces.get(side); } @@ -130,13 +131,13 @@ public class TRSRBakedModel implements IBakedModel { @Override public ItemOverrideList getOverrides() { - return null; + return original.getOverrides(); } public static class Transformer extends VertexTransformer { - protected Matrix4f transformation; - protected Matrix3f normalTransformation; + protected final Matrix4f transformation; + protected final Matrix3f normalTransformation; public Transformer(TRSRTransformation transformation, VertexFormat format) { super(new UnpackedBakedQuad.Builder(format)); diff --git a/src/main/java/forestry/core/models/baker/ModelBaker.java b/src/main/java/forestry/core/models/baker/ModelBaker.java index b57faa3b2..292aba632 100644 --- a/src/main/java/forestry/core/models/baker/ModelBaker.java +++ b/src/main/java/forestry/core/models/baker/ModelBaker.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.models.baker; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -47,21 +46,17 @@ public class ModelBaker implements IModelBaker { private static final float quadsUV[] = new float[]{0, 0, 1, 1, 0, 0, 1, 1}; private final List faces = new ArrayList<>(); private final List> bakedModels = new ArrayList<>(); - @Nonnull + protected AxisAlignedBB renderBounds = Block.FULL_BLOCK_AABB; - protected ModelBakerModel currentModel = new ModelBakerModel(ModelManager.getInstance().DEFAULT_BLOCK); + protected final ModelBakerModel currentModel = new ModelBakerModel(ModelManager.getInstance().DEFAULT_BLOCK); protected final FaceBakery faceBakery = new FaceBakery(); - protected final float[] defUVs = new float[] { 0, 0, 1, 1 }; + protected final float[] defUVs = new float[]{0, 0, 1, 1}; @Override - public void setRenderBounds(@Nonnull AxisAlignedBB renderBounds) { - if (renderBounds == null) { - return; - } - + public void setRenderBounds(AxisAlignedBB renderBounds) { this.renderBounds = renderBounds; } @@ -76,32 +71,32 @@ public class ModelBaker implements IModelBaker { public void setColorIndex(int colorIndex) { this.colorIndex = colorIndex; } - + @Override - public void addModel(@Nonnull AxisAlignedBB renderBounds, @Nonnull TextureAtlasSprite[] textures, int colorIndex) { + public void addModel(AxisAlignedBB renderBounds, TextureAtlasSprite[] textures, int colorIndex) { setRenderBounds(renderBounds); - + setColorIndex(colorIndex); - + for (EnumFacing facing : EnumFacing.VALUES) { addFace(facing, textures[facing.ordinal()]); } setRenderBounds(Block.FULL_BLOCK_AABB); } - + @Override - public void addModel(@Nonnull AxisAlignedBB renderBounds, @Nonnull TextureAtlasSprite texture, int colorIndex) { - addModel(renderBounds, new TextureAtlasSprite[]{ texture, texture, texture, texture, texture, texture }, colorIndex); + public void addModel(AxisAlignedBB renderBounds, TextureAtlasSprite texture, int colorIndex) { + addModel(renderBounds, new TextureAtlasSprite[]{texture, texture, texture, texture, texture, texture}, colorIndex); } - + @Override - public void addBlockModel(@Nonnull Block block, @Nonnull AxisAlignedBB renderBounds, @Nullable BlockPos pos, @Nonnull TextureAtlasSprite[] textures, int colorIndex) { + public void addBlockModel(Block block, AxisAlignedBB renderBounds, @Nullable BlockPos pos, TextureAtlasSprite[] textures, int colorIndex) { setRenderBounds(renderBounds); - + setColorIndex(colorIndex); - - if(pos != null){ + + if (pos != null) { World world = Proxies.common.getRenderWorld(); IBlockState blockState = world.getBlockState(pos); for (EnumFacing facing : EnumFacing.VALUES) { @@ -109,7 +104,7 @@ public class ModelBaker implements IModelBaker { addFace(facing, textures[facing.ordinal()]); } } - }else { + } else { for (EnumFacing facing : EnumFacing.VALUES) { addFace(facing, textures[facing.ordinal()]); } @@ -119,15 +114,13 @@ public class ModelBaker implements IModelBaker { } @Override - public void addBlockModel(@Nonnull Block block, @Nonnull AxisAlignedBB renderBounds, @Nullable BlockPos pos, @Nonnull TextureAtlasSprite texture, int colorIndex) { - addBlockModel(block, renderBounds, pos, new TextureAtlasSprite[]{ texture, texture, texture, texture, texture, texture }, colorIndex); + public void addBlockModel(Block block, AxisAlignedBB renderBounds, @Nullable BlockPos pos, TextureAtlasSprite texture, int colorIndex) { + addBlockModel(block, renderBounds, pos, new TextureAtlasSprite[]{texture, texture, texture, texture, texture, texture}, colorIndex); } - + @Override - public void addBakedModel(@Nullable IBlockState state, @Nonnull IBakedModel model) { - if(model != null){ - this.bakedModels.add(Pair.of(state, model)); - } + public void addBakedModel(@Nullable IBlockState state, IBakedModel model) { + this.bakedModels.add(Pair.of(state, model)); } protected static float[] getFaceUvs(final EnumFacing face, final Vector3f to_16, final Vector3f from_16) { @@ -137,43 +130,43 @@ public class ModelBaker implements IModelBaker { float to_b = 0; switch (face) { - case UP: - from_a = from_16.x / 16.0f; - from_b = from_16.z / 16.0f; - to_a = to_16.x / 16.0f; - to_b = to_16.z / 16.0f; - break; - case DOWN: - from_a = from_16.x / 16.0f; - from_b = from_16.z / 16.0f; - to_a = to_16.x / 16.0f; - to_b = to_16.z / 16.0f; - break; - case SOUTH: - from_a = from_16.x / 16.0f; - from_b = from_16.y / 16.0f; - to_a = to_16.x / 16.0f; - to_b = to_16.y / 16.0f; - break; - case NORTH: - from_a = from_16.x / 16.0f; - from_b = from_16.y / 16.0f; - to_a = to_16.x / 16.0f; - to_b = to_16.y / 16.0f; - break; - case EAST: - from_a = from_16.y / 16.0f; - from_b = from_16.z / 16.0f; - to_a = to_16.y / 16.0f; - to_b = to_16.z / 16.0f; - break; - case WEST: - from_a = from_16.y / 16.0f; - from_b = from_16.z / 16.0f; - to_a = to_16.y / 16.0f; - to_b = to_16.z / 16.0f; - break; - default: + case UP: + from_a = from_16.x / 16.0f; + from_b = from_16.z / 16.0f; + to_a = to_16.x / 16.0f; + to_b = to_16.z / 16.0f; + break; + case DOWN: + from_a = from_16.x / 16.0f; + from_b = from_16.z / 16.0f; + to_a = to_16.x / 16.0f; + to_b = to_16.z / 16.0f; + break; + case SOUTH: + from_a = from_16.x / 16.0f; + from_b = from_16.y / 16.0f; + to_a = to_16.x / 16.0f; + to_b = to_16.y / 16.0f; + break; + case NORTH: + from_a = from_16.x / 16.0f; + from_b = from_16.y / 16.0f; + to_a = to_16.x / 16.0f; + to_b = to_16.y / 16.0f; + break; + case EAST: + from_a = from_16.y / 16.0f; + from_b = from_16.z / 16.0f; + to_a = to_16.y / 16.0f; + to_b = to_16.z / 16.0f; + break; + case WEST: + from_a = from_16.y / 16.0f; + from_b = from_16.z / 16.0f; + to_a = to_16.y / 16.0f; + to_b = to_16.z / 16.0f; + break; + default: } from_a = 1.0f - from_a; @@ -197,11 +190,7 @@ public class ModelBaker implements IModelBaker { } @Override - public void addFace(@Nonnull EnumFacing facing, @Nonnull TextureAtlasSprite sprite) { - if (sprite == null) { - return; - } - + public void addFace(EnumFacing facing, TextureAtlasSprite sprite) { Vector3f to = new Vector3f((float) renderBounds.minX * 16.0f, (float) renderBounds.minY * 16.0f, (float) renderBounds.minZ * 16.0f); Vector3f from = new Vector3f((float) renderBounds.maxX * 16.0f, (float) renderBounds.maxY * 16.0f, (float) renderBounds.maxZ * 16.0f); @@ -215,9 +204,9 @@ public class ModelBaker implements IModelBaker { if (flip) { mr = ModelRotation.X0_Y180; } - + //Add baked models to the current model. - for(Pair bakedModel : bakedModels){ + for (Pair bakedModel : bakedModels) { currentModel.addModelQuads(bakedModel); } @@ -232,12 +221,12 @@ public class ModelBaker implements IModelBaker { currentModel.addQuad(myFace, bf); } - + return currentModel; } - + @Override - public void setModelState(IModelState modelState){ + public void setModelState(@Nullable IModelState modelState) { currentModel.setModelState(modelState); } diff --git a/src/main/java/forestry/core/models/baker/ModelBakerFace.java b/src/main/java/forestry/core/models/baker/ModelBakerFace.java index a6d52d3b7..31f8a090b 100644 --- a/src/main/java/forestry/core/models/baker/ModelBakerFace.java +++ b/src/main/java/forestry/core/models/baker/ModelBakerFace.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.core.models.baker; -import javax.annotation.Nonnull; - import org.lwjgl.util.vector.Vector3f; import net.minecraft.client.renderer.texture.TextureAtlasSprite; @@ -25,7 +23,6 @@ import net.minecraftforge.fml.relauncher.SideOnly; */ @SideOnly(Side.CLIENT) public class ModelBakerFace { - @Nonnull public final EnumFacing face; public final Vector3f to; @@ -37,7 +34,7 @@ public class ModelBakerFace { public final int colorIndex; - public ModelBakerFace(@Nonnull EnumFacing face, int colorIndex, Vector3f to, Vector3f from, float[] defUVs2, TextureAtlasSprite sprite) { + public ModelBakerFace(EnumFacing face, int colorIndex, Vector3f to, Vector3f from, float[] defUVs2, TextureAtlasSprite sprite) { this.colorIndex = colorIndex; this.face = face; this.to = to; diff --git a/src/main/java/forestry/core/models/baker/ModelBakerModel.java b/src/main/java/forestry/core/models/baker/ModelBakerModel.java index 8ad7d9329..2040c818a 100644 --- a/src/main/java/forestry/core/models/baker/ModelBakerModel.java +++ b/src/main/java/forestry/core/models/baker/ModelBakerModel.java @@ -10,18 +10,15 @@ ******************************************************************************/ package forestry.core.models.baker; +import javax.annotation.Nullable; +import javax.vecmath.Matrix4f; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; -import javax.annotation.Nonnull; -import javax.vecmath.Matrix4f; - -import org.apache.commons.lang3.tuple.Pair; - import com.google.common.collect.ImmutableMap; - +import forestry.api.core.IModelBakerModel; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; @@ -34,22 +31,24 @@ import net.minecraftforge.common.model.IModelState; import net.minecraftforge.common.model.TRSRTransformation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; - -import forestry.api.core.IModelBakerModel; +import org.apache.commons.lang3.tuple.Pair; @SideOnly(Side.CLIENT) public class ModelBakerModel implements IModelBakerModel { - + private boolean isGui3d; private boolean isAmbientOcclusion; + @Nullable private TextureAtlasSprite particleSprite; + @Nullable private IModelState modelState; - private ImmutableMap transforms; - + @Nullable + private ImmutableMap transforms; + private final Map> faceQuads; private final List generalQuads; private final List> models; - + private float[] rotation = getDefaultRotation(); private float[] translation = getDefaultTranslation(); private float[] scale = getDefaultScale(); @@ -61,8 +60,8 @@ public class ModelBakerModel implements IModelBakerModel { isGui3d = true; isAmbientOcclusion = false; setModelState(modelState); - - for(EnumFacing face : EnumFacing.VALUES){ + + for (EnumFacing face : EnumFacing.VALUES) { faceQuads.put(face, new ArrayList<>()); } } @@ -79,7 +78,7 @@ public class ModelBakerModel implements IModelBakerModel { this.particleSprite = particleSprite; setModelState(modelState); } - + @Override public void setGui3d(boolean gui3d) { this.isGui3d = gui3d; @@ -94,12 +93,12 @@ public class ModelBakerModel implements IModelBakerModel { public void setAmbientOcclusion(boolean ambientOcclusion) { this.isAmbientOcclusion = ambientOcclusion; } - + @Override public boolean isAmbientOcclusion() { return isAmbientOcclusion; } - + @Override public void setParticleSprite(TextureAtlasSprite particleSprite) { this.particleSprite = particleSprite; @@ -109,7 +108,7 @@ public class ModelBakerModel implements IModelBakerModel { public TextureAtlasSprite getParticleTexture() { return particleSprite; } - + @Override public boolean isBuiltInRenderer() { return false; @@ -126,32 +125,32 @@ public class ModelBakerModel implements IModelBakerModel { } public static float[] getDefaultRotation() { - return new float[] { -80, -45, 170 }; + return new float[]{-80, -45, 170}; } public static float[] getDefaultTranslation() { - return new float[] { 0, 1.5F, -2.75F }; + return new float[]{0, 1.5F, -2.75F}; } public static float[] getDefaultScale() { - return new float[] { 0.375F, 0.375F, 0.375F }; + return new float[]{0.375F, 0.375F, 0.375F}; } - + @Override public void setRotation(float[] rotation) { this.rotation = rotation; } - + @Override public void setTranslation(float[] translation) { this.translation = translation; } - + @Override public void setScale(float[] scale) { this.scale = scale; } - + @Override public float[] getRotation() { return rotation; @@ -166,42 +165,35 @@ public class ModelBakerModel implements IModelBakerModel { public float[] getScale() { return scale; } - - public void setModelState(IModelState modelState) { + + public void setModelState(@Nullable IModelState modelState) { this.modelState = modelState; this.transforms = MapWrapper.getTransforms(modelState); } - - @Override - public IModelState getModelState() { - return modelState; - } public void addModelQuads(Pair model) { - if(model != null){ - this.models.add(model); - } + this.models.add(model); } - + @Override - public void addQuad(EnumFacing facing, @Nonnull BakedQuad quad) { - if(facing != null){ + public void addQuad(@Nullable EnumFacing facing, BakedQuad quad) { + if (facing != null) { faceQuads.get(facing).add(quad); - }else{ + } else { generalQuads.add(quad); } } @Override - public List getQuads(IBlockState state, EnumFacing side, long rand) { + public List getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { List quads = new ArrayList<>(); for (Pair model : this.models) { List modelQuads = model.getRight().getQuads(model.getLeft(), side, rand); - if(modelQuads != null && !modelQuads.isEmpty()){ + if (modelQuads != null && !modelQuads.isEmpty()) { quads.addAll(modelQuads); } } - if(side != null){ + if (side != null) { quads.addAll(faceQuads.get(side)); } quads.addAll(generalQuads); @@ -212,9 +204,8 @@ public class ModelBakerModel implements IModelBakerModel { return new ModelBakerModel(models, faceQuads, generalQuads, isGui3d, isAmbientOcclusion, modelState, rotation, translation, scale, particleSprite); } - @Override - public Pair handlePerspective(TransformType cameraTransformType) - { - return MapWrapper.handlePerspective(this, transforms, cameraTransformType); - } + @Override + public Pair handlePerspective(TransformType cameraTransformType) { + return MapWrapper.handlePerspective(this, transforms, cameraTransformType); + } } diff --git a/src/main/java/forestry/core/models/baker/package-info.java b/src/main/java/forestry/core/models/baker/package-info.java new file mode 100644 index 000000000..35c3e32d4 --- /dev/null +++ b/src/main/java/forestry/core/models/baker/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.models.baker; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/models/package-info.java b/src/main/java/forestry/core/models/package-info.java new file mode 100644 index 000000000..680190827 --- /dev/null +++ b/src/main/java/forestry/core/models/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.models; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java index 5d28d5998..8a79ba3c4 100644 --- a/src/main/java/forestry/core/multiblock/FakeMultiblockController.java +++ b/src/main/java/forestry/core/multiblock/FakeMultiblockController.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.multiblock; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.Collection; import java.util.Collections; @@ -21,8 +20,7 @@ import forestry.api.core.EnumTemperature; import forestry.api.core.IErrorLogic; import forestry.api.multiblock.IMultiblockComponent; import forestry.core.errors.FakeErrorLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.owner.FakeOwnerHandler; import forestry.core.owner.IOwnerHandler; import net.minecraft.nbt.NBTTagCompound; @@ -67,7 +65,7 @@ public abstract class FakeMultiblockController implements IMultiblockControllerI @Override public BlockPos getReferenceCoord() { - return null; + return BlockPos.ORIGIN; } @Override @@ -110,13 +108,13 @@ public abstract class FakeMultiblockController implements IMultiblockControllerI } - @Nonnull + @Override public Set checkForDisconnections() { return Collections.emptySet(); } - @Nonnull + @Override public Set detachAllBlocks() { return Collections.emptySet(); @@ -138,7 +136,7 @@ public abstract class FakeMultiblockController implements IMultiblockControllerI } @Override - @Nonnull + public Collection getComponents() { return Collections.emptyList(); } @@ -184,12 +182,12 @@ public abstract class FakeMultiblockController implements IMultiblockControllerI } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { } } diff --git a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java index c9c9d6241..35a39cb06 100644 --- a/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java +++ b/src/main/java/forestry/core/multiblock/IMultiblockControllerInternal.java @@ -10,26 +10,26 @@ ******************************************************************************/ package forestry.core.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Set; -import forestry.core.owner.IOwnedTile; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.core.IErrorLogicSource; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockController; import forestry.core.network.IStreamableGui; +import forestry.core.owner.IOwnedTile; import forestry.core.tiles.IClimatised; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; // internal implementation of IMultiblockController public interface IMultiblockControllerInternal extends IMultiblockController, INbtWritable, INbtReadable, IOwnedTile, IErrorLogicSource, IClimatised, IStreamableGui { /** * Attach a new part to this machine. + * * @param part The part to add. */ void attachBlock(IMultiblockComponent part); @@ -37,7 +37,8 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * Call to detach a block from this machine. Generally, this should be called * when the tile entity is being released, e.g. on block destruction. - * @param part The part to detach from this machine. + * + * @param part The part to detach from this machine. * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. */ void detachBlock(IMultiblockComponent part, boolean chunkUnloading); @@ -61,6 +62,7 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * Called when this machine is consumed by another controller. * Essentially, forcibly tear down this object. + * * @param otherController The controller consuming this controller. */ void _onAssimilated(IMultiblockControllerInternal otherController); @@ -70,6 +72,7 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN * All blocks have been stripped out of this object and handed over to the * other controller. * This is intended primarily for cleanup. + * * @param assimilator The controller which has assimilated this controller. */ void onAssimilated(IMultiblockControllerInternal assimilator); @@ -83,6 +86,7 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. */ + @Nullable BlockPos getReferenceCoord(); /** @@ -93,12 +97,14 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * Called when the save delegate's tile entity is being asked for its description packet + * * @param data A fresh compound tag to write your multiblock data into */ void formatDescriptionPacket(NBTTagCompound data); /** * Called when the save delegate's tile entity receiving a description packet + * * @param data A compound tag containing multiblock data to import */ void decodeDescriptionPacket(NBTTagCompound data); @@ -114,6 +120,7 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN * Tests whether this multiblock should consume the other multiblock * and become the new multiblock master when the two multiblocks * are adjacent. Assumes both multiblocks are the same type. + * * @param otherController The other multiblock controller. * @return True if this multiblock should consume the other, false otherwise. */ @@ -134,16 +141,18 @@ public interface IMultiblockControllerInternal extends IMultiblockController, IN /** * Called when this machine may need to check for blocks that are no * longer physically connected to the reference coordinate. + * * @return the parts that were disconnected and removed */ - @Nonnull + Set checkForDisconnections(); /** * Detach all parts. Return a set of all parts which still * have a valid tile entity. Chunk-safe. + * * @return A set of all parts which still have a valid tile entity. */ - @Nonnull + Set detachAllBlocks(); } diff --git a/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java b/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java index 5ad7da197..8ae490014 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java +++ b/src/main/java/forestry/core/multiblock/MultiblockClientTickHandler.java @@ -10,7 +10,7 @@ public class MultiblockClientTickHandler { @SubscribeEvent public void onClientTick(TickEvent.ClientTickEvent event) { if (event.phase == TickEvent.Phase.START) { - MultiblockRegistry.tickStart(Minecraft.getMinecraft().theWorld); + MultiblockRegistry.tickStart(Minecraft.getMinecraft().world); } } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java index e82adfa80..7c2dd3fba 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerBase.java @@ -1,6 +1,6 @@ package forestry.core.multiblock; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -9,6 +9,9 @@ import java.util.List; import java.util.Random; import java.util.Set; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.core.utils.Log; +import forestry.core.utils.Translator; import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -17,24 +20,20 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.core.utils.Log; -import forestry.core.utils.Translator; - /** * This class contains the base logic for "multiblock controllers". Conceptually, they are * meta-TileEntities. They govern the logic for an associated group of TileEntities. - * + *

* Subordinate TileEntities implement the IMultiblockComponent class and, generally, should not have an update() loop. */ public abstract class MultiblockControllerBase implements IMultiblockControllerInternal { // Multiblock stuff - do not mess with - protected World worldObj; + protected final World world; // Ticks private static final Random rand = new Random(); private int tickCount = rand.nextInt(256); - + // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled protected enum AssemblyState { Disassembled, Assembled, Paused @@ -43,39 +42,44 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI protected AssemblyState assemblyState; protected HashSet connectedParts; - - /** This is a deterministically-picked coordinate that identifies this + + /** + * This is a deterministically-picked coordinate that identifies this * multiblock uniquely in its dimension. * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. * If something has the same X but a lower Y coordinate, it will be the reference. Etc. */ + @Nullable private BlockPos referenceCoord; /** * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ + @Nullable private BlockPos minimumCoord; /** * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ + @Nullable private BlockPos maximumCoord; - + /** * Set to true whenever a part is removed from this controller. */ private boolean shouldCheckForDisconnections; - + /** * Set whenever we validate the multiblock */ + @Nullable private MultiblockValidationException lastValidationException; protected MultiblockControllerBase(World world) { - this.worldObj = world; + this.world = world; this.connectedParts = new HashSet<>(); this.referenceCoord = null; @@ -89,14 +93,15 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } @Override - @Nonnull + public Collection getComponents() { return Collections.unmodifiableCollection(connectedParts); } - + /** * Call when a block with cached save-delegate data is added to the multiblock. * The part will be notified that the data has been used after this call completes. + * * @param part The NBT tag containing this controller's data. */ protected abstract void onAttachedPartWithMultiblockData(IMultiblockComponent part, NBTTagCompound data); @@ -108,11 +113,11 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI if (!connectedParts.add(part)) { Log.warning("[%s] Controller %s is double-adding part %d @ %s. This is unusual. " + "If you encounter odd behavior, please tear down the machine and rebuild it.", - worldObj.isRemote ? "CLIENT" : "SERVER", hashCode(), part.hashCode(), coord); + world.isRemote ? "CLIENT" : "SERVER", hashCode(), part.hashCode(), coord); } MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); - + logic.setController(this); this.onBlockAdded(part); @@ -121,18 +126,18 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI onAttachedPartWithMultiblockData(part, savedData); logic.onMultiblockDataAssimilated(); } - + if (this.referenceCoord == null) { referenceCoord = coord; logic.becomeMultiblockSaveDelegate(); } else if (coord.compareTo(referenceCoord) < 0) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord); + TileEntity te = this.world.getTileEntity(referenceCoord); if (te instanceof IMultiblockComponent) { IMultiblockComponent tePart = (IMultiblockComponent) te; MultiblockLogic teLogic = (MultiblockLogic) tePart.getMultiblockLogic(); teLogic.forfeitMultiblockSaveDelegate(); } - + referenceCoord = coord; logic.becomeMultiblockSaveDelegate(); } else { @@ -150,7 +155,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI minimumCoord = new BlockPos(minimumCoord.getX(), minimumCoord.getY(), coord.getZ()); } } - + if (maximumCoord != null) { if (coord.getX() > maximumCoord.getX()) { maximumCoord = new BlockPos(coord.getX(), maximumCoord.getY(), maximumCoord.getZ()); @@ -162,29 +167,31 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI maximumCoord = new BlockPos(maximumCoord.getX(), maximumCoord.getY(), coord.getZ()); } } - - MultiblockRegistry.addDirtyController(worldObj, this); + + MultiblockRegistry.addDirtyController(world, this); } /** * Called when a new part is added to the machine. Good time to register things into lists. + * * @param newPart The part being added. */ protected abstract void onBlockAdded(IMultiblockComponent newPart); /** * Called when a part is removed from the machine. Good time to clean up lists. + * * @param oldPart The part being removed. */ protected abstract void onBlockRemoved(IMultiblockComponent oldPart); - + /** * Called when a machine is assembled from a disassembled state. */ protected void onMachineAssembled() { } - + /** * Called when a machine is restored to the assembled state from a paused state. */ @@ -199,7 +206,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI protected void onMachinePaused() { } - + /** * Called when a machine is disassembled from an assembled state. * This happens due to user or in-game actions (e.g. explosions) @@ -207,10 +214,11 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI protected void onMachineDisassembled() { } - + /** * Callback whenever a part is removed (or will very shortly be removed) from a controller. * Do housekeeping/callbacks, also nulls min/max coords. + * * @param part The part being removed. */ private void onDetachBlock(IMultiblockComponent part) { @@ -221,11 +229,11 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI logic.forfeitMultiblockSaveDelegate(); minimumCoord = maximumCoord = null; - + if (referenceCoord != null && referenceCoord.equals(part.getCoordinates())) { referenceCoord = null; } - + shouldCheckForDisconnections = true; } @@ -242,16 +250,16 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI BlockPos partCoords = part.getCoordinates(); Log.warning("[%s] Double-removing part (%d) @ %d, %d, %d, this is unexpected and may cause problems. " + "If you encounter anomalies, please tear down the reactor and rebuild it.", - worldObj.isRemote ? "CLIENT" : "SERVER", part.hashCode(), partCoords.getX(), partCoords.getY(), partCoords.getZ()); + world.isRemote ? "CLIENT" : "SERVER", part.hashCode(), partCoords.getX(), partCoords.getY(), partCoords.getZ()); } if (connectedParts.isEmpty()) { // Destroy/unregister - MultiblockRegistry.addDeadController(this.worldObj, this); + MultiblockRegistry.addDeadController(this.world, this); return; } - MultiblockRegistry.addDirtyController(this.worldObj, this); + MultiblockRegistry.addDirtyController(this.world, this); // Find new save delegate if we need to. if (referenceCoord == null) { @@ -269,7 +277,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI @Override public void reassemble() { - MultiblockRegistry.addDirtyController(worldObj, this); + MultiblockRegistry.addDirtyController(world, this); } /** @@ -289,7 +297,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI lastValidationException = e; isWhole = false; } - + if (isWhole) { // This will alter assembly state assembleMachine(oldState); @@ -299,7 +307,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } // Else Paused, do nothing } - + /** * Called when a machine becomes "whole" and should begin * functioning as a game-logically finished machine. @@ -307,7 +315,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI */ private void assembleMachine(AssemblyState oldState) { this.assemblyState = AssemblyState.Assembled; - + for (IMultiblockComponent part : connectedParts) { part.onMachineAssembled(this, getMinimumCoord(), getMaximumCoord()); } @@ -318,7 +326,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI onMachineAssembled(); } } - + /** * Called when the machine needs to be disassembled. * It is not longer "whole" and should not be functional, usually @@ -334,11 +342,12 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI onMachineDisassembled(); } - + @Override public void assimilate(IMultiblockControllerInternal other) { BlockPos otherReferenceCoord = other.getReferenceCoord(); - if (otherReferenceCoord != null && getReferenceCoord().compareTo(otherReferenceCoord) >= 0) { + BlockPos referenceCoord = getReferenceCoord(); + if (otherReferenceCoord != null && referenceCoord != null && referenceCoord.compareTo(otherReferenceCoord) >= 0) { throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); } @@ -346,13 +355,13 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI // releases all blocks and references gently so they can be incorporated into another multiblock other._onAssimilated(this); - + for (IMultiblockComponent acquiredPart : partsToAcquire) { // By definition, none of these can be the minimum block. if (isInvalid(acquiredPart)) { continue; } - + connectedParts.add(acquiredPart); MultiblockLogic logic = (MultiblockLogic) acquiredPart.getMultiblockLogic(); logic.setController(this); @@ -362,17 +371,18 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI this.onAssimilate(other); other.onAssimilated(this); } - + /** * Called when this machine is consumed by another controller. * Essentially, forcibly tear down this object. + * * @param otherController The controller consuming this controller. */ @Override public void _onAssimilated(IMultiblockControllerInternal otherController) { if (referenceCoord != null) { - if (worldObj.getChunkProvider().getLoadedChunk(referenceCoord.getX() >> 4, referenceCoord.getZ() >> 4) != null) { - TileEntity te = this.worldObj.getTileEntity(referenceCoord); + if (world.getChunkProvider().getLoadedChunk(referenceCoord.getX() >> 4, referenceCoord.getZ() >> 4) != null) { + TileEntity te = this.world.getTileEntity(referenceCoord); if (te instanceof IMultiblockComponent) { IMultiblockComponent part = (IMultiblockComponent) te; MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); @@ -384,32 +394,34 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI connectedParts.clear(); } - + /** * Callback. Called after this controller assimilates all the blocks * from another controller. * Use this to absorb that controller's game data. + * * @param assimilated The controller whose uniqueness was added to our own. */ protected abstract void onAssimilate(IMultiblockControllerInternal assimilated); - + /** * Callback. Called after this controller is assimilated into another controller. * All blocks have been stripped out of this object and handed over to the * other controller. * This is intended primarily for cleanup. + * * @param assimilator The controller which has assimilated this controller. */ @Override public abstract void onAssimilated(IMultiblockControllerInternal assimilator); - + @Override public final void updateMultiblockEntity() { tickCount++; if (connectedParts.isEmpty()) { // This shouldn't happen, but just in case... - MultiblockRegistry.addDeadController(this.worldObj, this); + MultiblockRegistry.addDeadController(this.world, this); return; } @@ -418,22 +430,22 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI return; } - if (worldObj.isRemote) { + if (world.isRemote) { updateClient(tickCount); } else if (updateServer(tickCount)) { // If this returns true, the server has changed its internal data. // If our chunks are loaded (they should be), we must mark our chunks as dirty. if (minimumCoord != null && maximumCoord != null && - worldObj.isAreaLoaded(minimumCoord, maximumCoord)) { + world.isAreaLoaded(minimumCoord, maximumCoord)) { int minChunkX = minimumCoord.getX() >> 4; int minChunkZ = minimumCoord.getZ() >> 4; int maxChunkX = maximumCoord.getX() >> 4; int maxChunkZ = maximumCoord.getZ() >> 4; - + for (int x = minChunkX; x <= maxChunkX; x++) { for (int z = minChunkZ; z <= maxChunkZ; z++) { // Ensure that we save our data, even if the our save delegate is in has no TEs. - Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); + Chunk chunkToSave = this.world.getChunkFromChunkCoords(x, z); chunkToSave.setChunkModified(); } } @@ -441,16 +453,17 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } // Else: Server, but no need to save data. } - + /** * The server-side update loop! Use this similarly to a TileEntity's update loop. * You do not need to call your superclass' update() if you're directly * derived from MultiblockControllerBase. This is a callback. * Note that this will only be called when the machine is assembled. + * * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. */ protected abstract boolean updateServer(int tickCount); - + /** * Client-side update loop. Generally, this shouldn't do anything, but if you want * to do some interpolation or something, do it here. @@ -460,39 +473,41 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI protected final boolean updateOnInterval(int tickInterval) { return tickCount % tickInterval == 0; } - + // Validation helpers /** * @param level the level of the block on the multiblock, starting at 0 for the bottom. * @param world World object for the world in which this controller is located. - * @param pos coordinate of the block being tested + * @param pos coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed on the machine's side faces */ protected void isBlockGoodForExteriorLevel(int level, World world, BlockPos pos) throws MultiblockValidationException { Block block = world.getBlockState(pos).getBlock(); throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.invalid.interior", block.getLocalizedName())); } - + /** * The interior is any block that does not touch blocks outside the machine. + * * @param world World object for the world in which this controller is located. - * @param pos coordinate of the block being tested + * @param pos coordinate of the block being tested * @throws MultiblockValidationException if the tested block is not allowed in the machine's interior */ protected void isBlockGoodForInterior(World world, BlockPos pos) throws MultiblockValidationException { Block block = world.getBlockState(pos).getBlock(); throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.invalid.interior", block.getLocalizedName())); } - + @Override + @Nullable public BlockPos getReferenceCoord() { if (referenceCoord == null) { - selectNewReferenceCoord(); + return selectNewReferenceCoord(); } return referenceCoord; } - + /** * @return The number of blocks connected to this controller. */ @@ -535,7 +550,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI maximumCoord = new BlockPos(maxX, maxY, maxZ); } } - + /** * @return The minimum bounding-box coordinate containing this machine's blocks. */ @@ -579,6 +594,9 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } protected final boolean isCoordInMultiblock(int x, int y, int z) { + if (minimumCoord == null || maximumCoord == null) { + return false; + } return x >= minimumCoord.getX() && x <= maximumCoord.getX() && y >= minimumCoord.getY() && y <= maximumCoord.getY() && z >= minimumCoord.getZ() && z <= maximumCoord.getZ(); } @@ -592,11 +610,11 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI if (!otherController.getClass().equals(getClass())) { throw new IllegalArgumentException("Attempting to merge two multiblocks with different master classes - this should never happen!"); } - + if (otherController == this) { return false; } // Don't be silly, don't eat yourself. - + int res = _shouldConsume(otherController); if (res < 0) { return true; @@ -604,10 +622,10 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI return false; } else { // Strip dead parts from both and retry - Log.warning("[%s] Encountered two controllers with the same reference coordinate. Auditing connected parts and retrying.", worldObj.isRemote ? "CLIENT" : "SERVER"); + Log.warning("[%s] Encountered two controllers with the same reference coordinate. Auditing connected parts and retrying.", world.isRemote ? "CLIENT" : "SERVER"); auditParts(); otherController.auditParts(); - + res = _shouldConsume(otherController); if (res < 0) { return true; @@ -616,19 +634,19 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } else { Log.error("My Controller (%d): size (%d), parts: %s", hashCode(), connectedParts.size(), getPartsListString()); Log.error("Other Controller (%d): size (%d), coords: %s", otherController.hashCode(), otherController.getComponents().size(), otherController.getPartsListString()); - throw new IllegalArgumentException("[" + (worldObj.isRemote ? "CLIENT" : "SERVER") + "] " + + throw new IllegalArgumentException("[" + (world.isRemote ? "CLIENT" : "SERVER") + "] " + "Two controllers with the same reference coord that somehow both have valid parts - this should never happen!"); } } } - + private int _shouldConsume(IMultiblockControllerInternal otherController) { BlockPos myCoord = getReferenceCoord(); BlockPos theirCoord = otherController.getReferenceCoord(); - + // Always consume other controllers if their reference coordinate is null - this means they're empty and can be assimilated on the cheap - if (theirCoord == null) { + if (theirCoord == null || myCoord == null) { return -1; } else { return myCoord.compareTo(theirCoord); @@ -647,42 +665,42 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI sb.append(String.format("(%d: %d, %d, %d)", part.hashCode(), partCoord.getX(), partCoord.getY(), partCoord.getZ())); first = false; } - + return sb.toString(); } - + @Override public void auditParts() { HashSet deadParts = new HashSet<>(); for (IMultiblockComponent part : connectedParts) { BlockPos partCoord = part.getCoordinates(); - if (isInvalid(part) || worldObj.getTileEntity(partCoord) != part) { + if (isInvalid(part) || world.getTileEntity(partCoord) != part) { onDetachBlock(part); deadParts.add(part); } } - + connectedParts.removeAll(deadParts); - Log.warning("[%s] Controller found %d dead parts during an audit, %d parts remain attached", worldObj.isRemote ? "CLIENT" : "SERVER", deadParts.size(), connectedParts.size()); + Log.warning("[%s] Controller found %d dead parts during an audit, %d parts remain attached", world.isRemote ? "CLIENT" : "SERVER", deadParts.size(), connectedParts.size()); } @Override - @Nonnull + public Set checkForDisconnections() { if (!this.shouldCheckForDisconnections) { return Collections.emptySet(); } - + if (this.isEmpty()) { - MultiblockRegistry.addDeadController(worldObj, this); + MultiblockRegistry.addDeadController(world, this); return Collections.emptySet(); } - - IChunkProvider chunkProvider = worldObj.getChunkProvider(); + + IChunkProvider chunkProvider = world.getChunkProvider(); // Invalidate our reference coord, we'll recalculate it shortly referenceCoord = null; - + // Reset visitations and find the minimum coordinate Set deadParts = new HashSet<>(); BlockPos c; @@ -698,8 +716,8 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI onDetachBlock(part); continue; } - - if (worldObj.getTileEntity(partCoord) != part) { + + if (world.getTileEntity(partCoord) != part) { deadParts.add(part); onDetachBlock(part); continue; @@ -709,7 +727,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI logic.setUnvisited(); logic.forfeitMultiblockSaveDelegate(); - + c = part.getCoordinates(); if (referenceCoord == null) { referenceCoord = c; @@ -719,14 +737,14 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI referencePart = part; } } - + connectedParts.removeAll(deadParts); deadParts.clear(); - + if (referencePart == null || isEmpty()) { // There are no valid parts remaining. The entire multiblock was unloaded during a chunk unload. Halt. shouldCheckForDisconnections = false; - MultiblockRegistry.addDeadController(worldObj, this); + MultiblockRegistry.addDeadController(world, this); return Collections.emptySet(); } else { MultiblockLogic logic = (MultiblockLogic) referencePart.getMultiblockLogic(); @@ -738,13 +756,13 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI LinkedList partsToCheck = new LinkedList<>(); partsToCheck.add(referencePart); - + while (!partsToCheck.isEmpty()) { part = partsToCheck.removeFirst(); MultiblockLogic partLogic = (MultiblockLogic) part.getMultiblockLogic(); partLogic.setVisited(); - List nearbyParts = MultiblockUtil.getNeighboringParts(worldObj, part); // Chunk-safe on server, but not on client + List nearbyParts = MultiblockUtil.getNeighboringParts(world, part); // Chunk-safe on server, but not on client for (IMultiblockComponent nearbyPart : nearbyParts) { // Ignore different machines MultiblockLogic nearbyPartLogic = (MultiblockLogic) nearbyPart.getMultiblockLogic(); @@ -758,7 +776,7 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI } } } - + // Finally, remove all parts that remain disconnected. Set removedParts = new HashSet<>(); for (IMultiblockComponent orphanCandidate : connectedParts) { @@ -772,29 +790,25 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI // Trim any blocks that were invalid, or were removed. connectedParts.removeAll(deadParts); - + // Cleanup. Not necessary, really. deadParts.clear(); - + // Juuuust in case. if (referenceCoord == null) { selectNewReferenceCoord(); } - + // We've run the checks from here on out. shouldCheckForDisconnections = false; - + return removedParts; } @Override - @Nonnull + public Set detachAllBlocks() { - if (worldObj == null) { - return new HashSet<>(); - } - - IChunkProvider chunkProvider = worldObj.getChunkProvider(); + IChunkProvider chunkProvider = world.getChunkProvider(); for (IMultiblockComponent part : connectedParts) { BlockPos partCoord = part.getCoordinates(); if (chunkProvider.getLoadedChunk(partCoord.getX() >> 4, partCoord.getZ() >> 4) != null) { @@ -814,9 +828,10 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI public boolean isAssembled() { return this.assemblyState == AssemblyState.Assembled; } - - private void selectNewReferenceCoord() { - IChunkProvider chunkProvider = worldObj.getChunkProvider(); + + @Nullable + private BlockPos selectNewReferenceCoord() { + IChunkProvider chunkProvider = world.getChunkProvider(); IMultiblockComponent theChosenOne = null; referenceCoord = null; @@ -837,13 +852,15 @@ public abstract class MultiblockControllerBase implements IMultiblockControllerI MultiblockLogic logic = (MultiblockLogic) theChosenOne.getMultiblockLogic(); logic.becomeMultiblockSaveDelegate(); } + + return referenceCoord; } private static boolean isInvalid(IMultiblockComponent part) { return part instanceof TileEntity && ((TileEntity) part).isInvalid(); } - - protected boolean onlyUpdateWhenAssembled(){ + + protected boolean onlyUpdateWhenAssembled() { return true; } } diff --git a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java index 42c67eeb7..41d9de7a2 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockControllerForestry.java @@ -10,23 +10,19 @@ ******************************************************************************/ package forestry.core.multiblock; -import javax.annotation.Nonnull; - -import forestry.api.core.ILocatable; - import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import com.mojang.authlib.GameProfile; import forestry.api.core.ForestryAPI; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; +import forestry.api.core.ILocatable; import forestry.api.multiblock.IMultiblockComponent; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.owner.IOwnerHandler; import forestry.core.owner.IOwnedTile; +import forestry.core.owner.IOwnerHandler; import forestry.core.owner.OwnerHandler; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -58,14 +54,14 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB @Override public World getWorldObj() { - return worldObj; + return world; } @Override protected void onMachineAssembled() { super.onMachineAssembled(); - if (worldObj.isRemote) { + if (world.isRemote) { return; } @@ -107,7 +103,7 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB } /* INVENTORY */ - @Nonnull + public IInventoryAdapter getInternalInventory() { return FakeInventoryAdapter.instance(); } @@ -131,7 +127,7 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB public final ItemStack decrStackSize(int slotIndex, int amount) { return getInternalInventory().decrStackSize(slotIndex, amount); } - + @Override public ItemStack removeStackFromSlot(int slotIndex) { return getInternalInventory().removeStackFromSlot(slotIndex); @@ -156,22 +152,22 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB public final void closeInventory(EntityPlayer player) { getInternalInventory().closeInventory(player); } - + @Override public String getName() { return getInternalInventory().getName(); } - + @Override public ITextComponent getDisplayName() { return getInternalInventory().getDisplayName(); } @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); + public final boolean isUsableByPlayer(EntityPlayer player) { + return getInternalInventory().isUsableByPlayer(player); } - + @Override public boolean hasCustomName() { return getInternalInventory().hasCustomName(); @@ -181,7 +177,7 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); } - + @Override public int[] getSlotsForFace(EnumFacing side) { return getInternalInventory().getSlotsForFace(side); @@ -196,22 +192,22 @@ public abstract class MultiblockControllerForestry extends MultiblockControllerB public final boolean canExtractItem(int slotIndex, ItemStack itemStack, EnumFacing side) { return getInternalInventory().canExtractItem(slotIndex, itemStack, side); } - + @Override public int getField(int id) { return getInternalInventory().getField(id); } - + @Override public int getFieldCount() { return getInternalInventory().getFieldCount(); } - + @Override public void setField(int id, int value) { getInternalInventory().setField(id, value); } - + @Override public void clear() { getInternalInventory().clear(); diff --git a/src/main/java/forestry/core/multiblock/MultiblockLogic.java b/src/main/java/forestry/core/multiblock/MultiblockLogic.java index 41e7b7ab3..4289e8da0 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockLogic.java +++ b/src/main/java/forestry/core/multiblock/MultiblockLogic.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.multiblock; +import javax.annotation.Nullable; + import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -22,7 +24,9 @@ public abstract class MultiblockLogic i private final Class controllerClass; private boolean visited; private boolean saveMultiblockData; + @Nullable private NBTTagCompound cachedMultiblockData; + @Nullable protected T controller; protected MultiblockLogic(Class controllerClass) { @@ -33,7 +37,7 @@ public abstract class MultiblockLogic i this.cachedMultiblockData = null; } - public void setController(IMultiblockControllerInternal controller) { + public void setController(@Nullable IMultiblockControllerInternal controller) { if (controller == null) { this.controller = null; } else if (controllerClass.isAssignableFrom(controller.getClass())) { @@ -52,7 +56,7 @@ public abstract class MultiblockLogic i /** * This is called when a block is being marked as valid by the chunk, but has not yet fully - * been placed into the world's TileEntity cache. this.worldObj, xCoord, yCoord and zCoord have + * been placed into the world's TileEntity cache. this.world, xCoord, yCoord and zCoord have * been initialized, but any attempts to read data about the world can cause infinite loops - * if you call getTileEntity on this TileEntity's coordinate from within validate(), you will * blow your call stack. @@ -113,7 +117,7 @@ public abstract class MultiblockLogic i @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { - if (isMultiblockSaveDelegate() && isConnected()) { + if (isMultiblockSaveDelegate() && this.controller != null) { NBTTagCompound multiblockData = new NBTTagCompound(); this.controller.writeToNBT(multiblockData); data.setTag("multiblockData", multiblockData); @@ -162,6 +166,7 @@ public abstract class MultiblockLogic i return this.cachedMultiblockData != null; } + @Nullable public final NBTTagCompound getMultiblockSaveData() { return this.cachedMultiblockData; } @@ -178,7 +183,7 @@ public abstract class MultiblockLogic i */ @Override public void encodeDescriptionPacket(NBTTagCompound packetData) { - if (this.isMultiblockSaveDelegate() && isConnected()) { + if (this.isMultiblockSaveDelegate() && controller != null) { NBTTagCompound tag = new NBTTagCompound(); controller.formatDescriptionPacket(tag); packetData.setTag("multiblockData", tag); @@ -194,7 +199,7 @@ public abstract class MultiblockLogic i public void decodeDescriptionPacket(NBTTagCompound packetData) { if (packetData.hasKey("multiblockData")) { NBTTagCompound tag = packetData.getCompoundTag("multiblockData"); - if (isConnected()) { + if (controller != null) { controller.decodeDescriptionPacket(tag); } else { // This part hasn't been added to a machine yet, so cache the data. diff --git a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java index 73d87c5b5..89059b1a7 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockRegistry.java @@ -4,22 +4,24 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import net.minecraft.world.World; - +import com.google.common.collect.ImmutableSet; import forestry.api.multiblock.IMultiblockComponent; import forestry.core.utils.Log; +import net.minecraft.world.World; /** * This is a very static singleton registry class which directs incoming events to sub-objects, which * actually manage each individual world's multiblocks. + * * @author Erogenous Beef */ public class MultiblockRegistry { // World > WorldRegistry map private static final Map registries = new HashMap<>(); - + /** * Called before Tile Entities are ticked in the world. Do bookkeeping here. + * * @param world The world being ticked */ public static void tickStart(World world) { @@ -29,10 +31,11 @@ public class MultiblockRegistry { registry.tickStart(); } } - + /** * Called when the world has finished loading a chunk. - * @param world The world which has finished loading a chunk + * + * @param world The world which has finished loading a chunk * @param chunkX The X coordinate of the chunk * @param chunkZ The Z coordinate of the chunk */ @@ -44,29 +47,32 @@ public class MultiblockRegistry { /** * Register a new part in the system. The part has been created either through user action or via a chunk loading. + * * @param world The world into which this part is loading. - * @param part The part being loaded. + * @param part The part being loaded. */ public static void onPartAdded(World world, IMultiblockComponent part) { MultiblockWorldRegistry registry = getOrCreateRegistry(world); registry.onPartAdded(part); } - + /** * Call to remove a part from world lists. + * * @param world The world from which a multiblock part is being removed. - * @param part The part being removed. + * @param part The part being removed. */ public static void onPartRemovedFromWorld(World world, IMultiblockComponent part) { if (registries.containsKey(world)) { registries.get(world).onPartRemovedFromWorld(part); } - + } - + /** * Called whenever a world is unloaded. Unload the relevant registry, if we have one. + * * @param world The world being unloaded. */ public static void onWorldUnloaded(World world) { @@ -79,8 +85,9 @@ public class MultiblockRegistry { /** * Call to mark a controller as dirty. Dirty means that parts have * been added or removed this tick. - * @param world The world containing the multiblock - * @param controller The dirty controller + * + * @param world The world containing the multiblock + * @param controller The dirty controller */ public static void addDirtyController(World world, IMultiblockControllerInternal controller) { if (registries.containsKey(world)) { @@ -89,11 +96,12 @@ public class MultiblockRegistry { throw new IllegalArgumentException("Adding a dirty controller to a world that has no registered controllers!"); } } - + /** * Call to mark a controller as dead. It should only be marked as dead * when it has no connected parts. It will be removed after the next world tick. - * @param world The world formerly containing the multiblock + * + * @param world The world formerly containing the multiblock * @param controller The dead controller */ public static void addDeadController(World world, IMultiblockControllerInternal controller) { @@ -106,17 +114,17 @@ public class MultiblockRegistry { /** * @param world The world whose controllers you wish to retrieve. - * @return An unmodifiable set of controllers active in the given world, or null if there are none. + * @return An unmodifiable set of controllers active in the given world. */ public static Set getControllersFromWorld(World world) { if (registries.containsKey(world)) { return registries.get(world).getControllers(); } - return null; + return ImmutableSet.of(); } - + /// *** PRIVATE HELPERS *** /// - + private static MultiblockWorldRegistry getOrCreateRegistry(World world) { if (registries.containsKey(world)) { return registries.get(world); diff --git a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java index 6212767c6..93679a84c 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockTileEntityForestry.java @@ -10,20 +10,10 @@ ******************************************************************************/ package forestry.core.multiblock; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import forestry.api.core.ILocatable; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; +import forestry.api.core.ILocatable; import forestry.api.multiblock.IMultiblockLogic; import forestry.api.multiblock.MultiblockTileEntityBase; import forestry.core.config.Constants; @@ -33,6 +23,13 @@ import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.tiles.IFilterSlotDelegate; import forestry.core.utils.PlayerUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.world.World; public abstract class MultiblockTileEntityForestry extends MultiblockTileEntityBase implements ISidedInventory, IFilterSlotDelegate, ILocatable, IGuiHandlerTile { @Nullable @@ -61,7 +58,6 @@ public abstract class MultiblockTileEntityForestry e getInternalInventory().readFromNBT(data); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { data = super.writeToNBT(data); @@ -85,6 +81,11 @@ public abstract class MultiblockTileEntityForestry e return false; } + @Override + public boolean isEmpty() { + return getInternalInventory().isEmpty(); + } + @Override public final int getSizeInventory() { return getInternalInventory().getSizeInventory(); @@ -99,7 +100,7 @@ public abstract class MultiblockTileEntityForestry e public final ItemStack decrStackSize(int slotIndex, int amount) { return getInternalInventory().decrStackSize(slotIndex, amount); } - + @Override public ItemStack removeStackFromSlot(int slotIndex) { return getInternalInventory().removeStackFromSlot(slotIndex); @@ -129,15 +130,15 @@ public abstract class MultiblockTileEntityForestry e public final String getName() { return getInternalInventory().getName(); } - + @Override public ITextComponent getDisplayName() { return getInternalInventory().getDisplayName(); } @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); + public final boolean isUsableByPlayer(EntityPlayer player) { + return getInternalInventory().isUsableByPlayer(player); } @Override @@ -149,7 +150,7 @@ public abstract class MultiblockTileEntityForestry e public final boolean isItemValidForSlot(int slotIndex, ItemStack itemStack) { return getInternalInventory().isItemValidForSlot(slotIndex, itemStack); } - + @Override public int[] getSlotsForFace(EnumFacing side) { if (allowsAutomation()) { @@ -161,20 +162,12 @@ public abstract class MultiblockTileEntityForestry e @Override public final boolean canInsertItem(int slotIndex, ItemStack itemStack, EnumFacing side) { - if (allowsAutomation()) { - return getInternalInventory().canInsertItem(slotIndex, itemStack, side); - } else { - return false; - } + return allowsAutomation() && getInternalInventory().canInsertItem(slotIndex, itemStack, side); } @Override public final boolean canExtractItem(int slotIndex, ItemStack itemStack, EnumFacing side) { - if (allowsAutomation()) { - return getInternalInventory().canExtractItem(slotIndex, itemStack, side); - } else { - return false; - } + return allowsAutomation() && getInternalInventory().canExtractItem(slotIndex, itemStack, side); } @Override @@ -190,36 +183,37 @@ public abstract class MultiblockTileEntityForestry e /* ILocatable */ @Override public final World getWorldObj() { - return worldObj; + return world; } /* IMultiblockComponent */ - @Nonnull + @Override + @Nullable public final GameProfile getOwner() { return owner; } - public final void setOwner(@Nonnull GameProfile owner) { + public final void setOwner(GameProfile owner) { this.owner = owner; } - + /* Fields */ @Override public int getField(int id) { return getInternalInventory().getField(id); } - + @Override public int getFieldCount() { return getInternalInventory().getFieldCount(); } - + @Override public void setField(int id, int value) { getInternalInventory().setField(id, value); } - + @Override public void clear() { getInternalInventory().clear(); diff --git a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java index a4880fa89..fbd953f7d 100644 --- a/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java +++ b/src/main/java/forestry/core/multiblock/MultiblockWorldRegistry.java @@ -8,16 +8,15 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import forestry.api.multiblock.IMultiblockComponent; +import forestry.api.multiblock.IMultiblockLogic; +import forestry.core.utils.Log; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; -import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IMultiblockLogic; -import forestry.core.utils.Log; - /** * This class manages all the multiblock controllers that exist in a given world, * either client- or server-side. @@ -26,9 +25,8 @@ import forestry.core.utils.Log; * @author Erogenous Beef */ public class MultiblockWorldRegistry { + private final World world; - private World worldObj; - private final Set controllers; // Active controllers private final Set dirtyControllers; // Controllers whose parts lists have changed private final Set deadControllers; // Controllers which are empty @@ -40,39 +38,39 @@ public class MultiblockWorldRegistry { // A list of parts which have been detached during internal operations private final Set detachedParts; - + // A list of parts whose chunks have not yet finished loading // They will be added to the orphan list when they are finished loading. // Indexed by the hashed chunk coordinate // This can be added-to asynchronously via chunk loads! private final HashMap> partsAwaitingChunkLoad; - + // Mutexes to protect lists which may be changed due to asynchronous events, such as chunk loads private final Object partsAwaitingChunkLoadMutex; private final Object orphanedPartsMutex; - - public MultiblockWorldRegistry(World world) { - worldObj = world; - - controllers = new HashSet<>(); - deadControllers = new HashSet<>(); - dirtyControllers = new HashSet<>(); - - detachedParts = new HashSet<>(); - orphanedParts = new HashSet<>(); - partsAwaitingChunkLoad = new HashMap<>(); - partsAwaitingChunkLoadMutex = new Object(); - orphanedPartsMutex = new Object(); + public MultiblockWorldRegistry(World world) { + this.world = world; + + this.controllers = new HashSet<>(); + this.deadControllers = new HashSet<>(); + this.dirtyControllers = new HashSet<>(); + + this.detachedParts = new HashSet<>(); + this.orphanedParts = new HashSet<>(); + + this.partsAwaitingChunkLoad = new HashMap<>(); + this.partsAwaitingChunkLoadMutex = new Object(); + this.orphanedPartsMutex = new Object(); } - + /** * Called before Tile Entities are ticked in the world. Run game logic. */ public void tickStart() { if (!controllers.isEmpty()) { for (IMultiblockControllerInternal controller : controllers) { - if (controller.getWorldObj() == worldObj && controller.getWorldObj().isRemote == worldObj.isRemote) { + if (controller.getWorldObj() == world && controller.getWorldObj().isRemote == world.isRemote) { if (controller.isEmpty()) { // This happens on the server when the user breaks the last block. It's fine. // Mark 'er dead and move on. @@ -85,19 +83,19 @@ public class MultiblockWorldRegistry { } } } - + /** * Called prior to processing multiblock controllers. Do bookkeeping. */ public void processMultiblockChanges() { - IChunkProvider chunkProvider = worldObj.getChunkProvider(); + IChunkProvider chunkProvider = world.getChunkProvider(); BlockPos coord; // Merge pools - sets of adjacent machines which should be merged later on in processing List> mergePools = null; if (!orphanedParts.isEmpty()) { Set orphansToProcess = null; - + // Keep the synchronized block small. We can't iterate over orphanedParts directly // because the client does not know which chunks are actually loaded, so attachToNeighbors() // is not chunk-safe on the client, because Minecraft is stupid. @@ -108,10 +106,10 @@ public class MultiblockWorldRegistry { orphanedParts = new HashSet<>(); } } - + if (orphansToProcess != null && !orphansToProcess.isEmpty()) { Set compatibleControllers; - + // Process orphaned blocks // These are blocks that exist in a valid chunk and require a controller for (IMultiblockComponent orphan : orphansToProcess) { @@ -125,11 +123,11 @@ public class MultiblockWorldRegistry { continue; } - if (worldObj.getTileEntity(coord) != orphan) { + if (world.getTileEntity(coord) != orphan) { // This block has been replaced by another. continue; } - + // THIS IS THE ONLY PLACE WHERE PARTS ATTACH TO MACHINES // Try to attach to a neighbor's master controller compatibleControllers = attachToNeighbors(orphan); @@ -137,7 +135,7 @@ public class MultiblockWorldRegistry { // FOREVER ALONE! Create and register a new controller. // THIS IS THE ONLY PLACE WHERE NEW CONTROLLERS ARE CREATED. MultiblockLogic logic = (MultiblockLogic) orphan.getMultiblockLogic(); - IMultiblockControllerInternal newController = logic.createNewController(worldObj); + IMultiblockControllerInternal newController = logic.createNewController(world); newController.attachBlock(orphan); this.controllers.add(newController); } else if (compatibleControllers.size() > 1) { @@ -155,7 +153,7 @@ public class MultiblockWorldRegistry { candidatePools.add(candidatePool); } } - + if (candidatePools.size() <= 0) { // No pools nearby, create a new merge pool mergePools.add(compatibleControllers); @@ -191,7 +189,7 @@ public class MultiblockWorldRegistry { newMaster = controller; } } - + if (newMaster == null) { Log.error("Multiblock system checked a merge pool of size %d, found no master candidates. This should never happen.", mergePool.size()); } else { @@ -221,23 +219,23 @@ public class MultiblockWorldRegistry { // POSTCONDITION: The controller must have informed those parts that // they are no longer connected to this machine. Set newlyDetachedParts = controller.checkForDisconnections(); - + if (!controller.isEmpty()) { controller.recalculateMinMaxCoords(); controller.checkIfMachineIsWhole(); } else { addDeadController(controller); } - + if (!newlyDetachedParts.isEmpty()) { // Controller has shed some parts - add them to the detached list for delayed processing detachedParts.addAll(newlyDetachedParts); } } - + dirtyControllers.clear(); } - + // Unregister dead controllers if (!deadControllers.isEmpty()) { for (IMultiblockControllerInternal controller : deadControllers) { @@ -251,10 +249,10 @@ public class MultiblockWorldRegistry { // THIS IS THE ONLY PLACE WHERE CONTROLLERS ARE UNREGISTERED. this.controllers.remove(controller); } - + deadControllers.clear(); } - + // Process detached blocks // Any blocks which have been detached this tick should be moved to the orphaned // list, and will be checked next tick to see if their chunk is still loaded. @@ -263,7 +261,7 @@ public class MultiblockWorldRegistry { MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); logic.assertDetached(part); } - + addAllOrphanedPartsThreadsafe(detachedParts); detachedParts.clear(); } @@ -276,7 +274,7 @@ public class MultiblockWorldRegistry { MultiblockLogic logic = (MultiblockLogic) part.getMultiblockLogic(); Class controllerClass = logic.getControllerClass(); // Look for a compatible controller in our neighboring parts. - List partsToCheck = MultiblockUtil.getNeighboringParts(worldObj, part); + List partsToCheck = MultiblockUtil.getNeighboringParts(world, part); for (IMultiblockComponent neighborPart : partsToCheck) { IMultiblockLogic neighborLogic = neighborPart.getMultiblockLogic(); if (neighborLogic.isConnected()) { @@ -307,12 +305,13 @@ public class MultiblockWorldRegistry { * Called when a multiblock part is added to the world, either via chunk-load or user action. * If its chunk is loaded, it will be processed during the next tick. * If the chunk is not loaded, it will be added to a list of objects waiting for a chunkload. + * * @param part The part which is being added to this world. */ public void onPartAdded(IMultiblockComponent part) { BlockPos worldLocation = part.getCoordinates(); - - if (worldObj.getChunkProvider().getLoadedChunk(worldLocation.getX() >> 4, worldLocation.getZ() >> 4) == null) { + + if (world.getChunkProvider().getLoadedChunk(worldLocation.getX() >> 4, worldLocation.getZ() >> 4) == null) { // Part goes into the waiting-for-chunk-load list Set partSet; long chunkHash = ChunkPos.asLong(worldLocation.getX() >> 4, worldLocation.getZ() >> 4); @@ -323,7 +322,7 @@ public class MultiblockWorldRegistry { } else { partSet = partsAwaitingChunkLoad.get(chunkHash); } - + partSet.add(part); } } else { @@ -331,24 +330,23 @@ public class MultiblockWorldRegistry { addOrphanedPartThreadsafe(part); } } - + /** * Called when a part is removed from the world, via user action or via chunk unloads. * This part is removed from any lists in which it may be, and its machine is marked for recalculation. + * * @param part The part which is being removed. */ public void onPartRemovedFromWorld(IMultiblockComponent part) { BlockPos coord = part.getCoordinates(); - if (coord != null) { - long hash = ChunkPos.asLong(coord.getX() >> 4, coord.getZ() >> 4); - - if (partsAwaitingChunkLoad.containsKey(hash)) { - synchronized (partsAwaitingChunkLoadMutex) { - if (partsAwaitingChunkLoad.containsKey(hash)) { - partsAwaitingChunkLoad.get(hash).remove(part); - if (partsAwaitingChunkLoad.get(hash).size() <= 0) { - partsAwaitingChunkLoad.remove(hash); - } + long hash = ChunkPos.asLong(coord.getX() >> 4, coord.getZ() >> 4); + + if (partsAwaitingChunkLoad.containsKey(hash)) { + synchronized (partsAwaitingChunkLoadMutex) { + if (partsAwaitingChunkLoad.containsKey(hash)) { + partsAwaitingChunkLoad.get(hash).remove(part); + if (partsAwaitingChunkLoad.get(hash).size() <= 0) { + partsAwaitingChunkLoad.remove(hash); } } } @@ -373,18 +371,16 @@ public class MultiblockWorldRegistry { controllers.clear(); deadControllers.clear(); dirtyControllers.clear(); - + detachedParts.clear(); - + synchronized (partsAwaitingChunkLoadMutex) { partsAwaitingChunkLoad.clear(); } - + synchronized (orphanedPartsMutex) { orphanedParts.clear(); } - - worldObj = null; } /** @@ -427,7 +423,7 @@ public class MultiblockWorldRegistry { public void addDirtyController(IMultiblockControllerInternal dirtyController) { this.dirtyControllers.add(dirtyController); } - + /** * Use this only if you know what you're doing. You should rarely need to iterate * over all controllers in a world! @@ -439,13 +435,13 @@ public class MultiblockWorldRegistry { } /* *** PRIVATE HELPERS *** */ - + private void addOrphanedPartThreadsafe(IMultiblockComponent part) { synchronized (orphanedPartsMutex) { orphanedParts.add(part); } } - + private void addAllOrphanedPartsThreadsafe(Collection parts) { synchronized (orphanedPartsMutex) { orphanedParts.addAll(parts); diff --git a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java index 623ae6e1d..a0c67bd46 100644 --- a/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java +++ b/src/main/java/forestry/core/multiblock/RectangularMultiblockControllerBase.java @@ -68,7 +68,7 @@ public abstract class RectangularMultiblockControllerBase extends MultiblockCont for (int z = minimumCoord.getZ(); z <= maximumCoord.getZ(); z++) { // Okay, figure out what sort of block this should be. BlockPos pos = new BlockPos(x, y, z); - te = this.worldObj.getTileEntity(pos); + te = this.world.getTileEntity(pos); if (te instanceof IMultiblockComponent) { part = (IMultiblockComponent) te; @@ -110,13 +110,13 @@ public abstract class RectangularMultiblockControllerBase extends MultiblockCont if (part != null) { isGoodForExteriorLevel(part, exteriorLevel); } else { - isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, pos); + isBlockGoodForExteriorLevel(exteriorLevel, this.world, pos); } } else { if (part != null) { isGoodForInterior(part); } else { - isBlockGoodForInterior(this.worldObj, pos); + isBlockGoodForInterior(this.world, pos); } } } diff --git a/src/main/java/forestry/core/multiblock/package-info.java b/src/main/java/forestry/core/multiblock/package-info.java new file mode 100644 index 000000000..8163549f5 --- /dev/null +++ b/src/main/java/forestry/core/multiblock/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.multiblock; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/network/DataInputStreamForestry.java b/src/main/java/forestry/core/network/DataInputStreamForestry.java deleted file mode 100644 index ee7aaf3f0..000000000 --- a/src/main/java/forestry/core/network/DataInputStreamForestry.java +++ /dev/null @@ -1,154 +0,0 @@ -package forestry.core.network; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InvalidObjectException; -import java.util.Collection; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTSizeTracker; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.utils.ItemStackUtil; - -public class DataInputStreamForestry extends DataInputStream { - - public DataInputStreamForestry(InputStream in) { - super(in); - } - - public ItemStack readItemStack() throws IOException { - ItemStack itemstack = null; - String itemName = readUTF(); - - if (!itemName.isEmpty()) { - Item item = ItemStackUtil.getItemFromRegistry(itemName); - int stackSize = readVarInt(); - int meta = readVarInt(); - itemstack = new ItemStack(item, stackSize, meta); - - if (item.isDamageable() || item.getShareTag()) { - itemstack.setTagCompound(readNBTTagCompound()); - } - } - - return itemstack; - } - - public ItemStack[] readItemStacks() throws IOException { - int stackCount = readVarInt(); - - ItemStack[] itemStacks = new ItemStack[stackCount]; - for (int i = 0; i < stackCount; i++) { - itemStacks[i] = readItemStack(); - } - - return itemStacks; - } - - public void readItemStacks(Collection itemStacks) throws IOException { - itemStacks.clear(); - - int stackCount = readVarInt(); - for (int i = 0; i < stackCount; i++) { - itemStacks.add(readItemStack()); - } - } - - public void readInventory(IInventory inventory) throws IOException { - int size = readVarInt(); - - for (int i = 0; i < size; i++) { - ItemStack stack = readItemStack(); - inventory.setInventorySlotContents(i, stack); - } - } - - public T readStreamable(Class streamableClass) throws IOException { - if (readBoolean()) { - try { - T streamable = streamableClass.newInstance(); - streamable.readData(this); - return streamable; - } catch (IllegalAccessException | InstantiationException | IOException e) { - throw new InvalidObjectException("Failed to read Streamable for class " + streamableClass + " with error " + e); - } - } - return null; - } - - public void readStreamables(List outputList, Class streamableClass) throws IOException { - outputList.clear(); - int length = readVarInt(); - if (length > 0) { - for (int i = 0; i < length; i++) { - T streamable = readStreamable(streamableClass); - outputList.add(streamable); - } - } - } - - /** - * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant - * bit dictates whether another byte should be read. - */ - public int readVarInt() throws IOException { - int varInt = 0; - int size = 0; - byte b0; - - do { - b0 = readByte(); - varInt |= (b0 & 127) << size++ * 7; - - if (size > 5) { - throw new InvalidObjectException("VarInt too big"); - } - } while ((b0 & 128) == 128); - - return varInt; - } - - public > T readEnum(T[] enumValues) throws IOException { - int ordinal; - if (enumValues.length <= 256) { - ordinal = readByte(); - } else { - ordinal = readVarInt(); - } - return enumValues[ordinal]; - } - - public NBTTagCompound readNBTTagCompound() throws IOException { - int length = readVarInt(); - - if (length < 0) { - return null; - } else { - return CompressedStreamTools.read(this, new NBTSizeTracker(2097152L)); - } - } - - public FluidStack readFluidStack() throws IOException { - int amount = readVarInt(); - if (amount > 0) { - String fluidName = readUTF(); - Fluid fluid = FluidRegistry.getFluid(fluidName); - if (fluid == null) { - return null; - } - - return new FluidStack(fluid, amount); - } - return null; - } -} diff --git a/src/main/java/forestry/core/network/DataOutputStreamForestry.java b/src/main/java/forestry/core/network/DataOutputStreamForestry.java deleted file mode 100644 index 370ddfaac..000000000 --- a/src/main/java/forestry/core/network/DataOutputStreamForestry.java +++ /dev/null @@ -1,122 +0,0 @@ -package forestry.core.network; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collection; -import java.util.List; - -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.fluids.FluidStack; - -import forestry.core.utils.ItemStackUtil; - -public class DataOutputStreamForestry extends DataOutputStream { - - public DataOutputStreamForestry(OutputStream out) { - super(out); - } - - public void writeItemStack(ItemStack itemstack) throws IOException { - if (itemstack == null) { - writeUTF(""); - } else { - writeUTF(ItemStackUtil.getItemNameFromRegistryAsString(itemstack.getItem())); - writeVarInt(itemstack.stackSize); - writeVarInt(itemstack.getItemDamage()); - - if (itemstack.getItem().isDamageable() || itemstack.getItem().getShareTag()) { - writeNBTTagCompound(itemstack.getTagCompound()); - } - } - } - - public void writeItemStacks(ItemStack[] itemStacks) throws IOException { - writeVarInt(itemStacks.length); - for (ItemStack itemstack : itemStacks) { - writeItemStack(itemstack); - } - } - - public void writeItemStacks(Collection itemStacks) throws IOException { - writeVarInt(itemStacks.size()); - for (ItemStack itemstack : itemStacks) { - writeItemStack(itemstack); - } - } - - public void writeInventory(IInventory inventory) throws IOException { - int size = inventory.getSizeInventory(); - writeVarInt(size); - - for (int i = 0; i < size; i++) { - ItemStack stack = inventory.getStackInSlot(i); - writeItemStack(stack); - } - } - - public void writeStreamable(IStreamable streamable) throws IOException { - if (streamable != null) { - writeBoolean(true); - streamable.writeData(this); - } else { - writeBoolean(false); - } - } - - public void writeStreamables(List streamables) throws IOException { - if (streamables == null) { - writeVarInt(0); - } else { - writeVarInt(streamables.size()); - for (IStreamable streamable : streamables) { - writeStreamable(streamable); - } - } - } - - /** - * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of - * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates - * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have - * values below 128. - */ - public void writeVarInt(int varInt) throws IOException { - while ((varInt & -128) != 0) { - writeByte(varInt & 127 | 128); - varInt >>>= 7; - } - - writeByte(varInt); - } - - public > void writeEnum(T enumValue, T[] enumValues) throws IOException { - if (enumValues.length <= 256) { - writeByte(enumValue.ordinal()); - } else { - writeVarInt(enumValue.ordinal()); - } - } - - public void writeNBTTagCompound(NBTTagCompound nbttagcompound) throws IOException { - if (nbttagcompound == null) { - writeVarInt(-1); - } else { - writeVarInt(0); - CompressedStreamTools.write(nbttagcompound, this); - } - } - - public void writeFluidStack(FluidStack fluidStack) throws IOException { - if (fluidStack == null) { - writeVarInt(-1); - } else { - writeVarInt(fluidStack.amount); - writeUTF(fluidStack.getFluid().getName()); - } - } -} diff --git a/src/main/java/forestry/core/network/ForestryPacket.java b/src/main/java/forestry/core/network/ForestryPacket.java index 765b81d63..c1bae3472 100755 --- a/src/main/java/forestry/core/network/ForestryPacket.java +++ b/src/main/java/forestry/core/network/ForestryPacket.java @@ -12,37 +12,25 @@ package forestry.core.network; import java.io.IOException; -import net.minecraft.network.PacketBuffer; - +import forestry.core.utils.Log; +import io.netty.buffer.Unpooled; import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; -import forestry.core.utils.Log; - -import io.netty.buffer.ByteBufOutputStream; -import io.netty.buffer.Unpooled; - public abstract class ForestryPacket implements IForestryPacket { - private final IPacketId id = getPacketId(); - @Override public final FMLProxyPacket getPacket() { - ByteBufOutputStream buf = new ByteBufOutputStream(Unpooled.buffer()); - DataOutputStreamForestry data = new DataOutputStreamForestry(buf); + PacketBufferForestry data = new PacketBufferForestry(Unpooled.buffer()); try { + IPacketId id = getPacketId(); data.writeByte(id.ordinal()); writeData(data); } catch (IOException e) { Log.error("Failed to write packet.", e); } - return new FMLProxyPacket(new PacketBuffer(buf.buffer()), PacketHandler.channelId); + return new FMLProxyPacket(data, PacketHandler.channelId); } - protected void writeData(DataOutputStreamForestry data) throws IOException { - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - } + protected abstract void writeData(PacketBufferForestry data) throws IOException; } diff --git a/src/main/java/forestry/core/network/IForestryPacket.java b/src/main/java/forestry/core/network/IForestryPacket.java index f20f0bdd7..08d47fea0 100644 --- a/src/main/java/forestry/core/network/IForestryPacket.java +++ b/src/main/java/forestry/core/network/IForestryPacket.java @@ -10,14 +10,9 @@ ******************************************************************************/ package forestry.core.network; -import java.io.IOException; - import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; public interface IForestryPacket { - void readData(DataInputStreamForestry data) throws IOException; - FMLProxyPacket getPacket(); - IPacketId getPacketId(); } diff --git a/src/main/java/forestry/core/network/IForestryPacketClient.java b/src/main/java/forestry/core/network/IForestryPacketClient.java index 1f56d7300..c732db81d 100644 --- a/src/main/java/forestry/core/network/IForestryPacketClient.java +++ b/src/main/java/forestry/core/network/IForestryPacketClient.java @@ -10,14 +10,10 @@ ******************************************************************************/ package forestry.core.network; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - -/** A packet sent from the server to the client */ +/** + * A packet sent from the server to the client + */ public interface IForestryPacketClient extends IForestryPacket { - void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException; - @Override PacketIdClient getPacketId(); } diff --git a/src/main/java/forestry/core/network/IForestryPacketHandler.java b/src/main/java/forestry/core/network/IForestryPacketHandler.java new file mode 100644 index 000000000..ca0cbde62 --- /dev/null +++ b/src/main/java/forestry/core/network/IForestryPacketHandler.java @@ -0,0 +1,5 @@ +package forestry.core.network; + +public interface IForestryPacketHandler { + +} diff --git a/src/main/java/forestry/core/network/IForestryPacketHandlerClient.java b/src/main/java/forestry/core/network/IForestryPacketHandlerClient.java new file mode 100644 index 000000000..d14240d28 --- /dev/null +++ b/src/main/java/forestry/core/network/IForestryPacketHandlerClient.java @@ -0,0 +1,9 @@ +package forestry.core.network; + +import java.io.IOException; + +import net.minecraft.entity.player.EntityPlayer; + +public interface IForestryPacketHandlerClient extends IForestryPacketHandler { + void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException; +} diff --git a/src/main/java/forestry/core/network/IForestryPacketHandlerServer.java b/src/main/java/forestry/core/network/IForestryPacketHandlerServer.java new file mode 100644 index 000000000..46bacb5f5 --- /dev/null +++ b/src/main/java/forestry/core/network/IForestryPacketHandlerServer.java @@ -0,0 +1,9 @@ +package forestry.core.network; + +import java.io.IOException; + +import net.minecraft.entity.player.EntityPlayerMP; + +public interface IForestryPacketHandlerServer extends IForestryPacketHandler { + void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException; +} diff --git a/src/main/java/forestry/core/network/IForestryPacketServer.java b/src/main/java/forestry/core/network/IForestryPacketServer.java index 2c36c6a2f..0c2fa683b 100644 --- a/src/main/java/forestry/core/network/IForestryPacketServer.java +++ b/src/main/java/forestry/core/network/IForestryPacketServer.java @@ -10,13 +10,7 @@ ******************************************************************************/ package forestry.core.network; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - public interface IForestryPacketServer extends IForestryPacket { - void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException; - @Override PacketIdServer getPacketId(); } diff --git a/src/main/java/forestry/core/network/IStreamable.java b/src/main/java/forestry/core/network/IStreamable.java index 7c7127e63..029266a4a 100644 --- a/src/main/java/forestry/core/network/IStreamable.java +++ b/src/main/java/forestry/core/network/IStreamable.java @@ -13,7 +13,7 @@ package forestry.core.network; import java.io.IOException; public interface IStreamable { - void writeData(DataOutputStreamForestry data) throws IOException; + void writeData(PacketBufferForestry data); - void readData(DataInputStreamForestry data) throws IOException; + void readData(PacketBufferForestry data) throws IOException; } diff --git a/src/main/java/forestry/core/network/IStreamableGui.java b/src/main/java/forestry/core/network/IStreamableGui.java index d71587008..882c6f196 100644 --- a/src/main/java/forestry/core/network/IStreamableGui.java +++ b/src/main/java/forestry/core/network/IStreamableGui.java @@ -13,7 +13,7 @@ package forestry.core.network; import java.io.IOException; public interface IStreamableGui { - void writeGuiData(DataOutputStreamForestry data) throws IOException; + void writeGuiData(PacketBufferForestry data); - void readGuiData(DataInputStreamForestry data) throws IOException; + void readGuiData(PacketBufferForestry data) throws IOException; } diff --git a/src/main/java/forestry/core/network/PacketBufferForestry.java b/src/main/java/forestry/core/network/PacketBufferForestry.java new file mode 100644 index 000000000..7e363bc8c --- /dev/null +++ b/src/main/java/forestry/core/network/PacketBufferForestry.java @@ -0,0 +1,182 @@ +package forestry.core.network; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.io.InvalidObjectException; +import java.util.List; + +import io.netty.buffer.ByteBuf; +import net.minecraft.entity.Entity; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.network.PacketBuffer; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +public class PacketBufferForestry extends PacketBuffer { + public PacketBufferForestry(ByteBuf wrapped) { + super(wrapped); + } + + public String readString() { + return super.readString(1024); + } + + public void writeItemStacks(NonNullList itemStacks) { + writeVarInt(itemStacks.size()); + for (ItemStack stack : itemStacks) { + writeItemStack(stack); + } + } + + public NonNullList readItemStacks() throws IOException { + int stackCount = readVarInt(); + NonNullList itemStacks = NonNullList.withSize(stackCount, ItemStack.EMPTY); + for (int i = 0; i < stackCount; i++) { + itemStacks.set(i, readItemStack()); + } + return itemStacks; + } + + public void readItemStacks(NonNullList itemStacks) throws IOException { + int stackCount = readVarInt(); + for (int i = 0; i < stackCount; i++) { + itemStacks.set(i, readItemStack()); + } + } + + public void writeItemStacksArray(ItemStack[] itemStacks) { + writeVarInt(itemStacks.length); + for (ItemStack stack : itemStacks) { + writeItemStack(stack); + } + } + + public ItemStack[] readItemStacksArray() throws IOException { + int stackCount = readVarInt(); + ItemStack[] itemStacks = new ItemStack[stackCount]; + for (int i = 0; i < stackCount; i++) { + itemStacks[i] = readItemStack(); + } + return itemStacks; + } + + public void writeInventory(IInventory inventory) { + int size = inventory.getSizeInventory(); + writeVarInt(size); + + for (int i = 0; i < size; i++) { + ItemStack stack = inventory.getStackInSlot(i); + writeItemStack(stack); + } + } + + public void readInventory(IInventory inventory) throws IOException { + int size = readVarInt(); + + for (int i = 0; i < size; i++) { + ItemStack stack = readItemStack(); + inventory.setInventorySlotContents(i, stack); + } + } + + public void writeFluidStack(@Nullable FluidStack fluidStack) { + if (fluidStack == null) { + writeVarInt(-1); + } else { + writeVarInt(fluidStack.amount); + writeString(fluidStack.getFluid().getName()); + } + } + + @Nullable + public FluidStack readFluidStack() { + int amount = readVarInt(); + if (amount > 0) { + String fluidName = readString(); + Fluid fluid = FluidRegistry.getFluid(fluidName); + if (fluid == null) { + return null; + } + + return new FluidStack(fluid, amount); + } + return null; + } + + public void writeEntityById(Entity entity) { + writeVarInt(entity.getEntityId()); + } + + @Nullable + public Entity readEntityById(World world) { + int entityId = readVarInt(); + return world.getEntityByID(entityId); + } + + public > void writeEnum(T enumValue, T[] enumValues) { + if (enumValues.length <= 256) { + writeByte(enumValue.ordinal()); + } else { + writeVarInt(enumValue.ordinal()); + } + } + + public > T readEnum(T[] enumValues) { + int ordinal; + if (enumValues.length <= 256) { + ordinal = readByte(); + } else { + ordinal = readVarInt(); + } + return enumValues[ordinal]; + } + + public void writeStreamable(@Nullable IStreamable streamable) { + if (streamable != null) { + writeBoolean(true); + streamable.writeData(this); + } else { + writeBoolean(false); + } + } + + @Nullable + public T readStreamable(Class streamableClass) throws IOException { + if (readBoolean()) { + try { + T streamable = streamableClass.newInstance(); + streamable.readData(this); + return streamable; + } catch (IllegalAccessException | InstantiationException | IOException e) { + throw new InvalidObjectException("Failed to read Streamable for class " + streamableClass + " with error " + e); + } + } + return null; + } + + public void writeStreamables(@Nullable List streamables) { + if (streamables == null) { + writeVarInt(0); + } else { + writeVarInt(streamables.size()); + for (IStreamable streamable : streamables) { + writeStreamable(streamable); + } + } + } + + public void readStreamables(List outputList, Class streamableClass) throws IOException { + outputList.clear(); + int length = readVarInt(); + if (length > 0) { + for (int i = 0; i < length; i++) { + T streamable = readStreamable(streamableClass); + outputList.add(streamable); + } + } + } +} diff --git a/src/main/java/forestry/core/network/PacketHandler.java b/src/main/java/forestry/core/network/PacketHandler.java index 1f64bab2f..6e596e35f 100644 --- a/src/main/java/forestry/core/network/PacketHandler.java +++ b/src/main/java/forestry/core/network/PacketHandler.java @@ -11,7 +11,6 @@ package forestry.core.network; import java.io.IOException; -import java.io.InputStream; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; @@ -29,8 +28,6 @@ import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; import forestry.core.proxy.Proxies; import forestry.core.utils.Log; -import io.netty.buffer.ByteBufInputStream; - public class PacketHandler { public static final String channelId = "FOR"; private final FMLEventChannel channel; @@ -42,70 +39,49 @@ public class PacketHandler { @SubscribeEvent public void onPacket(ServerCustomPacketEvent event) { - DataInputStreamForestry data = getStream(event.getPacket()); + PacketBufferForestry data = new PacketBufferForestry(event.getPacket().payload()); EntityPlayerMP player = ((NetHandlerPlayServer) event.getHandler()).playerEntity; - try { - byte packetIdOrdinal = data.readByte(); - PacketIdServer packetId = PacketIdServer.VALUES[packetIdOrdinal]; - IForestryPacketServer packetHandler = packetId.getPacketHandler(); - checkThreadAndEnqueue(packetHandler, data, player, player.getServerWorld()); - } catch (IOException e) { - Log.error("Failed to read packet.", e); - } + byte packetIdOrdinal = data.readByte(); + PacketIdServer packetId = PacketIdServer.VALUES[packetIdOrdinal]; + IForestryPacketHandlerServer packetHandler = packetId.getPacketHandler(); + checkThreadAndEnqueue(packetHandler, data, player, player.getServerWorld()); } @SubscribeEvent public void onPacket(ClientCustomPacketEvent event) { - DataInputStreamForestry data = getStream(event.getPacket()); + PacketBufferForestry data = new PacketBufferForestry(event.getPacket().payload()); EntityPlayer player = Proxies.common.getPlayer(); - try { - byte packetIdOrdinal = data.readByte(); - PacketIdClient packetId = PacketIdClient.VALUES[packetIdOrdinal]; - IForestryPacketClient packetHandler = packetId.getPacketHandler(); - checkThreadAndEnqueue(packetHandler, data, player, Minecraft.getMinecraft()); - } catch (IOException e) { - Log.error("Failed to read packet.", e); - } - } - - private static DataInputStreamForestry getStream(FMLProxyPacket fmlPacket) { - InputStream is = new ByteBufInputStream(fmlPacket.payload()); - return new DataInputStreamForestry(is); + byte packetIdOrdinal = data.readByte(); + PacketIdClient packetId = PacketIdClient.VALUES[packetIdOrdinal]; + IForestryPacketHandlerClient packetHandler = packetId.getPacketHandler(); + checkThreadAndEnqueue(packetHandler, data, player, Minecraft.getMinecraft()); } public void sendPacket(FMLProxyPacket packet, EntityPlayerMP player) { channel.sendTo(packet, player); } - private static void checkThreadAndEnqueue(final IForestryPacketClient packet, final DataInputStreamForestry data, final EntityPlayer player, IThreadListener threadListener) { + private static void checkThreadAndEnqueue(final IForestryPacketHandlerClient packet, final PacketBufferForestry data, final EntityPlayer player, IThreadListener threadListener) { if (!threadListener.isCallingFromMinecraftThread()) { - threadListener.addScheduledTask(new Runnable() { - @Override - public void run() { - try { - packet.readData(data); - packet.onPacketData(data, player); - } catch (IOException e) { - Log.error("Network Error", e); - } + threadListener.addScheduledTask(() -> { + try { + packet.onPacketData(data, player); + } catch (IOException e) { + Log.error("Network Error", e); } }); } } - private static void checkThreadAndEnqueue(final IForestryPacketServer packet, final DataInputStreamForestry data, final EntityPlayerMP player, IThreadListener threadListener) { + private static void checkThreadAndEnqueue(final IForestryPacketHandlerServer packet, final PacketBufferForestry data, final EntityPlayerMP player, IThreadListener threadListener) { if (!threadListener.isCallingFromMinecraftThread()) { - threadListener.addScheduledTask(new Runnable() { - @Override - public void run() { - try { - packet.readData(data); - packet.onPacketData(data, player); - } catch (IOException e) { - Log.error("Network Error", e); - } + threadListener.addScheduledTask(() -> { + try { + packet.onPacketData(data, player); + } catch (IOException e) { + Log.error("Network Error", e); } }); } diff --git a/src/main/java/forestry/core/network/PacketIdClient.java b/src/main/java/forestry/core/network/PacketIdClient.java index 9c38d3709..aa8136305 100644 --- a/src/main/java/forestry/core/network/PacketIdClient.java +++ b/src/main/java/forestry/core/network/PacketIdClient.java @@ -12,7 +12,7 @@ package forestry.core.network; import javax.annotation.Nonnull; -import forestry.core.network.packets.PacketDummyClient; +import forestry.core.network.packets.PacketHandlerDummyClient; /** Packets sent to the client from the server */ public enum PacketIdClient implements IPacketId { @@ -64,18 +64,18 @@ public enum PacketIdClient implements IPacketId { public static final PacketIdClient[] VALUES = values(); @Nonnull - private IForestryPacketClient packetHandler; + private IForestryPacketHandlerClient packetHandler; PacketIdClient() { - this.packetHandler = PacketDummyClient.instance; + this.packetHandler = PacketHandlerDummyClient.instance; } - public void setPacketHandler(@Nonnull IForestryPacketClient packetHandler) { + public void setPacketHandler(@Nonnull IForestryPacketHandlerClient packetHandler) { this.packetHandler = packetHandler; } @Nonnull - public IForestryPacketClient getPacketHandler() { + public IForestryPacketHandlerClient getPacketHandler() { return packetHandler; } } diff --git a/src/main/java/forestry/core/network/PacketIdServer.java b/src/main/java/forestry/core/network/PacketIdServer.java index a48c5608d..add47b9f3 100644 --- a/src/main/java/forestry/core/network/PacketIdServer.java +++ b/src/main/java/forestry/core/network/PacketIdServer.java @@ -12,7 +12,7 @@ package forestry.core.network; import javax.annotation.Nonnull; -import forestry.core.network.packets.PacketDummyServer; +import forestry.core.network.packets.PacketHandlerDummyServer; /** Packets sent to the server from the client */ public enum PacketIdServer implements IPacketId { @@ -42,18 +42,18 @@ public enum PacketIdServer implements IPacketId { public static final PacketIdServer[] VALUES = values(); @Nonnull - private IForestryPacketServer packetHandler; + private IForestryPacketHandlerServer packetHandler; PacketIdServer() { - this.packetHandler = PacketDummyServer.instance; + this.packetHandler = PacketHandlerDummyServer.instance; } - public void setPacketHandler(@Nonnull IForestryPacketServer packetHandler) { + public void setPacketHandler(@Nonnull IForestryPacketHandlerServer packetHandler) { this.packetHandler = packetHandler; } @Nonnull - public IForestryPacketServer getPacketHandler() { + public IForestryPacketHandlerServer getPacketHandler() { return packetHandler; } } diff --git a/src/main/java/forestry/core/network/PacketRegistry.java b/src/main/java/forestry/core/network/PacketRegistry.java deleted file mode 100644 index 4a2c72e74..000000000 --- a/src/main/java/forestry/core/network/PacketRegistry.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public abstract class PacketRegistry implements IPacketRegistry { - protected static void registerClientPacket(IForestryPacketClient packet) { - packet.getPacketId().setPacketHandler(packet); - } - - protected static void registerServerPacket(IForestryPacketServer packet) { - packet.getPacketId().setPacketHandler(packet); - } -} diff --git a/src/main/java/forestry/core/network/PacketRegistryCore.java b/src/main/java/forestry/core/network/PacketRegistryCore.java index 8e1784d52..bf910c6d4 100644 --- a/src/main/java/forestry/core/network/PacketRegistryCore.java +++ b/src/main/java/forestry/core/network/PacketRegistryCore.java @@ -30,28 +30,28 @@ import forestry.core.network.packets.PacketTankLevelUpdate; import forestry.core.network.packets.PacketTileStream; import forestry.core.network.packets.PacketUpdateClimateControl; -public class PacketRegistryCore extends PacketRegistry { +public class PacketRegistryCore implements IPacketRegistry { @Override public void registerPackets() { - registerClientPacket(new PacketErrorUpdate()); - registerClientPacket(new PacketErrorUpdateEntity()); - registerClientPacket(new PacketGuiUpdate()); - registerClientPacket(new PacketGuiUpdateEntity()); - registerClientPacket(new PacketGuiLayoutSelect()); - registerClientPacket(new PacketGuiEnergy()); - registerClientPacket(new PacketSocketUpdate()); - registerClientPacket(new PacketTileStream()); - registerClientPacket(new PacketItemStackDisplay()); - registerClientPacket(new PacketFXSignal()); - registerClientPacket(new PacketTankLevelUpdate()); - registerClientPacket(new PacketGenomeTrackerSync()); - registerClientPacket(new PacketCamouflageSelectClient()); + PacketIdClient.ERROR_UPDATE.setPacketHandler(new PacketErrorUpdate.Handler()); + PacketIdClient.ERROR_UPDATE_ENTITY.setPacketHandler(new PacketErrorUpdateEntity.Handler()); + PacketIdClient.GUI_UPDATE.setPacketHandler(new PacketGuiUpdate.Handler()); + PacketIdClient.GUI_UPDATE_ENTITY.setPacketHandler(new PacketGuiUpdateEntity.Handler()); + PacketIdClient.GUI_LAYOUT_SELECT.setPacketHandler(new PacketGuiLayoutSelect.Handler()); + PacketIdClient.GUI_ENERGY.setPacketHandler(new PacketGuiEnergy.Handler()); + PacketIdClient.SOCKET_UPDATE.setPacketHandler(new PacketSocketUpdate.Handler()); + PacketIdClient.TILE_FORESTRY_UPDATE.setPacketHandler(new PacketTileStream.Handler()); + PacketIdClient.ITEMSTACK_DISPLAY.setPacketHandler(new PacketItemStackDisplay.Handler()); + PacketIdClient.FX_SIGNAL.setPacketHandler(new PacketFXSignal.Handler()); + PacketIdClient.TANK_LEVEL_UPDATE.setPacketHandler(new PacketTankLevelUpdate.Handler()); + PacketIdClient.GENOME_TRACKER_UPDATE.setPacketHandler(new PacketGenomeTrackerSync.Handler()); + PacketIdClient.CAMOUFLAGE_SELECTION.setPacketHandler(new PacketCamouflageSelectClient.Handler()); - registerServerPacket(new PacketGuiSelectRequest()); - registerServerPacket(new PacketPipetteClick()); - registerServerPacket(new PacketChipsetClick()); - registerServerPacket(new PacketSolderingIronClick()); - registerServerPacket(new PacketCamouflageSelectServer()); - registerServerPacket(new PacketUpdateClimateControl()); + PacketIdServer.GUI_SELECTION_REQUEST.setPacketHandler(new PacketGuiSelectRequest.Handler()); + PacketIdServer.PIPETTE_CLICK.setPacketHandler(new PacketPipetteClick.Handler()); + PacketIdServer.CHIPSET_CLICK.setPacketHandler(new PacketChipsetClick.Handler()); + PacketIdServer.SOLDERING_IRON_CLICK.setPacketHandler(new PacketSolderingIronClick.Handler()); + PacketIdServer.CAMOUFLAGE_SELECTION.setPacketHandler(new PacketCamouflageSelectServer.Handler()); + PacketIdServer.CLIMATE_CONTROL_UPDATE.setPacketHandler(new PacketUpdateClimateControl.Handler()); } } diff --git a/src/main/java/forestry/core/network/PacketRegistryDummy.java b/src/main/java/forestry/core/network/PacketRegistryDummy.java deleted file mode 100644 index 3aadef49a..000000000 --- a/src/main/java/forestry/core/network/PacketRegistryDummy.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network; - -public class PacketRegistryDummy implements IPacketRegistry { - public static final PacketRegistryDummy instance = new PacketRegistryDummy(); - - private PacketRegistryDummy() { - - } - - @Override - public void registerPackets() { - - } -} diff --git a/src/main/java/forestry/core/network/package-info.java b/src/main/java/forestry/core/network/package-info.java new file mode 100644 index 000000000..05e9eb8f3 --- /dev/null +++ b/src/main/java/forestry/core/network/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.network; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/network/packets/PacketCamouflageSelectClient.java b/src/main/java/forestry/core/network/packets/PacketCamouflageSelectClient.java index ef5864cab..caeb5939b 100644 --- a/src/main/java/forestry/core/network/packets/PacketCamouflageSelectClient.java +++ b/src/main/java/forestry/core/network/packets/PacketCamouflageSelectClient.java @@ -12,29 +12,28 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflagedTile; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockController; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -public class PacketCamouflageSelectClient extends PacketCoordinates implements IForestryPacketClient{ +public class PacketCamouflageSelectClient extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final ItemStack camouflageStack; + private final String camouflageType; + private final CamouflageSelectionType selectionType; - private ItemStack camouflageStack; - private String camouflageType; - private CamouflageSelectionType selectionType; - - public PacketCamouflageSelectClient() { - } - public PacketCamouflageSelectClient(ICamouflageHandler handler, String camouflageType, CamouflageSelectionType selectionType) { - super(handler.getCoordinates()); + this.pos = handler.getCoordinates(); this.camouflageStack = handler.getCamouflageBlock(camouflageType); this.selectionType = selectionType; this.camouflageType = camouflageType; @@ -46,53 +45,48 @@ public class PacketCamouflageSelectClient extends PacketCoordinates implements I } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeShort(selectionType.ordinal()); - data.writeBoolean(camouflageType != null); - if(camouflageType != null){ - data.writeUTF(camouflageType); - } + data.writeString(camouflageType); data.writeItemStack(camouflageStack); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - selectionType = CamouflageSelectionType.values()[data.readShort()]; - if(data.readBoolean()){ - camouflageType = data.readUTF(); - } - camouflageStack = data.readItemStack(); - } + public static class Handler implements IForestryPacketHandlerClient { - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) { - TileEntity tile = getTarget(player.worldObj); - ICamouflageHandler handler = null; - if(selectionType == CamouflageSelectionType.MULTIBLOCK){ - if (tile instanceof IMultiblockComponent) { - IMultiblockController controller = ((IMultiblockComponent) tile).getMultiblockLogic().getController(); - - if (controller instanceof ICamouflageHandler) { - handler = (ICamouflageHandler) controller; - if(handler.setCamouflageBlock(camouflageType, camouflageStack, false)){ - for (IMultiblockComponent comp : controller.getComponents()) { - if (comp instanceof ICamouflagedTile) { - ICamouflagedTile camBlock = (ICamouflagedTile) comp; - if (camouflageType != null && camBlock.getCamouflageType() != null && camBlock.getCamouflageType().equals(camouflageType)) { - player.worldObj.markBlockRangeForRenderUpdate(camBlock.getCoordinates(), camBlock.getCoordinates()); + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + CamouflageSelectionType selectionType = CamouflageSelectionType.values()[data.readShort()]; + String camouflageType = data.readString(); + ItemStack camouflageStack = data.readItemStack(); + + TileEntity tile = player.world.getTileEntity(pos); + ICamouflageHandler handler; + if (selectionType == CamouflageSelectionType.MULTIBLOCK) { + if (tile instanceof IMultiblockComponent) { + IMultiblockController controller = ((IMultiblockComponent) tile).getMultiblockLogic().getController(); + + if (controller instanceof ICamouflageHandler) { + handler = (ICamouflageHandler) controller; + if (handler.setCamouflageBlock(camouflageType, camouflageStack, false)) { + for (IMultiblockComponent comp : controller.getComponents()) { + if (comp instanceof ICamouflagedTile) { + ICamouflagedTile camBlock = (ICamouflagedTile) comp; + if (camBlock.getCamouflageType().equals(camouflageType)) { + player.world.markBlockRangeForRenderUpdate(camBlock.getCoordinates(), camBlock.getCoordinates()); + } } } } } } - } - }else if(selectionType == CamouflageSelectionType.TILE){ - if (tile instanceof ICamouflageHandler) { - handler = (ICamouflageHandler) tile; - if(handler.setCamouflageBlock(camouflageType, camouflageStack, false)){ - player.worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + } else if (selectionType == CamouflageSelectionType.TILE) { + if (tile instanceof ICamouflageHandler) { + handler = (ICamouflageHandler) tile; + if (handler.setCamouflageBlock(camouflageType, camouflageStack, false)) { + player.world.markBlockRangeForRenderUpdate(pos, pos); + } } } } diff --git a/src/main/java/forestry/core/network/packets/PacketCamouflageSelectServer.java b/src/main/java/forestry/core/network/packets/PacketCamouflageSelectServer.java index 9b3f6cf0f..1f98d77b1 100644 --- a/src/main/java/forestry/core/network/packets/PacketCamouflageSelectServer.java +++ b/src/main/java/forestry/core/network/packets/PacketCamouflageSelectServer.java @@ -12,31 +12,30 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; import forestry.api.core.ICamouflageHandler; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockController; import forestry.core.gui.ContainerCamouflageSprayCan; import forestry.core.inventory.ItemInventoryCamouflageSprayCan; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; import forestry.core.proxy.Proxies; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -public class PacketCamouflageSelectServer extends PacketCoordinates implements IForestryPacketServer{ +public class PacketCamouflageSelectServer extends ForestryPacket implements IForestryPacketServer { + private final BlockPos pos; + private final ItemStack camouflageStack; + private final String camouflageType; + private final CamouflageSelectionType selectionType; - private ItemStack camouflageStack; - private String camouflageType; - private CamouflageSelectionType selectionType; - - public PacketCamouflageSelectServer() { - } - public PacketCamouflageSelectServer(ICamouflageHandler handler, String camouflageType, CamouflageSelectionType selectionType) { - super(handler.getCoordinates()); + this.pos = handler.getCoordinates(); this.camouflageStack = handler.getCamouflageBlock(camouflageType); this.selectionType = selectionType; this.camouflageType = camouflageType; @@ -48,56 +47,51 @@ public class PacketCamouflageSelectServer extends PacketCoordinates implements I } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeShort(selectionType.ordinal()); - data.writeBoolean(camouflageType != null); - if(camouflageType != null){ - data.writeUTF(camouflageType); - } + data.writeString(camouflageType); data.writeItemStack(camouflageStack); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - selectionType = CamouflageSelectionType.values()[data.readShort()]; - if(data.readBoolean()){ - camouflageType = data.readUTF(); - } - camouflageStack = data.readItemStack(); - } + public static class Handler implements IForestryPacketHandlerServer { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + BlockPos pos = data.readBlockPos(); + CamouflageSelectionType selectionType = CamouflageSelectionType.values()[data.readShort()]; + String camouflageType = data.readString(); + ItemStack camouflageStack = data.readItemStack(); + + TileEntity tile = player.world.getTileEntity(pos); + ICamouflageHandler handler = null; + if (selectionType == CamouflageSelectionType.MULTIBLOCK) { + if (tile instanceof IMultiblockComponent) { + IMultiblockController controller = ((IMultiblockComponent) tile).getMultiblockLogic().getController(); + + if (controller instanceof ICamouflageHandler) { + handler = (ICamouflageHandler) controller; + } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) { - TileEntity tile = getTarget(player.worldObj); - ICamouflageHandler handler = null; - if(selectionType == CamouflageSelectionType.MULTIBLOCK){ - if (tile instanceof IMultiblockComponent) { - IMultiblockController controller = ((IMultiblockComponent) tile).getMultiblockLogic().getController(); - - if (controller instanceof ICamouflageHandler) { - handler = (ICamouflageHandler) controller; } - - } - }else if(selectionType == CamouflageSelectionType.TILE){ - if (tile instanceof ICamouflageHandler) { - handler = (ICamouflageHandler) tile; - } - }else{ - if(player.openContainer instanceof ContainerCamouflageSprayCan){ - ContainerCamouflageSprayCan container = (ContainerCamouflageSprayCan) player.openContainer; - ItemInventoryCamouflageSprayCan itemInventoryCamouflageSprayCan = container.getItemInventory(); - if(itemInventoryCamouflageSprayCan != null){ - handler = itemInventoryCamouflageSprayCan; + } else if (selectionType == CamouflageSelectionType.TILE) { + if (tile instanceof ICamouflageHandler) { + handler = (ICamouflageHandler) tile; + } + } else { + if (player.openContainer instanceof ContainerCamouflageSprayCan) { + ContainerCamouflageSprayCan container = (ContainerCamouflageSprayCan) player.openContainer; + ItemInventoryCamouflageSprayCan itemInventoryCamouflageSprayCan = container.getItemInventory(); + if (!itemInventoryCamouflageSprayCan.isEmpty()) { + handler = itemInventoryCamouflageSprayCan; + } } } - } - - if (handler != null) { - if(handler.setCamouflageBlock(camouflageType, camouflageStack, true) && selectionType != CamouflageSelectionType.ITEM){ - Proxies.net.sendNetworkPacket(new PacketCamouflageSelectClient(handler, camouflageType, selectionType), player.worldObj); + + if (handler != null) { + if (handler.setCamouflageBlock(camouflageType, camouflageStack, true) && selectionType != CamouflageSelectionType.ITEM) { + Proxies.net.sendNetworkPacket(new PacketCamouflageSelectClient(handler, camouflageType, selectionType), pos, player.world); + } } } } diff --git a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java index 449d16082..90777c3b6 100644 --- a/src/main/java/forestry/core/network/packets/PacketChipsetClick.java +++ b/src/main/java/forestry/core/network/packets/PacketChipsetClick.java @@ -12,40 +12,44 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; - import forestry.core.circuits.ItemCircuitBoard; import forestry.core.gui.IContainerSocketed; -import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; -public class PacketChipsetClick extends PacketSlotClick implements IForestryPacketServer { +public class PacketChipsetClick extends ForestryPacket implements IForestryPacketServer { + private final int slot; - public PacketChipsetClick() { - } - - public PacketChipsetClick(TileEntity tile, int slot) { - super(tile, slot); + public PacketChipsetClick(int slot) { + this.slot = slot; } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof IContainerSocketed)) { - return; - } - ItemStack itemstack = player.inventory.getItemStack(); - if (!(itemstack.getItem() instanceof ItemCircuitBoard)) { - return; - } - - ((IContainerSocketed) player.openContainer).handleChipsetClickServer(getSlot(), player, itemstack); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeVarInt(slot); } @Override public PacketIdServer getPacketId() { return PacketIdServer.CHIPSET_CLICK; } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + int slot = data.readVarInt(); + + if (player.openContainer instanceof IContainerSocketed) { + ItemStack itemstack = player.inventory.getItemStack(); + if (itemstack.getItem() instanceof ItemCircuitBoard) { + ((IContainerSocketed) player.openContainer).handleChipsetClickServer(slot, player, itemstack); + } + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketCoordinates.java b/src/main/java/forestry/core/network/packets/PacketCoordinates.java deleted file mode 100644 index ad3c07092..000000000 --- a/src/main/java/forestry/core/network/packets/PacketCoordinates.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; -import forestry.core.network.ILocatedPacket; - -public abstract class PacketCoordinates extends ForestryPacket implements ILocatedPacket { - - private BlockPos pos; - - public PacketCoordinates() { - } - - protected PacketCoordinates(TileEntity tileEntity) { - this(tileEntity.getPos()); - } - - protected PacketCoordinates(BlockPos pos) { - this.pos = pos; - } - - protected PacketCoordinates(int posX, int posY, int posZ) { - this(new BlockPos(posX, posY, posX)); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - data.writeVarInt(getPos().getX()); - data.writeVarInt(getPos().getY()); - data.writeVarInt(getPos().getZ()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - int posX = data.readVarInt(); - int posY = data.readVarInt(); - int posZ = data.readVarInt(); - pos = new BlockPos(posX, posY, posZ); - } - - @Override - public BlockPos getPos() { - return pos; - } - - public final TileEntity getTarget(World world) { - return world.getTileEntity(pos); - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketDummyClient.java b/src/main/java/forestry/core/network/packets/PacketDummyClient.java deleted file mode 100644 index 42ba5ef85..000000000 --- a/src/main/java/forestry/core/network/packets/PacketDummyClient.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketDummyClient extends PacketDummy implements IForestryPacketClient { - public static final PacketDummyClient instance = new PacketDummyClient(); - - private PacketDummyClient() { - - } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.INVALID; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java b/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java deleted file mode 100644 index 1e0c76c85..000000000 --- a/src/main/java/forestry/core/network/packets/PacketEntityUpdate.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.Entity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; -import forestry.core.network.ILocatedPacket; - -public abstract class PacketEntityUpdate extends ForestryPacket implements ILocatedPacket { - // sending - private Entity entity; - // receiving - private int entityId; - - public PacketEntityUpdate() { - } - - public PacketEntityUpdate(Entity entity) { - this.entity = entity; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(entity.getEntityId()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - entityId = data.readVarInt(); - } - - public Entity getTarget(World world) { - return world.getEntityByID(entityId); - } - - @Override - public BlockPos getPos() { - return entity.getPosition(); - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java index cac3a74d3..c9f8e139b 100644 --- a/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketErrorUpdate.java @@ -12,47 +12,49 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; +import net.minecraft.util.math.BlockPos; -public class PacketErrorUpdate extends PacketCoordinates implements IForestryPacketClient { - - private IErrorLogic errorLogic; - - public PacketErrorUpdate() { - } +public class PacketErrorUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final IErrorLogic errorLogic; public PacketErrorUpdate(TileEntity tile, IErrorLogicSource errorLogicSource) { - super(tile); + this.pos = tile.getPos(); this.errorLogic = errorLogicSource.getErrorLogic(); } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); errorLogic.writeData(data); } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IErrorLogicSource) { - IErrorLogicSource errorSourceTile = (IErrorLogicSource) tile; - errorLogic = errorSourceTile.getErrorLogic(); - errorLogic.readData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.ERROR_UPDATE; } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof IErrorLogicSource) { + IErrorLogicSource errorSourceTile = (IErrorLogicSource) tile; + IErrorLogic errorLogic = errorSourceTile.getErrorLogic(); + errorLogic.readData(data); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java b/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java index 93399c9a1..bd2d06fc4 100644 --- a/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketErrorUpdateEntity.java @@ -12,46 +12,45 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.api.core.IErrorLogic; +import forestry.api.core.IErrorLogicSource; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; -import forestry.api.core.IErrorLogic; -import forestry.api.core.IErrorLogicSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketErrorUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { - private IErrorLogic errorLogic; - - public PacketErrorUpdateEntity() { - } +public class PacketErrorUpdateEntity extends ForestryPacket implements IForestryPacketClient { + private final Entity entity; + private final IErrorLogic errorLogic; public PacketErrorUpdateEntity(Entity entity, IErrorLogicSource errorLogicSource) { - super(entity); + this.entity = entity; this.errorLogic = errorLogicSource.getErrorLogic(); } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - errorLogic.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(Proxies.common.getRenderWorld()); - if (entity instanceof IErrorLogicSource) { - IErrorLogicSource errorSourceTile = (IErrorLogicSource) entity; - errorLogic = errorSourceTile.getErrorLogic(); - errorLogic.readData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.ERROR_UPDATE_ENTITY; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeEntityById(entity); + errorLogic.writeData(data); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + Entity entity = data.readEntityById(player.world); + if (entity instanceof IErrorLogicSource) { + IErrorLogicSource errorSourceTile = (IErrorLogicSource) entity; + IErrorLogic errorLogic = errorSourceTile.getErrorLogic(); + errorLogic.readData(data); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketFXSignal.java b/src/main/java/forestry/core/network/packets/PacketFXSignal.java index 85e06c377..af1142e1f 100644 --- a/src/main/java/forestry/core/network/packets/PacketFXSignal.java +++ b/src/main/java/forestry/core/network/packets/PacketFXSignal.java @@ -12,6 +12,12 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import forestry.core.proxy.Proxies; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; @@ -20,13 +26,7 @@ import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketFXSignal extends PacketCoordinates implements IForestryPacketClient { +public class PacketFXSignal extends ForestryPacket implements IForestryPacketClient { public enum VisualFXType { NONE, BLOCK_BREAK, SAPLING_PLACE @@ -36,13 +36,10 @@ public class PacketFXSignal extends PacketCoordinates implements IForestryPacket NONE, BLOCK_BREAK, BLOCK_PLACE; } - private VisualFXType visualFX; - private SoundFXType soundFX; - - private IBlockState blockState; - - public PacketFXSignal() { - } + private final BlockPos pos; + private final VisualFXType visualFX; + private final SoundFXType soundFX; + private final IBlockState blockState; public PacketFXSignal(VisualFXType type, BlockPos pos, IBlockState blockState) { this(type, SoundFXType.NONE, pos, blockState); @@ -53,15 +50,15 @@ public class PacketFXSignal extends PacketCoordinates implements IForestryPacket } public PacketFXSignal(VisualFXType visualFX, SoundFXType soundFX, BlockPos pos, IBlockState blockState) { - super(pos); + this.pos = pos; this.visualFX = visualFX; this.soundFX = soundFX; this.blockState = blockState; } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeByte(visualFX.ordinal()); data.writeByte(soundFX.ordinal()); Block block = blockState.getBlock(); @@ -69,38 +66,35 @@ public class PacketFXSignal extends PacketCoordinates implements IForestryPacket data.writeVarInt(block.getMetaFromState(blockState)); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - this.visualFX = VisualFXType.values()[data.readByte()]; - this.soundFX = SoundFXType.values()[data.readByte()]; - Block block = Block.getBlockById(data.readVarInt()); - this.blockState = block.getStateFromMeta(data.readVarInt()); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - World world = player.getEntityWorld(); - BlockPos pos = getPos(); - - if (visualFX == VisualFXType.BLOCK_BREAK) { - Proxies.common.addBlockDestroyEffects(world, pos, blockState); - } - - if (soundFX != SoundFXType.NONE) { - Block block = blockState.getBlock(); - SoundType soundType = block.getSoundType(); - - if (soundFX == SoundFXType.BLOCK_BREAK) { - world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, soundType.getBreakSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false); - } else if (soundFX == SoundFXType.BLOCK_PLACE) { - world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, soundType.getPlaceSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false); - } - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.FX_SIGNAL; } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + VisualFXType visualFX = VisualFXType.values()[data.readByte()]; + SoundFXType soundFX = SoundFXType.values()[data.readByte()]; + Block block = Block.getBlockById(data.readVarInt()); + IBlockState blockState = block.getStateFromMeta(data.readVarInt()); + + World world = player.world; + + if (visualFX == VisualFXType.BLOCK_BREAK) { + Proxies.common.addBlockDestroyEffects(world, pos, blockState); + } + + if (soundFX != SoundFXType.NONE) { + SoundType soundType = block.getSoundType(blockState, world, pos, null); + + if (soundFX == SoundFXType.BLOCK_BREAK) { + world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, soundType.getBreakSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false); + } else if (soundFX == SoundFXType.BLOCK_PLACE) { + world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, soundType.getPlaceSound(), SoundCategory.BLOCKS, (soundType.getVolume() + 1.0F) / 2.0F, soundType.getPitch() * 0.8F, false); + } + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java index cbb881ef1..051181eea 100644 --- a/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java +++ b/src/main/java/forestry/core/network/packets/PacketGenomeTrackerSync.java @@ -12,46 +12,51 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.common.MinecraftForge; - import forestry.api.core.ForestryEvent; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IBreedingTracker; import forestry.api.genetics.ISpeciesRoot; import forestry.core.genetics.BreedingTracker; -import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.MinecraftForge; -public class PacketGenomeTrackerSync extends PacketNBT implements IForestryPacketClient { - - public PacketGenomeTrackerSync() { - } +public class PacketGenomeTrackerSync extends ForestryPacket implements IForestryPacketClient { + private final NBTTagCompound nbt; public PacketGenomeTrackerSync(NBTTagCompound nbtTagCompound) { - super(nbtTagCompound); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - IBreedingTracker tracker = null; - String type = getTagCompound().getString(BreedingTracker.TYPE_KEY); - - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(type); - if (root != null && player != null) { - tracker = root.getBreedingTracker(player.getEntityWorld(), player.getGameProfile()); - } - if (tracker != null) { - tracker.decodeFromNBT(getTagCompound()); - MinecraftForge.EVENT_BUS.post(new ForestryEvent.SyncedBreedingTracker(tracker, player)); - } + this.nbt = nbtTagCompound; } @Override public PacketIdClient getPacketId() { return PacketIdClient.GENOME_TRACKER_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeCompoundTag(nbt); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + NBTTagCompound nbt = data.readCompoundTag(); + if (nbt != null) { + String type = nbt.getString(BreedingTracker.TYPE_KEY); + + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(type); + if (root != null) { + IBreedingTracker tracker = root.getBreedingTracker(player.getEntityWorld(), player.getGameProfile()); + tracker.decodeFromNBT(nbt); + MinecraftForge.EVENT_BUS.post(new ForestryEvent.SyncedBreedingTracker(tracker, player)); + } + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java index ea3f37c42..9cccb30e6 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiEnergy.java @@ -12,22 +12,17 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; - import forestry.core.gui.ContainerTile; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; +import net.minecraft.entity.player.EntityPlayer; public class PacketGuiEnergy extends ForestryPacket implements IForestryPacketClient { - - private int windowId; - private int value; - - public PacketGuiEnergy() { - } + private final int windowId; + private final int value; public PacketGuiEnergy(int windowId, int value) { this.windowId = windowId; @@ -35,26 +30,24 @@ public class PacketGuiEnergy extends ForestryPacket implements IForestryPacketCl } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public PacketIdClient getPacketId() { + return PacketIdClient.GUI_ENERGY; + } + + @Override + public void writeData(PacketBufferForestry data) throws IOException { data.writeVarInt(windowId); data.writeVarInt(value); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - windowId = data.readVarInt(); - value = data.readVarInt(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - if (player.openContainer instanceof ContainerTile && player.openContainer.windowId == windowId) { - ((ContainerTile) player.openContainer).onGuiEnergy(value); + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + int windowId = data.readVarInt(); + int value = data.readVarInt(); + if (player.openContainer instanceof ContainerTile && player.openContainer.windowId == windowId) { + ((ContainerTile) player.openContainer).onGuiEnergy(value); + } } } - - @Override - public PacketIdClient getPacketId() { - return PacketIdClient.GUI_ENERGY; - } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java index d54205b90..842dee8fe 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiLayoutSelect.java @@ -12,35 +12,42 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.circuits.ContainerSolderingIron; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; -import forestry.core.circuits.ContainerSolderingIron; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; - -public class PacketGuiLayoutSelect extends PacketString implements IForestryPacketClient { - - public PacketGuiLayoutSelect() { - } +public class PacketGuiLayoutSelect extends ForestryPacket implements IForestryPacketClient { + private final String string; public PacketGuiLayoutSelect(String string) { - super(string); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof ContainerSolderingIron)) { - return; - } - - ((ContainerSolderingIron) container).setLayout(getString()); + this.string = string; } @Override public PacketIdClient getPacketId() { return PacketIdClient.GUI_LAYOUT_SELECT; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeString(string); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + String string = data.readString(); + Container container = player.openContainer; + if (!(container instanceof ContainerSolderingIron)) { + return; + } + + ((ContainerSolderingIron) container).setLayout(string); + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiSelect.java b/src/main/java/forestry/core/network/packets/PacketGuiSelect.java deleted file mode 100644 index ebff74529..000000000 --- a/src/main/java/forestry/core/network/packets/PacketGuiSelect.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; - -public abstract class PacketGuiSelect extends ForestryPacket { - private int primaryIndex; - private int secondaryIndex; - - protected PacketGuiSelect() { - } - - protected PacketGuiSelect(int primaryIndex, int secondaryIndex) { - this.primaryIndex = primaryIndex; - this.secondaryIndex = secondaryIndex; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(primaryIndex); - data.writeVarInt(secondaryIndex); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - primaryIndex = data.readVarInt(); - secondaryIndex = data.readVarInt(); - } - - public int getPrimaryIndex() { - return primaryIndex; - } - - public int getSecondaryIndex() { - return secondaryIndex; - } - -} diff --git a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java index fb3d97f17..822ece664 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiSelectRequest.java @@ -12,35 +12,46 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.gui.IGuiSelectable; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdServer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; -import forestry.core.gui.IGuiSelectable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketGuiSelectRequest extends PacketGuiSelect implements IForestryPacketServer { - - public PacketGuiSelectRequest() { - } +public class PacketGuiSelectRequest extends ForestryPacket implements IForestryPacketServer { + private final int primaryIndex; + private final int secondaryIndex; public PacketGuiSelectRequest(int primaryIndex, int secondaryIndex) { - super(primaryIndex, secondaryIndex); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - Container container = player.openContainer; - if (!(container instanceof IGuiSelectable)) { - return; - } - - ((IGuiSelectable) container).handleSelectionRequest(player, this); + this.primaryIndex = primaryIndex; + this.secondaryIndex = secondaryIndex; } @Override public PacketIdServer getPacketId() { return PacketIdServer.GUI_SELECTION_REQUEST; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeVarInt(primaryIndex); + data.writeVarInt(secondaryIndex); + } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + int primary = data.readVarInt(); + int secondary = data.readVarInt(); + + Container container = player.openContainer; + if ((container instanceof IGuiSelectable)) { + IGuiSelectable guiSelectable = (IGuiSelectable) container; + guiSelectable.handleSelectionRequest(player, primary, secondary); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java b/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java index 2f360aa3a..6c4311b15 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiUpdate.java @@ -13,45 +13,45 @@ package forestry.core.network.packets; import java.io.IOException; import forestry.api.core.ILocatable; - +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IStreamableGui; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketGuiUpdate extends PacketCoordinates implements IForestryPacketClient { - - private IStreamableGui guiDataTile; - - public PacketGuiUpdate() { - } +public class PacketGuiUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final IStreamableGui guiDataTile; public PacketGuiUpdate(T guiDataTile) { - super(guiDataTile.getCoordinates()); + this.pos = guiDataTile.getCoordinates(); this.guiDataTile = guiDataTile; } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); guiDataTile.writeGuiData(data); } - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IStreamableGui) { - ((IStreamableGui) tile).readGuiData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.GUI_UPDATE; } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof IStreamableGui) { + ((IStreamableGui) tile).readGuiData(data); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java b/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java index 57bb9c164..7722b8eed 100644 --- a/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java +++ b/src/main/java/forestry/core/network/packets/PacketGuiUpdateEntity.java @@ -12,42 +12,42 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IStreamableGui; -import forestry.core.network.PacketIdClient; - -public class PacketGuiUpdateEntity extends PacketEntityUpdate implements IForestryPacketClient { - private IStreamableGui streamableGui; - - public PacketGuiUpdateEntity() { - } +public class PacketGuiUpdateEntity extends ForestryPacket implements IForestryPacketClient { + private final Entity entity; + private final IStreamableGui streamableGui; public PacketGuiUpdateEntity(IStreamableGui streamableGui, Entity entity) { - super(entity); + this.entity = entity; this.streamableGui = streamableGui; } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - streamableGui.writeGuiData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Entity entity = getTarget(player.getEntityWorld()); - if (entity instanceof IStreamableGui) { - ((IStreamableGui) entity).readGuiData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.GUI_UPDATE_ENTITY; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeEntityById(entity); + streamableGui.writeGuiData(data); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + Entity entity = data.readEntityById(player.world); + if (entity instanceof IStreamableGui) { + ((IStreamableGui) entity).readGuiData(data); + } + } + } } diff --git a/src/main/java/forestry/core/network/ILocatedPacket.java b/src/main/java/forestry/core/network/packets/PacketHandlerDummy.java old mode 100755 new mode 100644 similarity index 73% rename from src/main/java/forestry/core/network/ILocatedPacket.java rename to src/main/java/forestry/core/network/packets/PacketHandlerDummy.java index 1a52f0f4c..8d9a67370 --- a/src/main/java/forestry/core/network/ILocatedPacket.java +++ b/src/main/java/forestry/core/network/packets/PacketHandlerDummy.java @@ -8,10 +8,12 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.core.network; +package forestry.core.network.packets; -import net.minecraft.util.math.BlockPos; +import forestry.core.network.IForestryPacketHandler; -public interface ILocatedPacket { - BlockPos getPos(); +public abstract class PacketHandlerDummy implements IForestryPacketHandler { + protected PacketHandlerDummy() { + + } } diff --git a/src/main/java/forestry/core/network/packets/PacketDummy.java b/src/main/java/forestry/core/network/packets/PacketHandlerDummyClient.java similarity index 57% rename from src/main/java/forestry/core/network/packets/PacketDummy.java rename to src/main/java/forestry/core/network/packets/PacketHandlerDummyClient.java index 71f47fa4e..15197f517 100644 --- a/src/main/java/forestry/core/network/packets/PacketDummy.java +++ b/src/main/java/forestry/core/network/packets/PacketHandlerDummyClient.java @@ -1,35 +1,28 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraftforge.fml.common.network.internal.FMLProxyPacket; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacket; - -public abstract class PacketDummy implements IForestryPacket { - protected PacketDummy() { - - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - - } - - @Override - public FMLProxyPacket getPacket() { - return null; - } - -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.entity.player.EntityPlayer; + +public class PacketHandlerDummyClient extends PacketHandlerDummy implements IForestryPacketHandlerClient { + public static final PacketHandlerDummyClient instance = new PacketHandlerDummyClient(); + + private PacketHandlerDummyClient() { + + } + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) { + + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketDummyServer.java b/src/main/java/forestry/core/network/packets/PacketHandlerDummyServer.java similarity index 56% rename from src/main/java/forestry/core/network/packets/PacketDummyServer.java rename to src/main/java/forestry/core/network/packets/PacketHandlerDummyServer.java index 4c4c86ed9..38348306d 100644 --- a/src/main/java/forestry/core/network/packets/PacketDummyServer.java +++ b/src/main/java/forestry/core/network/packets/PacketHandlerDummyServer.java @@ -1,37 +1,30 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayerMP; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; - -public class PacketDummyServer extends PacketDummy implements IForestryPacketServer { - public static final PacketDummyServer instance = new PacketDummyServer(); - - private PacketDummyServer() { - - } - - @Override - public PacketIdServer getPacketId() { - return PacketIdServer.INVALID; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.core.network.packets; + +import java.io.IOException; + +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.entity.player.EntityPlayerMP; + +public class PacketHandlerDummyServer extends PacketHandlerDummy implements IForestryPacketHandlerServer { + public static final PacketHandlerDummyServer instance = new PacketHandlerDummyServer(); + + private PacketHandlerDummyServer() { + + } + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + + } +} diff --git a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java index 3e90e5427..fadcb9d4b 100644 --- a/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java +++ b/src/main/java/forestry/core/network/packets/PacketItemStackDisplay.java @@ -10,55 +10,50 @@ ******************************************************************************/ package forestry.core.network.packets; -import javax.annotation.Nullable; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import forestry.core.tiles.IItemStackDisplay; +import forestry.core.tiles.TileForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IItemStackDisplay; -import forestry.core.tiles.TileForestry; +public class PacketItemStackDisplay extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final ItemStack itemStack; -public class PacketItemStackDisplay extends PacketCoordinates implements IForestryPacketClient { - - private ItemStack itemStack; - - public PacketItemStackDisplay() { - } - - public PacketItemStackDisplay(T tile, @Nullable ItemStack itemStack) { - super(tile); + public PacketItemStackDisplay(T tile, ItemStack itemStack) { + this.pos = tile.getPos(); this.itemStack = itemStack; } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeItemStack(itemStack); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - itemStack = data.readItemStack(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IItemStackDisplay) { - ((IItemStackDisplay) tile).handleItemStackForDisplay(itemStack); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.ITEMSTACK_DISPLAY; } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + ItemStack itemStack = data.readItemStack(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof IItemStackDisplay) { + ((IItemStackDisplay) tile).handleItemStackForDisplay(itemStack); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketNBT.java b/src/main/java/forestry/core/network/packets/PacketNBT.java deleted file mode 100644 index 6fd6652ff..000000000 --- a/src/main/java/forestry/core/network/packets/PacketNBT.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.nbt.NBTTagCompound; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; - -public abstract class PacketNBT extends ForestryPacket { - - private NBTTagCompound nbttagcompound; - - protected PacketNBT() { - } - - protected PacketNBT(NBTTagCompound nbttagcompound) { - this.nbttagcompound = nbttagcompound; - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - data.writeNBTTagCompound(nbttagcompound); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - this.nbttagcompound = data.readNBTTagCompound(); - } - - protected NBTTagCompound getTagCompound() { - return this.nbttagcompound; - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java index b143409b1..d33bdfbc4 100644 --- a/src/main/java/forestry/core/network/packets/PacketPipetteClick.java +++ b/src/main/java/forestry/core/network/packets/PacketPipetteClick.java @@ -12,32 +12,38 @@ package forestry.core.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; - import forestry.core.gui.IContainerLiquidTanks; -import forestry.core.network.DataInputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; +import net.minecraft.entity.player.EntityPlayerMP; -public class PacketPipetteClick extends PacketSlotClick implements IForestryPacketServer { +public class PacketPipetteClick extends ForestryPacket implements IForestryPacketServer { + private final int slot; - public PacketPipetteClick() { - } - - public PacketPipetteClick(TileEntity tile, int slot) { - super(tile, slot); + public PacketPipetteClick(int slot) { + this.slot = slot; } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (player.openContainer instanceof IContainerLiquidTanks) { - ((IContainerLiquidTanks) player.openContainer).handlePipetteClick(getSlot(), player); - } + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeVarInt(slot); } @Override public PacketIdServer getPacketId() { return PacketIdServer.PIPETTE_CLICK; } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + int slot = data.readVarInt(); + if (player.openContainer instanceof IContainerLiquidTanks) { + ((IContainerLiquidTanks) player.openContainer).handlePipetteClick(slot, player); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketSlotClick.java b/src/main/java/forestry/core/network/packets/PacketSlotClick.java deleted file mode 100644 index 31a189648..000000000 --- a/src/main/java/forestry/core/network/packets/PacketSlotClick.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; - -public abstract class PacketSlotClick extends PacketCoordinates { - private int slot; - - protected PacketSlotClick() { - } - - protected PacketSlotClick(TileEntity tile, int slot) { - super(tile); - this.slot = slot; - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - this.slot = data.readVarInt(); - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(slot); - } - - public int getSlot() { - return slot; - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java index 85f0c37b5..f72eb7702 100644 --- a/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketSocketUpdate.java @@ -12,55 +12,28 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.circuits.ISocketable; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; -import forestry.core.circuits.ISocketable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketSocketUpdate extends PacketCoordinates implements IForestryPacketClient { - - private ItemStack[] itemStacks; - - public PacketSocketUpdate() { - } +public class PacketSocketUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final NonNullList itemStacks; public PacketSocketUpdate(T tile) { - super(tile); + this.pos = tile.getPos(); - itemStacks = new ItemStack[tile.getSocketCount()]; + this.itemStacks = NonNullList.withSize(tile.getSocketCount(), ItemStack.EMPTY); for (int i = 0; i < tile.getSocketCount(); i++) { - itemStacks[i] = tile.getSocket(i); - } - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeItemStacks(itemStacks); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - itemStacks = data.readItemStacks(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (!(tile instanceof ISocketable)) { - return; - } - - ISocketable socketable = (ISocketable) tile; - for (int i = 0; i < itemStacks.length; i++) { - socketable.setSocket(i, itemStacks[i]); + this.itemStacks.set(i, tile.getSocket(i)); } } @@ -68,4 +41,26 @@ public class PacketSocketUpdate extends PacketCoordinates implements IForestryPa public PacketIdClient getPacketId() { return PacketIdClient.SOCKET_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeItemStacks(itemStacks); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + NonNullList itemStacks = data.readItemStacks(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof ISocketable) { + ISocketable socketable = (ISocketable) tile; + for (int i = 0; i < itemStacks.size(); i++) { + socketable.setSocket(i, itemStacks.get(i)); + } + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java index b8e50dcba..8b745fe6b 100644 --- a/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java +++ b/src/main/java/forestry/core/network/packets/PacketSolderingIronClick.java @@ -12,36 +12,43 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.gui.IContainerSocketed; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdServer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import forestry.core.gui.IContainerSocketed; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; +public class PacketSolderingIronClick extends ForestryPacket implements IForestryPacketServer { + private final int slot; -public class PacketSolderingIronClick extends PacketSlotClick implements IForestryPacketServer { - - public PacketSolderingIronClick() { - } - - public PacketSolderingIronClick(TileEntity tile, int slot) { - super(tile, slot); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof IContainerSocketed)) { - return; - } - ItemStack itemstack = player.inventory.getItemStack(); - - ((IContainerSocketed) player.openContainer).handleSolderingIronClickServer(getSlot(), player, itemstack); + public PacketSolderingIronClick(int slot) { + this.slot = slot; } @Override public PacketIdServer getPacketId() { return PacketIdServer.SOLDERING_IRON_CLICK; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeVarInt(slot); + } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + int slot = data.readVarInt(); + + if (!(player.openContainer instanceof IContainerSocketed)) { + return; + } + ItemStack itemstack = player.inventory.getItemStack(); + + ((IContainerSocketed) player.openContainer).handleSolderingIronClickServer(slot, player, itemstack); + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketString.java b/src/main/java/forestry/core/network/packets/PacketString.java deleted file mode 100644 index c3a910d0f..000000000 --- a/src/main/java/forestry/core/network/packets/PacketString.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.network.packets; - -import java.io.IOException; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.ForestryPacket; - -public abstract class PacketString extends ForestryPacket { - - private String string; - - protected PacketString() { - } - - protected PacketString(String string) { - this.string = string; - } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(string); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - string = data.readUTF(); - } - - public String getString() { - return string; - } -} diff --git a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java index 2442e5b9c..5e8bb92e9 100644 --- a/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java +++ b/src/main/java/forestry/core/network/packets/PacketTankLevelUpdate.java @@ -10,60 +10,58 @@ ******************************************************************************/ package forestry.core.network.packets; +import javax.annotation.Nullable; import java.io.IOException; +import forestry.core.fluids.ITankManager; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import forestry.core.tiles.ILiquidTankTile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; - +import net.minecraft.util.math.BlockPos; import net.minecraftforge.fluids.FluidStack; -import forestry.core.fluids.ITankManager; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.ILiquidTankTile; +public class PacketTankLevelUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final int tankIndex; + @Nullable + private final FluidStack contents; -public class PacketTankLevelUpdate extends PacketCoordinates implements IForestryPacketClient { - - private int tankIndex; - private FluidStack contents; - - public PacketTankLevelUpdate() { - } - - public PacketTankLevelUpdate(ILiquidTankTile tileEntity, int tankIndex, FluidStack contents) { - super(tileEntity.getCoordinates()); + public PacketTankLevelUpdate(ILiquidTankTile tileEntity, int tankIndex, @Nullable FluidStack contents) { + this.pos = tileEntity.getCoordinates(); this.tankIndex = tankIndex; this.contents = contents; } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeVarInt(tankIndex); - data.writeFluidStack(contents); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankIndex = data.readVarInt(); - contents = data.readFluidStack(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tileEntity = getTarget(Proxies.common.getRenderWorld()); - if (tileEntity instanceof ILiquidTankTile) { - ITankManager tankManager = ((ILiquidTankTile) tileEntity).getTankManager(); - tankManager.processTankUpdate(tankIndex, contents); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.TANK_LEVEL_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeVarInt(tankIndex); + data.writeFluidStack(contents); + } + + public static class Handler implements IForestryPacketHandlerClient { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + int tankIndex = data.readVarInt(); + FluidStack contents = data.readFluidStack(); + + TileEntity tileEntity = player.world.getTileEntity(pos); + if (tileEntity instanceof ILiquidTankTile) { + ITankManager tankManager = ((ILiquidTankTile) tileEntity).getTankManager(); + tankManager.processTankUpdate(tankIndex, contents); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketTileStream.java b/src/main/java/forestry/core/network/packets/PacketTileStream.java index 9d7a9c084..ab2e6cdec 100644 --- a/src/main/java/forestry/core/network/packets/PacketTileStream.java +++ b/src/main/java/forestry/core/network/packets/PacketTileStream.java @@ -12,44 +12,44 @@ package forestry.core.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.IStreamable; -import forestry.core.network.PacketIdClient; -import forestry.core.proxy.Proxies; - -public class PacketTileStream extends PacketCoordinates implements IForestryPacketClient { - - private IStreamable streamable; - - public PacketTileStream() { - } +public class PacketTileStream extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final IStreamable streamable; public PacketTileStream(T streamable) { - super(streamable); + this.pos = streamable.getPos(); this.streamable = streamable; } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - streamable.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof IStreamable) { - ((IStreamable) tile).readData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.TILE_FORESTRY_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) { + data.writeBlockPos(pos); + streamable.writeData(data); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof IStreamable) { + ((IStreamable) tile).readData(data); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/PacketUpdateClimateControl.java b/src/main/java/forestry/core/network/packets/PacketUpdateClimateControl.java index c0a120e90..32f194723 100644 --- a/src/main/java/forestry/core/network/packets/PacketUpdateClimateControl.java +++ b/src/main/java/forestry/core/network/packets/PacketUpdateClimateControl.java @@ -6,67 +6,63 @@ import forestry.api.climate.IClimateControl; import forestry.api.climate.IClimateControlProvider; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockLogic; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -public class PacketUpdateClimateControl extends PacketCoordinates implements IForestryPacketServer { +public class PacketUpdateClimateControl extends ForestryPacket implements IForestryPacketServer { + private final BlockPos pos; + private final float controlTemperature; + private final float controlHumidity; - private float controlTemperature; - private float controlHumidity; - - public PacketUpdateClimateControl() { - } - public PacketUpdateClimateControl(IClimateControlProvider provider) { - super(provider.getCoordinates()); - + pos = provider.getCoordinates(); + IClimateControl control = provider.getClimateControl(); controlTemperature = control.getControlTemperature(); controlHumidity = control.getControlHumidity(); } - - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - - data.writeFloat(controlTemperature); - data.writeFloat(controlHumidity); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - - controlTemperature = data.readFloat(); - controlHumidity = data.readFloat(); - } - + @Override public PacketIdServer getPacketId() { return PacketIdServer.CLIMATE_CONTROL_UPDATE; } - + @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - IClimateControl control = null; - if(tile instanceof IMultiblockComponent){ - IMultiblockComponent component = (IMultiblockComponent) tile; - IMultiblockLogic logic = component.getMultiblockLogic(); - if(logic.isConnected() && logic.getController() instanceof IClimateControlProvider){ - control = ((IClimateControlProvider) logic.getController()).getClimateControl(); - } - }else if(tile instanceof IClimateControlProvider){ - control = ((IClimateControlProvider) tile).getClimateControl(); - } - if(control != null){ - control.setControlTemperature(controlTemperature); - control.setControlHumidity(controlHumidity); - } + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeFloat(controlTemperature); + data.writeFloat(controlHumidity); } + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + BlockPos pos = data.readBlockPos(); + float controlTemperature = data.readFloat(); + float controlHumidity = data.readFloat(); + + TileEntity tile = player.world.getTileEntity(pos); + IClimateControl control = null; + if (tile instanceof IMultiblockComponent) { + IMultiblockComponent component = (IMultiblockComponent) tile; + IMultiblockLogic logic = component.getMultiblockLogic(); + if (logic.isConnected() && logic.getController() instanceof IClimateControlProvider) { + control = ((IClimateControlProvider) logic.getController()).getClimateControl(); + } + } else if (tile instanceof IClimateControlProvider) { + control = ((IClimateControlProvider) tile).getClimateControl(); + } + + if (control != null) { + control.setControlTemperature(controlTemperature); + control.setControlHumidity(controlHumidity); + } + } + } } diff --git a/src/main/java/forestry/core/network/packets/package-info.java b/src/main/java/forestry/core/network/packets/package-info.java new file mode 100644 index 000000000..aceae9cf3 --- /dev/null +++ b/src/main/java/forestry/core/network/packets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.network.packets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/owner/FakeOwnerHandler.java b/src/main/java/forestry/core/owner/FakeOwnerHandler.java index 979e5f63b..e4620956f 100644 --- a/src/main/java/forestry/core/owner/FakeOwnerHandler.java +++ b/src/main/java/forestry/core/owner/FakeOwnerHandler.java @@ -10,11 +10,12 @@ ******************************************************************************/ package forestry.core.owner; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import com.mojang.authlib.GameProfile; public class FakeOwnerHandler implements IOwnerHandler { + @Nullable private static FakeOwnerHandler instance; public static FakeOwnerHandler getInstance() { @@ -34,7 +35,7 @@ public class FakeOwnerHandler implements IOwnerHandler { } @Override - public void setOwner(@Nonnull GameProfile owner) { + public void setOwner(GameProfile owner) { } } diff --git a/src/main/java/forestry/core/owner/GameProfileDataSerializer.java b/src/main/java/forestry/core/owner/GameProfileDataSerializer.java index 562363ccd..401ce40c4 100644 --- a/src/main/java/forestry/core/owner/GameProfileDataSerializer.java +++ b/src/main/java/forestry/core/owner/GameProfileDataSerializer.java @@ -1,8 +1,8 @@ package forestry.core.owner; +import java.util.Optional; import java.util.UUID; -import com.google.common.base.Optional; import com.mojang.authlib.GameProfile; import net.minecraft.network.PacketBuffer; import net.minecraft.network.datasync.DataParameter; @@ -20,6 +20,7 @@ public class GameProfileDataSerializer implements DataSerializer value) { if (!value.isPresent()) { @@ -27,7 +28,7 @@ public class GameProfileDataSerializer implements DataSerializer read(PacketBuffer buf) { if (buf.readBoolean()) { - UUID uuid = buf.readUuid(); - String name = buf.readStringFromBuffer(1024); + UUID uuid = buf.readUniqueId(); + String name = buf.readString(1024); GameProfile gameProfile = new GameProfile(uuid, name); return Optional.of(gameProfile); } else { - return Optional.absent(); + return Optional.empty(); } } diff --git a/src/main/java/forestry/core/owner/IOwnerHandler.java b/src/main/java/forestry/core/owner/IOwnerHandler.java index 051513413..bd5c6ecdd 100644 --- a/src/main/java/forestry/core/owner/IOwnerHandler.java +++ b/src/main/java/forestry/core/owner/IOwnerHandler.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.owner; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.mojang.authlib.GameProfile; @@ -19,5 +18,5 @@ public interface IOwnerHandler { @Nullable GameProfile getOwner(); - void setOwner(@Nonnull GameProfile owner); + void setOwner(GameProfile owner); } diff --git a/src/main/java/forestry/core/owner/OwnerHandler.java b/src/main/java/forestry/core/owner/OwnerHandler.java index 88da89d93..8029f22d2 100644 --- a/src/main/java/forestry/core/owner/OwnerHandler.java +++ b/src/main/java/forestry/core/owner/OwnerHandler.java @@ -10,48 +10,49 @@ ******************************************************************************/ package forestry.core.owner; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.UUID; import com.mojang.authlib.GameProfile; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.utils.PlayerUtil; import net.minecraft.nbt.NBTTagCompound; public class OwnerHandler implements IOwnerHandler, IStreamable, INbtWritable, INbtReadable { + @Nullable private GameProfile owner = null; @Override + @Nullable public GameProfile getOwner() { return owner; } @Override - public void setOwner(@Nonnull GameProfile owner) { + public void setOwner(GameProfile owner) { this.owner = owner; } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { if (owner == null) { data.writeBoolean(false); } else { data.writeBoolean(true); data.writeLong(owner.getId().getMostSignificantBits()); data.writeLong(owner.getId().getLeastSignificantBits()); - data.writeUTF(owner.getName()); + data.writeString(owner.getName()); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { if (data.readBoolean()) { - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); + GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readString()); setOwner(owner); } } diff --git a/src/main/java/forestry/core/owner/package-info.java b/src/main/java/forestry/core/owner/package-info.java new file mode 100644 index 000000000..39b94f399 --- /dev/null +++ b/src/main/java/forestry/core/owner/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.owner; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/package-info.java b/src/main/java/forestry/core/package-info.java new file mode 100644 index 000000000..33ca3fcf3 --- /dev/null +++ b/src/main/java/forestry/core/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/proxy/Proxies.java b/src/main/java/forestry/core/proxy/Proxies.java index 6e2572c21..5a7cd10fc 100755 --- a/src/main/java/forestry/core/proxy/Proxies.java +++ b/src/main/java/forestry/core/proxy/Proxies.java @@ -13,10 +13,15 @@ package forestry.core.proxy; import net.minecraftforge.fml.common.SidedProxy; public class Proxies { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.core.proxy.ProxyClient", serverSide = "forestry.core.proxy.ProxyCommon") public static ProxyCommon common; + + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.core.proxy.ProxyNetworkClient", serverSide = "forestry.core.proxy.ProxyNetwork") public static ProxyNetwork net; + + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.core.proxy.ProxyRenderClient", serverSide = "forestry.core.proxy.ProxyRender") public static ProxyRender render; } diff --git a/src/main/java/forestry/core/proxy/ProxyClient.java b/src/main/java/forestry/core/proxy/ProxyClient.java index 35c081a2f..f6c655d74 100644 --- a/src/main/java/forestry/core/proxy/ProxyClient.java +++ b/src/main/java/forestry/core/proxy/ProxyClient.java @@ -35,6 +35,7 @@ import forestry.core.multiblock.MultiblockClientTickHandler; import forestry.core.render.TextureManager; import forestry.core.worldgen.WorldGenerator; +@SuppressWarnings("unused") public class ProxyClient extends ProxyCommon { @Override @@ -64,7 +65,7 @@ public class ProxyClient extends ProxyCommon { @Override public World getRenderWorld() { - return getClientInstance().theWorld; + return getClientInstance().world; } @Override @@ -93,7 +94,7 @@ public class ProxyClient extends ProxyCommon { @Override public EntityPlayer getPlayer() { - return Minecraft.getMinecraft().thePlayer; + return Minecraft.getMinecraft().player; } @Override diff --git a/src/main/java/forestry/core/proxy/ProxyNetwork.java b/src/main/java/forestry/core/proxy/ProxyNetwork.java index 105431c06..c998b55ef 100755 --- a/src/main/java/forestry/core/proxy/ProxyNetwork.java +++ b/src/main/java/forestry/core/proxy/ProxyNetwork.java @@ -13,6 +13,7 @@ package forestry.core.proxy; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.management.PlayerChunkMap; +import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.WorldServer; @@ -21,20 +22,19 @@ import net.minecraftforge.common.util.FakePlayer; import forestry.Forestry; import forestry.core.network.IForestryPacketClient; import forestry.core.network.IForestryPacketServer; -import forestry.core.network.ILocatedPacket; public class ProxyNetwork { - public

void sendNetworkPacket(P packet, World world) { - if (packet == null || !(world instanceof WorldServer)) { + public

void sendNetworkPacket(P packet, BlockPos pos, World world) { + if (!(world instanceof WorldServer)) { return; } WorldServer worldServer = (WorldServer) world; PlayerChunkMap playerManager = worldServer.getPlayerChunkMap(); - int chunkX = packet.getPos().getX() >> 4; - int chunkZ = packet.getPos().getZ() >> 4; + int chunkX = pos.getX() >> 4; + int chunkZ = pos.getZ() >> 4; for (Object playerObj : world.playerEntities) { if (playerObj instanceof EntityPlayerMP) { diff --git a/src/main/java/forestry/core/proxy/ProxyNetworkClient.java b/src/main/java/forestry/core/proxy/ProxyNetworkClient.java index 8a43af080..6a48659a9 100644 --- a/src/main/java/forestry/core/proxy/ProxyNetworkClient.java +++ b/src/main/java/forestry/core/proxy/ProxyNetworkClient.java @@ -14,6 +14,7 @@ import net.minecraft.client.network.NetHandlerPlayClient; import forestry.core.network.IForestryPacketServer; +@SuppressWarnings("unused") public class ProxyNetworkClient extends ProxyNetwork { @Override diff --git a/src/main/java/forestry/core/proxy/ProxyRenderClient.java b/src/main/java/forestry/core/proxy/ProxyRenderClient.java index 832aad75c..e079d7bdb 100644 --- a/src/main/java/forestry/core/proxy/ProxyRenderClient.java +++ b/src/main/java/forestry/core/proxy/ProxyRenderClient.java @@ -72,6 +72,7 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.common.animation.ITimeValue; import net.minecraftforge.common.model.animation.IAnimationStateMachine; +@SuppressWarnings("unused") public class ProxyRenderClient extends ProxyRender { @Override @@ -95,9 +96,6 @@ public class ProxyRenderClient extends ProxyRender { @Override public TileEntitySpecialRenderer getRenderDefaultMachine(String gfxBase) { - if (gfxBase == null) { - return null; - } return new RenderMachine(gfxBase); } @@ -319,10 +317,11 @@ public class ProxyRenderClient extends ProxyRender { float blue = (color & 255) / 255.0F; ParticleManager effectRenderer = Minecraft.getMinecraft().effectRenderer; - Particle Particle = effectRenderer.spawnEffectParticle(EnumParticleTypes.SPELL.getParticleID(), x, y, z, 0, 0, 0); - Particle.setRBGColorF(red, green, blue); - - effectRenderer.addEffect(Particle); + Particle particle = effectRenderer.spawnEffectParticle(EnumParticleTypes.SPELL.getParticleID(), x, y, z, 0, 0, 0); + if (particle != null) { + particle.setRBGColorF(red, green, blue); + effectRenderer.addEffect(particle); + } } private static class BlockModeStateMapper extends StateMapperBase { diff --git a/src/main/java/forestry/core/proxy/package-info.java b/src/main/java/forestry/core/proxy/package-info.java new file mode 100644 index 000000000..c115250f6 --- /dev/null +++ b/src/main/java/forestry/core/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/recipes/RecipeUtil.java b/src/main/java/forestry/core/recipes/RecipeUtil.java index 8ed0838cf..75c7aee25 100644 --- a/src/main/java/forestry/core/recipes/RecipeUtil.java +++ b/src/main/java/forestry/core/recipes/RecipeUtil.java @@ -10,11 +10,16 @@ ******************************************************************************/ package forestry.core.recipes; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.api.recipes.RecipeManagers; +import forestry.core.fluids.Fluids; +import forestry.core.utils.ItemStackUtil; +import forestry.factory.inventory.InventoryCraftingForestry; import net.minecraft.block.Block; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; @@ -22,28 +27,20 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.NonNullList; import net.minecraft.world.World; - import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapelessOreRecipe; -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.api.recipes.RecipeManagers; -import forestry.core.fluids.Fluids; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.Log; -import forestry.factory.inventory.InventoryCraftingForestry; - public abstract class RecipeUtil { public static void addFermenterRecipes(ItemStack resource, int fermentationValue, Fluids output) { if (RecipeManagers.fermenterManager == null) { return; } - + RecipeManagers.fermenterManager.addRecipe(resource, fermentationValue, 1.0f, output.getFluid(1), new FluidStack(FluidRegistry.WATER, 1)); if (FluidRegistry.isFluidRegistered(Fluids.JUICE.getFluid())) { @@ -55,47 +52,8 @@ public abstract class RecipeUtil { } } - /** - * Returns a list of the ore dictionary names if they exist. - * Returns a list containing itemStack if there are no ore dictionary names. - * Used for creating recipes that should accept equivalent itemStacks, based on the ore dictionary. - */ - public static List getOreDictRecipeEquivalents(ItemStack itemStack) { - int[] oreDictIds = OreDictionary.getOreIDs(itemStack); - List oreDictNames = new ArrayList<>(oreDictIds.length); - for (int oreId : oreDictIds) { - String oreDictName = OreDictionary.getOreName(oreId); - oreDictNames.add(oreDictName); - } - if (oreDictNames.isEmpty()) { - return Collections.singletonList(itemStack); - } - return oreDictNames; - } - - public static Object[] getCraftingRecipeAsArray(IDescriptiveRecipe recipe) { - - try { - return getShapedRecipeAsArray(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients(), recipe.getRecipeOutput()); - } catch (RuntimeException ex) { - Log.warning("Exception while trying to parse an ItemStack[10] from an IRecipe:", ex); - } - - return null; - } - - private static Object[] getShapedRecipeAsArray(int width, int height, Object[] ingredients, ItemStack output) { - Object[] result = new Object[10]; - - for (int y = 0; y < height; y++) { - System.arraycopy(ingredients, y * width, result, y * 3, width); - } - - result[9] = output; - return result; - } - - public static InventoryCraftingForestry getCraftRecipe(ItemStack[] recipeItems, ItemStack[] availableItems, World world, ItemStack recipeOutput) { + @Nullable + public static InventoryCraftingForestry getCraftRecipe(NonNullList recipeItems, NonNullList availableItems, World world, ItemStack recipeOutput) { // Need at least one matched set if (ItemStackUtil.containsSets(recipeItems, availableItems, true, true) == 0) { return null; @@ -111,30 +69,30 @@ public abstract class RecipeUtil { // in place of the ones in the saved crafting inventory. // Check that the recipe it makes is the same as the currentRecipe. InventoryCraftingForestry crafting = new InventoryCraftingForestry(); - ItemStack[] stockCopy = ItemStackUtil.condenseStacks(availableItems); + NonNullList stockCopy = ItemStackUtil.condenseStacks(availableItems); - for (int slot = 0; slot < recipeItems.length; slot++) { - ItemStack recipeStack = recipeItems[slot]; - if (recipeStack == null) { + for (int slot = 0; slot < recipeItems.size(); slot++) { + ItemStack recipeStack = recipeItems.get(slot); + if (recipeStack.isEmpty()) { continue; } // Use crafting equivalent (not oredict) items first for (ItemStack stockStack : stockCopy) { - if (stockStack.stackSize > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, false, false)) { - ItemStack stack = ItemStackUtil.createSplitStack(stockStack, 1); - stockStack.stackSize--; + if (stockStack.getCount() > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, false, false)) { + ItemStack stack = ItemStackUtil.createCopyWithCount(stockStack, 1); + stockStack.shrink(1); crafting.setInventorySlotContents(slot, stack); break; } } // Use oredict items if crafting equivalent items aren't available - if (crafting.getStackInSlot(slot) == null) { + if (crafting.getStackInSlot(slot).isEmpty()) { for (ItemStack stockStack : stockCopy) { - if (stockStack.stackSize > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, true, true)) { - ItemStack stack = ItemStackUtil.createSplitStack(stockStack, 1); - stockStack.stackSize--; + if (stockStack.getCount() > 0 && ItemStackUtil.isCraftingEquivalent(recipeStack, stockStack, true, true)) { + ItemStack stack = ItemStackUtil.createCopyWithCount(stockStack, 1); + stockStack.shrink(1); crafting.setInventorySlotContents(slot, stack); break; } @@ -149,10 +107,9 @@ public abstract class RecipeUtil { return crafting; } - @Nonnull public static List findMatchingRecipes(InventoryCrafting inventory, World world) { ItemStack repairRecipe = findRepairRecipe(inventory); - if (repairRecipe != null) { + if (!repairRecipe.isEmpty()) { return Collections.singletonList(repairRecipe); } @@ -174,13 +131,13 @@ public abstract class RecipeUtil { private static ItemStack findRepairRecipe(InventoryCrafting inventory) { int craftIngredientCount = 0; - ItemStack itemstack0 = null; - ItemStack itemstack1 = null; + ItemStack itemstack0 = ItemStack.EMPTY; + ItemStack itemstack1 = ItemStack.EMPTY; for (int j = 0; j < inventory.getSizeInventory(); j++) { ItemStack itemstack = inventory.getStackInSlot(j); - if (itemstack != null) { + if (!itemstack.isEmpty()) { if (craftIngredientCount == 0) { itemstack0 = itemstack; } @@ -193,12 +150,11 @@ public abstract class RecipeUtil { } } - if (craftIngredientCount == 2 && itemstack0.getItem() == itemstack1.getItem() && itemstack0.stackSize == 1 && itemstack1.stackSize == 1 && itemstack0.getItem().isRepairable()) { - Item item = itemstack0.getItem(); - int damage0 = item.getMaxDamage() - itemstack0.getItemDamage(); - int damage1 = item.getMaxDamage() - itemstack1.getItemDamage(); - int repairAmount = damage0 + damage1 + item.getMaxDamage() * 5 / 100; - int repairedDamage = item.getMaxDamage() - repairAmount; + if (craftIngredientCount == 2 && itemstack0.getItem() == itemstack1.getItem() && itemstack0.getCount() == 1 && itemstack1.getCount() == 1 && itemstack0.getItem().isRepairable()) { + int damage0 = itemstack0.getMaxDamage() - itemstack0.getItemDamage(); + int damage1 = itemstack0.getMaxDamage() - itemstack1.getItemDamage(); + int repairAmount = damage0 + damage1 + itemstack0.getMaxDamage() * 5 / 100; + int repairedDamage = itemstack0.getMaxDamage() - repairAmount; if (repairedDamage < 0) { repairedDamage = 0; @@ -207,7 +163,7 @@ public abstract class RecipeUtil { return new ItemStack(itemstack0.getItem(), 1, repairedDamage); } - return null; + return ItemStack.EMPTY; } public static void addRecipe(Block block, Object... obj) { @@ -239,23 +195,17 @@ public abstract class RecipeUtil { } public static void addSmelting(ItemStack res, ItemStack prod, float xp) { - if (res == null || res.getItem() == null) { - throw new IllegalArgumentException("Tried to register smelting recipe with null input"); - } - if (prod == null || prod.getItem() == null) { - throw new IllegalArgumentException("Tried to register smelting recipe with null output"); - } GameRegistry.addSmelting(res, prod, xp); } public static boolean matches(IDescriptiveRecipe recipe, IInventory inventoryCrafting) { - Object[] recipeIngredients = recipe.getIngredients(); + NonNullList> recipeIngredients = recipe.getIngredients(); int width = recipe.getWidth(); int height = recipe.getHeight(); return matches(recipeIngredients, width, height, inventoryCrafting); } - public static boolean matches(Object[] recipeIngredients, int width, int height, IInventory inventoryCrafting) { + public static boolean matches(NonNullList> recipeIngredients, int width, int height, IInventory inventoryCrafting) { ItemStack[][] resources = getResources(inventoryCrafting); return matches(recipeIngredients, width, height, resources); } @@ -271,7 +221,7 @@ public abstract class RecipeUtil { return resources; } - public static boolean matches(Object[] recipeIngredients, int width, int height, ItemStack[][] resources) { + public static boolean matches(NonNullList> recipeIngredients, int width, int height, ItemStack[][] resources) { for (int i = 0; i <= 3 - width; i++) { for (int j = 0; j <= 3 - height; j++) { if (checkMatch(recipeIngredients, width, height, resources, i, j, true)) { @@ -287,20 +237,20 @@ public abstract class RecipeUtil { return false; } - private static boolean checkMatch(Object[] recipeIngredients, int width, int height, ItemStack[][] resources, int xInGrid, int yInGrid, boolean mirror) { + private static boolean checkMatch(NonNullList> recipeIngredients, int width, int height, ItemStack[][] resources, int xInGrid, int yInGrid, boolean mirror) { for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { ItemStack resource = resources[k][l]; int widthIt = k - xInGrid; int heightIt = l - yInGrid; - Object recipeIngredient = null; + NonNullList recipeIngredient = null; if (widthIt >= 0 && heightIt >= 0 && widthIt < width && heightIt < height) { if (mirror) { - recipeIngredient = recipeIngredients[width - widthIt - 1 + heightIt * width]; + recipeIngredient = recipeIngredients.get(width - widthIt - 1 + heightIt * width); } else { - recipeIngredient = recipeIngredients[widthIt + heightIt * width]; + recipeIngredient = recipeIngredients.get(widthIt + heightIt * width); } } @@ -313,20 +263,15 @@ public abstract class RecipeUtil { return true; } - private static boolean checkIngredientMatch(Object recipeIngredient, ItemStack resource) { - if (recipeIngredient == null && resource == null) { - return true; - } else if (recipeIngredient instanceof ItemStack) { - return ItemStackUtil.isCraftingEquivalent((ItemStack) recipeIngredient, resource); - } else if (recipeIngredient instanceof Iterable) { - for (Object item : (Iterable) recipeIngredient) { - if (checkIngredientMatch(item, resource)) { - return true; - } - } - return false; - } else { - return false; + private static boolean checkIngredientMatch(@Nullable NonNullList recipeIngredient, ItemStack resource) { + if (recipeIngredient == null) { + return resource.isEmpty(); } + for (ItemStack item : recipeIngredient) { + if (ItemStackUtil.isCraftingEquivalent(item, resource)) { + return true; + } + } + return false; } } diff --git a/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java b/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java index dc77767e3..4d75bec61 100644 --- a/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java +++ b/src/main/java/forestry/core/recipes/ShapedRecipeCustom.java @@ -12,34 +12,31 @@ package forestry.core.recipes; import java.util.HashMap; import java.util.Iterator; -import java.util.List; +import forestry.api.recipes.IDescriptiveRecipe; +import forestry.core.utils.ItemStackUtil; import net.minecraft.block.Block; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.world.World; - import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.ShapedOreRecipe; -import forestry.api.recipes.IDescriptiveRecipe; -import forestry.core.utils.ItemStackUtil; - public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveRecipe { //Added in for future ease of change, but hard coded for now. private static final int MAX_CRAFT_GRID_WIDTH = 3; private static final int MAX_CRAFT_GRID_HEIGHT = 3; - private ItemStack output = null; - private Object[] input = null; + private NonNullList> input; private int width; private int height; private boolean mirrored = true; public ShapedRecipeCustom(ItemStack result, Object... recipe) { super(result, recipe); - output = result.copy(); + ItemStack output = result.copy(); String shape = ""; int idx = 0; @@ -80,18 +77,27 @@ public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveR throw new RuntimeException(ret); } - HashMap itemMap = new HashMap<>(); + HashMap> itemMap = new HashMap<>(); for (; idx < recipe.length; idx += 2) { Character chr = (Character) recipe[idx]; Object in = recipe[idx + 1]; if (in instanceof ItemStack) { - itemMap.put(chr, ((ItemStack) in).copy()); + ItemStack copy = ((ItemStack) in).copy(); + NonNullList ingredient = NonNullList.create(); + ingredient.add(copy); + itemMap.put(chr, ingredient); } else if (in instanceof Item) { - itemMap.put(chr, new ItemStack((Item) in)); + ItemStack itemStack = new ItemStack((Item) in); + NonNullList ingredient = NonNullList.create(); + ingredient.add(itemStack); + itemMap.put(chr, ingredient); } else if (in instanceof Block) { - itemMap.put(chr, new ItemStack((Block) in, 1, OreDictionary.WILDCARD_VALUE)); + ItemStack itemStack = new ItemStack((Block) in, 1, OreDictionary.WILDCARD_VALUE); + NonNullList ingredient = NonNullList.create(); + ingredient.add(itemStack); + itemMap.put(chr, ingredient); } else if (in instanceof String) { itemMap.put(chr, OreDictionary.getOres((String) in)); } else { @@ -104,10 +110,13 @@ public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveR } } - input = new Object[width * height]; + input = NonNullList.withSize(9, NonNullList.create()); int x = 0; for (char chr : shape.toCharArray()) { - input[x++] = itemMap.get(chr); + NonNullList stacks = itemMap.get(chr); + if (stacks != null) { + input.set(x++, stacks); + } } } @@ -122,8 +131,8 @@ public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveR } @Override - public Object[] getIngredients() { - return getInput(); + public NonNullList> getIngredients() { + return input; } @Override @@ -144,40 +153,35 @@ public class ShapedRecipeCustom extends ShapedOreRecipe implements IDescriptiveR } @Override - @SuppressWarnings("unchecked") public boolean checkMatch(InventoryCrafting inv, int startX, int startY, boolean mirror) { for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { int subX = x - startX; int subY = y - startY; - Object target = null; + NonNullList target = null; if (subX >= 0 && subY >= 0 && subX < width && subY < height) { if (mirror) { - target = input[width - subX - 1 + subY * width]; + target = input.get(width - subX - 1 + subY * width); } else { - target = input[subX + subY * width]; + target = input.get(subX + subY * width); } } - ItemStack slot = inv.getStackInRowAndColumn(x, y); + ItemStack stackInSlot = inv.getStackInRowAndColumn(x, y); - if (target instanceof ItemStack) { - if (!ItemStackUtil.isCraftingEquivalent((ItemStack) target, slot)) { - return false; - } - } else if (target instanceof List) { + if (target != null) { boolean matched = false; - Iterator itr = ((List) target).iterator(); + Iterator itr = target.iterator(); while (itr.hasNext() && !matched) { - matched = ItemStackUtil.isCraftingEquivalent(itr.next(), slot); + matched = ItemStackUtil.isCraftingEquivalent(itr.next(), stackInSlot); } if (!matched) { return false; } - } else if (target == null && slot != null) { + } else if (!stackInSlot.isEmpty()) { return false; } } diff --git a/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java b/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java index d85ccfb7e..57f8c0626 100644 --- a/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java +++ b/src/main/java/forestry/core/recipes/jei/ForestryRecipeCategory.java @@ -1,31 +1,24 @@ package forestry.core.recipes.jei; -import javax.annotation.Nonnull; - import forestry.core.utils.Translator; - import mezz.jei.api.gui.IDrawable; import mezz.jei.api.recipe.BlankRecipeCategory; import mezz.jei.api.recipe.IRecipeWrapper; public abstract class ForestryRecipeCategory extends BlankRecipeCategory { - @Nonnull private final IDrawable background; - @Nonnull private final String localizedName; - - public ForestryRecipeCategory(@Nonnull IDrawable background, String unlocalizedName) { + + public ForestryRecipeCategory(IDrawable background, String unlocalizedName) { this.background = background; this.localizedName = Translator.translateToLocal(unlocalizedName); } - @Nonnull @Override public String getTitle() { return localizedName; } - @Nonnull @Override public IDrawable getBackground() { return background; diff --git a/src/main/java/forestry/core/recipes/jei/ForestryRecipeWrapper.java b/src/main/java/forestry/core/recipes/jei/ForestryRecipeWrapper.java index a61afab54..4f22655e1 100644 --- a/src/main/java/forestry/core/recipes/jei/ForestryRecipeWrapper.java +++ b/src/main/java/forestry/core/recipes/jei/ForestryRecipeWrapper.java @@ -1,21 +1,15 @@ package forestry.core.recipes.jei; -import javax.annotation.Nonnull; - import mezz.jei.api.recipe.BlankRecipeWrapper; public abstract class ForestryRecipeWrapper extends BlankRecipeWrapper { - - @Nonnull private final R recipe; - public ForestryRecipeWrapper(@Nonnull R recipe) { + public ForestryRecipeWrapper(R recipe) { this.recipe = recipe; } - @Nonnull public R getRecipe() { return recipe; } - } diff --git a/src/main/java/forestry/core/recipes/jei/package-info.java b/src/main/java/forestry/core/recipes/jei/package-info.java new file mode 100644 index 000000000..7b0af9f7e --- /dev/null +++ b/src/main/java/forestry/core/recipes/jei/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.recipes.jei; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/recipes/package-info.java b/src/main/java/forestry/core/recipes/package-info.java new file mode 100644 index 000000000..624030cd8 --- /dev/null +++ b/src/main/java/forestry/core/recipes/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.recipes; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/render/EmptyStateMapper.java b/src/main/java/forestry/core/render/EmptyStateMapper.java deleted file mode 100644 index 970ce201c..000000000 --- a/src/main/java/forestry/core/render/EmptyStateMapper.java +++ /dev/null @@ -1,27 +0,0 @@ -package forestry.core.render; - -import java.util.Collections; -import java.util.Map; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.statemap.IStateMapper; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class EmptyStateMapper implements IStateMapper { - - public static final EmptyStateMapper instance = new EmptyStateMapper(); - - private EmptyStateMapper() { - } - - @Override - public Map putStateModelLocations(Block block) { - return Collections.emptyMap(); - } - -} diff --git a/src/main/java/forestry/core/render/ForestryStateMapper.java b/src/main/java/forestry/core/render/ForestryStateMapper.java index 15761dfcb..1e3ab592e 100644 --- a/src/main/java/forestry/core/render/ForestryStateMapper.java +++ b/src/main/java/forestry/core/render/ForestryStateMapper.java @@ -12,7 +12,7 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; public abstract class ForestryStateMapper implements IStateMapper { - protected Map mapStateModelLocations = Maps.newLinkedHashMap(); + protected final Map mapStateModelLocations = Maps.newLinkedHashMap(); @SuppressWarnings("unchecked") public String getPropertyString(Map, Comparable> map) { diff --git a/src/main/java/forestry/core/render/MachineParticleCallback.java b/src/main/java/forestry/core/render/MachineParticleCallback.java index 9951da0c8..e8860d75a 100644 --- a/src/main/java/forestry/core/render/MachineParticleCallback.java +++ b/src/main/java/forestry/core/render/MachineParticleCallback.java @@ -10,6 +10,11 @@ ******************************************************************************/ package forestry.core.render; +import forestry.core.blocks.BlockBase; +import forestry.core.blocks.IBlockType; +import forestry.core.blocks.IMachineProperties; +import forestry.core.blocks.IMachinePropertiesTesr; +import forestry.core.proxy.Proxies; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.ParticleDigging; @@ -19,25 +24,19 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.core.blocks.BlockBase; -import forestry.core.blocks.IBlockType; -import forestry.core.blocks.IMachineProperties; -import forestry.core.blocks.IMachinePropertiesTesr; -import forestry.core.proxy.Proxies; - public class MachineParticleCallback

& IBlockType & IStringSerializable> extends ParticleHelper.DefaultCallback { - + private final P blockType; - + public MachineParticleCallback(BlockBase block, P blockType) { super(block); this.blockType = blockType; } - + @Override protected void setTexture(ParticleDigging fx, World world, BlockPos pos, IBlockState state) { IMachineProperties machineProperties = blockType.getMachineProperties(); - if(machineProperties instanceof IMachinePropertiesTesr){ + if (machineProperties instanceof IMachinePropertiesTesr) { Minecraft minecraft = Proxies.common.getClientInstance(); TextureMap textureMapBlocks = minecraft.getTextureMapBlocks(); IMachinePropertiesTesr machinePropertiesTesr = (IMachinePropertiesTesr) machineProperties; diff --git a/src/main/java/forestry/core/render/MachineStateMapper.java b/src/main/java/forestry/core/render/MachineStateMapper.java index a6728e511..97832abb8 100644 --- a/src/main/java/forestry/core/render/MachineStateMapper.java +++ b/src/main/java/forestry/core/render/MachineStateMapper.java @@ -1,10 +1,12 @@ package forestry.core.render; -import com.google.common.collect.Maps; - import java.util.LinkedHashMap; import java.util.Map; +import com.google.common.collect.Maps; +import forestry.core.blocks.BlockBase; +import forestry.core.blocks.IBlockType; +import forestry.core.blocks.IMachinePropertiesTesr; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; @@ -12,14 +14,9 @@ import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.util.ResourceLocation; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.core.blocks.BlockBase; -import forestry.core.blocks.IBlockType; -import forestry.core.blocks.IMachinePropertiesTesr; - @SideOnly(Side.CLIENT) public class MachineStateMapper & IBlockType & IStringSerializable> extends ForestryStateMapper { diff --git a/src/main/java/forestry/core/render/ParticleHelper.java b/src/main/java/forestry/core/render/ParticleHelper.java index 2b29bfdc0..1834925a1 100644 --- a/src/main/java/forestry/core/render/ParticleHelper.java +++ b/src/main/java/forestry/core/render/ParticleHelper.java @@ -72,8 +72,10 @@ public class ParticleHelper { } ParticleDigging fx = (ParticleDigging) effectRenderer.spawnEffectParticle(EnumParticleTypes.BLOCK_DUST.getParticleID(), px, py, pz, 0.0D, 0.0D, 0.0D, Block.getStateId(iblockstate)); - callback.addHitEffects(fx, world, pos, iblockstate); - effectRenderer.addEffect(fx.setBlockPos(new BlockPos(x, y, z)).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); + if (fx != null) { + callback.addHitEffects(fx, world, pos, iblockstate); + effectRenderer.addEffect(fx.setBlockPos(new BlockPos(x, y, z)).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); + } } return true; } @@ -101,8 +103,10 @@ public class ParticleHelper { double pz = pos.getZ() + (k + 0.5D) / iterations; ParticleDigging fx = (ParticleDigging) effectRenderer.spawnEffectParticle(EnumParticleTypes.BLOCK_CRACK.getParticleID(), px, py, pz, px - pos.getX() - 0.5D, py - pos.getY() - 0.5D, pz - pos.getZ() - 0.5D, Block.getStateId(state)); - callback.addDestroyEffects(fx, world, pos, state); - effectRenderer.addEffect(fx.setBlockPos(pos)); + if (fx != null) { + callback.addDestroyEffects(fx, world, pos, state); + effectRenderer.addEffect(fx.setBlockPos(pos)); + } } } } diff --git a/src/main/java/forestry/core/render/RenderAnalyzer.java b/src/main/java/forestry/core/render/RenderAnalyzer.java index f556dd6da..6fe459ac2 100755 --- a/src/main/java/forestry/core/render/RenderAnalyzer.java +++ b/src/main/java/forestry/core/render/RenderAnalyzer.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.render; +import javax.annotation.Nullable; + import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.RenderManager; @@ -40,22 +42,25 @@ public class RenderAnalyzer extends TileEntitySpecialRenderer { @Override public void renderTileEntityAt(TileAnalyzer analyzer, double x, double y, double z, float partialTicks, int destroyStage) { if (analyzer != null) { - IBlockState blockState = analyzer.getWorldObj().getBlockState(analyzer.getPos()); - if (blockState != null && blockState.getBlock() instanceof BlockBase) { - EnumFacing facing = blockState.getValue(BlockBase.FACING); - render(analyzer.getIndividualOnDisplay(), analyzer.getWorld(), facing, x, y, z); - return; + World worldObj = analyzer.getWorldObj(); + if (worldObj.isBlockLoaded(analyzer.getPos())) { + IBlockState blockState = worldObj.getBlockState(analyzer.getPos()); + if (blockState.getBlock() instanceof BlockBase) { + EnumFacing facing = blockState.getValue(BlockBase.FACING); + render(analyzer.getIndividualOnDisplay(), analyzer.getWorld(), facing, x, y, z); + return; + } } } - render(null, null, EnumFacing.WEST, x, y, z); + render(ItemStack.EMPTY, null, EnumFacing.WEST, x, y, z); } - private void render(ItemStack itemstack, World world, EnumFacing orientation, double x, double y, double z) { + private void render(ItemStack itemstack, @Nullable World world, EnumFacing orientation, double x, double y, double z) { - dummyEntityItem.worldObj = world; + dummyEntityItem.world = world; model.render(orientation, (float) x, (float) y, (float) z); - if (itemstack == null) { + if (itemstack.isEmpty() || world == null) { return; } float renderScale = 1.0f; diff --git a/src/main/java/forestry/core/render/RenderEscritoire.java b/src/main/java/forestry/core/render/RenderEscritoire.java index 83d544292..4e62f16f5 100755 --- a/src/main/java/forestry/core/render/RenderEscritoire.java +++ b/src/main/java/forestry/core/render/RenderEscritoire.java @@ -12,6 +12,11 @@ package forestry.core.render; import javax.annotation.Nullable; +import forestry.core.blocks.BlockBase; +import forestry.core.config.Constants; +import forestry.core.models.ModelEscritoire; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.TileEscritoire; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.RenderManager; @@ -22,19 +27,13 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -import forestry.core.blocks.BlockBase; -import forestry.core.config.Constants; -import forestry.core.models.ModelEscritoire; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileEscritoire; - public class RenderEscritoire extends TileEntitySpecialRenderer { private static final ResourceLocation texture = new ForestryResource(Constants.TEXTURE_PATH_BLOCKS + "/escritoire.png"); private final ModelEscritoire modelEscritoire = new ModelEscritoire(); private final EntityItem dummyEntityItem = new EntityItem(null); private long lastTick; - + /** * @param escritoire If it null its render the item else it render the tile entity. */ @@ -42,28 +41,27 @@ public class RenderEscritoire extends TileEntitySpecialRenderer public void renderTileEntityAt(@Nullable TileEscritoire escritoire, double x, double y, double z, float partialTicks, int destroyStage) { if (escritoire != null) { World world = escritoire.getWorldObj(); - IBlockState blockState = world.getBlockState(escritoire.getPos()); - if (blockState != null && blockState.getBlock() instanceof BlockBase) { - EnumFacing facing = blockState.getValue(BlockBase.FACING); - render(escritoire.getIndividualOnDisplay(), world, facing, x, y, z); - return; + if (world.isBlockLoaded(escritoire.getPos())) { + IBlockState blockState = world.getBlockState(escritoire.getPos()); + if (blockState.getBlock() instanceof BlockBase) { + EnumFacing facing = blockState.getValue(BlockBase.FACING); + render(escritoire.getIndividualOnDisplay(), world, facing, x, y, z); + return; + } } } - render(null, null, EnumFacing.SOUTH, x, y, z); + render(ItemStack.EMPTY, null, EnumFacing.SOUTH, x, y, z); } - - private void render(@Nullable ItemStack itemstack, @Nullable World world, EnumFacing orientation, double x, double y, double z) { + + private void render(ItemStack itemstack, @Nullable World world, EnumFacing orientation, double x, double y, double z) { float factor = (float) (1.0 / 16.0); GlStateManager.pushMatrix(); { GlStateManager.translate((float) x + 0.5f, (float) y + 0.875f, (float) z + 0.5f); - + float[] angle = {(float) Math.PI, 0, 0}; - - if (orientation == null) { - orientation = EnumFacing.WEST; - } + switch (orientation) { case EAST: angle[1] = (float) Math.PI / 2; @@ -78,15 +76,15 @@ public class RenderEscritoire extends TileEntitySpecialRenderer angle[1] = -(float) Math.PI / 2; break; } - + Proxies.render.bindTexture(texture); modelEscritoire.render(null, angle[0], angle[1], angle[2], 0f, 0f, factor); } GlStateManager.popMatrix(); - - if (itemstack != null && world != null) { - dummyEntityItem.worldObj = world; - + + if (!itemstack.isEmpty() && world != null) { + dummyEntityItem.world = world; + float renderScale = 0.75f; GlStateManager.pushMatrix(); @@ -94,18 +92,18 @@ public class RenderEscritoire extends TileEntitySpecialRenderer GlStateManager.translate((float) x + 0.5f, (float) y + 0.6f, (float) z + 0.5f); GlStateManager.scale(renderScale, renderScale, renderScale); dummyEntityItem.setEntityItemStack(itemstack); - + if (world.getTotalWorldTime() != lastTick) { lastTick = world.getTotalWorldTime(); dummyEntityItem.onUpdate(); } - + RenderManager rendermanager = Proxies.common.getClientInstance().getRenderManager(); rendermanager.doRenderEntity(dummyEntityItem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F, false); } GlStateManager.popMatrix(); - dummyEntityItem.worldObj = null; // prevent leaking the world object + dummyEntityItem.world = null; // prevent leaking the world object } } } diff --git a/src/main/java/forestry/core/render/RenderMachine.java b/src/main/java/forestry/core/render/RenderMachine.java index 4eadf8051..129f35acf 100755 --- a/src/main/java/forestry/core/render/RenderMachine.java +++ b/src/main/java/forestry/core/render/RenderMachine.java @@ -14,6 +14,11 @@ import java.awt.Color; import java.util.EnumMap; import java.util.Locale; +import forestry.core.blocks.BlockBase; +import forestry.core.fluids.Fluids; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.IRenderableTile; +import forestry.core.tiles.TileBase; import net.minecraft.block.state.IBlockState; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; @@ -21,12 +26,7 @@ import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; - -import forestry.core.blocks.BlockBase; -import forestry.core.fluids.Fluids; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.IRenderableTile; -import forestry.core.tiles.TileBase; +import net.minecraft.world.World; public class RenderMachine extends TileEntitySpecialRenderer { @@ -35,13 +35,13 @@ public class RenderMachine extends TileEntitySpecialRenderer { private final ModelRenderer resourceTank; private final ModelRenderer productTank; - private ResourceLocation textureBase; - private ResourceLocation textureResourceTank; - private ResourceLocation textureProductTank; + private final ResourceLocation textureBase; + private final ResourceLocation textureResourceTank; + private final ResourceLocation textureProductTank; private final EnumMap texturesTankLevels = new EnumMap<>(EnumTankLevel.class); - private RenderMachine() { + public RenderMachine(String baseTexture) { ModelBase model = new RenderModelBase(); basefront = new ModelRenderer(model, 0, 0); @@ -67,10 +67,6 @@ public class RenderMachine extends TileEntitySpecialRenderer { productTank.rotationPointX = 8; productTank.rotationPointY = 8; productTank.rotationPointZ = 8; - } - - public RenderMachine(String baseTexture) { - this(); textureBase = new ForestryResource(baseTexture + "base.png"); textureProductTank = new ForestryResource(baseTexture + "tank_product_empty.png"); @@ -84,7 +80,7 @@ public class RenderMachine extends TileEntitySpecialRenderer { texturesTankLevels.put(tankLevel, new ForestryResource("textures/blocks/machine_tank_" + tankLevelString + ".png")); } } - + /** * @param tile If it null its render the item else it render the tile entity. */ @@ -92,11 +88,14 @@ public class RenderMachine extends TileEntitySpecialRenderer { public void renderTileEntityAt(TileBase tile, double x, double y, double z, float partialTicks, int destroyStage) { if (tile != null) { IRenderableTile generator = (IRenderableTile) tile; - IBlockState blockState = tile.getWorldObj().getBlockState(tile.getPos()); - if (blockState != null && blockState.getBlock() instanceof BlockBase) { - EnumFacing facing = blockState.getValue(BlockBase.FACING); - render(generator.getResourceTankInfo(), generator.getProductTankInfo(), facing, x, y, z, destroyStage); - return; + World worldObj = tile.getWorldObj(); + if (worldObj.isBlockLoaded(tile.getPos())) { + IBlockState blockState = worldObj.getBlockState(tile.getPos()); + if (blockState.getBlock() instanceof BlockBase) { + EnumFacing facing = blockState.getValue(BlockBase.FACING); + render(generator.getResourceTankInfo(), generator.getProductTankInfo(), facing, x, y, z, destroyStage); + return; + } } } render(TankRenderInfo.EMPTY, TankRenderInfo.EMPTY, EnumFacing.SOUTH, x, y, z, -1); @@ -107,9 +106,6 @@ public class RenderMachine extends TileEntitySpecialRenderer { GlStateManager.translate((float) x, (float) y, (float) z); float[] angle = {0, 0, 0}; - if (orientation == null) { - orientation = EnumFacing.WEST; - } switch (orientation) { case EAST: angle[1] = (float) Math.PI; @@ -151,17 +147,17 @@ public class RenderMachine extends TileEntitySpecialRenderer { productTank.rotateAngleZ = angle[2]; float factor = (float) (1.0 / 16.0); - - Proxies.render.bindTexture(textureBase); - + + Proxies.render.bindTexture(textureBase); + basefront.render(factor); baseback.render(factor); renderTank(resourceTank, textureResourceTank, resourceTankInfo, factor); renderTank(productTank, textureProductTank, productTankInfo, factor); - GlStateManager.popMatrix(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.popMatrix(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); } private void renderTank(ModelRenderer tankModel, ResourceLocation textureBase, TankRenderInfo renderInfo, float factor) { @@ -172,7 +168,7 @@ public class RenderMachine extends TileEntitySpecialRenderer { if (textureResourceTankLevel == null) { return; } - + // TODO: render fluid overlay on tank Fluids fluidDefinition = Fluids.getFluidDefinition(renderInfo.getFluidStack()); Color primaryTankColor = fluidDefinition == null ? Color.BLUE : fluidDefinition.getParticleColor(); diff --git a/src/main/java/forestry/core/render/RenderMill.java b/src/main/java/forestry/core/render/RenderMill.java index 29fcc17e6..22e7316a4 100755 --- a/src/main/java/forestry/core/render/RenderMill.java +++ b/src/main/java/forestry/core/render/RenderMill.java @@ -21,12 +21,9 @@ import forestry.core.proxy.Proxies; import forestry.core.tiles.TileMill; public class RenderMill extends TileEntitySpecialRenderer { - - private final ModelBase model = new MillModelBase(); - private enum Textures {PEDESTAL, EXTENSION, BLADE_1, BLADE_2, CHARGE} - private ResourceLocation[] textures; + private final ResourceLocation[] textures; private final ModelRenderer pedestal; private final ModelRenderer column; @@ -34,7 +31,8 @@ public class RenderMill extends TileEntitySpecialRenderer { private final ModelRenderer blade1; private final ModelRenderer blade2; - public RenderMill() { + public RenderMill(String baseTexture) { + ModelBase model = new MillModelBase(); pedestal = new ModelRenderer(model, 0, 0); pedestal.addBox(-8F, -8F, -8F, 16, 1, 16); pedestal.rotationPointX = 8; @@ -65,11 +63,6 @@ public class RenderMill extends TileEntitySpecialRenderer { blade2.rotationPointY = 8; blade2.rotationPointZ = 8; - } - - public RenderMill(String baseTexture) { - this(); - textures = new ResourceLocation[12]; textures[Textures.PEDESTAL.ordinal()] = new ForestryResource(baseTexture + "pedestal.png"); @@ -117,9 +110,6 @@ public class RenderMill extends TileEntitySpecialRenderer { float[] translate = {0, 0, 0}; float tfactor = step / 16; - if (orientation == null) { - orientation = EnumFacing.WEST; - } switch (orientation) { case EAST: // angle [2] = (float) Math.PI / 2; diff --git a/src/main/java/forestry/core/render/RenderNaturalistChest.java b/src/main/java/forestry/core/render/RenderNaturalistChest.java index 3be1c35b5..e5f7906e3 100644 --- a/src/main/java/forestry/core/render/RenderNaturalistChest.java +++ b/src/main/java/forestry/core/render/RenderNaturalistChest.java @@ -20,6 +20,7 @@ import net.minecraft.util.ResourceLocation; import forestry.core.blocks.BlockBase; import forestry.core.config.Constants; import forestry.core.tiles.TileNaturalistChest; +import net.minecraft.world.World; public class RenderNaturalistChest extends TileEntitySpecialRenderer { @@ -36,11 +37,14 @@ public class RenderNaturalistChest extends TileEntitySpecialRenderer() { - @Override - public String call() throws Exception { - return texture.getIconName(); - } - }); - crashreportcategory.setDetail("Sprite size", new ICrashReportDetail() { - @Override - public String call() throws Exception { - return texture.getIconWidth() + " x " + texture.getIconHeight(); - } - }); - crashreportcategory.setDetail("Sprite frames", new ICrashReportDetail() { - @Override - public String call() throws Exception { - return texture.getFrameCount() + " frames"; - } - }); + crashreportcategory.setDetail("Sprite name", texture::getIconName); + crashreportcategory.setDetail("Sprite size", () -> texture.getIconWidth() + " x " + texture.getIconHeight()); + crashreportcategory.setDetail("Sprite frames", () -> texture.getFrameCount() + " frames"); crashreportcategory.addCrashSection("Mipmap levels", 0); throw new ReportedException(crashreport); } diff --git a/src/main/java/forestry/core/render/TileRendererIndex.java b/src/main/java/forestry/core/render/TileRendererIndex.java deleted file mode 100755 index 6d28001d6..000000000 --- a/src/main/java/forestry/core/render/TileRendererIndex.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.core.render; - -import net.minecraft.block.Block; - -public class TileRendererIndex { - private final Block block; - private final int meta; - - public TileRendererIndex(Block block, int meta) { - this.block = block; - this.meta = meta; - } - - @Override - public int hashCode() { - return block.hashCode() + meta; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof TileRendererIndex)) { - return false; - } - - TileRendererIndex index = (TileRendererIndex) obj; - - return index.block == block && index.meta == meta; - } -} diff --git a/src/main/java/forestry/core/render/package-info.java b/src/main/java/forestry/core/render/package-info.java new file mode 100644 index 000000000..653bab3e7 --- /dev/null +++ b/src/main/java/forestry/core/render/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.render; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/tiles/AdjacentTileCache.java b/src/main/java/forestry/core/tiles/AdjacentTileCache.java index f0b438012..e580d6460 100644 --- a/src/main/java/forestry/core/tiles/AdjacentTileCache.java +++ b/src/main/java/forestry/core/tiles/AdjacentTileCache.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.tiles; +import javax.annotation.Nullable; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; @@ -53,6 +54,7 @@ public final class AdjacentTileCache { listeners.add(listener); } + @Nullable private TileEntity searchSide(EnumFacing side) { World world = source.getWorld(); BlockPos pos = source.getPos().offset(side); @@ -84,7 +86,7 @@ public final class AdjacentTileCache { Arrays.fill(delay, DELAY_MIN); } - protected void setTile(int side, TileEntity tile) { + protected void setTile(int side, @Nullable TileEntity tile) { if (cache[side] != tile) { cache[side] = tile; changed(); diff --git a/src/main/java/forestry/core/tiles/EscritoireGame.java b/src/main/java/forestry/core/tiles/EscritoireGame.java index c4410a307..e89c6335a 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGame.java +++ b/src/main/java/forestry/core/tiles/EscritoireGame.java @@ -10,22 +10,20 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.Random; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IIndividual; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class EscritoireGame implements INbtWritable, INbtReadable, IStreamable { private static final Random rand = new Random(); @@ -36,7 +34,6 @@ public class EscritoireGame implements INbtWritable, INbtReadable, IStreamable { public static final Status[] VALUES = values(); } - @Nonnull private EscritoireGameBoard gameBoard; private long lastUpdate; private int bountyLevel; @@ -46,6 +43,7 @@ public class EscritoireGame implements INbtWritable, INbtReadable, IStreamable { gameBoard = new EscritoireGameBoard(); } + @Nullable public EscritoireGameToken getToken(int index) { return gameBoard.getToken(index); } @@ -84,14 +82,14 @@ public class EscritoireGame implements INbtWritable, INbtReadable, IStreamable { /* NETWORK */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeInt(bountyLevel); gameBoard.writeData(data); data.writeEnum(status, Status.VALUES); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { bountyLevel = data.readInt(); gameBoard.readData(data); status = data.readEnum(Status.VALUES); @@ -126,12 +124,10 @@ public class EscritoireGame implements INbtWritable, INbtReadable, IStreamable { int revealCount = getSampleSize(slotCount); for (int i = 0; i < revealCount; i++) { ItemStack sample = inventory.decrStackSize(startSlot + i, 1); - if (sample == null || sample.stackSize <= 0) { - continue; - } - - if (rand.nextFloat() < species.getResearchSuitability(sample)) { - gameBoard.probe(); + if (!sample.isEmpty()) { + if (rand.nextFloat() < species.getResearchSuitability(sample)) { + gameBoard.probe(); + } } } diff --git a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java index 2c1c0f324..018f2bc26 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameBoard.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameBoard.java @@ -10,27 +10,25 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; -import forestry.api.genetics.IAllele; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; - import forestry.api.core.INbtWritable; import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IGenome; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; public class EscritoireGameBoard implements INbtWritable, IStreamable { private static final Random rand = new Random(); @@ -44,7 +42,7 @@ public class EscritoireGameBoard implements INbtWritable, IStreamable { } - public EscritoireGameBoard(@Nonnull NBTTagCompound nbt) { + public EscritoireGameBoard(NBTTagCompound nbt) { tokenCount = nbt.getInteger("TokenCount"); if (tokenCount > 0) { @@ -82,6 +80,7 @@ public class EscritoireGameBoard implements INbtWritable, IStreamable { return true; } + @Nullable public EscritoireGameToken getToken(int index) { if (index >= tokenCount) { return null; @@ -112,6 +111,7 @@ public class EscritoireGameBoard implements INbtWritable, IStreamable { return unrevealed; } + @Nullable private EscritoireGameToken getSelected() { for (EscritoireGameToken token : gameTokens) { if (token.isSelected()) { @@ -217,13 +217,13 @@ public class EscritoireGameBoard implements INbtWritable, IStreamable { /* IStreamable */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeVarInt(tokenCount); data.writeStreamables(gameTokens); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { tokenCount = data.readVarInt(); data.readStreamables(gameTokens, EscritoireGameToken.class); } diff --git a/src/main/java/forestry/core/tiles/EscritoireGameToken.java b/src/main/java/forestry/core/tiles/EscritoireGameToken.java index a8098e9ff..6de5f98eb 100644 --- a/src/main/java/forestry/core/tiles/EscritoireGameToken.java +++ b/src/main/java/forestry/core/tiles/EscritoireGameToken.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -20,9 +19,8 @@ import forestry.api.genetics.IAllele; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.utils.ColourUtil; import forestry.core.utils.Translator; import net.minecraft.item.ItemStack; @@ -45,9 +43,8 @@ public class EscritoireGameToken implements INbtWritable, IStreamable { @Nullable private IIndividual tokenIndividual; - @Nullable - private ItemStack tokenStack; - @Nonnull + private ItemStack tokenStack = ItemStack.EMPTY; + private State state = State.UNREVEALED; @SuppressWarnings("unused") @@ -55,23 +52,16 @@ public class EscritoireGameToken implements INbtWritable, IStreamable { // required for IStreamable serialization } - public EscritoireGameToken(@Nullable String speciesUid) { + public EscritoireGameToken(String speciesUid) { setTokenSpecies(speciesUid); } - public EscritoireGameToken(@Nonnull NBTTagCompound nbttagcompound) { + public EscritoireGameToken(NBTTagCompound nbttagcompound) { if (nbttagcompound.hasKey("state")) { int stateOrdinal = nbttagcompound.getInteger("state"); state = State.values()[stateOrdinal]; } - // legacy - if (nbttagcompound.hasKey("tokenStack")) { - tokenStack = ItemStack.loadItemStackFromNBT(nbttagcompound.getCompoundTag("tokenStack")); - ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(tokenStack); - tokenIndividual = speciesRoot.getMember(tokenStack); - } - if (nbttagcompound.hasKey("tokenSpecies")) { String speciesUid = nbttagcompound.getString("tokenSpecies"); setTokenSpecies(speciesUid); @@ -91,7 +81,6 @@ public class EscritoireGameToken implements INbtWritable, IStreamable { } } - @Nullable public ItemStack getTokenStack() { return tokenStack; } @@ -146,9 +135,9 @@ public class EscritoireGameToken implements INbtWritable, IStreamable { } } - @Nonnull + public String getTooltip() { - return tokenStack != null ? tokenStack.getDisplayName() : Translator.translateToLocal("for.gui.unknown"); + return !tokenStack.isEmpty() ? tokenStack.getDisplayName() : Translator.translateToLocal("for.gui.unknown"); } public String[] getOverlayIcons() { @@ -178,21 +167,21 @@ public class EscritoireGameToken implements INbtWritable, IStreamable { /* IStreamable */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeEnum(state, State.VALUES); if (tokenIndividual != null) { data.writeBoolean(true); - data.writeUTF(tokenIndividual.getGenome().getPrimary().getUID()); + data.writeString(tokenIndividual.getGenome().getPrimary().getUID()); } else { data.writeBoolean(false); } } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { state = data.readEnum(State.VALUES); if (data.readBoolean()) { - String speciesUid = data.readUTF(); + String speciesUid = data.readString(); setTokenSpecies(speciesUid); } } diff --git a/src/main/java/forestry/core/tiles/EscritoireTextSource.java b/src/main/java/forestry/core/tiles/EscritoireTextSource.java index 40867c260..3d6876ab2 100644 --- a/src/main/java/forestry/core/tiles/EscritoireTextSource.java +++ b/src/main/java/forestry/core/tiles/EscritoireTextSource.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.tiles; +import javax.annotation.Nullable; + import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; @@ -45,12 +47,14 @@ public class EscritoireTextSource { researchNotes.put(Notes.empty, Translator.translateToLocal("for.gui.escritoire.instructions")); } + @Nullable private String researchNote; + @Nullable private Notes lastNoteLevel; public String getText(EscritoireGame escritoireGame) { Notes noteLevel = getNoteLevel(escritoireGame); - if (lastNoteLevel != noteLevel) { + if (lastNoteLevel != noteLevel || researchNote == null) { researchNote = getRandomNote(noteLevel); lastNoteLevel = noteLevel; } diff --git a/src/main/java/forestry/core/tiles/ILiquidTankTile.java b/src/main/java/forestry/core/tiles/ILiquidTankTile.java index 2ef83cb65..341830ff9 100644 --- a/src/main/java/forestry/core/tiles/ILiquidTankTile.java +++ b/src/main/java/forestry/core/tiles/ILiquidTankTile.java @@ -10,58 +10,10 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; - import forestry.api.core.ILocatable; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; -import net.minecraftforge.fluids.capability.IFluidTankProperties; - import forestry.core.fluids.ITankManager; -public interface ILiquidTankTile extends ILocatable, IFluidHandler { - - @Nonnull +public interface ILiquidTankTile extends ILocatable { ITankManager getTankManager(); - - @Override - default int fill(EnumFacing from, FluidStack resource, boolean doFill) { - return getTankManager().fill(resource, doFill); - } - - @Override - default FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain) { - return getTankManager().drain(resource, doDrain); - } - - @Override - default FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain) { - return getTankManager().drain(maxDrain, doDrain); - } - - @Override - default boolean canFill(EnumFacing from, Fluid fluid) { - return getTankManager().canFillFluidType(new FluidStack(fluid, Fluid.BUCKET_VOLUME)); - } - - @Override - default boolean canDrain(EnumFacing from, Fluid fluid) { - return getTankManager().canDrainFluidType(new FluidStack(fluid, Fluid.BUCKET_VOLUME)); - } - - @Override - default FluidTankInfo[] getTankInfo(EnumFacing from) { - IFluidTankProperties[] tankProperties = getTankManager().getTankProperties(); - FluidTankInfo[] tankInfos = new FluidTankInfo[tankProperties.length]; - for (int i = 0; i < tankProperties.length; i++) { - IFluidTankProperties fluidTankProperties = tankProperties[i]; - tankInfos[i] = new FluidTankInfo(fluidTankProperties.getContents(), fluidTankProperties.getCapacity()); - } - return tankInfos; - } } diff --git a/src/main/java/forestry/core/tiles/TileAnalyzer.java b/src/main/java/forestry/core/tiles/TileAnalyzer.java index d336dbe8c..967e3b875 100644 --- a/src/main/java/forestry/core/tiles/TileAnalyzer.java +++ b/src/main/java/forestry/core/tiles/TileAnalyzer.java @@ -10,42 +10,38 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - import forestry.api.arboriculture.TreeManager; import forestry.api.core.ForestryAPI; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IIndividual; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.Fluids; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; import forestry.core.gui.ContainerAnalyzer; import forestry.core.gui.GuiAnalyzer; import forestry.core.inventory.InventoryAnalyzer; import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.PacketItemStackDisplay; import forestry.core.proxy.Proxies; import forestry.core.utils.GeneticsUtil; import forestry.core.utils.InventoryUtil; import forestry.plugins.ForestryPluginUids; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiquidTankTile, IItemStackDisplay { private static final int TIME_TO_ANALYZE = 125; @@ -57,8 +53,9 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui private final IInventory invInput; private final IInventory invOutput; + @Nullable private IIndividual specimenToAnalyze; - private ItemStack individualOnDisplayClient; + private ItemStack individualOnDisplayClient = ItemStack.EMPTY; /* CONSTRUCTOR */ public TileAnalyzer() { @@ -71,7 +68,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } /* SAVING & LOADING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -85,7 +82,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui tankManager.readFromNBT(nbttagcompound); ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - if (stackToAnalyze != null) { + if (!stackToAnalyze.isEmpty()) { specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(stackToAnalyze); } } @@ -104,7 +101,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui @Override public boolean workCycle() { ItemStack stackToAnalyze = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - if (stackToAnalyze == null) { + if (stackToAnalyze.isEmpty() || specimenToAnalyze == null) { return false; } @@ -127,13 +124,14 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui return false; } - setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, null); + setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, ItemStack.EMPTY); PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } + @Nullable private Integer getInputSlotIndex() { for (int slotIndex = 0; slotIndex < invInput.getSizeInventory(); slotIndex++) { ItemStack inputStack = invInput.getStackInSlot(slotIndex); @@ -146,7 +144,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui /* Network */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); ItemStack displayStack = getIndividualOnDisplay(); data.writeItemStack(displayStack); @@ -154,7 +152,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); individualOnDisplayClient = data.readItemStack(); tankManager.readData(data); @@ -164,7 +162,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui public void handleItemStackForDisplay(ItemStack itemStack) { if (!ItemStack.areItemStacksEqual(itemStack, individualOnDisplayClient)) { individualOnDisplayClient = itemStack; - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } } @@ -175,14 +173,14 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui ItemStack specimen = getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); - boolean hasSpecimen = specimen != null; + boolean hasSpecimen = !specimen.isEmpty(); boolean hasResource = true; boolean hasSpace = true; if (hasSpecimen) { hasSpace = InventoryUtil.tryAddStack(invOutput, specimen, true, false); - if (!specimenToAnalyze.isAnalyzed()) { + if (specimenToAnalyze != null && !specimenToAnalyze.isAnalyzed()) { FluidStack drained = resourceTank.drain(HONEY_REQUIRED, false); hasResource = drained != null && drained.amount == HONEY_REQUIRED; } @@ -196,7 +194,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } private void moveSpecimenToAnalyzeSlot() { - if (getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE) != null) { + if (!getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE).isEmpty()) { return; } @@ -206,15 +204,12 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } ItemStack inputStack = invInput.getStackInSlot(slotIndex); - if (inputStack == null) { + if (inputStack.isEmpty()) { return; } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ARBORICULTURE) && !TreeManager.treeRoot.isMember(inputStack)) { - ItemStack ersatz = GeneticsUtil.convertToGeneticEquivalent(inputStack); - if (ersatz != null) { - inputStack = ersatz; - } + inputStack = GeneticsUtil.convertToGeneticEquivalent(inputStack); } specimenToAnalyze = AlleleManager.alleleRegistry.getIndividual(inputStack); @@ -223,7 +218,7 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } setInventorySlotContents(InventoryAnalyzer.SLOT_ANALYZE, inputStack); - invInput.setInventorySlotContents(slotIndex, null); + invInput.setInventorySlotContents(slotIndex, ItemStack.EMPTY); if (specimenToAnalyze.isAnalyzed()) { setTicksPerWorkCycle(1); @@ -234,31 +229,32 @@ public class TileAnalyzer extends TilePowered implements ISidedInventory, ILiqui } PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); + Proxies.net.sendNetworkPacket(packet, pos, world); } public ItemStack getIndividualOnDisplay() { - if (worldObj.isRemote) { + if (world.isRemote) { return individualOnDisplayClient; } return getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); } /* ILiquidTankTile */ - @Nonnull + @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/core/tiles/TileBase.java b/src/main/java/forestry/core/tiles/TileBase.java index c133f2475..b8b12b1b9 100644 --- a/src/main/java/forestry/core/tiles/TileBase.java +++ b/src/main/java/forestry/core/tiles/TileBase.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.tiles; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -28,7 +29,7 @@ import forestry.core.gui.IHintSource; public abstract class TileBase extends TileForestry implements IHintSource { protected final List hints; - protected TileBase(String hintKey) { + protected TileBase(@Nullable String hintKey) { this.hints = new ArrayList<>(Config.hints.get(hintKey)); } diff --git a/src/main/java/forestry/core/tiles/TileEngine.java b/src/main/java/forestry/core/tiles/TileEngine.java index 536e52b4d..853a3c768 100644 --- a/src/main/java/forestry/core/tiles/TileEngine.java +++ b/src/main/java/forestry/core/tiles/TileEngine.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -20,21 +19,19 @@ import forestry.core.blocks.BlockBase; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.proxy.Proxies; import forestry.energy.EnergyHelper; import forestry.energy.EnergyManager; import forestry.energy.EnergyTransferMode; -import forestry.energy.compat.rf.IEnergyConnectionDelegated; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; -public abstract class TileEngine extends TileBase implements IEnergyConnectionDelegated, IActivatable, IStreamableGui { +public abstract class TileEngine extends TileBase implements IActivatable, IStreamableGui { private static final int CANT_SEND_ENERGY_TIME = 20; private boolean active = false; // Used for smp. @@ -56,7 +53,7 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe public float progress; protected final EnergyManager energyManager; - protected TileEngine(String hintKey, int maxHeat, int maxEnergy) { + protected TileEngine(@Nullable String hintKey, int maxHeat, int maxEnergy) { super(hintKey); this.maxHeat = maxHeat; energyManager = new EnergyManager(2000, maxEnergy); @@ -114,9 +111,9 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe errorLogic.setCondition(!enabledRedstone, EnumErrorCode.NO_REDSTONE); // Determine targeted tile - IBlockState blockState = worldObj.getBlockState(getPos()); + IBlockState blockState = world.getBlockState(getPos()); EnumFacing facing = blockState.getValue(BlockBase.FACING); - TileEntity tile = worldObj.getTileEntity(getPos().offset(facing)); + TileEntity tile = world.getTileEntity(getPos().offset(facing)); float newPistonSpeed = getPistonSpeed(); if (newPistonSpeed != pistonSpeedServer) { @@ -175,8 +172,8 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe } this.active = active; - if (!worldObj.isRemote) { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + if (!world.isRemote) { + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), pos, world); } } @@ -245,7 +242,7 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe forceCooldown = nbt.getBoolean("ForceCooldown"); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt = super.writeToNBT(nbt); @@ -259,7 +256,7 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe /* NETWORK */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); data.writeBoolean(active); data.writeInt(heat); @@ -268,41 +265,40 @@ public abstract class TileEngine extends TileBase implements IEnergyConnectionDe } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); active = data.readBoolean(); heat = data.readInt(); pistonSpeedServer = data.readFloat(); energyManager.readData(data); } - + @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { data.writeInt(currentOutput); data.writeInt(heat); energyManager.writeData(data); } - + @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { currentOutput = data.readInt(); heat = data.readInt(); energyManager.readData(data); } - @Override public EnergyManager getEnergyManager() { return energyManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return energyManager.hasCapability(capability) || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { T energyCapability = energyManager.getCapability(capability); if (energyCapability != null) { return energyCapability; diff --git a/src/main/java/forestry/core/tiles/TileEscritoire.java b/src/main/java/forestry/core/tiles/TileEscritoire.java index c3f853f06..b50486f63 100644 --- a/src/main/java/forestry/core/tiles/TileEscritoire.java +++ b/src/main/java/forestry/core/tiles/TileEscritoire.java @@ -10,9 +10,9 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import java.io.IOException; +import forestry.core.network.PacketBufferForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -28,8 +28,6 @@ import forestry.core.gui.GuiEscritoire; import forestry.core.inventory.InventoryAnalyzer; import forestry.core.inventory.InventoryEscritoire; import forestry.core.inventory.watchers.ISlotPickupWatcher; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; import forestry.core.network.packets.PacketItemStackDisplay; import forestry.core.proxy.Proxies; @@ -38,7 +36,7 @@ import forestry.core.utils.InventoryUtil; public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPickupWatcher, IStreamableGui, IItemStackDisplay { private final EscritoireGame game = new EscritoireGame(); - private ItemStack individualOnDisplayClient; + private ItemStack individualOnDisplayClient = ItemStack.EMPTY; public TileEscritoire() { super("escritoire"); @@ -52,7 +50,7 @@ public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPi game.readFromNBT(nbttagcompound); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -81,7 +79,7 @@ public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPi } IAlleleSpecies species = individual.getGenome().getPrimary(); - for (ItemStack itemstack : species.getResearchBounty(worldObj, gameProfile, individual, game.getBountyLevel())) { + for (ItemStack itemstack : species.getResearchBounty(world, gameProfile, individual, game.getBountyLevel())) { InventoryUtil.addStack(getInternalInventory(), itemstack, InventoryEscritoire.SLOT_RESULTS_1, InventoryEscritoire.SLOTS_RESULTS_COUNT, true); } } @@ -90,7 +88,7 @@ public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPi int filledSlots = 0; int required = game.getSampleSize(InventoryEscritoire.SLOTS_INPUT_COUNT); for (int i = InventoryEscritoire.SLOT_INPUT_1; i < InventoryEscritoire.SLOT_INPUT_1 + required; i++) { - if (getStackInSlot(i) != null) { + if (!getStackInSlot(i).isEmpty()) { filledSlots++; } } @@ -99,57 +97,57 @@ public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPi } public void probe() { - if (worldObj.isRemote) { + if (world.isRemote) { return; } ItemStack analyze = getStackInSlot(InventoryEscritoire.SLOT_ANALYZE); - if (analyze != null && areProbeSlotsFilled()) { + if (!analyze.isEmpty() && areProbeSlotsFilled()) { game.probe(analyze, this, InventoryEscritoire.SLOT_INPUT_1, InventoryEscritoire.SLOTS_INPUT_COUNT); } } /* NETWORK */ @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { game.writeData(data); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { game.readData(data); } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); ItemStack displayStack = getIndividualOnDisplay(); data.writeItemStack(displayStack); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); individualOnDisplayClient = data.readItemStack(); } /* ISlotPickupWatcher */ @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + public void onTake(int slotIndex, EntityPlayer player) { if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { game.reset(); PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); + Proxies.net.sendNetworkPacket(packet, pos, world); } } @Override - public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { + public void setInventorySlotContents(int slotIndex, ItemStack itemstack) { super.setInventorySlotContents(slotIndex, itemstack); if (slotIndex == InventoryEscritoire.SLOT_ANALYZE) { PacketItemStackDisplay packet = new PacketItemStackDisplay(this, getIndividualOnDisplay()); - Proxies.net.sendNetworkPacket(packet, worldObj); + Proxies.net.sendNetworkPacket(packet, pos, world); } } @@ -167,12 +165,12 @@ public class TileEscritoire extends TileBase implements ISidedInventory, ISlotPi public void handleItemStackForDisplay(ItemStack itemStack) { if (!ItemStack.areItemStacksEqual(itemStack, individualOnDisplayClient)) { individualOnDisplayClient = itemStack; - worldObj.markBlockRangeForRenderUpdate(getPos(), getPos()); + world.markBlockRangeForRenderUpdate(getPos(), getPos()); } } public ItemStack getIndividualOnDisplay() { - if (worldObj.isRemote) { + if (world.isRemote) { return individualOnDisplayClient; } return getStackInSlot(InventoryAnalyzer.SLOT_ANALYZE); diff --git a/src/main/java/forestry/core/tiles/TileForestry.java b/src/main/java/forestry/core/tiles/TileForestry.java index 2ae46723b..7b3abdbcd 100644 --- a/src/main/java/forestry/core/tiles/TileForestry.java +++ b/src/main/java/forestry/core/tiles/TileForestry.java @@ -10,27 +10,23 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; - -import forestry.api.core.ILocatable; - import java.io.IOException; import java.util.Random; +import com.google.common.base.Preconditions; import forestry.api.core.IErrorLogic; import forestry.api.core.IErrorLogicSource; +import forestry.api.core.ILocatable; import forestry.core.errors.ErrorLogic; import forestry.core.gui.IGuiHandlerTile; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.PacketTileStream; import forestry.core.proxy.Proxies; import forestry.core.utils.NBTUtilForestry; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; @@ -42,9 +38,7 @@ import net.minecraft.util.ITickable; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; -import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.wrapper.InvWrapper; @@ -56,7 +50,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE private final ErrorLogic errorHandler = new ErrorLogic(); private final AdjacentTileCache tileCache = new AdjacentTileCache(this); - @Nonnull + private IInventoryAdapter inventory = FakeInventoryAdapter.instance(); private int tickCount = rand.nextInt(256); @@ -66,7 +60,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE return tileCache; } - public void onNeighborTileChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { + public void onNeighborTileChange(World world, BlockPos pos, BlockPos neighbor) { tileCache.onNeighborChange(); } @@ -87,7 +81,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public final void update() { tickCount++; - if (!worldObj.isRemote) { + if (!world.isRemote) { updateServerSide(); } else { updateClientSide(); @@ -116,7 +110,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE inventory.readFromNBT(data); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { data = super.writeToNBT(data); @@ -130,7 +124,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE return new SPacketUpdateTileEntity(this.getPos(), 0, getUpdateTag()); } - @Nonnull + @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = super.getUpdateTag(); @@ -138,7 +132,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); NBTUtilForestry.readStreamableFromNbt(this, tag); } @@ -146,17 +140,17 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE /* INetworkedEntity */ protected final void sendNetworkUpdate() { PacketTileStream packet = new PacketTileStream(this); - Proxies.net.sendNetworkPacket(packet, worldObj); + Proxies.net.sendNetworkPacket(packet, pos, world); } /* IStreamable */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { } @@ -165,7 +159,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE @Override public World getWorldObj() { - return worldObj; + return world; } /* ITriggerProvider */ @@ -184,7 +178,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE // / REDSTONE INFO protected boolean isRedstoneActivated() { - return worldObj.isBlockIndirectlyGettingPowered(getPos()) > 0; + return world.isBlockIndirectlyGettingPowered(getPos()) > 0; } protected final void setNeedsNetworkUpdate() { @@ -213,13 +207,17 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE } protected final void setInternalInventory(IInventoryAdapter inv) { - if (inv == null) { - throw new NullPointerException("Inventory cannot be null"); - } + Preconditions.checkNotNull(inv); this.inventory = inv; } /* ISidedInventory */ + + @Override + public boolean isEmpty() { + return getInternalInventory().isEmpty(); + } + @Override public final int getSizeInventory() { return getInternalInventory().getSizeInventory(); @@ -234,7 +232,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public ItemStack decrStackSize(int slotIndex, int amount) { return getInternalInventory().decrStackSize(slotIndex, amount); } - + @Override public ItemStack removeStackFromSlot(int slotIndex) { return getInternalInventory().removeStackFromSlot(slotIndex); @@ -259,7 +257,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public final void closeInventory(EntityPlayer player) { getInternalInventory().closeInventory(player); } - + @Override public String getName() { return getUnlocalizedTitle(); @@ -269,12 +267,12 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public ITextComponent getDisplayName() { return new TextComponentTranslation(getUnlocalizedTitle()); } - + @Override - public final boolean isUseableByPlayer(EntityPlayer player) { - return getInternalInventory().isUseableByPlayer(player); + public final boolean isUsableByPlayer(EntityPlayer player) { + return getInternalInventory().isUsableByPlayer(player); } - + @Override public boolean hasCustomName() { return getInternalInventory().hasCustomName(); @@ -294,7 +292,7 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public boolean isLocked(int slotIndex) { return getInternalInventory().isLocked(slotIndex); } - + @Override public int[] getSlotsForFace(EnumFacing side) { return getInternalInventory().getSlotsForFace(side); @@ -314,46 +312,44 @@ public abstract class TileForestry extends TileEntity implements IStreamable, IE public final BlockPos getCoordinates() { return getPos(); } - + @Override public int getField(int id) { return 0; } - + @Override public int getFieldCount() { return 0; } - + @Override public void setField(int id, int value) { } - + @Override public void clear() { } - - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { - if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY && inventory != null){ - if(facing != null){ + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { + if (facing != null) { SidedInvWrapper sidedInvWrapper = new SidedInvWrapper(inventory, facing); return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(sidedInvWrapper); - }else{ + } else { InvWrapper invWrapper = new InvWrapper(inventory); return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(invWrapper); } - + } return super.getCapability(capability, facing); } - + @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { - if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY && inventory != null){ - return true; - } - return super.hasCapability(capability, facing); + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || + super.hasCapability(capability, facing); } } diff --git a/src/main/java/forestry/core/tiles/TileMill.java b/src/main/java/forestry/core/tiles/TileMill.java index 7804885e2..234f0a82a 100644 --- a/src/main/java/forestry/core/tiles/TileMill.java +++ b/src/main/java/forestry/core/tiles/TileMill.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.core.tiles; +import javax.annotation.Nullable; import java.io.IOException; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; public abstract class TileMill extends TileBase { @@ -22,7 +22,7 @@ public abstract class TileMill extends TileBase { public int charge = 0; public float progress; - protected TileMill(String hintKey) { + protected TileMill(@Nullable String hintKey) { super(hintKey); speed = 0.01F; } @@ -38,7 +38,7 @@ public abstract class TileMill extends TileBase { } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); data.writeInt(charge); data.writeFloat(speed); @@ -46,7 +46,7 @@ public abstract class TileMill extends TileBase { } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); charge = data.readInt(); speed = data.readFloat(); diff --git a/src/main/java/forestry/core/tiles/TileNaturalistChest.java b/src/main/java/forestry/core/tiles/TileNaturalistChest.java index d55eef40a..218e9afeb 100644 --- a/src/main/java/forestry/core/tiles/TileNaturalistChest.java +++ b/src/main/java/forestry/core/tiles/TileNaturalistChest.java @@ -12,20 +12,18 @@ package forestry.core.tiles; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.SoundEvents; -import net.minecraft.util.SoundCategory; -import net.minecraft.util.SoundEvent; -import net.minecraft.util.math.AxisAlignedBB; - import forestry.api.genetics.ISpeciesRoot; import forestry.core.gui.ContainerNaturalistInventory; import forestry.core.gui.GuiHandler; import forestry.core.gui.GuiNaturalistInventory; import forestry.core.gui.IPagedInventory; import forestry.core.inventory.InventoryNaturalistChest; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.SoundEvents; +import net.minecraft.util.SoundCategory; +import net.minecraft.util.SoundEvent; +import net.minecraft.util.math.AxisAlignedBB; public abstract class TileNaturalistChest extends TileBase implements IPagedInventory { private static final float lidAngleVariationPerTick = 0.1F; @@ -59,7 +57,7 @@ public abstract class TileNaturalistChest extends TileBase implements IPagedInve protected void updateClientSide() { updates(); } - + @Override protected void updateServerSide() { updates(); @@ -90,7 +88,7 @@ public abstract class TileNaturalistChest extends TileBase implements IPagedInve } private void playLidSound(SoundEvent sound) { - this.worldObj.playSound(null, getPos(), sound, SoundCategory.BLOCKS, 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F); + this.world.playSound(null, getPos(), sound, SoundCategory.BLOCKS, 0.5F, this.world.rand.nextFloat() * 0.1F + 0.9F); } @Override @@ -100,13 +98,13 @@ public abstract class TileNaturalistChest extends TileBase implements IPagedInve /* IStreamable */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); data.writeInt(numPlayersUsing); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); numPlayersUsing = data.readInt(); } diff --git a/src/main/java/forestry/core/tiles/TilePowered.java b/src/main/java/forestry/core/tiles/TilePowered.java index f8fc22618..d07317cf4 100644 --- a/src/main/java/forestry/core/tiles/TilePowered.java +++ b/src/main/java/forestry/core/tiles/TilePowered.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -18,21 +17,18 @@ import forestry.api.core.IErrorLogic; import forestry.core.circuits.ISpeedUpgradable; import forestry.core.config.Config; import forestry.core.errors.EnumErrorCode; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.energy.EnergyHelper; import forestry.energy.EnergyManager; import forestry.energy.EnergyTransferMode; -import forestry.energy.compat.rf.IEnergyHandlerDelegated; -import forestry.energy.compat.rf.IEnergyReceiverDelegated; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; //@Optional.Interface(iface = "buildcraft.api.tiles.IHasWork", modid = "BuildCraftAPI|tiles") -public abstract class TilePowered extends TileBase implements IRenderableTile, IEnergyReceiverDelegated, IEnergyHandlerDelegated, ISpeedUpgradable, IStreamableGui { +public abstract class TilePowered extends TileBase implements IRenderableTile, ISpeedUpgradable, IStreamableGui { private static final int WORK_TICK_INTERVAL = 5; // one Forestry work tick happens every WORK_TICK_INTERVAL game ticks private final EnergyManager energyManager; @@ -67,7 +63,7 @@ public abstract class TilePowered extends TileBase implements IRenderableTile, I } public int getTicksPerWorkCycle() { - if (worldObj.isRemote) { + if (world.isRemote) { return ticksPerWorkCycle; } return Math.round(ticksPerWorkCycle / speedMultiplier); @@ -149,7 +145,6 @@ public abstract class TilePowered extends TileBase implements IRenderableTile, I return workCounter * i / ticksPerWorkCycle; } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt = super.writeToNBT(nbt); @@ -164,14 +159,14 @@ public abstract class TilePowered extends TileBase implements IRenderableTile, I } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { energyManager.writeData(data); data.writeVarInt(workCounter); data.writeVarInt(getTicksPerWorkCycle()); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { energyManager.readData(data); workCounter = data.readVarInt(); ticksPerWorkCycle = data.readVarInt(); @@ -198,18 +193,13 @@ public abstract class TilePowered extends TileBase implements IRenderableTile, I /* IPowerHandler */ @Override - public EnergyManager getEnergyManager() { - return energyManager; - } - - @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return energyManager.hasCapability(capability) || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { T energyCapability = energyManager.getCapability(capability); if (energyCapability != null) { return energyCapability; diff --git a/src/main/java/forestry/core/tiles/TileUtil.java b/src/main/java/forestry/core/tiles/TileUtil.java index 399b946bf..461807aeb 100644 --- a/src/main/java/forestry/core/tiles/TileUtil.java +++ b/src/main/java/forestry/core/tiles/TileUtil.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; @@ -30,29 +29,16 @@ import net.minecraftforge.items.wrapper.SidedInvWrapper; public abstract class TileUtil { public static boolean isUsableByPlayer(EntityPlayer player, TileEntity tile) { - if (tile == null) { - return false; - } BlockPos pos = tile.getPos(); World world = tile.getWorld(); - - if (tile.isInvalid()) { - return false; - } - - if (world.getTileEntity(pos) != tile) { - return false; - } - - return player.getDistanceSq(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D) <= 64.0D; + return !tile.isInvalid() && + world.getTileEntity(pos) == tile && + player.getDistanceSq(pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D) <= 64.0D; } @Nullable - public static T getTile(@Nonnull IBlockAccess world, @Nonnull BlockPos pos, @Nonnull Class tileClass) { - if(pos == null){ - return null; - } + public static T getTile( IBlockAccess world, BlockPos pos, Class tileClass) { TileEntity tileEntity = world.getTileEntity(pos); if (tileClass.isInstance(tileEntity)) { return tileClass.cast(tileEntity); @@ -61,6 +47,7 @@ public abstract class TileUtil { } } + @Nullable public static IItemHandler getInventoryFromTile(@Nullable TileEntity tile, @Nullable EnumFacing side) { if (tile == null) { return null; diff --git a/src/main/java/forestry/core/tiles/package-info.java b/src/main/java/forestry/core/tiles/package-info.java new file mode 100644 index 000000000..95f967c42 --- /dev/null +++ b/src/main/java/forestry/core/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/triggers/package-info.java b/src/main/java/forestry/core/triggers/package-info.java new file mode 100644 index 000000000..533b2aac2 --- /dev/null +++ b/src/main/java/forestry/core/triggers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.triggers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/utils/BlockUtil.java b/src/main/java/forestry/core/utils/BlockUtil.java index dd5b21fe2..712799c58 100644 --- a/src/main/java/forestry/core/utils/BlockUtil.java +++ b/src/main/java/forestry/core/utils/BlockUtil.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.core.utils; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; @@ -24,7 +23,6 @@ import net.minecraft.block.BlockStaticLiquid; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.AxisAlignedBB; @@ -67,7 +65,7 @@ public abstract class BlockUtil { } return null; } - + public static boolean isValidPodLocation(World world, BlockPos pos, EnumFacing direction) { pos = pos.offset(direction); if (!world.isBlockLoaded(pos)) { @@ -83,13 +81,16 @@ public abstract class BlockUtil { } public static boolean isWoodSlabBlock(IBlockState blockState, Block block, IBlockAccess world, BlockPos pos) { - if (blockState == null || block == null || block.isAir(blockState, world, pos)) { + if (block.isAir(blockState, world, pos)) { return false; } - if(Item.getItemFromBlock(block) == null){ + + ItemStack stack = new ItemStack(block); + if (stack.isEmpty()) { return false; } - int[] oreIds = OreDictionary.getOreIDs(new ItemStack(block)); + + int[] oreIds = OreDictionary.getOreIDs(stack); for (int oreId : oreIds) { if (oreId == slabWoodId) { return true; @@ -104,14 +105,16 @@ public abstract class BlockUtil { return block.isReplaceable(world, pos) && !(block instanceof BlockStaticLiquid); } - public static RayTraceResult collisionRayTrace(@Nonnull BlockPos pos, @Nonnull Vec3d startVec, @Nonnull Vec3d endVec, @Nonnull AxisAlignedBB bounds) { + @Nullable + public static RayTraceResult collisionRayTrace(BlockPos pos, Vec3d startVec, Vec3d endVec, AxisAlignedBB bounds) { return collisionRayTrace(pos, startVec, endVec, bounds.minX, bounds.minY, bounds.minZ, bounds.maxX, bounds.maxY, bounds.maxZ); } /** * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. */ - public static RayTraceResult collisionRayTrace(@Nonnull BlockPos pos, @Nonnull Vec3d startVec, @Nonnull Vec3d endVec, double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + @Nullable + public static RayTraceResult collisionRayTrace(BlockPos pos, Vec3d startVec, Vec3d endVec, double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { startVec = startVec.addVector(-pos.getX(), -pos.getY(), -pos.getZ()); endVec = endVec.addVector(-pos.getX(), -pos.getY(), -pos.getZ()); Vec3d vec32 = startVec.getIntermediateWithXValue(endVec, minX); @@ -147,7 +150,7 @@ public abstract class BlockUtil { Vec3d minHit = null; - if (vec32 != null && (minHit == null || startVec.squareDistanceTo(vec32) < startVec.squareDistanceTo(minHit))) { + if (vec32 != null) { minHit = vec32; } @@ -207,21 +210,21 @@ public abstract class BlockUtil { /** * Checks if a vector is within the Y and Z bounds of the block. */ - private static boolean isVecInsideYZBounds(Vec3d vec, double minY, double minZ, double maxY, double maxZ) { + private static boolean isVecInsideYZBounds(@Nullable Vec3d vec, double minY, double minZ, double maxY, double maxZ) { return vec != null && vec.yCoord >= minY && vec.yCoord <= maxY && vec.zCoord >= minZ && vec.zCoord <= maxZ; } /** * Checks if a vector is within the X and Z bounds of the block. */ - private static boolean isVecInsideXZBounds(Vec3d vec, double minX, double minZ, double maxX, double maxZ) { + private static boolean isVecInsideXZBounds(@Nullable Vec3d vec, double minX, double minZ, double maxX, double maxZ) { return vec != null && vec.xCoord >= minX && vec.xCoord <= maxX && vec.zCoord >= minZ && vec.zCoord <= maxZ; } /** * Checks if a vector is within the X and Y bounds of the block. */ - private static boolean isVecInsideXYBounds(Vec3d vec, double minX, double minY, double maxX, double maxY) { + private static boolean isVecInsideXYBounds(@Nullable Vec3d vec, double minX, double minY, double maxX, double maxY) { return vec != null && vec.xCoord >= minX && vec.xCoord <= maxX && vec.yCoord >= minY && vec.yCoord <= maxY; } @@ -229,19 +232,19 @@ public abstract class BlockUtil { public static boolean canReplace(IBlockState blockState, World world, BlockPos pos) { Block block = blockState.getBlock(); - return block.isReplaceable(world, pos) && !block.getMaterial(blockState).isLiquid(); + return block.isReplaceable(world, pos) && !blockState.getMaterial().isLiquid(); } - - public static boolean canPlaceTree(IBlockState blockState, World world, BlockPos pos){ + + public static boolean canPlaceTree(IBlockState blockState, World world, BlockPos pos) { BlockPos downPos = pos.down(); Block block = world.getBlockState(downPos).getBlock(); - if(block.isReplaceable(world, downPos) && block.getMaterial(blockState).isLiquid() || block.isLeaves(blockState, world, downPos) || block.isWood(world, downPos)){ - return false; - } - return true; + return !(block.isReplaceable(world, downPos) && + blockState.getMaterial().isLiquid()) && + !block.isLeaves(blockState, world, downPos) && + !block.isWood(world, downPos); } - - public static BlockPos getNextReplaceableUpPos(World world, BlockPos pos){ + + public static BlockPos getNextReplaceableUpPos(World world, BlockPos pos) { IBlockState blockState; do { @@ -251,8 +254,8 @@ public abstract class BlockUtil { return pos; } - - public static BlockPos getNextSolidDownPos(World world, BlockPos pos){ + + public static BlockPos getNextSolidDownPos(World world, BlockPos pos) { IBlockState blockState; do { @@ -263,7 +266,9 @@ public abstract class BlockUtil { return pos; } - /** Copied from {@link Block#shouldSideBeRendered} */ + /** + * Copied from {@link Block#shouldSideBeRendered} + */ public static boolean shouldSideBeRendered(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { AxisAlignedBB axisalignedbb = blockState.getBoundingBox(blockAccess, pos); @@ -302,28 +307,28 @@ public abstract class BlockUtil { return !blockAccess.getBlockState(pos.offset(side)).doesSideBlockRendering(blockAccess, pos.offset(side), side.getOpposite()); } - public static boolean setBlockWithPlaceSound(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState blockState) { + public static boolean setBlockWithPlaceSound(World world, BlockPos pos, IBlockState blockState) { if (world.setBlockState(pos, blockState)) { PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.SoundFXType.BLOCK_PLACE, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } return false; } - public static boolean setBlockWithBreakSound(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState blockState, @Nonnull IBlockState oldState) { + public static boolean setBlockWithBreakSound(World world, BlockPos pos, IBlockState blockState, IBlockState oldState) { if (world.setBlockState(pos, blockState)) { PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, oldState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } return false; } - public static boolean setBlockToAirWithSound(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState oldState) { + public static boolean setBlockToAirWithSound(World world, BlockPos pos, IBlockState oldState) { if (world.setBlockToAir(pos)) { PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, oldState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } return false; @@ -331,7 +336,7 @@ public abstract class BlockUtil { @Nullable public static > IProperty getProperty(Block block, String propertyName, Class valueClass) { - for (IProperty property : block.getDefaultState().getPropertyNames()) { + for (IProperty property : block.getDefaultState().getPropertyKeys()) { if (property.getName().equals(propertyName)) { if (property.getValueClass().isAssignableFrom(valueClass)) { //noinspection unchecked diff --git a/src/main/java/forestry/core/utils/CamouflageUtil.java b/src/main/java/forestry/core/utils/CamouflageUtil.java index 92dcfa223..8e204d8d8 100644 --- a/src/main/java/forestry/core/utils/CamouflageUtil.java +++ b/src/main/java/forestry/core/utils/CamouflageUtil.java @@ -10,14 +10,14 @@ ******************************************************************************/ package forestry.core.utils; +import javax.annotation.Nullable; import java.io.IOException; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflagedTile; import forestry.api.multiblock.IMultiblockComponent; import forestry.api.multiblock.IMultiblockController; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; @@ -26,54 +26,52 @@ import net.minecraft.world.IBlockAccess; public class CamouflageUtil { - public static void writeCamouflageBlockToNBT(NBTTagCompound data, ICamouflageHandler handler, String type){ + public static void writeCamouflageBlockToNBT(NBTTagCompound data, ICamouflageHandler handler, String type) { ItemStack camouflageBlock = handler.getCamouflageBlock(type); - if(camouflageBlock != null){ + if (!camouflageBlock.isEmpty()) { NBTTagCompound nbtTag = new NBTTagCompound(); camouflageBlock.writeToNBT(nbtTag); data.setTag("Camouflage" + type, nbtTag); } } - - public static void readCamouflageBlockFromNBT(NBTTagCompound data, ICamouflageHandler handler, String type){ - if(data.hasKey("Camouflage" + type)){ - handler.setCamouflageBlock(type, ItemStack.loadItemStackFromNBT(data.getCompoundTag("Camouflage" + type)), false); + + public static void readCamouflageBlockFromNBT(NBTTagCompound data, ICamouflageHandler handler, String type) { + if (data.hasKey("Camouflage" + type)) { + handler.setCamouflageBlock(type, new ItemStack(data.getCompoundTag("Camouflage" + type)), false); } } - - public static void writeCamouflageBlockToData(DataOutputStreamForestry data, ICamouflageHandler handler, String type) throws IOException{ + + public static void writeCamouflageBlockToData(PacketBufferForestry data, ICamouflageHandler handler, String type) { ItemStack camouflageBlock = handler.getCamouflageBlock(type); - if(camouflageBlock != null){ + if (!camouflageBlock.isEmpty()) { data.writeShort(1); - data.writeUTF(type); + data.writeString(type); data.writeItemStack(camouflageBlock); - }else{ + } else { data.writeShort(0); } } - - public static void readCamouflageBlockFromData(DataInputStreamForestry data, ICamouflageHandler handler) throws IOException{ - if(data.readShort() == 1){ - handler.setCamouflageBlock(data.readUTF(), data.readItemStack(), false); + + public static void readCamouflageBlockFromData(PacketBufferForestry data, ICamouflageHandler handler) throws IOException { + if (data.readShort() == 1) { + handler.setCamouflageBlock(data.readString(), data.readItemStack(), false); } } - - public static ICamouflageHandler getCamouflageHandler(IBlockAccess world, BlockPos pos){ - if(pos == null || world == null){ - return null; - } + + @Nullable + public static ICamouflageHandler getCamouflageHandler(IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); - if(tile instanceof ICamouflagedTile){ + if (tile instanceof ICamouflagedTile) { ICamouflagedTile block = (ICamouflagedTile) tile; String type = block.getCamouflageType(); ICamouflageHandler handler = null; - if(tile instanceof ICamouflageHandler){ + if (tile instanceof ICamouflageHandler) { handler = (ICamouflageHandler) tile; } - if((handler == null || handler.getCamouflageBlock(type) == null) && tile instanceof IMultiblockComponent){ + if ((handler == null || handler.getCamouflageBlock(type).isEmpty()) && tile instanceof IMultiblockComponent) { IMultiblockComponent component = (IMultiblockComponent) tile; IMultiblockController controller = component.getMultiblockLogic().getController(); - if(controller instanceof ICamouflageHandler){ + if (controller instanceof ICamouflageHandler) { handler = (ICamouflageHandler) controller; } } @@ -81,41 +79,30 @@ public class CamouflageUtil { } return null; } - - public static ItemStack getCamouflageBlock(IBlockAccess world, BlockPos pos){ - if(pos == null || world == null){ - return null; - } + + public static ItemStack getCamouflageBlock(IBlockAccess world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); - if(tile instanceof ICamouflagedTile){ + if (tile instanceof ICamouflagedTile) { ICamouflagedTile block = (ICamouflagedTile) tile; String type = block.getCamouflageType(); - ItemStack camouflageStack = null; - ICamouflageHandler tileHandler = null; - ICamouflageHandler multiblockHandler = null; - if(tile instanceof ICamouflageHandler){ - tileHandler = (ICamouflageHandler) tile; + ItemStack camouflageStack = ItemStack.EMPTY; + + if (tile instanceof ICamouflageHandler) { + ICamouflageHandler tileHandler = (ICamouflageHandler) tile; camouflageStack = tileHandler.getCamouflageBlock(type); } - if(camouflageStack == null && tile instanceof IMultiblockComponent){ + else if (tile instanceof IMultiblockComponent) { IMultiblockComponent component = (IMultiblockComponent) tile; IMultiblockController controller = component.getMultiblockLogic().getController(); - if(controller.isAssembled() && controller instanceof ICamouflageHandler){ - multiblockHandler = (ICamouflageHandler) controller; + if (controller.isAssembled() && controller instanceof ICamouflageHandler) { + ICamouflageHandler multiblockHandler = (ICamouflageHandler) controller; camouflageStack = multiblockHandler.getCamouflageBlock(type); } } - if(camouflageStack == null){ - if(tileHandler != null){ - camouflageStack = tileHandler.getDefaultCamouflageBlock(type); - } - if(multiblockHandler != null && camouflageStack == null){ - camouflageStack = multiblockHandler.getDefaultCamouflageBlock(type); - } - } + return camouflageStack; } - return null; + return ItemStack.EMPTY; } - + } diff --git a/src/main/java/forestry/core/utils/ClimateUtil.java b/src/main/java/forestry/core/utils/ClimateUtil.java index 6ee7d6d96..1f27ba741 100644 --- a/src/main/java/forestry/core/utils/ClimateUtil.java +++ b/src/main/java/forestry/core/utils/ClimateUtil.java @@ -20,21 +20,16 @@ import forestry.api.core.EnumTemperature; import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IClimateHelper; import forestry.core.climate.ClimateRoom; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import net.minecraft.util.math.BlockPos; +import forestry.core.network.PacketBufferForestry; public class ClimateUtil implements IClimateHelper { @Override public boolean isWithinLimits(EnumTemperature temperature, EnumHumidity humidity, - EnumTemperature baseTemp, EnumTolerance tolTemp, - EnumHumidity baseHumid, EnumTolerance tolHumid) { - if (!getToleratedTemperature(baseTemp, tolTemp).contains(temperature)) { - return false; - } - - return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); + EnumTemperature baseTemp, EnumTolerance tolTemp, + EnumHumidity baseHumid, EnumTolerance tolHumid) { + return getToleratedTemperature(baseTemp, tolTemp).contains(temperature) && + getToleratedHumidity(baseHumid, tolHumid).contains(humidity); } @Override @@ -46,7 +41,7 @@ public class ClimateUtil implements IClimateHelper { public boolean isWithinLimits(EnumHumidity humidity, EnumHumidity baseHumid, EnumTolerance tolHumid) { return getToleratedHumidity(baseHumid, tolHumid).contains(humidity); } - + @Override public ArrayList getToleratedHumidity(EnumHumidity prefered, EnumTolerance tolerance) { @@ -209,24 +204,22 @@ public class ClimateUtil implements IClimateHelper { public String toDisplay(EnumHumidity humidity) { return Translator.translateToLocal("for.gui." + humidity.toString().toLowerCase(Locale.ENGLISH)); } - - public static void writeRoomPositionData(IClimatePosition position, DataOutputStreamForestry data) throws IOException { - data.writeInt(position.getPos().getX()); - data.writeInt(position.getPos().getY()); - data.writeInt(position.getPos().getZ()); + + public static void writeRoomPositionData(IClimatePosition position, PacketBufferForestry data) { + data.writeBlockPos(position.getPos()); writePositionData(position, data); } - - public static void writePositionData(IClimatePosition position, DataOutputStreamForestry data) throws IOException { + + public static void writePositionData(IClimatePosition position, PacketBufferForestry data) { data.writeFloat(position.getTemperature()); data.writeFloat(position.getHumidity()); } - - public static void readRoomPositionData(ClimateRoom room, DataInputStreamForestry data) throws IOException { - room.addPosition(new BlockPos(data.readInt(), data.readInt(), data.readInt()), data.readFloat(), data.readFloat()); + + public static void readRoomPositionData(ClimateRoom room, PacketBufferForestry data) { + room.addPosition(data.readBlockPos(), data.readFloat(), data.readFloat()); } - - public static void readPositionData(IClimatePosition position, DataInputStreamForestry data) throws IOException { + + public static void readPositionData(IClimatePosition position, PacketBufferForestry data) { position.setTemperature(data.readFloat()); position.setHumidity(data.readFloat()); } diff --git a/src/main/java/forestry/core/utils/EntityUtil.java b/src/main/java/forestry/core/utils/EntityUtil.java index 51449c13b..91445dd5b 100644 --- a/src/main/java/forestry/core/utils/EntityUtil.java +++ b/src/main/java/forestry/core/utils/EntityUtil.java @@ -10,17 +10,19 @@ ******************************************************************************/ package forestry.core.utils; +import javax.annotation.Nullable; + +import forestry.api.core.ForestryAPI; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; +import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; - import net.minecraftforge.fml.common.registry.EntityRegistry; -import forestry.api.core.ForestryAPI; - public abstract class EntityUtil { + @Nullable public static E spawnEntity(World world, Class entityClass, double x, double y, double z) { E entityLiving = createEntity(world, entityClass); if (entityLiving == null) { @@ -30,35 +32,28 @@ public abstract class EntityUtil { } public static E spawnEntity(World world, E living, double x, double y, double z) { - if (living == null) { - return null; - } - living.setLocationAndAngles(x, y, z, MathHelper.wrapDegrees(world.rand.nextFloat() * 360.0f), 0.0f); living.rotationYawHead = living.rotationYaw; living.renderYawOffset = living.rotationYaw; living.onInitialSpawn(null, null); - world.spawnEntityInWorld(living); + world.spawnEntity(living); living.playLivingSound(); return living; } - public static void registerEntity(Class entityClass, String ident, int id, int eggForeground, int eggBackground, int trackingRange, int updateFrequency, boolean sendVelocity) { - EntityRegistry.registerModEntity(entityClass, ident, id, ForestryAPI.instance, trackingRange, updateFrequency, sendVelocity); + public static void registerEntity(ResourceLocation registryName, Class entityClass, String ident, int id, int eggForeground, int eggBackground, int trackingRange, int updateFrequency, boolean sendVelocity) { + EntityRegistry.registerModEntity(registryName, entityClass, ident, id, ForestryAPI.instance, trackingRange, updateFrequency, sendVelocity); Log.debug("Registered entity %s (%s) with id %s.", ident, entityClass.toString(), id); } + @Nullable private static E createEntity(World world, Class entityClass) { - if (!EntityList.CLASS_TO_NAME.containsKey(entityClass)) { + ResourceLocation name = EntityList.getKey(entityClass); + if (name == null) { return null; } - String entityString = EntityList.CLASS_TO_NAME.get(entityClass); - if (entityString == null) { - return null; - } - - Entity entity = EntityList.createEntityByName(entityString, world); + Entity entity = EntityList.createEntityByIDFromName(name, world); return entityClass.cast(entity); } } diff --git a/src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java b/src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java new file mode 100644 index 000000000..bd12f6ef2 --- /dev/null +++ b/src/main/java/forestry/core/utils/FieldsAreNonnullByDefault.java @@ -0,0 +1,13 @@ +package forestry.core.utils; + +import javax.annotation.Nonnull; +import javax.annotation.meta.TypeQualifierDefault; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Nonnull +@TypeQualifierDefault(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface FieldsAreNonnullByDefault { +} diff --git a/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java b/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java index 4e302bc1c..6772449ab 100755 --- a/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java +++ b/src/main/java/forestry/core/utils/ForestryModEnvWarningCallable.java @@ -10,26 +10,22 @@ ******************************************************************************/ package forestry.core.utils; -import com.google.common.base.Joiner; - -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Set; -import net.minecraftforge.fml.common.FMLCommonHandler; -import net.minecraftforge.fml.common.ICrashCallable; - +import com.google.common.base.Joiner; import forestry.core.config.Constants; import forestry.plugins.ForestryPlugin; import forestry.plugins.IForestryPlugin; import forestry.plugins.PluginManager; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.ICrashCallable; /** * ICrashCallable for listing disabled modules for crash reports. **/ public class ForestryModEnvWarningCallable implements ICrashCallable { - @Nonnull private final String disabledModulesMessage; public static void register() { @@ -47,17 +43,15 @@ public class ForestryModEnvWarningCallable implements ICrashCallable { } } - private ForestryModEnvWarningCallable(@Nonnull String disabledModulesMessage) { + private ForestryModEnvWarningCallable(String disabledModulesMessage) { this.disabledModulesMessage = disabledModulesMessage; } - @Nonnull @Override public String call() { return disabledModulesMessage; } - @Nonnull @Override public String getLabel() { return Constants.MOD_ID + " "; diff --git a/src/main/java/forestry/core/utils/GeneticsUtil.java b/src/main/java/forestry/core/utils/GeneticsUtil.java index 81b0ac8c7..a868e4f52 100644 --- a/src/main/java/forestry/core/utils/GeneticsUtil.java +++ b/src/main/java/forestry/core/utils/GeneticsUtil.java @@ -37,6 +37,7 @@ import forestry.core.genetics.ItemGE; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -46,12 +47,8 @@ import net.minecraft.world.World; public class GeneticsUtil { public static boolean hasNaturalistEye(EntityPlayer player) { - if (player == null) { - return false; - } - - ItemStack armorItemStack = player.inventory.armorInventory[3]; - if (armorItemStack == null) { + ItemStack armorItemStack = player.getItemStackFromSlot(EntityEquipmentSlot.HEAD); + if (armorItemStack.isEmpty()) { return false; } @@ -65,7 +62,7 @@ public class GeneticsUtil { return false; } - return armorNaturalist.canSeePollination(player, armorItemStack, true); + return armorNaturalist != null && armorNaturalist.canSeePollination(player, armorItemStack, true); } public static boolean canNurse(IButterfly butterfly, World world, final BlockPos pos) { @@ -83,6 +80,7 @@ public class GeneticsUtil { * Returns an ICheckPollinatable that can be checked but not mated. * Used to check for pollination traits without altering the world by changing vanilla leaves to forestry ones. */ + @Nullable public static ICheckPollinatable getCheckPollinatable(World world, final BlockPos pos) { TileEntity tile = world.getTileEntity(pos); @@ -93,8 +91,8 @@ public class GeneticsUtil { IIndividual pollen = getPollen(world, pos); if (pollen != null) { ISpeciesRoot root = pollen.getGenome().getSpeciesRoot(); - if(root instanceof ISpeciesRootPollinatable){ - return ((ISpeciesRootPollinatable)root).createPollinatable(pollen); + if (root instanceof ISpeciesRootPollinatable) { + return ((ISpeciesRootPollinatable) root).createPollinatable(pollen); } } @@ -104,7 +102,8 @@ public class GeneticsUtil { /** * Returns an IPollinatable that can be mated. This will convert vanilla leaves to Forestry leaves. */ - public static IPollinatable getOrCreatePollinatable(GameProfile owner, World world, final BlockPos pos) { + @Nullable + public static IPollinatable getOrCreatePollinatable(@Nullable GameProfile owner, World world, final BlockPos pos) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof IPollinatable) { @@ -112,9 +111,9 @@ public class GeneticsUtil { } final IIndividual pollen = getPollen(world, pos); - if(pollen != null){ + if (pollen != null) { ISpeciesRoot root = pollen.getGenome().getSpeciesRoot(); - if(root instanceof ISpeciesRootPollinatable){ + if (root instanceof ISpeciesRootPollinatable) { return ((ISpeciesRootPollinatable) root).tryConvertToPollinatable(owner, world, pos, pollen); } } @@ -127,6 +126,10 @@ public class GeneticsUtil { */ @Nullable public static IIndividual getPollen(World world, final BlockPos pos) { + if (!world.isBlockLoaded(pos)) { + return null; + } + TileEntity tile = world.getTileEntity(pos); if (tile instanceof ICheckPollinatable) { @@ -134,9 +137,6 @@ public class GeneticsUtil { } IBlockState blockState = world.getBlockState(pos); - if (blockState == null) { - return null; - } Block block = blockState.getBlock(); ILeafTranslator leafTranslator = AlleleManager.leafTranslators.get(block); @@ -147,11 +147,8 @@ public class GeneticsUtil { return leafTranslator.getTreeFromLeaf(blockState); } + @Nullable public static IIndividual getGeneticEquivalent(ItemStack itemStack) { - if (itemStack == null) { - return null; - } - Item item = itemStack.getItem(); if (item instanceof ItemGE) { return ((ItemGE) item).getIndividual(itemStack); @@ -165,22 +162,15 @@ public class GeneticsUtil { } public static ItemStack convertToGeneticEquivalent(ItemStack foreign) { - if (foreign == null) { - return null; + if (AlleleManager.alleleRegistry.getSpeciesRoot(foreign) == null) { + IIndividual individual = getGeneticEquivalent(foreign); + if (individual instanceof ITree) { + ItemStack equivalent = TreeManager.treeRoot.getMemberStack(individual, EnumGermlingType.SAPLING); + equivalent.setCount(foreign.getCount()); + return equivalent; + } } - - if (AlleleManager.alleleRegistry.getSpeciesRoot(foreign) != null) { - return foreign; - } - - IIndividual individual = getGeneticEquivalent(foreign); - if (individual instanceof ITree) { - ItemStack equivalent = TreeManager.treeRoot.getMemberStack(individual, EnumGermlingType.SAPLING); - equivalent.stackSize = foreign.stackSize; - return equivalent; - } - - return null; + return foreign; } public static int getResearchComplexity(IAlleleSpecies species, IChromosomeType speciesChromosome) { diff --git a/src/main/java/forestry/core/utils/InventoryUtil.java b/src/main/java/forestry/core/utils/InventoryUtil.java index 50d687ed4..08f9abb2c 100644 --- a/src/main/java/forestry/core/utils/InventoryUtil.java +++ b/src/main/java/forestry/core/utils/InventoryUtil.java @@ -20,6 +20,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -30,8 +31,8 @@ import net.minecraftforge.oredict.OreDictionary; import forestry.api.core.ForestryAPI; import forestry.core.circuits.ISocketable; -import forestry.core.inventory.filters.StandardStackFilters; -import forestry.core.inventory.manipulators.ItemHandlerInventoryManipulator; +import forestry.core.inventory.StandardStackFilters; +import forestry.core.inventory.ItemHandlerInventoryManipulator; import forestry.core.tiles.AdjacentTileCache; import forestry.plugins.ForestryPluginUids; @@ -54,7 +55,7 @@ public abstract class InventoryUtil { } public static boolean isItemEqual(final ItemStack a, final ItemStack b, final boolean matchDamage, final boolean matchNBT) { - if (a == null || b == null) { + if (a.isEmpty() || b.isEmpty()) { return false; } if (a.getItem() != b.getItem()) { @@ -198,40 +199,41 @@ public abstract class InventoryUtil { * If the inventory doesn't have all the required items, returns false without removing anything. * If stowContainer is true, items with containers will have their container stowed. */ - public static boolean removeSets(IInventory inventory, int count, ItemStack[] set, @Nullable EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools, boolean doRemove) { - ItemStack[] stock = getStacks(inventory); + public static boolean removeSets(IInventory inventory, int count, NonNullList set, @Nullable EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools, boolean doRemove) { + NonNullList stock = getStacks(inventory); if (doRemove) { - ItemStack[] removed = removeSets(inventory, count, set, player, stowContainer, oreDictionary, craftingTools); - return removed != null && removed.length >= count; + NonNullList removed = removeSets(inventory, count, set, player, stowContainer, oreDictionary, craftingTools); + return removed != null && removed.size() >= count; } else { return ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) >= count; } } - public static ItemStack[] removeSets(IInventory inventory, int count, ItemStack[] set, @Nullable EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { - ItemStack[] removed = new ItemStack[set.length]; - ItemStack[] stock = getStacks(inventory); + @Nullable + public static NonNullList removeSets(IInventory inventory, int count, NonNullList set, @Nullable EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { + NonNullList removed = NonNullList.withSize(set.size(), ItemStack.EMPTY); + NonNullList stock = getStacks(inventory); if (ItemStackUtil.containsSets(set, stock, oreDictionary, craftingTools) < count) { return null; } - for (int i = 0; i < set.length; i++) { - if (set[i] == null) { - continue; - } - ItemStack stackToRemove = set[i].copy(); - stackToRemove.stackSize *= count; + for (int i = 0; i < set.size(); i++) { + ItemStack itemStack = set.get(i); + if (!itemStack.isEmpty()) { + ItemStack stackToRemove = itemStack.copy(); + stackToRemove.setCount(stackToRemove.getCount() * count); - // try to remove the exact stack first - ItemStack removedStack = removeStack(inventory, stackToRemove, player, stowContainer, false, false); - if (removedStack == null) { - // remove crafting equivalents next - removedStack = removeStack(inventory, stackToRemove, player, stowContainer, oreDictionary, craftingTools); - } + // try to remove the exact stack first + ItemStack removedStack = removeStack(inventory, stackToRemove, player, stowContainer, false, false); + if (removedStack.isEmpty()) { + // remove crafting equivalents next + removedStack = removeStack(inventory, stackToRemove, player, stowContainer, oreDictionary, craftingTools); + } - removed[i] = removedStack; + removed.set(i, removedStack); + } } return removed; } @@ -242,36 +244,32 @@ public abstract class InventoryUtil { private static ItemStack removeStack(IInventory inventory, ItemStack stackToRemove, @Nullable EntityPlayer player, boolean stowContainer, boolean oreDictionary, boolean craftingTools) { for (int j = 0; j < inventory.getSizeInventory(); j++) { ItemStack stackInSlot = inventory.getStackInSlot(j); - if (stackInSlot == null) { - continue; - } + if (!stackInSlot.isEmpty()) { + if (ItemStackUtil.isCraftingEquivalent(stackToRemove, stackInSlot, oreDictionary, craftingTools)) { + ItemStack removed = inventory.decrStackSize(j, stackToRemove.getCount()); + stackToRemove.shrink(removed.getCount()); - if (!ItemStackUtil.isCraftingEquivalent(stackToRemove, stackInSlot, oreDictionary, craftingTools)) { - continue; - } + if (stowContainer && stackToRemove.getItem().hasContainerItem(stackToRemove)) { + stowContainerItem(removed, inventory, j, player); + } - ItemStack removed = inventory.decrStackSize(j, stackToRemove.stackSize); - stackToRemove.stackSize -= removed.stackSize; - - if (stowContainer && stackToRemove.getItem().hasContainerItem(stackToRemove)) { - stowContainerItem(removed, inventory, j, player); - } - - if (stackToRemove.stackSize == 0) { - return removed; + if (stackToRemove.isEmpty()) { + return removed; + } + } } } - return null; + return ItemStack.EMPTY; } /* CONTAINS */ - public static boolean contains(IInventory inventory, ItemStack[] query) { + public static boolean contains(IInventory inventory, NonNullList query) { return contains(inventory, query, 0, inventory.getSizeInventory()); } - public static boolean contains(IInventory inventory, ItemStack[] query, int startSlot, int slots) { - ItemStack[] stock = getStacks(inventory, startSlot, slots); + public static boolean contains(IInventory inventory, NonNullList query, int startSlot, int slots) { + NonNullList stock = getStacks(inventory, startSlot, slots); return ItemStackUtil.containsSets(query, stock) > 0; } @@ -288,7 +286,7 @@ public abstract class InventoryUtil { continue; } - amount += itemStack.stackSize; + amount += itemStack.getCount(); stackMax += itemStack.getMaxStackSize(); } if (stackMax == 0) { @@ -299,30 +297,30 @@ public abstract class InventoryUtil { public static boolean isEmpty(IInventory inventory, int slotStart, int slotCount) { for (int i = slotStart; i < slotStart + slotCount; i++) { - if (inventory.getStackInSlot(i) != null) { + if (!inventory.getStackInSlot(i).isEmpty()) { return false; } } return true; } - public static ItemStack[] getStacks(IInventory inventory) { - ItemStack[] stacks = new ItemStack[inventory.getSizeInventory()]; + public static NonNullList getStacks(IInventory inventory) { + NonNullList stacks = NonNullList.withSize(inventory.getSizeInventory(), ItemStack.EMPTY); for (int i = 0; i < inventory.getSizeInventory(); i++) { - stacks[i] = inventory.getStackInSlot(i); + stacks.set(i, inventory.getStackInSlot(i)); } return stacks; } - public static ItemStack[] getStacks(IInventory inventory, int slot1, int length) { - ItemStack[] result = new ItemStack[length]; + public static NonNullList getStacks(IInventory inventory, int slot1, int length) { + NonNullList result = NonNullList.withSize(length, ItemStack.EMPTY); for (int i = slot1; i < slot1 + length; i++) { - result[i - slot1] = inventory.getStackInSlot(i); + result.set(i - slot1, inventory.getStackInSlot(i)); } return result; } - public static boolean tryAddStacksCopy(IInventory inventory, ItemStack[] stacks, int startSlot, int slots, boolean all) { + public static boolean tryAddStacksCopy(IInventory inventory, NonNullList stacks, int startSlot, int slots, boolean all) { for (ItemStack stack : stacks) { if (stack == null) { @@ -354,7 +352,7 @@ public abstract class InventoryUtil { public static boolean tryAddStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean all, boolean doAdd) { int added = addStack(inventory, stack, startSlot, slots, false); - boolean success = all ? added == stack.stackSize : added > 0; + boolean success = all ? added == stack.getCount() : added > 0; if (success && doAdd) { addStack(inventory, stack, startSlot, slots, true); @@ -368,6 +366,9 @@ public abstract class InventoryUtil { } public static int addStack(IInventory inventory, ItemStack stack, int startSlot, int slots, boolean doAdd) { + if (stack.isEmpty()) { + return 0; + } int added = 0; // Add to existing stacks first @@ -375,7 +376,7 @@ public abstract class InventoryUtil { ItemStack inventoryStack = inventory.getStackInSlot(i); // Empty slot. Add - if (inventoryStack == null || inventoryStack.getItem() == null) { + if (inventoryStack.isEmpty()) { continue; } @@ -390,8 +391,8 @@ public abstract class InventoryUtil { continue; } - int remain = stack.stackSize - added; - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + int remain = stack.getCount() - added; + int space = inventoryStack.getMaxStackSize() - inventoryStack.getCount(); // No space left, skip this slot. if (space <= 0) { continue; @@ -399,34 +400,31 @@ public abstract class InventoryUtil { // Enough space if (space >= remain) { if (doAdd) { - inventoryStack.stackSize += remain; + inventoryStack.grow(remain); } - return stack.stackSize; + return stack.getCount(); } // Not enough space if (doAdd) { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); + inventoryStack.setCount(inventoryStack.getMaxStackSize()); } added += space; } - if (added >= stack.stackSize) { + if (added >= stack.getCount()) { return added; } for (int i = startSlot; i < startSlot + slots; i++) { - if (inventory.getStackInSlot(i) != null) { - continue; + if (inventory.getStackInSlot(i).isEmpty()) { + if (doAdd) { + inventory.setInventorySlotContents(i, stack.copy()); + inventory.getStackInSlot(i).setCount(stack.getCount() - added); + } + return stack.getCount(); } - - if (doAdd) { - inventory.setInventorySlotContents(i, stack.copy()); - inventory.getStackInSlot(i).stackSize = stack.stackSize - added; - } - return stack.stackSize; - } return added; @@ -444,16 +442,16 @@ public abstract class InventoryUtil { ItemStack inventoryStack = inventory.getStackInSlot(i); // Grab those free slots - if (inventoryStack == null) { + if (inventoryStack.isEmpty()) { if (doAdd) { inventory.setInventorySlotContents(i, itemstack.copy()); - itemstack.stackSize = 0; + itemstack.setCount(0); } return true; } // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + if (inventoryStack.getCount() >= inventoryStack.getMaxStackSize()) { continue; } @@ -465,20 +463,20 @@ public abstract class InventoryUtil { continue; } - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + int space = inventoryStack.getMaxStackSize() - inventoryStack.getCount(); // Enough space to add all - if (space > itemstack.stackSize) { + if (space > itemstack.getCount()) { if (doAdd) { - inventoryStack.stackSize += itemstack.stackSize; - itemstack.stackSize = 0; + inventoryStack.grow(itemstack.getCount()); + itemstack.setCount(0); } return true; // Only part can be added } else { if (doAdd) { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); - itemstack.stackSize -= space; + inventoryStack.setCount(inventoryStack.getMaxStackSize()); + itemstack.shrink(space); } added = true; } @@ -494,7 +492,7 @@ public abstract class InventoryUtil { } ItemStack container = ForgeHooks.getContainerItem(itemstack); - if (container != null) { + if (!container.isEmpty()) { if (!tryAddStack(stowing, container, slotIndex, 1, true)) { if (!tryAddStack(stowing, container, true) && player != null) { player.dropItem(container, true); @@ -504,16 +502,13 @@ public abstract class InventoryUtil { } public static void deepCopyInventoryContents(IInventory source, IInventory destination) { - if (source == null || destination == null) { - throw new IllegalArgumentException("Inventory can't be null. Source: " + source + ", Destination: " + destination); - } if (source.getSizeInventory() != destination.getSizeInventory()) { throw new IllegalArgumentException("Inventory sizes do not match. Source: " + source + ", Destination: " + destination); } for (int i = 0; i < source.getSizeInventory(); i++) { ItemStack stack = source.getStackInSlot(i); - if (stack != null) { + if (!stack.isEmpty()) { stack = stack.copy(); } destination.setInventorySlotContents(i, stack); @@ -521,15 +516,11 @@ public abstract class InventoryUtil { } public static void dropInventory(IInventory inventory, World world, double x, double y, double z) { - if (inventory == null) { - return; - } - // Release inventory for (int slot = 0; slot < inventory.getSizeInventory(); slot++) { ItemStack itemstack = inventory.getStackInSlot(slot); dropItemStackFromInventory(itemstack, world, x, y, z); - inventory.setInventorySlotContents(slot, null); + inventory.setInventorySlotContents(slot, ItemStack.EMPTY); } } @@ -541,7 +532,7 @@ public abstract class InventoryUtil { for (int slot = 0; slot < socketable.getSocketCount(); slot++) { ItemStack itemstack = socketable.getSocket(slot); dropItemStackFromInventory(itemstack, world, x, y, z); - socketable.setSocket(slot, null); + socketable.setSocket(slot, ItemStack.EMPTY); } } @@ -550,7 +541,7 @@ public abstract class InventoryUtil { } public static void dropItemStackFromInventory(ItemStack itemStack, World world, double x, double y, double z) { - if (itemStack == null) { + if (itemStack.isEmpty()) { return; } @@ -558,10 +549,10 @@ public abstract class InventoryUtil { float f1 = world.rand.nextFloat() * 0.8F + 0.1F; float f2 = world.rand.nextFloat() * 0.8F + 0.1F; - while (itemStack.stackSize > 0) { + while (!itemStack.isEmpty()) { int stackPartial = world.rand.nextInt(21) + 10; - if (stackPartial > itemStack.stackSize) { - stackPartial = itemStack.stackSize; + if (stackPartial > itemStack.getCount()) { + stackPartial = itemStack.getCount(); } ItemStack drop = itemStack.splitStack(stackPartial); EntityItem entityitem = new EntityItem(world, x + f, y + f1, z + f2, drop); @@ -569,7 +560,7 @@ public abstract class InventoryUtil { entityitem.motionX = (float) world.rand.nextGaussian() * accel; entityitem.motionY = (float) world.rand.nextGaussian() * accel + 0.2F; entityitem.motionZ = (float) world.rand.nextGaussian() * accel; - world.spawnEntityInWorld(entityitem); + world.spawnEntity(entityitem); } } @@ -584,14 +575,14 @@ public abstract class InventoryUtil { for (int j = 0; j < nbttaglist.tagCount(); ++j) { NBTTagCompound nbttagcompound2 = nbttaglist.getCompoundTagAt(j); int index = nbttagcompound2.getByte("Slot"); - inventory.setInventorySlotContents(index, ItemStack.loadItemStackFromNBT(nbttagcompound2)); + inventory.setInventorySlotContents(index, new ItemStack(nbttagcompound2)); } } public static void writeToNBT(IInventory inventory, NBTTagCompound nbttagcompound) { NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < inventory.getSizeInventory(); i++) { - if (inventory.getStackInSlot(i) != null) { + if (!inventory.getStackInSlot(i).isEmpty()) { NBTTagCompound nbttagcompound2 = new NBTTagCompound(); nbttagcompound2.setByte("Slot", (byte) i); inventory.getStackInSlot(i).writeToNBT(nbttagcompound2); diff --git a/src/main/java/forestry/core/utils/ItemStackUtil.java b/src/main/java/forestry/core/utils/ItemStackUtil.java index 224883dbd..3025f1b3e 100644 --- a/src/main/java/forestry/core/utils/ItemStackUtil.java +++ b/src/main/java/forestry/core/utils/ItemStackUtil.java @@ -22,11 +22,10 @@ import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.fml.common.registry.IForgeRegistry; import net.minecraftforge.oredict.OreDictionary; @@ -43,7 +42,7 @@ public abstract class ItemStackUtil { return true; } - if (lhs == null || rhs == null) { + if (lhs.isEmpty() || rhs.isEmpty()) { return false; } @@ -59,21 +58,21 @@ public abstract class ItemStackUtil { return ItemStack.areItemStackTagsEqual(lhs, rhs); } - + /** - * * @return The registry name of the item as {@link ResourceLocation} */ + @Nullable public static ResourceLocation getItemNameFromRegistry(Item item) { - if (item == null) { + IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; + if (itemRegistry.containsValue(item)) { + return itemRegistry.getKey(item); + } else { return null; } - IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; - return itemRegistry.getKey(item); } - + /** - * * @return The registry name of the item as {@link String} */ @Nullable @@ -87,15 +86,11 @@ public abstract class ItemStackUtil { @Nullable public static String getStringForItemStack(ItemStack itemStack) { - if (itemStack == null) { + if (itemStack.isEmpty()) { return null; } Item item = itemStack.getItem(); - if (item == null) { - return null; - } - String itemStackString = getItemNameFromRegistryAsString(item); if (itemStackString == null) { return null; @@ -108,64 +103,48 @@ public abstract class ItemStackUtil { return itemStackString; } } - + /** - * @return The item from the item registry * @param itemName The registry name from the item as {@link String} + * @return The item from the item registry */ + @Nullable public static Item getItemFromRegistry(String itemName) { return getItemFromRegistry(new ResourceLocation(itemName)); } - + /** - * @return The item from the item registry * @param itemName The registry name from the item as {@link ResourceLocation} + * @return The item from the item registry */ + @Nullable public static Item getItemFromRegistry(ResourceLocation itemName) { - if (itemName == null) { + IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; + if (!itemRegistry.containsKey(itemName)) { return null; } - IForgeRegistry itemRegistry = ForgeRegistries.ITEMS; return itemRegistry.getValue(itemName); } - + /** - * - * @return The registry name of the block as {@link ResourceLocation} - */ - public static ResourceLocation getBlockNameFromRegistry(Block block) { - if (block == null) { - return null; - } - IForgeRegistry blockRegistry = ForgeRegistries.BLOCKS; - return blockRegistry.getKey(block); - } - - /** - * - * @return The registry name of the block as {@link String} - */ - public static String getBlockNameFromRegistryAsSting(Block block) { - return getBlockNameFromRegistry(block).toString(); - } - - /** - * @return The block from the block registry * @param itemName The registry name from the block as {@link String} + * @return The block from the block registry */ + @Nullable public static Block getBlockFromRegistry(String itemName) { return getBlockFromRegistry(new ResourceLocation(itemName)); } - + /** - * @return The block from the block registry * @param itemName The registry name from the block as {@link ResourceLocation} + * @return The block from the block registry */ + @Nullable public static Block getBlockFromRegistry(ResourceLocation itemName) { - if (itemName == null) { + IForgeRegistry blockRegistry = ForgeRegistries.BLOCKS; + if (!blockRegistry.containsKey(itemName)) { return null; } - IForgeRegistry blockRegistry = ForgeRegistries.BLOCKS; return blockRegistry.getValue(itemName); } @@ -173,7 +152,7 @@ public abstract class ItemStackUtil { * Merges the giving stack into the receiving stack as far as possible */ public static void mergeStacks(ItemStack giver, ItemStack receptor) { - if (receptor.stackSize >= 64) { + if (receptor.getCount() >= receptor.getMaxStackSize()) { return; } @@ -181,47 +160,40 @@ public abstract class ItemStackUtil { return; } - if (giver.stackSize <= receptor.getMaxStackSize() - receptor.stackSize) { - receptor.stackSize += giver.stackSize; - giver.stackSize = 0; + if (giver.getCount() <= receptor.getMaxStackSize() - receptor.getCount()) { + receptor.grow(giver.getCount()); + giver.setCount(0); return; } - ItemStack temp = giver.splitStack(receptor.getMaxStackSize() - receptor.stackSize); - receptor.stackSize += temp.stackSize; - temp.stackSize = 0; + ItemStack temp = giver.splitStack(receptor.getMaxStackSize() - receptor.getCount()); + receptor.grow(temp.getCount()); + temp.setCount(0); } /** - * Creates a split stack of the specified amount, preserving NBT data, + * Creates a copy stack of the specified amount, preserving NBT data, * without decreasing the source stack. */ - public static ItemStack createSplitStack(ItemStack stack, int amount) { - ItemStack split = new ItemStack(stack.getItem(), amount, stack.getItemDamage()); - if (stack.getTagCompound() != null) { - NBTTagCompound nbttagcompound = stack.getTagCompound().copy(); - split.setTagCompound(nbttagcompound); - } - return split; + + public static ItemStack createCopyWithCount(ItemStack stack, int count) { + ItemStack copy = stack.copy(); + copy.setCount(count); + return copy; } - /** - */ - public static ItemStack[] condenseStacks(ItemStack[] stacks) { - List condensed = new ArrayList<>(); + public static NonNullList condenseStacks(NonNullList stacks) { + NonNullList condensed = NonNullList.create(); for (ItemStack stack : stacks) { - if (stack == null) { - continue; - } - if (stack.stackSize <= 0) { + if (stack.isEmpty()) { continue; } boolean matched = false; for (ItemStack cached : condensed) { if (cached.isItemEqual(stack) && ItemStack.areItemStackTagsEqual(cached, stack)) { - cached.stackSize += stack.stackSize; + cached.grow(stack.getCount()); matched = true; } } @@ -233,7 +205,7 @@ public abstract class ItemStackUtil { } - return condensed.toArray(new ItemStack[condensed.size()]); + return condensed; } public static boolean containsItemStack(Iterable list, ItemStack itemStack) { @@ -248,25 +220,25 @@ public abstract class ItemStackUtil { /** * Counts how many full sets are contained in the passed stock */ - public static int containsSets(ItemStack[] set, ItemStack[] stock) { + public static int containsSets(NonNullList set, NonNullList stock) { return containsSets(set, stock, false, false); } /** * Counts how many full sets are contained in the passed stock */ - public static int containsSets(ItemStack[] set, ItemStack[] stock, boolean oreDictionary, boolean craftingTools) { + public static int containsSets(NonNullList set, NonNullList stock, boolean oreDictionary, boolean craftingTools) { int totalSets = 0; - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(set); - ItemStack[] condensedOffered = ItemStackUtil.condenseStacks(stock); + NonNullList condensedRequired = ItemStackUtil.condenseStacks(set); + NonNullList condensedOffered = ItemStackUtil.condenseStacks(stock); for (ItemStack req : condensedRequired) { int reqCount = 0; for (ItemStack offer : condensedOffered) { if (isCraftingEquivalent(req, offer, oreDictionary, craftingTools)) { - int stackCount = (int) Math.floor(offer.stackSize / req.stackSize); + int stackCount = (int) Math.floor(offer.getCount() / req.getCount()); reqCount = Math.max(reqCount, stackCount); } } @@ -283,21 +255,17 @@ public abstract class ItemStackUtil { return totalSets; } - public static boolean equalSets(ItemStack[] set1, ItemStack[] set2) { + public static boolean equalSets(NonNullList set1, NonNullList set2) { if (set1 == set2) { return true; } - if (set1 == null || set2 == null) { + if (set1.size() != set2.size()) { return false; } - if (set1.length != set2.length) { - return false; - } - - for (int i = 0; i < set1.length; i++) { - if (!isIdenticalItem(set1[i], set2[i])) { + for (int i = 0; i < set1.size(); i++) { + if (!isIdenticalItem(set1.get(i), set2.get(i))) { return false; } } @@ -309,7 +277,7 @@ public abstract class ItemStackUtil { * Compare two item stacks for crafting equivalency without oreDictionary or craftingTools */ public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { + if (base.isEmpty() || comparison.isEmpty()) { return false; } @@ -324,7 +292,7 @@ public abstract class ItemStackUtil { } // When the base stackTagCompound is null or empty, treat it as a wildcard for crafting - if (!base.hasTagCompound() || base.getTagCompound().hasNoTags()) { + if (base.getTagCompound() == null || base.getTagCompound().hasNoTags()) { return true; } else { return ItemStack.areItemStackTagsEqual(base, comparison); @@ -335,7 +303,7 @@ public abstract class ItemStackUtil { * Compare two item stacks for crafting equivalency. */ public static boolean isCraftingEquivalent(ItemStack base, ItemStack comparison, boolean oreDictionary, boolean craftingTools) { - if (base == null || comparison == null) { + if (base.isEmpty() || comparison.isEmpty()) { return false; } @@ -347,7 +315,7 @@ public abstract class ItemStackUtil { return true; } - if (base.hasTagCompound() && !base.getTagCompound().hasNoTags()) { + if (base.getTagCompound() != null && !base.getTagCompound().hasNoTags()) { if (!ItemStack.areItemStacksEqual(base, comparison)) { return false; } @@ -377,7 +345,7 @@ public abstract class ItemStackUtil { } public static boolean isCraftingToolEquivalent(ItemStack base, ItemStack comparison) { - if (base == null || comparison == null) { + if (base.isEmpty() || comparison.isEmpty()) { return false; } @@ -387,7 +355,7 @@ public abstract class ItemStackUtil { return false; } - if (!base.hasTagCompound() || base.getTagCompound().hasNoTags()) { + if (base.getTagCompound() == null || base.getTagCompound().hasNoTags()) { // tool uses meta for damage return true; } else { @@ -402,13 +370,13 @@ public abstract class ItemStackUtil { public static void dropItemStackAsEntity(ItemStack items, World world, double x, double y, double z) { dropItemStackAsEntity(items, world, x, y, z, 10); } - + public static void dropItemStackAsEntity(ItemStack items, World world, BlockPos pos) { dropItemStackAsEntity(items, world, pos.getX(), pos.getY(), pos.getZ(), 10); } public static void dropItemStackAsEntity(ItemStack items, World world, double x, double y, double z, int delayForPickup) { - if (items == null || items.stackSize <= 0 || world.isRemote) { + if (items.isEmpty() || world.isRemote) { return; } @@ -419,18 +387,19 @@ public abstract class ItemStackUtil { EntityItem entityitem = new EntityItem(world, x + d, y + d1, z + d2, items); entityitem.setPickupDelay(delayForPickup); - world.spawnEntityInWorld(entityitem); + world.spawnEntity(entityitem); } + public static ItemStack copyWithRandomSize(ItemStack template, int max, Random rand) { int size = max <= 0 ? 0 : rand.nextInt(max); ItemStack created = template.copy(); if (size <= 0) { - created.stackSize = 1; + created.setCount(1); } else if (size > created.getMaxStackSize()) { - created.stackSize = created.getMaxStackSize(); + created.setCount(created.getMaxStackSize()); } else { - created.stackSize = size; + created.setCount(size); } return created; } @@ -449,7 +418,7 @@ public abstract class ItemStackUtil { public static boolean equals(Block block, ItemStack stack) { return block == getBlock(stack); } - + public static boolean equals(IBlockState state, ItemStack stack) { return state.getBlock() == getBlock(stack) && state.getBlock().getMetaFromState(state) == stack.getItemDamage(); } @@ -458,18 +427,24 @@ public abstract class ItemStackUtil { return block == getBlock(stack) && meta == stack.getItemDamage(); } + public static List parseItemStackStrings(String[] itemStackStrings, int missingMetaValue) { List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); return getItemStacks(stacks); } + public static List parseItemStackStrings(String itemStackStrings, int missingMetaValue) { List stacks = Stack.parseStackStrings(itemStackStrings, missingMetaValue); return getItemStacks(stacks); } - + + @Nullable public static ItemStack parseItemStackString(String itemStackString, int missingMetaValue) { Stack stack = Stack.parseStackString(itemStackString, missingMetaValue); + if (stack == null) { + return null; + } return getItemStack(stack); } @@ -485,7 +460,8 @@ public abstract class ItemStackUtil { } return itemStacks; } - + + @Nullable private static ItemStack getItemStack(Stack stack) { Item item = stack.getItem(); if (item != null) { diff --git a/src/main/java/forestry/core/utils/JeiUtil.java b/src/main/java/forestry/core/utils/JeiUtil.java index 61c5539b8..49bc8b3d3 100644 --- a/src/main/java/forestry/core/utils/JeiUtil.java +++ b/src/main/java/forestry/core/utils/JeiUtil.java @@ -5,6 +5,7 @@ import java.util.List; import mezz.jei.api.IModRegistry; import net.minecraft.block.Block; +import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; @@ -22,7 +23,7 @@ public class JeiUtil { public static void addDescription(IModRegistry registry, Block... blocks) { for (Block block : blocks) { Item item = Item.getItemFromBlock(block); - if (item != null) { + if (item != Items.AIR) { addDescription(registry, item); } else { Log.error("No item for block {}", block); diff --git a/src/main/java/forestry/core/utils/ModUtil.java b/src/main/java/forestry/core/utils/ModUtil.java index 1820109d9..aa02e791b 100644 --- a/src/main/java/forestry/core/utils/ModUtil.java +++ b/src/main/java/forestry/core/utils/ModUtil.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.utils; +import javax.annotation.Nullable; + import net.minecraftforge.fml.common.API; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.ModContainer; @@ -23,7 +25,7 @@ public abstract class ModUtil { return Loader.isModLoaded(modname); } - public static boolean isModLoaded(String modname, String versionRangeString) { + public static boolean isModLoaded(String modname, @Nullable String versionRangeString) { if (!isModLoaded(modname)) { return false; } @@ -58,7 +60,7 @@ public abstract class ModUtil { * @param apiName the package name of the package-info.java file to check. (for example "cofh.api.energy") * @param versionRangeString the version range, as defined in {@link VersionParser}. */ - public static boolean isAPILoaded(String apiName, String versionRangeString) { + public static boolean isAPILoaded(String apiName, @Nullable String versionRangeString) { Package apiPackage = Package.getPackage(apiName); if (apiPackage == null) { return false; diff --git a/src/main/java/forestry/core/utils/NBTUtilForestry.java b/src/main/java/forestry/core/utils/NBTUtilForestry.java index 8017fe123..c4b184334 100644 --- a/src/main/java/forestry/core/utils/NBTUtilForestry.java +++ b/src/main/java/forestry/core/utils/NBTUtilForestry.java @@ -10,12 +10,14 @@ ******************************************************************************/ package forestry.core.utils; -import com.google.common.collect.ForwardingList; - import java.io.IOException; import java.util.ArrayList; import java.util.List; +import com.google.common.collect.ForwardingList; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; +import io.netty.buffer.Unpooled; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagByte; import net.minecraft.nbt.NBTTagByteArray; @@ -29,18 +31,8 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagLong; import net.minecraft.nbt.NBTTagShort; import net.minecraft.nbt.NBTTagString; - import net.minecraftforge.fml.common.ObfuscationReflectionHelper; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.buffer.Unpooled; - /** * @author CovertJaguar */ @@ -66,16 +58,6 @@ public abstract class NBTUtilForestry { EnumNBTType(Class c) { this.classObject = c; } - - public static EnumNBTType fromClass(Class c) { - for (EnumNBTType type : VALUES) { - if (type.classObject == c) { - return type; - } - } - return null; - } - } public static NBTList getNBTList(NBTTagCompound nbt, String tag, EnumNBTType type) { @@ -101,18 +83,11 @@ public abstract class NBTUtilForestry { } public static NBTTagCompound writeStreamableToNbt(IStreamable streamable, NBTTagCompound nbt) { - ByteBufOutputStream buf = new ByteBufOutputStream(Unpooled.buffer()); - DataOutputStreamForestry data = new DataOutputStreamForestry(buf); - try { - streamable.writeData(data); - } catch (IOException e) { - Log.error("Failed to write streamable data", e); - return nbt; - } + PacketBufferForestry data = new PacketBufferForestry(Unpooled.buffer()); + streamable.writeData(data); - ByteBuf buffer = buf.buffer(); - byte[] bytes = new byte[buffer.readableBytes()]; - buf.buffer().getBytes(0, bytes); + byte[] bytes = new byte[data.readableBytes()]; + data.getBytes(0, bytes); nbt.setByteArray("dataBytes", bytes); return nbt; } @@ -120,8 +95,7 @@ public abstract class NBTUtilForestry { public static void readStreamableFromNbt(IStreamable streamable, NBTTagCompound nbt) { if (nbt.hasKey("dataBytes")) { byte[] bytes = nbt.getByteArray("dataBytes"); - ByteBufInputStream buf = new ByteBufInputStream(Unpooled.wrappedBuffer(bytes)); - DataInputStreamForestry data = new DataInputStreamForestry(buf); + PacketBufferForestry data = new PacketBufferForestry(Unpooled.wrappedBuffer(bytes)); try { streamable.readData(data); } catch (IOException e) { diff --git a/src/main/java/forestry/core/utils/PlayerUtil.java b/src/main/java/forestry/core/utils/PlayerUtil.java index e5d04e4b3..7662c4b81 100644 --- a/src/main/java/forestry/core/utils/PlayerUtil.java +++ b/src/main/java/forestry/core/utils/PlayerUtil.java @@ -10,19 +10,16 @@ ******************************************************************************/ package forestry.core.utils; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.UUID; +import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; import net.minecraft.util.StringUtils; import net.minecraft.world.World; import net.minecraft.world.WorldServer; - -import com.mojang.authlib.GameProfile; - import net.minecraftforge.common.util.FakePlayerFactory; public abstract class PlayerUtil { @@ -31,10 +28,6 @@ public abstract class PlayerUtil { private static final UUID emptyUUID = new UUID(0, 0); public static boolean isSameGameProfile(GameProfile player1, GameProfile player2) { - if (player1 == null || player2 == null) { - return false; - } - UUID id1 = player1.getId(); UUID id2 = player2.getId(); if (id1 != null && id2 != null && !id1.equals(emptyUUID) && !id2.equals(emptyUUID)) { @@ -44,7 +37,7 @@ public abstract class PlayerUtil { return player1.getName() != null && player1.getName().equals(player2.getName()); } - public static String getOwnerName(GameProfile profile) { + public static String getOwnerName(@Nullable GameProfile profile) { if (profile == null) { return Translator.translateToLocal("for.gui.derelict"); } else { @@ -57,11 +50,8 @@ public abstract class PlayerUtil { * If they are not in the World, returns a FakePlayer. * Do not store references to the return value, to prevent worlds staying in memory. */ - public static EntityPlayer getPlayer(World world, GameProfile profile) { - if (world == null) { - throw new IllegalArgumentException("World cannot be null"); - } - + @Nullable + public static EntityPlayer getPlayer(World world, @Nullable GameProfile profile) { if (profile == null || profile.getName() == null) { if (world instanceof WorldServer) { return FakePlayerFactory.getMinecraft((WorldServer) world); @@ -69,7 +59,7 @@ public abstract class PlayerUtil { return null; } } - + EntityPlayer player = world.getPlayerEntityByName(profile.getName()); if (player == null && world instanceof WorldServer) { player = FakePlayerFactory.get((WorldServer) world, profile); @@ -77,7 +67,7 @@ public abstract class PlayerUtil { return player; } - public static void writeGameProfile(@Nonnull NBTTagCompound tagCompound, @Nonnull GameProfile profile) { + public static void writeGameProfile(NBTTagCompound tagCompound, GameProfile profile) { if (!StringUtils.isNullOrEmpty(profile.getName())) { tagCompound.setString("Name", profile.getName()); } @@ -88,7 +78,7 @@ public abstract class PlayerUtil { } @Nullable - public static GameProfile readGameProfileFromNBT(@Nonnull NBTTagCompound compound) { + public static GameProfile readGameProfileFromNBT(NBTTagCompound compound) { return NBTUtil.readGameProfileFromNBT(compound); } } diff --git a/src/main/java/forestry/core/utils/SlotUtil.java b/src/main/java/forestry/core/utils/SlotUtil.java index be2311e66..f69691277 100644 --- a/src/main/java/forestry/core/utils/SlotUtil.java +++ b/src/main/java/forestry/core/utils/SlotUtil.java @@ -12,6 +12,7 @@ package forestry.core.utils; import java.util.List; +import forestry.core.gui.slots.SlotForestry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ClickType; @@ -19,8 +20,6 @@ import net.minecraft.inventory.Slot; import net.minecraft.inventory.SlotCrafting; import net.minecraft.item.ItemStack; -import forestry.core.gui.slots.SlotForestry; - public abstract class SlotUtil { public static boolean isSlotInRange(int slotIndex, int start, int count) { @@ -28,25 +27,25 @@ public abstract class SlotUtil { } public static ItemStack slotClickPhantom(SlotForestry slot, int mouseButton, ClickType clickTypeIn, EntityPlayer player) { - ItemStack stack = null; + ItemStack stack = ItemStack.EMPTY; ItemStack stackSlot = slot.getStack(); - if (stackSlot != null) { + if (!stackSlot.isEmpty()) { stack = stackSlot.copy(); } if (mouseButton == 2) { - fillPhantomSlot(slot, null, mouseButton); + fillPhantomSlot(slot, ItemStack.EMPTY, mouseButton); } else if (mouseButton == 0 || mouseButton == 1) { InventoryPlayer playerInv = player.inventory; ItemStack stackHeld = playerInv.getItemStack(); - if (stackSlot == null) { - if (stackHeld != null && slot.isItemValid(stackHeld)) { + if (stackSlot.isEmpty()) { + if (!stackHeld.isEmpty() && slot.isItemValid(stackHeld)) { fillPhantomSlot(slot, stackHeld, mouseButton); } - } else if (stackHeld == null) { + } else if (stackHeld.isEmpty()) { adjustPhantomSlot(slot, mouseButton, clickTypeIn); } else if (slot.isItemValid(stackHeld)) { if (ItemStackUtil.isIdenticalItem(stackSlot, stackHeld)) { @@ -65,10 +64,10 @@ public abstract class SlotUtil { return stack; } - public static ItemStack transferStackInSlot(List inventorySlots, EntityPlayer player, int slotIndex) { - Slot slot = (Slot) inventorySlots.get(slotIndex); + public static ItemStack transferStackInSlot(List inventorySlots, EntityPlayer player, int slotIndex) { + Slot slot = inventorySlots.get(slotIndex); if (slot == null || !slot.getHasStack()) { - return null; + return ItemStack.EMPTY; } boolean fromCraftingSlot = slot instanceof SlotCrafting; @@ -78,25 +77,25 @@ public abstract class SlotUtil { ItemStack originalStack = stackInSlot.copy(); if (!shiftItemStack(inventorySlots, stackInSlot, slotIndex, numSlots, fromCraftingSlot)) { - return null; + return ItemStack.EMPTY; } slot.onSlotChange(stackInSlot, originalStack); - if (stackInSlot.stackSize <= 0) { - slot.putStack(null); + if (stackInSlot.isEmpty()) { + slot.putStack(stackInSlot); } else { slot.onSlotChanged(); } - if (stackInSlot.stackSize == originalStack.stackSize) { - return null; + if (stackInSlot.getCount() == originalStack.getCount()) { + return ItemStack.EMPTY; } - slot.onPickupFromSlot(player, stackInSlot); + slot.onTake(player, stackInSlot); return originalStack; } - private static boolean shiftItemStack(List inventorySlots, ItemStack stackInSlot, int slotIndex, int numSlots, boolean fromCraftingSlot) { + private static boolean shiftItemStack(List inventorySlots, ItemStack stackInSlot, int slotIndex, int numSlots, boolean fromCraftingSlot) { if (isInPlayerInventory(slotIndex)) { if (shiftToMachineInventory(inventorySlots, stackInSlot, numSlots)) { return true; @@ -124,20 +123,16 @@ public abstract class SlotUtil { ItemStack stackSlot = slot.getStack(); int stackSize; if (clickTypeIn == ClickType.QUICK_MOVE) { - stackSize = mouseButton == 0 ? (stackSlot.stackSize + 1) / 2 : stackSlot.stackSize * 2; + stackSize = mouseButton == 0 ? (stackSlot.getCount() + 1) / 2 : stackSlot.getCount() * 2; } else { - stackSize = mouseButton == 0 ? stackSlot.stackSize - 1 : stackSlot.stackSize + 1; + stackSize = mouseButton == 0 ? stackSlot.getCount() - 1 : stackSlot.getCount() + 1; } if (stackSize > slot.getSlotStackLimit()) { stackSize = slot.getSlotStackLimit(); } - stackSlot.stackSize = stackSize; - - if (stackSlot.stackSize <= 0) { - stackSlot = null; - } + stackSlot.setCount(stackSize); slot.putStack(stackSlot); } @@ -147,47 +142,47 @@ public abstract class SlotUtil { return; } - if (stackHeld == null) { - slot.putStack(null); + if (stackHeld.isEmpty()) { + slot.putStack(ItemStack.EMPTY); return; } - int stackSize = mouseButton == 0 ? stackHeld.stackSize : 1; + int stackSize = mouseButton == 0 ? stackHeld.getCount() : 1; if (stackSize > slot.getSlotStackLimit()) { stackSize = slot.getSlotStackLimit(); } ItemStack phantomStack = stackHeld.copy(); - phantomStack.stackSize = stackSize; + phantomStack.setCount(stackSize); slot.putStack(phantomStack); } - private static boolean shiftItemStackToRange(List inventorySlots, ItemStack stackToShift, int start, int count) { + private static boolean shiftItemStackToRange(List inventorySlots, ItemStack stackToShift, int start, int count) { boolean changed = shiftItemStackToRangeMerge(inventorySlots, stackToShift, start, count); changed |= shiftItemStackToRangeOpenSlots(inventorySlots, stackToShift, start, count); return changed; } - private static boolean shiftItemStackToRangeMerge(List inventorySlots, ItemStack stackToShift, int start, int count) { - if (stackToShift == null || !stackToShift.isStackable() || stackToShift.stackSize <= 0) { + private static boolean shiftItemStackToRangeMerge(List inventorySlots, ItemStack stackToShift, int start, int count) { + if (!stackToShift.isStackable() || stackToShift.isEmpty()) { return false; } boolean changed = false; - for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { - Slot slot = (Slot) inventorySlots.get(slotIndex); + for (int slotIndex = start; !stackToShift.isEmpty() && slotIndex < start + count; slotIndex++) { + Slot slot = inventorySlots.get(slotIndex); ItemStack stackInSlot = slot.getStack(); - if (stackInSlot != null && ItemStackUtil.isIdenticalItem(stackInSlot, stackToShift)) { - int resultingStackSize = stackInSlot.stackSize + stackToShift.stackSize; + if (!stackInSlot.isEmpty() && ItemStackUtil.isIdenticalItem(stackInSlot, stackToShift)) { + int resultingStackSize = stackInSlot.getCount() + stackToShift.getCount(); int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); if (resultingStackSize <= max) { - stackToShift.stackSize = 0; - stackInSlot.stackSize = resultingStackSize; + stackToShift.setCount(0); + stackInSlot.setCount(resultingStackSize); slot.onSlotChanged(); changed = true; - } else if (stackInSlot.stackSize < max) { - stackToShift.stackSize -= max - stackInSlot.stackSize; - stackInSlot.stackSize = max; + } else if (stackInSlot.getCount() < max) { + stackToShift.shrink(max - stackInSlot.getCount()); + stackInSlot.setCount(max); slot.onSlotChanged(); changed = true; } @@ -196,20 +191,20 @@ public abstract class SlotUtil { return changed; } - private static boolean shiftItemStackToRangeOpenSlots(List inventorySlots, ItemStack stackToShift, int start, int count) { - if (stackToShift == null || stackToShift.stackSize <= 0) { + private static boolean shiftItemStackToRangeOpenSlots(List inventorySlots, ItemStack stackToShift, int start, int count) { + if (stackToShift.isEmpty()) { return false; } boolean changed = false; - for (int slotIndex = start; stackToShift.stackSize > 0 && slotIndex < start + count; slotIndex++) { - Slot slot = (Slot) inventorySlots.get(slotIndex); + for (int slotIndex = start; !stackToShift.isEmpty() && slotIndex < start + count; slotIndex++) { + Slot slot = inventorySlots.get(slotIndex); ItemStack stackInSlot = slot.getStack(); - if (stackInSlot == null) { + if (stackInSlot.isEmpty()) { int max = Math.min(stackToShift.getMaxStackSize(), slot.getSlotStackLimit()); stackInSlot = stackToShift.copy(); - stackInSlot.stackSize = Math.min(stackToShift.stackSize, max); - stackToShift.stackSize -= stackInSlot.stackSize; + stackInSlot.setCount(Math.min(stackToShift.getCount(), max)); + stackInSlot.shrink(stackInSlot.getCount()); slot.putStack(stackInSlot); slot.onSlotChanged(); changed = true; @@ -229,7 +224,7 @@ public abstract class SlotUtil { return SlotUtil.isSlotInRange(slotIndex, playerInventorySize - playerHotbarSize, playerInventorySize); } - private static boolean shiftToPlayerInventory(List inventorySlots, ItemStack stackInSlot) { + private static boolean shiftToPlayerInventory(List inventorySlots, ItemStack stackInSlot) { int playerHotbarStart = playerInventorySize - playerHotbarSize; // try to merge with existing stacks, hotbar first @@ -242,32 +237,32 @@ public abstract class SlotUtil { return shifted; } - private static boolean shiftToPlayerInventoryNoHotbar(List inventorySlots, ItemStack stackInSlot) { + private static boolean shiftToPlayerInventoryNoHotbar(List inventorySlots, ItemStack stackInSlot) { int playerHotbarStart = playerInventorySize - playerHotbarSize; return shiftItemStackToRange(inventorySlots, stackInSlot, 0, playerHotbarStart); } - private static boolean shiftToHotbar(List inventorySlots, ItemStack stackInSlot) { + private static boolean shiftToHotbar(List inventorySlots, ItemStack stackInSlot) { int playerHotbarStart = playerInventorySize - playerHotbarSize; return shiftItemStackToRange(inventorySlots, stackInSlot, playerHotbarStart, playerHotbarSize); } - private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots) { + private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots) { boolean success = false; if (stackToShift.isStackable()) { success = shiftToMachineInventory(inventorySlots, stackToShift, numSlots, true); } - if (stackToShift.stackSize > 0) { + if (!stackToShift.isEmpty()) { success |= shiftToMachineInventory(inventorySlots, stackToShift, numSlots, false); } return success; } // if mergeOnly = true, don't shift into empty slots. - private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots, boolean mergeOnly) { + private static boolean shiftToMachineInventory(List inventorySlots, ItemStack stackToShift, int numSlots, boolean mergeOnly) { for (int machineIndex = playerInventorySize; machineIndex < numSlots; machineIndex++) { - Slot slot = (Slot) inventorySlots.get(machineIndex); - if (mergeOnly && slot.getStack() == null) { + Slot slot = inventorySlots.get(machineIndex); + if (mergeOnly && slot.getStack().isEmpty()) { continue; } if (slot instanceof SlotForestry) { diff --git a/src/main/java/forestry/core/utils/Stack.java b/src/main/java/forestry/core/utils/Stack.java index a3b0ba9a8..562901121 100644 --- a/src/main/java/forestry/core/utils/Stack.java +++ b/src/main/java/forestry/core/utils/Stack.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.utils; +import javax.annotation.Nullable; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; @@ -17,7 +18,6 @@ import java.util.List; import net.minecraft.block.Block; import net.minecraft.item.Item; - import net.minecraftforge.oredict.OreDictionary; public class Stack { @@ -48,11 +48,8 @@ public class Stack { return stacks; } + @Nullable public static Stack parseStackString(String stackString, int missingMetaValue) { - if (stackString == null) { - return null; - } - stackString = stackString.trim(); if (stackString.isEmpty()) { return null; @@ -82,6 +79,7 @@ public class Stack { return new Stack(name, meta); } + @Nullable public Item getItem() { Item item = ItemStackUtil.getItemFromRegistry(name); if (item == null) { @@ -90,6 +88,7 @@ public class Stack { return item; } + @Nullable public Block getBlock() { Block block = ItemStackUtil.getBlockFromRegistry(name); if (block == null) { diff --git a/src/main/java/forestry/core/utils/VectUtil.java b/src/main/java/forestry/core/utils/VectUtil.java index 884896421..dd102372e 100644 --- a/src/main/java/forestry/core/utils/VectUtil.java +++ b/src/main/java/forestry/core/utils/VectUtil.java @@ -10,11 +10,10 @@ ******************************************************************************/ package forestry.core.utils; -import com.google.common.collect.AbstractIterator; - -import java.util.Iterator; +import javax.annotation.Nullable; import java.util.Random; +import com.google.common.collect.AbstractIterator; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; @@ -62,12 +61,7 @@ public final class VectUtil { final BlockPos minPos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); final BlockPos maxPos = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); - return new Iterable() { - @Override - public Iterator iterator() { - return new MutableBlockPosSpiralIterator(world, center, maxPos, minPos); - } - }; + return () -> new MutableBlockPosSpiralIterator(world, center, maxPos, minPos); } private static class MutableBlockPosSpiralIterator extends AbstractIterator { @@ -79,6 +73,7 @@ public final class VectUtil { private final int maxSpiralLayers; private int direction; + @Nullable private BlockPos.MutableBlockPos theBlockPos; public MutableBlockPosSpiralIterator(World world, BlockPos center, BlockPos maxPos, BlockPos minPos) { diff --git a/src/main/java/forestry/core/utils/VillagerTradeLists.java b/src/main/java/forestry/core/utils/VillagerTradeLists.java index 0c1495601..723e95d94 100644 --- a/src/main/java/forestry/core/utils/VillagerTradeLists.java +++ b/src/main/java/forestry/core/utils/VillagerTradeLists.java @@ -1,10 +1,10 @@ package forestry.core.utils; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Random; import net.minecraft.block.Block; +import net.minecraft.entity.IMerchant; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -18,22 +18,21 @@ public class VillagerTradeLists { * that takes ItemStacks as parameters and has emerald price info */ public static class GiveItemForItemAndEmerald implements EntityVillager.ITradeList { - @Nonnull - public ItemStack buyingItemStack; + public final ItemStack buyingItemStack; + public final ItemStack sellingItemstack; + @Nullable - public EntityVillager.PriceInfo buyingPriceInfo; + public final EntityVillager.PriceInfo buyingPriceInfo; @Nullable - public EntityVillager.PriceInfo emeraldPriceInfo; - @Nonnull - public ItemStack sellingItemstack; + public final EntityVillager.PriceInfo emeraldPriceInfo; @Nullable - public EntityVillager.PriceInfo sellingPriceInfo; + public final EntityVillager.PriceInfo sellingPriceInfo; public GiveItemForItemAndEmerald( - @Nonnull ItemStack buyingItemStack, + ItemStack buyingItemStack, @Nullable EntityVillager.PriceInfo buyingPriceInfo, @Nullable EntityVillager.PriceInfo emeraldPriceInfo, - @Nonnull ItemStack sellingItemstack, + ItemStack sellingItemstack, @Nullable EntityVillager.PriceInfo sellingPriceInfo) { this.buyingItemStack = buyingItemStack; this.buyingPriceInfo = buyingPriceInfo; @@ -43,7 +42,7 @@ public class VillagerTradeLists { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant merchant, MerchantRecipeList recipeList, Random random) { int buyAmount = 1; if (this.buyingPriceInfo != null) { buyAmount = this.buyingPriceInfo.getPrice(random); @@ -60,9 +59,9 @@ public class VillagerTradeLists { } ItemStack buyItemStack = this.buyingItemStack.copy(); - buyItemStack.stackSize = buyAmount; + buyItemStack.setCount(buyAmount); ItemStack sellItemStack = this.sellingItemstack.copy(); - sellItemStack.stackSize = sellAmount; + sellItemStack.setCount(sellAmount); recipeList.add(new MerchantRecipe(buyItemStack, new ItemStack(Items.EMERALD, emeraldAmount, 0), sellItemStack)); } } @@ -72,10 +71,11 @@ public class VillagerTradeLists { * that takes itemStack as a parameter */ public static class GiveEmeraldForItems implements EntityVillager.ITradeList { - public ItemStack buyingItem; - public EntityVillager.PriceInfo price; + public final ItemStack buyingItem; + @Nullable + public final EntityVillager.PriceInfo price; - public GiveEmeraldForItems(ItemStack itemIn, EntityVillager.PriceInfo priceIn) { + public GiveEmeraldForItems(ItemStack itemIn, @Nullable EntityVillager.PriceInfo priceIn) { this.buyingItem = itemIn; this.price = priceIn; } @@ -84,14 +84,14 @@ public class VillagerTradeLists { * Affects the given MerchantRecipeList to possibly add or remove MerchantRecipes. */ @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant merchant, MerchantRecipeList recipeList, Random random) { int buyAmount = 1; if (this.price != null) { buyAmount = this.price.getPrice(random); } ItemStack itemToBuy = this.buyingItem.copy(); - itemToBuy.stackSize = buyAmount; + itemToBuy.setCount(buyAmount); recipeList.add(new MerchantRecipe(itemToBuy, Items.EMERALD)); } } @@ -101,21 +101,20 @@ public class VillagerTradeLists { * that copies itemStacks properly */ public static class GiveItemForEmeralds implements EntityVillager.ITradeList { + public final ItemStack itemToSell; @Nullable - public EntityVillager.PriceInfo emeraldPriceInfo; - @Nonnull - public ItemStack itemToSell; + public final EntityVillager.PriceInfo emeraldPriceInfo; @Nullable - public EntityVillager.PriceInfo sellInfo; + public final EntityVillager.PriceInfo sellInfo; - public GiveItemForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, @Nonnull ItemStack itemToSell, @Nullable EntityVillager.PriceInfo sellInfo) { + public GiveItemForEmeralds(@Nullable EntityVillager.PriceInfo emeraldPriceInfo, ItemStack itemToSell, @Nullable EntityVillager.PriceInfo sellInfo) { this.emeraldPriceInfo = emeraldPriceInfo; this.itemToSell = itemToSell; this.sellInfo = sellInfo; } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant merchant, MerchantRecipeList recipeList, Random random) { int i = 1; if (this.sellInfo != null) { i = this.sellInfo.getPrice(random); @@ -127,7 +126,7 @@ public class VillagerTradeLists { } ItemStack sellStack = this.itemToSell.copy(); - sellStack.stackSize = i; + sellStack.setCount(i); ItemStack emeralds = new ItemStack(Items.EMERALD, j); @@ -136,16 +135,16 @@ public class VillagerTradeLists { } public static class GiveItemForLogsAndEmeralds implements EntityVillager.ITradeList { - @Nonnull - public ItemStack itemToSell; - @Nonnull - public EntityVillager.PriceInfo itemInfo; - @Nonnull - public EntityVillager.PriceInfo logsInfo; - @Nonnull - public EntityVillager.PriceInfo emeraldsInfo; - public GiveItemForLogsAndEmeralds(@Nonnull ItemStack itemToSell, @Nonnull EntityVillager.PriceInfo itemInfo, @Nonnull EntityVillager.PriceInfo logsInfo, @Nonnull EntityVillager.PriceInfo emeraldsInfo) { + public final ItemStack itemToSell; + + public final EntityVillager.PriceInfo itemInfo; + + public final EntityVillager.PriceInfo logsInfo; + + public final EntityVillager.PriceInfo emeraldsInfo; + + public GiveItemForLogsAndEmeralds(ItemStack itemToSell, EntityVillager.PriceInfo itemInfo, EntityVillager.PriceInfo logsInfo, EntityVillager.PriceInfo emeraldsInfo) { this.itemToSell = itemToSell; this.itemInfo = itemInfo; this.logsInfo = logsInfo; @@ -153,13 +152,13 @@ public class VillagerTradeLists { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant merchant, MerchantRecipeList recipeList, Random random) { int itemAmount = this.itemInfo.getPrice(random); int emeraldsAmount = this.emeraldsInfo.getPrice(random); int logsAmount = this.logsInfo.getPrice(random); ItemStack itemToSell = this.itemToSell.copy(); - itemToSell.stackSize = itemAmount; + itemToSell.setCount(itemAmount); int logMeta = random.nextInt(6); Block log; @@ -174,26 +173,27 @@ public class VillagerTradeLists { recipeList.add(new MerchantRecipe(randomLog, new ItemStack(Items.EMERALD, emeraldsAmount), itemToSell)); } } + public static class GiveItemForTwoItems implements EntityVillager.ITradeList { - @Nonnull - public ItemStack buyingItemStack; + + public final ItemStack buyingItemStack; @Nullable - public EntityVillager.PriceInfo buyingPriceInfo; - @Nonnull - public ItemStack buyingItemStackTwo; + public final EntityVillager.PriceInfo buyingPriceInfo; + + public final ItemStack buyingItemStackTwo; @Nullable - public EntityVillager.PriceInfo buyingPriceItemTwoInfo; - @Nonnull - public ItemStack sellingItemstack; + public final EntityVillager.PriceInfo buyingPriceItemTwoInfo; + + public final ItemStack sellingItemstack; @Nullable - public EntityVillager.PriceInfo sellingPriceInfo; + public final EntityVillager.PriceInfo sellingPriceInfo; public GiveItemForTwoItems( - @Nonnull ItemStack buyingItemStack, + ItemStack buyingItemStack, @Nullable EntityVillager.PriceInfo buyingPriceInfo, - @Nonnull ItemStack buyingItemStackTwo, + ItemStack buyingItemStackTwo, @Nullable EntityVillager.PriceInfo buyingPriceItemTwoInfo, - @Nonnull ItemStack sellingItemstack, + ItemStack sellingItemstack, @Nullable EntityVillager.PriceInfo sellingPriceInfo) { this.buyingItemStack = buyingItemStack; this.buyingPriceInfo = buyingPriceInfo; @@ -204,7 +204,7 @@ public class VillagerTradeLists { } @Override - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { + public void addMerchantRecipe(IMerchant merchant, MerchantRecipeList recipeList, Random random) { int buyAmount = 1; if (this.buyingPriceInfo != null) { buyAmount = this.buyingPriceInfo.getPrice(random); @@ -221,11 +221,11 @@ public class VillagerTradeLists { } ItemStack buyItemStack = this.buyingItemStack.copy(); - buyItemStack.stackSize = buyAmount; + buyItemStack.setCount(buyAmount); ItemStack buyItemStackTwo = this.buyingItemStackTwo.copy(); - buyItemStackTwo.stackSize = buyTwoAmount; + buyItemStackTwo.setCount(buyTwoAmount); ItemStack sellItemStack = this.sellingItemstack.copy(); - sellItemStack.stackSize = sellAmount; + sellItemStack.setCount(sellAmount); recipeList.add(new MerchantRecipe(buyItemStack, buyItemStackTwo, sellItemStack)); } } diff --git a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java b/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java index 578af5186..c2f47dd59 100644 --- a/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java +++ b/src/main/java/forestry/core/utils/datastructures/ItemStackMap.java @@ -47,7 +47,7 @@ public class ItemStackMap extends StackMap { if (key instanceof ItemStack) { return (ItemStack) key; } - return null; + return ItemStack.EMPTY; } } diff --git a/src/main/java/forestry/core/utils/datastructures/RevolvingList.java b/src/main/java/forestry/core/utils/datastructures/RevolvingList.java index 8faf699fc..07fa48d74 100644 --- a/src/main/java/forestry/core/utils/datastructures/RevolvingList.java +++ b/src/main/java/forestry/core/utils/datastructures/RevolvingList.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.core.utils.datastructures; +import javax.annotation.Nullable; + import com.google.common.collect.ForwardingCollection; import java.util.Collection; @@ -24,9 +26,6 @@ public class RevolvingList extends ForwardingCollection { private final Deque list = new LinkedList<>(); - public RevolvingList() { - } - public RevolvingList(Collection collection) { list.addAll(collection); } @@ -50,6 +49,7 @@ public class RevolvingList extends ForwardingCollection { list.addLast(list.removeFirst()); } + @Nullable public T getCurrent() { if (list.isEmpty()) { return null; @@ -57,7 +57,7 @@ public class RevolvingList extends ForwardingCollection { return list.getFirst(); } - public void setCurrent(T e) { + public void setCurrent(@Nullable T e) { if (!contains(e)) { return; } diff --git a/src/main/java/forestry/core/utils/datastructures/StackMap.java b/src/main/java/forestry/core/utils/datastructures/StackMap.java index 5fdd3ca6a..889097a93 100644 --- a/src/main/java/forestry/core/utils/datastructures/StackMap.java +++ b/src/main/java/forestry/core/utils/datastructures/StackMap.java @@ -10,9 +10,12 @@ ******************************************************************************/ package forestry.core.utils.datastructures; +import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; +import com.google.common.base.Preconditions; + /** * Map for fluids and items. Can add things like ore dictionary strings etc. * @@ -24,10 +27,9 @@ public abstract class StackMap extends HashMap { @Override public final T put(P key, T value) { - if (isValidKey(key) && key != null && value != null) { - return super.put(key, value); - } - return null; + Preconditions.checkArgument(isValidKey(key), "Key is invalid"); + Preconditions.checkNotNull(value); + return super.put(key, value); } private static final long serialVersionUID = 5383477742290646466L; @@ -47,6 +49,7 @@ public abstract class StackMap extends HashMap { } @Override + @Nullable public final T get(Object key) { P stack = getStack(key); if (stack == null) { @@ -83,6 +86,7 @@ public abstract class StackMap extends HashMap { * @param key * @return */ + @Nullable protected abstract P getStack(Object key); } diff --git a/src/main/java/forestry/core/utils/datastructures/package-info.java b/src/main/java/forestry/core/utils/datastructures/package-info.java new file mode 100644 index 000000000..4e8eca642 --- /dev/null +++ b/src/main/java/forestry/core/utils/datastructures/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.utils.datastructures; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/utils/package-info.java b/src/main/java/forestry/core/utils/package-info.java new file mode 100644 index 000000000..dfa91a4e5 --- /dev/null +++ b/src/main/java/forestry/core/utils/package-info.java @@ -0,0 +1,8 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.utils; + +import javax.annotation.ParametersAreNonnullByDefault; + +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/core/worldgen/WorldGenHelper.java b/src/main/java/forestry/core/worldgen/WorldGenHelper.java index b4db4d786..ce30bc423 100644 --- a/src/main/java/forestry/core/worldgen/WorldGenHelper.java +++ b/src/main/java/forestry/core/worldgen/WorldGenHelper.java @@ -1,12 +1,15 @@ package forestry.core.worldgen; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.EnumSet; import java.util.HashSet; import java.util.Random; import java.util.Set; +import forestry.api.world.ITreeGenData; +import forestry.arboriculture.worldgen.ITreeBlockType; +import forestry.arboriculture.worldgen.TreeBlockType; +import forestry.core.utils.VectUtil; import net.minecraft.block.BlockVine; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -15,11 +18,6 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; -import forestry.api.world.ITreeGenData; -import forestry.arboriculture.worldgen.ITreeBlockType; -import forestry.arboriculture.worldgen.TreeBlockType; -import forestry.core.utils.VectUtil; - public class WorldGenHelper { public static boolean addBlock(World world, BlockPos pos, ITreeBlockType type, EnumReplaceMode replaceMode) { @@ -106,12 +104,14 @@ public class WorldGenHelper { } } - /** Returns a list of trunk top coordinates */ + /** + * Returns a list of trunk top coordinates + */ public static Set generateTreeTrunk( - @Nonnull World world, + World world, Random rand, - @Nonnull ITreeBlockType wood, - @Nonnull BlockPos startPos, + ITreeBlockType wood, + BlockPos startPos, int height, int girth, int yStart, @@ -149,7 +149,9 @@ public class WorldGenHelper { prevXOffset = xOffset; prevZOffset = zOffset; if (y > 0) { - wood.setDirection(leanDirection); + if (leanDirection != null) { + wood.setDirection(leanDirection); + } addBlock(world, startPos.add(x + xOffset, y - 1, z + zOffset), wood, EnumReplaceMode.ALL); wood.setDirection(EnumFacing.UP); } diff --git a/src/main/java/forestry/core/worldgen/WorldGenerator.java b/src/main/java/forestry/core/worldgen/WorldGenerator.java index 1fe5588dc..5cafafa83 100644 --- a/src/main/java/forestry/core/worldgen/WorldGenerator.java +++ b/src/main/java/forestry/core/worldgen/WorldGenerator.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.core.worldgen; +import javax.annotation.Nullable; import java.util.Random; import net.minecraft.block.state.IBlockState; @@ -31,9 +32,11 @@ import forestry.core.config.Config; import forestry.plugins.PluginManager; public class WorldGenerator implements IWorldGenerator { - + @Nullable private WorldGenMinable apatiteGenerator; + @Nullable private WorldGenMinable copperGenerator; + @Nullable private WorldGenMinable tinGenerator; public WorldGenerator() { @@ -59,7 +62,7 @@ public class WorldGenerator implements IWorldGenerator { private void generateWorld(Random random, int chunkX, int chunkZ, World world) { - if (apatiteGenerator == null) { + if (apatiteGenerator == null || copperGenerator == null || tinGenerator == null) { BlockResourceOre resourcesBlock = PluginCore.blocks.resources; IBlockState apatiteBlockState = resourcesBlock.getStateFromMeta(EnumResourceType.APATITE.getMeta()); diff --git a/src/main/java/forestry/core/worldgen/package-info.java b/src/main/java/forestry/core/worldgen/package-info.java new file mode 100644 index 000000000..734e6a016 --- /dev/null +++ b/src/main/java/forestry/core/worldgen/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.core.worldgen; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/EnergyHelper.java b/src/main/java/forestry/energy/EnergyHelper.java index cd36fe33b..b1d592d0c 100644 --- a/src/main/java/forestry/energy/EnergyHelper.java +++ b/src/main/java/forestry/energy/EnergyHelper.java @@ -2,7 +2,6 @@ package forestry.energy; import forestry.api.core.ForestryAPI; import forestry.core.tiles.TileEngine; -import forestry.energy.compat.rf.RFHelper; import forestry.energy.compat.tesla.TeslaHelper; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; @@ -51,29 +50,33 @@ public class EnergyHelper { * @return amount sent */ public static int sendEnergy(EnergyManager energyManager, EnumFacing orientation, TileEntity tile, int amount, boolean simulate) { - if (tile != null) { - int extractable = energyManager.extractEnergy(amount, true); - if (extractable > 0) { - final int sent; - EnumFacing side = orientation.getOpposite(); - if (tile instanceof TileEngine) { // engine chaining - TileEngine receptor = (TileEngine) tile; - sent = receptor.getEnergyManager().receiveEnergy(extractable, simulate); - } else if (tile.hasCapability(CapabilityEnergy.ENERGY, side)) { - IEnergyStorage energyStorage = tile.getCapability(CapabilityEnergy.ENERGY, side); - sent = energyStorage.receiveEnergy(extractable, simulate); - } else if (TeslaHelper.isEnergyReceiver(tile, side)) { - sent = TeslaHelper.sendEnergy(tile, side, extractable, simulate); - } else if (RFHelper.isEnergyReceiver(tile, side)) { - sent = RFHelper.sendEnergy(tile, side, extractable, simulate); - } else { - sent = 0; - } + int extractable = energyManager.extractEnergy(amount, true); + if (extractable > 0) { + EnumFacing side = orientation.getOpposite(); + final int sent = sendEnergyToTile(tile, side, extractable, simulate); + energyManager.extractEnergy(sent, simulate); + return sent; + } + return 0; + } - energyManager.extractEnergy(sent, simulate); - return sent; + private static int sendEnergyToTile(TileEntity tile, EnumFacing side, int extractable, boolean simulate) { + if (tile instanceof TileEngine) { // engine chaining + TileEngine receptor = (TileEngine) tile; + return receptor.getEnergyManager().receiveEnergy(extractable, simulate); + } + + if (tile.hasCapability(CapabilityEnergy.ENERGY, side)) { + IEnergyStorage energyStorage = tile.getCapability(CapabilityEnergy.ENERGY, side); + if (energyStorage != null) { + return energyStorage.receiveEnergy(extractable, simulate); } } + + if (TeslaHelper.isEnergyReceiver(tile, side)) { + return TeslaHelper.sendEnergy(tile, side, extractable, simulate); + } + return 0; } @@ -85,24 +88,15 @@ public class EnergyHelper { } public static boolean isEnergyReceiverOrEngine(EnumFacing side, TileEntity tile) { - if (tile != null) { - if (tile instanceof TileEngine) { // engine chaining - return true; - } - - if (tile.hasCapability(CapabilityEnergy.ENERGY, side)) { - IEnergyStorage energyStorage = tile.getCapability(CapabilityEnergy.ENERGY, side); - return energyStorage.canReceive(); - } - - if (TeslaHelper.isEnergyReceiver(tile, side)) { - return true; - } - - if (RFHelper.isEnergyReceiver(tile, side)) { - return true; - } + if (tile instanceof TileEngine) { // engine chaining + return true; } - return false; + + if (tile.hasCapability(CapabilityEnergy.ENERGY, side)) { + IEnergyStorage energyStorage = tile.getCapability(CapabilityEnergy.ENERGY, side); + return energyStorage != null && energyStorage.canReceive(); + } + + return TeslaHelper.isEnergyReceiver(tile, side); } } diff --git a/src/main/java/forestry/energy/EnergyManager.java b/src/main/java/forestry/energy/EnergyManager.java index 8e416290d..2fed6a6e8 100644 --- a/src/main/java/forestry/energy/EnergyManager.java +++ b/src/main/java/forestry/energy/EnergyManager.java @@ -1,19 +1,20 @@ package forestry.energy; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.energy.compat.EnergyStorageWrapper; import forestry.energy.compat.tesla.TeslaConsumerWrapper; import forestry.energy.compat.tesla.TeslaHelper; import forestry.energy.compat.tesla.TeslaHolderWrapper; import forestry.energy.compat.tesla.TeslaProducerWrapper; +import net.darkhax.tesla.api.ITeslaConsumer; +import net.darkhax.tesla.api.ITeslaHolder; +import net.darkhax.tesla.api.ITeslaProducer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.energy.CapabilityEnergy; @@ -21,18 +22,16 @@ import net.minecraftforge.energy.EnergyStorage; import net.minecraftforge.energy.IEnergyStorage; public class EnergyManager extends EnergyStorage implements IStreamable, INbtReadable, INbtWritable { - @Nonnull private EnergyTransferMode externalMode = EnergyTransferMode.BOTH; public EnergyManager(int maxTransfer, int capacity) { super(EnergyHelper.scaleForDifficulty(capacity), EnergyHelper.scaleForDifficulty(maxTransfer), EnergyHelper.scaleForDifficulty(maxTransfer)); } - public void setExternalMode(@Nonnull EnergyTransferMode externalMode) { + public void setExternalMode(EnergyTransferMode externalMode) { this.externalMode = externalMode; } - @Nonnull public EnergyTransferMode getExternalMode() { return externalMode; } @@ -58,12 +57,12 @@ public class EnergyManager extends EnergyStorage implements IStreamable, INbtRea } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeVarInt(this.energy); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { int energyStored = data.readVarInt(); setEnergyStored(energyStored); } @@ -96,40 +95,31 @@ public class EnergyManager extends EnergyStorage implements IStreamable, INbtRea } public boolean hasCapability(Capability capability) { - if (capability == null) { - return false; - } - - if (capability == CapabilityEnergy.ENERGY) { - return true; - } else if (capability == TeslaHelper.TESLA_PRODUCER && externalMode.canExtract()) { - return true; - } else if (capability == TeslaHelper.TESLA_CONSUMER && externalMode.canReceive()) { - return true; - } else if (capability == TeslaHelper.TESLA_HOLDER) { - return true; - } else { - return false; - } + return capability == CapabilityEnergy.ENERGY || + capability == TeslaHelper.TESLA_PRODUCER && externalMode.canExtract() || + capability == TeslaHelper.TESLA_CONSUMER && externalMode.canReceive() || + capability == TeslaHelper.TESLA_HOLDER; } @Nullable public T getCapability(Capability capability) { - if (capability == null) { - return null; - } - if (capability == CapabilityEnergy.ENERGY) { IEnergyStorage energyStorage = new EnergyStorageWrapper(this, externalMode); return CapabilityEnergy.ENERGY.cast(energyStorage); - } else if (capability == TeslaHelper.TESLA_PRODUCER && externalMode.canExtract()) { - return TeslaHelper.TESLA_PRODUCER.cast(new TeslaProducerWrapper(this)); - } else if (capability == TeslaHelper.TESLA_CONSUMER && externalMode.canReceive()) { - return TeslaHelper.TESLA_CONSUMER.cast(new TeslaConsumerWrapper(this)); - } else if (capability == TeslaHelper.TESLA_HOLDER) { - return TeslaHelper.TESLA_HOLDER.cast(new TeslaHolderWrapper(this)); } else { - return null; + Capability teslaProducer = TeslaHelper.TESLA_PRODUCER; + Capability teslaConsumer = TeslaHelper.TESLA_CONSUMER; + Capability teslaHolder = TeslaHelper.TESLA_HOLDER; + + if (capability == teslaProducer && externalMode.canExtract()) { + return teslaProducer.cast(new TeslaProducerWrapper(this)); + } else if (capability == teslaConsumer && externalMode.canReceive()) { + return teslaConsumer.cast(new TeslaConsumerWrapper(this)); + } else if (capability == teslaHolder) { + return teslaHolder.cast(new TeslaHolderWrapper(this)); + } else { + return null; + } } } diff --git a/src/main/java/forestry/energy/PluginEnergy.java b/src/main/java/forestry/energy/PluginEnergy.java index c22e87575..f74e77dd0 100644 --- a/src/main/java/forestry/energy/PluginEnergy.java +++ b/src/main/java/forestry/energy/PluginEnergy.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.energy; +import javax.annotation.Nullable; + +import com.google.common.base.Preconditions; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -28,9 +31,11 @@ import forestry.plugins.ForestryPluginUids; @ForestryPlugin(pluginID = ForestryPluginUids.ENERGY, name = "Energy", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.energy.description") public class PluginEnergy extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.energy.proxy.ProxyEnergyClient", serverSide = "forestry.energy.proxy.ProxyEnergy") public static ProxyEnergy proxy; + @Nullable public static BlockRegistryEnergy blocks; @Override @@ -40,6 +45,7 @@ public class PluginEnergy extends BlankForestryPlugin { @Override public void doInit() { + Preconditions.checkState(blocks != null); blocks.peatEngine.init(); blocks.biogasEngine.init(); @@ -51,6 +57,7 @@ public class PluginEnergy extends BlankForestryPlugin { @Override public void registerRecipes() { super.registerRecipes(); + Preconditions.checkState(blocks != null); RecipeUtil.addRecipe(new ItemStack(blocks.peatEngine), "###", diff --git a/src/main/java/forestry/energy/blocks/BlockEngine.java b/src/main/java/forestry/energy/blocks/BlockEngine.java index eee5e0a6b..ac27003c2 100644 --- a/src/main/java/forestry/energy/blocks/BlockEngine.java +++ b/src/main/java/forestry/energy/blocks/BlockEngine.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.energy.blocks; +import javax.annotation.Nullable; import java.util.EnumMap; import java.util.List; @@ -58,7 +59,7 @@ public class BlockEngine extends BlockBase { } @Override - public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List collidingBoxes, Entity entityIn) { + public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List collidingBoxes, @Nullable Entity entityIn) { EnumFacing orientation = state.getValue(FACING); List boundingBoxes = boundingBoxesForDirections.get(orientation); if (boundingBoxes == null) { @@ -105,11 +106,8 @@ public class BlockEngine extends BlockBase { @Override public boolean rotateBlock(World world, BlockPos pos, EnumFacing axis) { - if (rotate(world, pos)) { - return true; - } - - return super.rotateBlock(world, pos, axis); + return rotate(world, pos) || + super.rotateBlock(world, pos, axis); } private static boolean isOrientedAtEnergyReciever(World world, BlockPos pos, EnumFacing orientation) { diff --git a/src/main/java/forestry/energy/blocks/BlockTypeEngine.java b/src/main/java/forestry/energy/blocks/BlockTypeEngine.java index cc5d40469..7284500d8 100644 --- a/src/main/java/forestry/energy/blocks/BlockTypeEngine.java +++ b/src/main/java/forestry/energy/blocks/BlockTypeEngine.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.energy.blocks; -import javax.annotation.Nonnull; - -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; - import forestry.core.blocks.IBlockTypeTesr; import forestry.core.blocks.IMachinePropertiesTesr; import forestry.core.blocks.MachinePropertiesTesr; @@ -24,37 +20,34 @@ import forestry.core.tiles.TileEngine; import forestry.energy.PluginEnergy; import forestry.energy.tiles.TileEngineBiogas; import forestry.energy.tiles.TileEngineClockwork; -import forestry.energy.tiles.TileEngineElectric; import forestry.energy.tiles.TileEnginePeat; -import forestry.energy.tiles.TileEuGenerator; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; public enum BlockTypeEngine implements IBlockTypeTesr { PEAT(createEngineProperties(TileEnginePeat.class, "peat", "/engine_copper")), BIOGAS(createEngineProperties(TileEngineBiogas.class, "biogas", "/engine_bronze")), - CLOCKWORK(createEngineProperties(TileEngineClockwork.class, "clockwork", "/engine_clock")), - ELECTRICAL(createEngineProperties(TileEngineElectric.class, "electrical", "/engine_tin")), - GENERATOR(createMachineProperties(TileEuGenerator.class, "generator", "/generator")); + CLOCKWORK(createEngineProperties(TileEngineClockwork.class, "clockwork", "/engine_clock")); +// ELECTRICAL(createEngineProperties(TileEngineElectric.class, "electrical", "/engine_tin")), +// GENERATOR(createMachineProperties(TileEuGenerator.class, "generator", "/generator")); public static final BlockTypeEngine[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeEngine(@Nonnull IMachinePropertiesTesr machineProperties) { + BlockTypeEngine(IMachinePropertiesTesr machineProperties) { this.machineProperties = machineProperties; } - protected static IMachinePropertiesTesr createEngineProperties(@Nonnull Class teClass, @Nonnull String name, @Nonnull String textureName) { + protected static IMachinePropertiesTesr createEngineProperties(Class teClass, String name, String textureName) { TileEntitySpecialRenderer renderer = PluginEnergy.proxy.getRenderDefaultEngine(Constants.TEXTURE_PATH_BLOCKS + textureName + "_"); return new MachinePropertiesEngine<>(teClass, name, renderer, Constants.MOD_ID + ":blocks" + textureName + ".0"); } - protected static IMachinePropertiesTesr createMachineProperties(@Nonnull Class teClass, @Nonnull String name, @Nonnull String textureName) { + protected static IMachinePropertiesTesr createMachineProperties(Class teClass, String name, String textureName) { TileEntitySpecialRenderer renderer = Proxies.render.getRenderDefaultMachine(Constants.TEXTURE_PATH_BLOCKS + textureName + "_"); return new MachinePropertiesTesr<>(teClass, name, renderer, Constants.MOD_ID + ":blocks" + textureName + ".0"); } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/energy/blocks/MachinePropertiesEngine.java b/src/main/java/forestry/energy/blocks/MachinePropertiesEngine.java index a18c85710..3075a30cd 100644 --- a/src/main/java/forestry/energy/blocks/MachinePropertiesEngine.java +++ b/src/main/java/forestry/energy/blocks/MachinePropertiesEngine.java @@ -1,15 +1,13 @@ package forestry.energy.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; - import forestry.core.blocks.MachinePropertiesTesr; import forestry.core.tiles.TileEngine; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; public class MachinePropertiesEngine extends MachinePropertiesTesr { - public MachinePropertiesEngine(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, String particleTextureLocation) { + public MachinePropertiesEngine(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, String particleTextureLocation) { super(teClass, name, renderer, particleTextureLocation); } } diff --git a/src/main/java/forestry/energy/blocks/package-info.java b/src/main/java/forestry/energy/blocks/package-info.java new file mode 100644 index 000000000..4eb2154a2 --- /dev/null +++ b/src/main/java/forestry/energy/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java index 1126108a5..c3196bcae 100644 --- a/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricBoost.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.circuits; - -public class CircuitElectricBoost extends CircuitElectricChange { - - public CircuitElectricBoost(String uid, int eu, int rf) { - super(uid); - this.configureChange(eu, rf); - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.circuits; +// +//public class CircuitElectricBoost extends CircuitElectricChange { +// +// public CircuitElectricBoost(String uid, int eu, int rf) { +// super(uid); +// this.configureChange(eu, rf); +// } +// +//} diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java index 182701cb7..01c13c344 100755 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChange.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChange.java @@ -1,63 +1,63 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.circuits; - -import forestry.core.circuits.Circuit; -import forestry.energy.tiles.TileEngineElectric; - -public abstract class CircuitElectricChange extends Circuit { - - private int euChange = 7; - private int rfChange = 20; - - protected CircuitElectricChange(String uid) { - super(uid); - } - - protected void configureChange(int euChange, int rfChange) { - this.euChange = euChange; - this.rfChange = rfChange; - } - - @Override - public boolean isCircuitable(Object tile) { - return tile instanceof TileEngineElectric; - } - - @Override - public void onInsertion(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } - - TileEngineElectric engine = (TileEngineElectric) tile; - engine.changeEnergyConfig(euChange, rfChange, 2 * euChange); - } - - @Override - public void onLoad(int slot, Object tile) { - onInsertion(slot, tile); - } - - @Override - public void onRemoval(int slot, Object tile) { - if (!isCircuitable(tile)) { - return; - } - - TileEngineElectric engine = (TileEngineElectric) tile; - engine.changeEnergyConfig(-euChange, -rfChange, -(2 * euChange)); - } - - @Override - public void onTick(int slot, Object tile) { - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.circuits; +// +//import forestry.core.circuits.Circuit; +//import forestry.energy.tiles.TileEngineElectric; +// +//public abstract class CircuitElectricChange extends Circuit { +// +// private int euChange = 7; +// private int rfChange = 20; +// +// protected CircuitElectricChange(String uid) { +// super(uid); +// } +// +// protected void configureChange(int euChange, int rfChange) { +// this.euChange = euChange; +// this.rfChange = rfChange; +// } +// +// @Override +// public boolean isCircuitable(Object tile) { +// return tile instanceof TileEngineElectric; +// } +// +// @Override +// public void onInsertion(int slot, Object tile) { +// if (!isCircuitable(tile)) { +// return; +// } +// +// TileEngineElectric engine = (TileEngineElectric) tile; +// engine.changeEnergyConfig(euChange, rfChange, 2 * euChange); +// } +// +// @Override +// public void onLoad(int slot, Object tile) { +// onInsertion(slot, tile); +// } +// +// @Override +// public void onRemoval(int slot, Object tile) { +// if (!isCircuitable(tile)) { +// return; +// } +// +// TileEngineElectric engine = (TileEngineElectric) tile; +// engine.changeEnergyConfig(-euChange, -rfChange, -(2 * euChange)); +// } +// +// @Override +// public void onTick(int slot, Object tile) { +// } +//} diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java index eecd6b982..5ce421410 100644 --- a/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricChoke.java @@ -1,19 +1,19 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.circuits; - -public class CircuitElectricChoke extends CircuitElectricChange { - - public CircuitElectricChoke(String uid) { - super(uid); - this.configureChange(-2, -10); - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.circuits; +// +//public class CircuitElectricChoke extends CircuitElectricChange { +// +// public CircuitElectricChoke(String uid) { +// super(uid); +// this.configureChange(-2, -10); +// } +//} diff --git a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java index e1a2fd827..afea1b112 100644 --- a/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java +++ b/src/main/java/forestry/energy/circuits/CircuitElectricEfficiency.java @@ -1,20 +1,20 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.circuits; - -public class CircuitElectricEfficiency extends CircuitElectricChange { - - public CircuitElectricEfficiency(String uid) { - super(uid); - this.configureChange(-1, 0); - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.circuits; +// +//public class CircuitElectricEfficiency extends CircuitElectricChange { +// +// public CircuitElectricEfficiency(String uid) { +// super(uid); +// this.configureChange(-1, 0); +// } +// +//} diff --git a/src/main/java/forestry/energy/circuits/package-info.java b/src/main/java/forestry/energy/circuits/package-info.java new file mode 100644 index 000000000..51b4027b1 --- /dev/null +++ b/src/main/java/forestry/energy/circuits/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.circuits; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/compat/package-info.java b/src/main/java/forestry/energy/compat/package-info.java new file mode 100644 index 000000000..d28fde44f --- /dev/null +++ b/src/main/java/forestry/energy/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/compat/rf/IEnergyConnectionDelegated.java b/src/main/java/forestry/energy/compat/rf/IEnergyConnectionDelegated.java deleted file mode 100644 index ba64d119d..000000000 --- a/src/main/java/forestry/energy/compat/rf/IEnergyConnectionDelegated.java +++ /dev/null @@ -1,26 +0,0 @@ -package forestry.energy.compat.rf; - -import cofh.api.energy.IEnergyConnection; -import forestry.core.config.Constants; -import forestry.core.tiles.IPowerHandler; -import forestry.energy.EnergyManager; -import forestry.energy.EnergyTransferMode; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.fml.common.Optional; - -/** - * Implements {@link IEnergyConnection} by using an {@link EnergyManager} as a delegate. - */ -@Optional.Interface(iface = "cofh.api.energy.IEnergyConnection", modid = Constants.RF_MOD_ID) -public interface IEnergyConnectionDelegated extends IEnergyConnection, IPowerHandler { - @Optional.Method(modid = Constants.RF_MOD_ID) - @Override - default boolean canConnectEnergy(EnumFacing from) { - EnergyManager energyManager = getEnergyManager(); - if (energyManager == null) { - return false; - } - EnergyTransferMode externalMode = energyManager.getExternalMode(); - return externalMode.canReceive() || externalMode.canExtract(); - } -} diff --git a/src/main/java/forestry/energy/compat/rf/IEnergyHandlerDelegated.java b/src/main/java/forestry/energy/compat/rf/IEnergyHandlerDelegated.java deleted file mode 100644 index 747482e6a..000000000 --- a/src/main/java/forestry/energy/compat/rf/IEnergyHandlerDelegated.java +++ /dev/null @@ -1,33 +0,0 @@ -package forestry.energy.compat.rf; - -import cofh.api.energy.IEnergyHandler; -import forestry.core.config.Constants; -import forestry.energy.EnergyManager; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.fml.common.Optional; - -/** - * Implements {@link IEnergyHandler} by using an {@link EnergyManager} as a delegate. - */ -@Optional.Interface(iface = "cofh.api.energy.IEnergyHandler", modid = Constants.RF_MOD_ID) -public interface IEnergyHandlerDelegated extends IEnergyHandler, IEnergyConnectionDelegated { - @Optional.Method(modid = Constants.RF_MOD_ID) - @Override - default int getEnergyStored(EnumFacing from) { - EnergyManager energyManager = getEnergyManager(); - if (energyManager == null) { - return 0; - } - return energyManager.getEnergyStored(); - } - - @Optional.Method(modid = Constants.RF_MOD_ID) - @Override - default int getMaxEnergyStored(EnumFacing from) { - EnergyManager energyManager = getEnergyManager(); - if (energyManager == null) { - return 0; - } - return energyManager.getMaxEnergyStored(); - } -} diff --git a/src/main/java/forestry/energy/compat/rf/IEnergyProviderDelegated.java b/src/main/java/forestry/energy/compat/rf/IEnergyProviderDelegated.java deleted file mode 100644 index 53f7bcb9d..000000000 --- a/src/main/java/forestry/energy/compat/rf/IEnergyProviderDelegated.java +++ /dev/null @@ -1,24 +0,0 @@ -package forestry.energy.compat.rf; - -import cofh.api.energy.IEnergyProvider; -import forestry.core.config.Constants; -import forestry.energy.EnergyManager; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.fml.common.Optional; - -/** - * Implements {@link IEnergyProvider} by using an {@link EnergyManager} as a delegate. - */ -@Optional.Interface(iface = "cofh.api.energy.IEnergyProvider", modid = Constants.RF_MOD_ID) -public interface IEnergyProviderDelegated extends IEnergyProvider, IEnergyHandlerDelegated { - @Optional.Method(modid = Constants.RF_MOD_ID) - @Override - default int extractEnergy(EnumFacing from, int maxExtract, boolean simulate) { - EnergyManager energyManager = getEnergyManager(); - if (energyManager.getExternalMode().canExtract()) { - return energyManager.extractEnergy(maxExtract, simulate); - } else { - return 0; - } - } -} diff --git a/src/main/java/forestry/energy/compat/rf/IEnergyReceiverDelegated.java b/src/main/java/forestry/energy/compat/rf/IEnergyReceiverDelegated.java deleted file mode 100644 index 0f4efd5f2..000000000 --- a/src/main/java/forestry/energy/compat/rf/IEnergyReceiverDelegated.java +++ /dev/null @@ -1,26 +0,0 @@ -package forestry.energy.compat.rf; - -import cofh.api.energy.IEnergyReceiver; -import forestry.core.config.Constants; -import forestry.energy.EnergyManager; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.fml.common.Optional; - -/** - * Implements {@link IEnergyReceiver} by using an {@link EnergyManager} as a delegate. - */ -@Optional.Interface(iface = "cofh.api.energy.IEnergyReceiver", modid = Constants.RF_MOD_ID) -public interface IEnergyReceiverDelegated extends IEnergyReceiver, IEnergyHandlerDelegated { - @Optional.Method(modid = Constants.RF_MOD_ID) - @Override - default int receiveEnergy(EnumFacing from, int maxReceive, boolean simulate) { - EnergyManager energyManager = getEnergyManager(); - if (energyManager == null) { - return 0; - } else if (energyManager.getExternalMode().canReceive()) { - return energyManager.receiveEnergy(maxReceive, simulate); - } else { - return 0; - } - } -} diff --git a/src/main/java/forestry/energy/compat/rf/RFHelper.java b/src/main/java/forestry/energy/compat/rf/RFHelper.java deleted file mode 100644 index f1130405c..000000000 --- a/src/main/java/forestry/energy/compat/rf/RFHelper.java +++ /dev/null @@ -1,52 +0,0 @@ -package forestry.energy.compat.rf; - -import cofh.api.energy.IEnergyReceiver; -import forestry.core.config.Constants; -import forestry.core.utils.ModUtil; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumFacing; -import net.minecraftforge.fml.common.Optional; - -public class RFHelper { - private static boolean loaded = ModUtil.isAPILoaded("cofh.api.energy"); - - public static boolean isLoaded() { - return loaded; - } - - public static boolean isEnergyReceiver(TileEntity tile, EnumFacing side) { - if (isLoaded()) { - return _isEnergyReceiver(tile, side); - } else { - return false; - } - } - - public static int sendEnergy(TileEntity tile, EnumFacing side, int amount, boolean simulate) { - if (isLoaded()) { - return _sendEnergy(tile, side, amount, simulate); - } else { - return 0; - } - } - - @Optional.Method(modid = Constants.RF_MOD_ID) - private static boolean _isEnergyReceiver(TileEntity tile, EnumFacing side) { - if (tile instanceof IEnergyReceiver) { - IEnergyReceiver energyReceiver = (IEnergyReceiver) tile; - return energyReceiver.canConnectEnergy(side); - } else { - return false; - } - } - - @Optional.Method(modid = Constants.RF_MOD_ID) - private static int _sendEnergy(TileEntity tile, EnumFacing side, int amount, boolean simulate) { - if (tile instanceof IEnergyReceiver) { - IEnergyReceiver receptor = (IEnergyReceiver) tile; - return receptor.receiveEnergy(side, amount, simulate); - } else { - return 0; - } - } -} diff --git a/src/main/java/forestry/energy/compat/tesla/TeslaHelper.java b/src/main/java/forestry/energy/compat/tesla/TeslaHelper.java index 96abe6787..aaff7d388 100644 --- a/src/main/java/forestry/energy/compat/tesla/TeslaHelper.java +++ b/src/main/java/forestry/energy/compat/tesla/TeslaHelper.java @@ -1,5 +1,7 @@ package forestry.energy.compat.tesla; +import javax.annotation.Nullable; + import forestry.core.config.Constants; import forestry.core.utils.Log; import net.darkhax.tesla.api.ITeslaConsumer; @@ -12,10 +14,15 @@ import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.fml.common.Optional; public class TeslaHelper { + @Nullable @CapabilityInject(ITeslaConsumer.class) public static Capability TESLA_CONSUMER = null; + + @Nullable @CapabilityInject(ITeslaProducer.class) public static Capability TESLA_PRODUCER = null; + + @Nullable @CapabilityInject(ITeslaHolder.class) public static Capability TESLA_HOLDER = null; @@ -24,11 +31,7 @@ public class TeslaHelper { } public static boolean isEnergyReceiver(TileEntity tile, EnumFacing side) { - if (isLoaded()) { - return _isEnergyReceiver(tile, side); - } else { - return false; - } + return isLoaded() && _isEnergyReceiver(tile, side); } public static int sendEnergy(TileEntity tile, EnumFacing side, int amount, boolean simulate) { diff --git a/src/main/java/forestry/energy/compat/tesla/package-info.java b/src/main/java/forestry/energy/compat/tesla/package-info.java new file mode 100644 index 000000000..87e7d7944 --- /dev/null +++ b/src/main/java/forestry/energy/compat/tesla/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.compat.tesla; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java b/src/main/java/forestry/energy/gui/BiogasSlot.java similarity index 83% rename from src/main/java/forestry/energy/gui/widgets/BiogasSlot.java rename to src/main/java/forestry/energy/gui/BiogasSlot.java index bf44715ff..54692ada3 100644 --- a/src/main/java/forestry/energy/gui/widgets/BiogasSlot.java +++ b/src/main/java/forestry/energy/gui/BiogasSlot.java @@ -1,44 +1,45 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui.widgets; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidTank; - -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.ReservoirWidget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.utils.Translator; - -public class BiogasSlot extends ReservoirWidget { - public BiogasSlot(WidgetManager manager, int xPos, int yPos, int slot) { - super(manager, xPos, yPos, slot); - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - IFluidTank tank = getTank(); - ToolTip toolTip = new ToolTip(); - FluidStack fluid = tank.getFluid(); - if (fluid == null) { - toolTip.add(Translator.translateToLocal("for.gui.empty")); - } else { - toolTip.add(fluid.getLocalizedName()); - } - - return toolTip; - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - // do not allow pipette - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.energy.gui; + +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidTank; + +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.ReservoirWidget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.utils.Translator; + +public class BiogasSlot extends ReservoirWidget { + public BiogasSlot(WidgetManager manager, int xPos, int yPos, int slot) { + super(manager, xPos, yPos, slot); + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + ToolTip toolTip = new ToolTip(); + IFluidTank tank = getTank(); + if (tank != null) { + FluidStack fluid = tank.getFluid(); + if (fluid == null) { + toolTip.add(Translator.translateToLocal("for.gui.empty")); + } else { + toolTip.add(fluid.getLocalizedName()); + } + } + return toolTip; + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + // do not allow pipette + } +} diff --git a/src/main/java/forestry/energy/gui/ContainerEngineElectric.java b/src/main/java/forestry/energy/gui/ContainerEngineElectric.java index c3456ac2a..76ce67659 100644 --- a/src/main/java/forestry/energy/gui/ContainerEngineElectric.java +++ b/src/main/java/forestry/energy/gui/ContainerEngineElectric.java @@ -1,36 +1,36 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui; - -import net.minecraft.entity.player.InventoryPlayer; - -import forestry.core.gui.ContainerSocketed; -import forestry.core.gui.slots.SlotFiltered; -import forestry.core.network.packets.PacketGuiUpdate; -import forestry.energy.inventory.InventoryEngineElectric; -import forestry.energy.tiles.TileEngineElectric; - -public class ContainerEngineElectric extends ContainerSocketed { - - public ContainerEngineElectric(InventoryPlayer player, TileEngineElectric tile) { - super(tile, player, 8, 84); - - this.addSlotToContainer(new SlotFiltered(tile, InventoryEngineElectric.SLOT_BATTERY, 84, 53)); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - PacketGuiUpdate packet = new PacketGuiUpdate(tile); - sendPacketToListeners(packet); - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.gui; +// +//import net.minecraft.entity.player.InventoryPlayer; +// +//import forestry.core.gui.ContainerSocketed; +//import forestry.core.gui.slots.SlotFiltered; +//import forestry.core.network.packets.PacketGuiUpdate; +//import forestry.energy.inventory.InventoryEngineElectric; +//import forestry.energy.tiles.TileEngineElectric; +// +//public class ContainerEngineElectric extends ContainerSocketed { +// +// public ContainerEngineElectric(InventoryPlayer player, TileEngineElectric tile) { +// super(tile, player, 8, 84); +// +// this.addSlotToContainer(new SlotFiltered(tile, InventoryEngineElectric.SLOT_BATTERY, 84, 53)); +// } +// +// @Override +// public void detectAndSendChanges() { +// super.detectAndSendChanges(); +// PacketGuiUpdate packet = new PacketGuiUpdate(tile); +// sendPacketToListeners(packet); +// } +// +//} diff --git a/src/main/java/forestry/energy/gui/ContainerGenerator.java b/src/main/java/forestry/energy/gui/ContainerGenerator.java index db6b54e03..8a39b73be 100755 --- a/src/main/java/forestry/energy/gui/ContainerGenerator.java +++ b/src/main/java/forestry/energy/gui/ContainerGenerator.java @@ -1,34 +1,34 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui; - -import net.minecraft.entity.player.InventoryPlayer; -import forestry.core.gui.ContainerLiquidTanks; -import forestry.core.gui.slots.SlotLiquidIn; -import forestry.core.network.packets.PacketGuiUpdate; -import forestry.energy.inventory.InventoryGenerator; -import forestry.energy.tiles.TileEuGenerator; - -public class ContainerGenerator extends ContainerLiquidTanks { - - public ContainerGenerator(InventoryPlayer player, TileEuGenerator tile) { - super(tile, player, 8, 84); - - this.addSlotToContainer(new SlotLiquidIn(tile, InventoryGenerator.SLOT_CAN, 22, 38)); - } - - @Override - public void detectAndSendChanges() { - super.detectAndSendChanges(); - PacketGuiUpdate packet = new PacketGuiUpdate(tile); - sendPacketToListeners(packet); - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.gui; +// +//import net.minecraft.entity.player.InventoryPlayer; +//import forestry.core.gui.ContainerLiquidTanks; +//import forestry.core.gui.slots.SlotLiquidIn; +//import forestry.core.network.packets.PacketGuiUpdate; +//import forestry.energy.inventory.InventoryGenerator; +//import forestry.energy.tiles.TileEuGenerator; +// +//public class ContainerGenerator extends ContainerLiquidTanks { +// +// public ContainerGenerator(InventoryPlayer player, TileEuGenerator tile) { +// super(tile, player, 8, 84); +// +// this.addSlotToContainer(new SlotLiquidIn(tile, InventoryGenerator.SLOT_CAN, 22, 38)); +// } +// +// @Override +// public void detectAndSendChanges() { +// super.detectAndSendChanges(); +// PacketGuiUpdate packet = new PacketGuiUpdate(tile); +// sendPacketToListeners(packet); +// } +//} diff --git a/src/main/java/forestry/energy/gui/GuiEngineBiogas.java b/src/main/java/forestry/energy/gui/GuiEngineBiogas.java index fe7c795f7..524f78436 100644 --- a/src/main/java/forestry/energy/gui/GuiEngineBiogas.java +++ b/src/main/java/forestry/energy/gui/GuiEngineBiogas.java @@ -14,7 +14,6 @@ import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Constants; import forestry.core.gui.widgets.TankWidget; -import forestry.energy.gui.widgets.BiogasSlot; import forestry.energy.tiles.TileEngineBiogas; public class GuiEngineBiogas extends GuiEngine { diff --git a/src/main/java/forestry/energy/gui/GuiEngineElectric.java b/src/main/java/forestry/energy/gui/GuiEngineElectric.java index 9e5cdaef8..da7661be9 100644 --- a/src/main/java/forestry/energy/gui/GuiEngineElectric.java +++ b/src/main/java/forestry/energy/gui/GuiEngineElectric.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui; - -import net.minecraft.entity.player.InventoryPlayer; - -import forestry.core.config.Constants; -import forestry.core.gui.widgets.SocketWidget; -import forestry.core.render.EnumTankLevel; -import forestry.energy.tiles.TileEngineElectric; - -public class GuiEngineElectric extends GuiEngine { - - public GuiEngineElectric(InventoryPlayer inventory, TileEngineElectric tile) { - super(Constants.TEXTURE_PATH_GUI + "/electricalengine.png", new ContainerEngineElectric(inventory, tile), tile); - widgetManager.add(new SocketWidget(this.widgetManager, 30, 40, tile, 0)); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - - TileEngineElectric engine = inventory; - int storageHeight = engine.getStorageScaled(46); - int storageMaxHeight = engine.getStorageScaled(100); - EnumTankLevel rated = EnumTankLevel.rateTankLevel(storageMaxHeight); - - drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); - } - - private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { - int i = 176 + rated.getLevelScaled(16); - int k = 0; - - this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.gui; +// +//import net.minecraft.entity.player.InventoryPlayer; +// +//import forestry.core.config.Constants; +//import forestry.core.gui.widgets.SocketWidget; +//import forestry.core.render.EnumTankLevel; +//import forestry.energy.tiles.TileEngineElectric; +// +//public class GuiEngineElectric extends GuiEngine { +// +// public GuiEngineElectric(InventoryPlayer inventory, TileEngineElectric tile) { +// super(Constants.TEXTURE_PATH_GUI + "/electricalengine.png", new ContainerEngineElectric(inventory, tile), tile); +// widgetManager.add(new SocketWidget(this.widgetManager, 30, 40, tile, 0)); +// } +// +// @Override +// protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { +// super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); +// +// TileEngineElectric engine = inventory; +// int storageHeight = engine.getStorageScaled(46); +// int storageMaxHeight = engine.getStorageScaled(100); +// EnumTankLevel rated = EnumTankLevel.rateTankLevel(storageMaxHeight); +// +// drawHealthMeter(guiLeft + 74, guiTop + 25, storageHeight, rated); +// } +// +// private void drawHealthMeter(int x, int y, int height, EnumTankLevel rated) { +// int i = 176 + rated.getLevelScaled(16); +// int k = 0; +// +// this.drawTexturedModalRect(x, y + 46 - height, i, k + 46 - height, 4, height); +// } +// +//} diff --git a/src/main/java/forestry/energy/gui/GuiGenerator.java b/src/main/java/forestry/energy/gui/GuiGenerator.java index fba17b2b1..486dfdf68 100755 --- a/src/main/java/forestry/energy/gui/GuiGenerator.java +++ b/src/main/java/forestry/energy/gui/GuiGenerator.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.gui; - -import net.minecraft.entity.player.InventoryPlayer; - -import forestry.core.config.Constants; -import forestry.core.gui.GuiForestryTitled; -import forestry.core.gui.widgets.TankWidget; -import forestry.energy.tiles.TileEuGenerator; - -public class GuiGenerator extends GuiForestryTitled { - - public GuiGenerator(InventoryPlayer inventory, TileEuGenerator tile) { - super(Constants.TEXTURE_PATH_GUI + "/generator.png", new ContainerGenerator(inventory, tile), tile); - widgetManager.add(new TankWidget(this.widgetManager, 49, 17, 0)); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); - - int progress = inventory.getStoredScaled(49); - if (progress > 0) { - drawTexturedModalRect(guiLeft + 108, guiTop + 38, 176, 91, progress, 18); - } - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.gui; +// +//import net.minecraft.entity.player.InventoryPlayer; +// +//import forestry.core.config.Constants; +//import forestry.core.gui.GuiForestryTitled; +//import forestry.core.gui.widgets.TankWidget; +//import forestry.energy.tiles.TileEuGenerator; +// +//public class GuiGenerator extends GuiForestryTitled { +// +// public GuiGenerator(InventoryPlayer inventory, TileEuGenerator tile) { +// super(Constants.TEXTURE_PATH_GUI + "/generator.png", new ContainerGenerator(inventory, tile), tile); +// widgetManager.add(new TankWidget(this.widgetManager, 49, 17, 0)); +// } +// +// @Override +// protected void drawGuiContainerBackgroundLayer(float var1, int mouseX, int mouseY) { +// super.drawGuiContainerBackgroundLayer(var1, mouseX, mouseY); +// +// int progress = inventory.getStoredScaled(49); +// if (progress > 0) { +// drawTexturedModalRect(guiLeft + 108, guiTop + 38, 176, 91, progress, 18); +// } +// } +// +//} diff --git a/src/main/java/forestry/energy/gui/package-info.java b/src/main/java/forestry/energy/gui/package-info.java new file mode 100644 index 000000000..e0bc9a6ea --- /dev/null +++ b/src/main/java/forestry/energy/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java index 7d10fb068..c71285815 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java +++ b/src/main/java/forestry/energy/inventory/InventoryEngineBiogas.java @@ -10,14 +10,13 @@ ******************************************************************************/ package forestry.energy.inventory; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.energy.tiles.TileEngineBiogas; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.energy.tiles.TileEngineBiogas; - public class InventoryEngineBiogas extends InventoryAdapterTile { public static final short SLOT_CAN = 0; @@ -29,12 +28,14 @@ public class InventoryEngineBiogas extends InventoryAdapterTile { - public static final short SLOT_BATTERY = 0; - - public InventoryEngineElectric(TileEngineElectric engineTin) { - super(engineTin, 1, "electrical"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_BATTERY) { - return ElectricItem.manager.getCharge(itemStack) > 0; - } - return false; - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.inventory; +// +//import net.minecraft.item.ItemStack; +// +//import forestry.core.inventory.InventoryAdapterTile; +//import forestry.energy.tiles.TileEngineElectric; +// +//import ic2.api.item.ElectricItem; +// +//public class InventoryEngineElectric extends InventoryAdapterTile { +// public static final short SLOT_BATTERY = 0; +// +// public InventoryEngineElectric(TileEngineElectric engineTin) { +// super(engineTin, 1, "electrical"); +// } +// +// @Override +// public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { +// if (slotIndex == SLOT_BATTERY) { +// return ElectricItem.manager.getCharge(itemStack) > 0; +// } +// return false; +// } +//} diff --git a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java index 7b6d3bb11..8d31f6e3b 100644 --- a/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java +++ b/src/main/java/forestry/energy/inventory/InventoryEnginePeat.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.energy.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.api.fuels.FuelManager; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.energy.tiles.TileEnginePeat; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryEnginePeat extends InventoryAdapterTile { public static final short SLOT_FUEL = 0; diff --git a/src/main/java/forestry/energy/inventory/InventoryGenerator.java b/src/main/java/forestry/energy/inventory/InventoryGenerator.java index 6b40cfe77..ebdfec465 100644 --- a/src/main/java/forestry/energy/inventory/InventoryGenerator.java +++ b/src/main/java/forestry/energy/inventory/InventoryGenerator.java @@ -1,37 +1,37 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.inventory; - -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - -import forestry.core.inventory.InventoryAdapterTile; -import forestry.energy.tiles.TileEuGenerator; - -public class InventoryGenerator extends InventoryAdapterTile { - public static final short SLOT_CAN = 0; - - public InventoryGenerator(TileEuGenerator generator) { - super(generator, 1, "Items"); - } - - @Override - public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { - if (slotIndex == SLOT_CAN) { - FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); - } - - return false; - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.inventory; +// +//import net.minecraft.item.ItemStack; +// +//import net.minecraftforge.fluids.FluidStack; +//import net.minecraftforge.fluids.FluidUtil; +// +//import forestry.core.inventory.InventoryAdapterTile; +//import forestry.energy.tiles.TileEuGenerator; +// +//public class InventoryGenerator extends InventoryAdapterTile { +// public static final short SLOT_CAN = 0; +// +// public InventoryGenerator(TileEuGenerator generator) { +// super(generator, 1, "Items"); +// } +// +// @Override +// public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { +// if (slotIndex == SLOT_CAN) { +// FluidStack fluid = FluidUtil.getFluidContained(itemStack); +// return tile.getTankManager().canFillFluidType(fluid); +// } +// +// return false; +// } +//} diff --git a/src/main/java/forestry/energy/inventory/package-info.java b/src/main/java/forestry/energy/inventory/package-info.java new file mode 100644 index 000000000..0e38b4f43 --- /dev/null +++ b/src/main/java/forestry/energy/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/package-info.java b/src/main/java/forestry/energy/package-info.java new file mode 100644 index 000000000..5daae0275 --- /dev/null +++ b/src/main/java/forestry/energy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/proxy/ProxyEnergy.java b/src/main/java/forestry/energy/proxy/ProxyEnergy.java index 8512a296d..c14c59eb8 100755 --- a/src/main/java/forestry/energy/proxy/ProxyEnergy.java +++ b/src/main/java/forestry/energy/proxy/ProxyEnergy.java @@ -10,11 +10,14 @@ ******************************************************************************/ package forestry.energy.proxy; +import javax.annotation.Nullable; + import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import forestry.core.tiles.TileEngine; public class ProxyEnergy { + @Nullable public TileEntitySpecialRenderer getRenderDefaultEngine(String gfxBase) { return null; } diff --git a/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java b/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java index be1950c4f..3261c0db6 100644 --- a/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java +++ b/src/main/java/forestry/energy/proxy/ProxyEnergyClient.java @@ -15,6 +15,7 @@ import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import forestry.core.tiles.TileEngine; import forestry.energy.render.RenderEngine; +@SuppressWarnings("unused") public class ProxyEnergyClient extends ProxyEnergy { @Override diff --git a/src/main/java/forestry/energy/proxy/package-info.java b/src/main/java/forestry/energy/proxy/package-info.java new file mode 100644 index 000000000..97c043ba7 --- /dev/null +++ b/src/main/java/forestry/energy/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/render/RenderEngine.java b/src/main/java/forestry/energy/render/RenderEngine.java index 6e4ac42b2..9d66dd0a7 100755 --- a/src/main/java/forestry/energy/render/RenderEngine.java +++ b/src/main/java/forestry/energy/render/RenderEngine.java @@ -26,6 +26,7 @@ import forestry.core.proxy.Proxies; import forestry.core.render.ForestryResource; import forestry.core.tiles.TemperatureState; import forestry.core.tiles.TileEngine; +import net.minecraft.world.World; public class RenderEngine extends TileEntitySpecialRenderer { private final ModelRenderer boiler; @@ -50,7 +51,7 @@ public class RenderEngine extends TileEntitySpecialRenderer { angleMap[EnumFacing.NORTH.ordinal()] = (float) -Math.PI / 2; } - public RenderEngine() { + public RenderEngine(String baseTexture) { ModelBase model = new EngineModelBase(); boiler = new ModelRenderer(model, 0, 0); boiler.addBox(-8F, -8F, -8F, 16, 6, 16); @@ -75,10 +76,6 @@ public class RenderEngine extends TileEntitySpecialRenderer { extension.rotationPointX = 8F; extension.rotationPointY = 8F; extension.rotationPointZ = 8F; - } - - public RenderEngine(String baseTexture) { - this(); textures = new ResourceLocation[]{ new ForestryResource(baseTexture + "base.png"), @@ -94,11 +91,14 @@ public class RenderEngine extends TileEntitySpecialRenderer { @Override public void renderTileEntityAt(@Nullable TileEngine engine, double x, double y, double z, float partialTicks, int destroyStage) { if (engine != null) { - IBlockState blockState = engine.getWorldObj().getBlockState(engine.getPos()); - if (blockState != null && blockState.getBlock() instanceof BlockBase) { - EnumFacing facing = blockState.getValue(BlockBase.FACING); - render(engine.getTemperatureState(), engine.progress, facing, x, y, z); - return; + World worldObj = engine.getWorldObj(); + if (worldObj.isBlockLoaded(engine.getPos())) { + IBlockState blockState = worldObj.getBlockState(engine.getPos()); + if (blockState.getBlock() instanceof BlockBase) { + EnumFacing facing = blockState.getValue(BlockBase.FACING); + render(engine.getTemperatureState(), engine.progress, facing, x, y, z); + return; + } } } render(TemperatureState.COOL, 0.25F, EnumFacing.UP, x, y, z); diff --git a/src/main/java/forestry/energy/render/package-info.java b/src/main/java/forestry/energy/render/package-info.java new file mode 100644 index 000000000..68678eaa1 --- /dev/null +++ b/src/main/java/forestry/energy/render/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.render; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/energy/tiles/TileEngineBiogas.java b/src/main/java/forestry/energy/tiles/TileEngineBiogas.java index 0087cb7c6..35644b87e 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineBiogas.java +++ b/src/main/java/forestry/energy/tiles/TileEngineBiogas.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.energy.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -19,12 +18,11 @@ import forestry.api.fuels.EngineBronzeFuel; import forestry.api.fuels.FuelManager; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.fluids.tanks.StandardTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TileEngine; import forestry.energy.gui.ContainerEngineBiogas; @@ -60,12 +58,12 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi this.tankManager = new TankManager(this, fuelTank, heatingTank, burnTank); } - @Nonnull @Override public TankManager getTankManager() { return tankManager; } + @Nullable public Fluid getBurnTankFluidType() { return burnTank.getFluidType(); } @@ -107,7 +105,7 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi } else if (shutdown) { - if (heatingTank.getFluidAmount() > 0 && heatingTank.getFluid().getFluid() == FluidRegistry.LAVA) { + if (heatingTank.getFluidAmount() > 0 && heatingTank.getFluidType() == FluidRegistry.LAVA) { addHeat(Constants.ENGINE_HEAT_VALUE_LAVA); heatingTank.drainInternal(1, true); } @@ -190,7 +188,7 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi /** * Returns the fuel value (power per cycle) an item of the passed fluid */ - private static int determineFuelValue(Fluid fluid) { + private static int determineFuelValue(@Nullable Fluid fluid) { if (FuelManager.bronzeEngineFuel.containsKey(fluid)) { return FuelManager.bronzeEngineFuel.get(fluid).getPowerPerCycle(); } else { @@ -238,7 +236,6 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi tankManager.readFromNBT(nbt); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbt) { nbt = super.writeToNBT(nbt); @@ -249,7 +246,7 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi /* NETWORK */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); data.writeBoolean(shutdown); tankManager.writeData(data); @@ -257,7 +254,7 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); shutdown = data.readBoolean(); tankManager.readData(data); @@ -265,13 +262,13 @@ public class TileEngineBiogas extends TileEngine implements ISidedInventory, ILi } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/energy/tiles/TileEngineClockwork.java b/src/main/java/forestry/energy/tiles/TileEngineClockwork.java index 9279bc0cd..fa25c352f 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineClockwork.java +++ b/src/main/java/forestry/energy/tiles/TileEngineClockwork.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.energy.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -77,7 +77,7 @@ public class TileEngineClockwork extends TileEngine { tension = nbttagcompound.getFloat("Wound"); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -155,11 +155,13 @@ public class TileEngineClockwork extends TileEngine { } @Override + @Nullable public Object getGui(EntityPlayer player, int data) { return null; } @Override + @Nullable public Object getContainer(EntityPlayer player, int data) { return null; } diff --git a/src/main/java/forestry/energy/tiles/TileEngineElectric.java b/src/main/java/forestry/energy/tiles/TileEngineElectric.java index b7c2a4051..552d85294 100644 --- a/src/main/java/forestry/energy/tiles/TileEngineElectric.java +++ b/src/main/java/forestry/energy/tiles/TileEngineElectric.java @@ -1,311 +1,311 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.tiles; - -import javax.annotation.Nonnull; -import java.io.IOException; - -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.CircuitSocketType; -import forestry.api.circuits.ICircuitBoard; -import forestry.api.circuits.ICircuitSocketType; -import forestry.api.core.IErrorLogic; -import forestry.core.circuits.ISocketable; -import forestry.core.config.Constants; -import forestry.core.errors.EnumErrorCode; -import forestry.core.inventory.InventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamableGui; -import forestry.core.tiles.TemperatureState; -import forestry.core.tiles.TileEngine; -import forestry.energy.gui.ContainerEngineElectric; -import forestry.energy.gui.GuiEngineElectric; -import forestry.energy.inventory.InventoryEngineElectric; -import forestry.plugins.compat.PluginIC2; -import ic2.api.energy.prefab.BasicSink; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -public class TileEngineElectric extends TileEngine implements ISocketable, IInventory, IStreamableGui { - protected static class EuConfig { - - public int euForCycle; - public int rfPerCycle; - public int euStorage; - - public EuConfig() { - this.euForCycle = Constants.ENGINE_TIN_EU_FOR_CYCLE; - this.rfPerCycle = Constants.ENGINE_TIN_ENERGY_PER_CYCLE; - this.euStorage = Constants.ENGINE_TIN_MAX_EU_STORED; - } - } - - private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); - private final EuConfig euConfig = new EuConfig(); - - private BasicSink ic2EnergySink; - - public TileEngineElectric() { - super("engine.tin", Constants.ENGINE_ELECTRIC_HEAT_MAX, 100000); - - setInternalInventory(new InventoryEngineElectric(this)); - - if (PluginIC2.instance.isAvailable()) { - ic2EnergySink = new BasicSink(this, euConfig.euStorage, 3); - } - } - - // / SAVING / LOADING - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - - if (ic2EnergySink != null) { - ic2EnergySink.readFromNBT(nbttagcompound); - } - sockets.readFromNBT(nbttagcompound); - - ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(chip); - if (chipset != null) { - chipset.onLoad(this); - } - } - } - - @Nonnull - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound = super.writeToNBT(nbttagcompound); - - if (ic2EnergySink != null) { - ic2EnergySink.writeToNBT(nbttagcompound); - } - sockets.writeToNBT(nbttagcompound); - return nbttagcompound; - } - - @Override - public void onChunkUnload() { - if (ic2EnergySink != null) { - ic2EnergySink.onChunkUnload(); - } - - super.onChunkUnload(); - } - - @Override - public void invalidate() { - if (ic2EnergySink != null) { - ic2EnergySink.invalidate(); - } - - super.invalidate(); - } - - // / HEAT MANAGEMENT - @Override - public int dissipateHeat() { - if (heat <= 0) { - return 0; - } - - int loss = 0; - - if (!isBurning() || !isRedstoneActivated()) { - loss += 1; - } - - TemperatureState tempState = getTemperatureState(); - if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { - loss += 1; - } - - heat -= loss; - return loss; - } - - @Override - public int generateHeat() { - - int gain = 0; - if (isRedstoneActivated() && isBurning()) { - gain++; - if (((double) energyManager.getEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { - gain++; - } - } - - addHeat(gain); - return gain; - } - - // / WORK - @Override - public void updateServerSide() { - IErrorLogic errorLogic = getErrorLogic(); - - // No work to be done if IC2 is unavailable. - if (errorLogic.setCondition(ic2EnergySink == null, EnumErrorCode.NO_ENERGY_NET)) { - return; - } - - ic2EnergySink.update(); - - super.updateServerSide(); - - if (forceCooldown) { - return; - } - - if (getStackInSlot(InventoryEngineElectric.SLOT_BATTERY) != null) { - replenishFromBattery(InventoryEngineElectric.SLOT_BATTERY); - } - - // Updating of gui delayed to prevent it from going crazy - if (!updateOnInterval(80)) { - return; - } - - boolean canUseEnergy = ic2EnergySink.canUseEnergy(euConfig.euForCycle); - errorLogic.setCondition(!canUseEnergy, EnumErrorCode.NO_FUEL); - } - - @Override - public void burn() { - - currentOutput = 0; - - if (!isRedstoneActivated()) { - return; - } - - if (ic2EnergySink.useEnergy(euConfig.euForCycle)) { - currentOutput = euConfig.rfPerCycle; - energyManager.generateEnergy(euConfig.rfPerCycle); - } - - } - - private void replenishFromBattery(int slot) { - if (!isRedstoneActivated()) { - return; - } - - ic2EnergySink.discharge(getStackInSlot(slot), euConfig.euForCycle * 3); - } - - // / STATE INFORMATION - @Override - protected boolean isBurning() { - return mayBurn() && ic2EnergySink != null && ic2EnergySink.canUseEnergy(euConfig.euForCycle); - } - - public int getStorageScaled(int i) { - if (ic2EnergySink == null) { - return 0; - } - - return Math.min(i, (int) (ic2EnergySink.getEnergyStored() * i) / ic2EnergySink.getCapacity()); - } - - // / SMP GUI - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - super.writeGuiData(data); - sockets.writeData(data); - final boolean hasIc2EnergySink = (ic2EnergySink != null); - data.writeBoolean(hasIc2EnergySink); - if (hasIc2EnergySink) { - data.writeVarInt((int) ic2EnergySink.getEnergyStored()); - } - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - super.readGuiData(data); - sockets.readData(data); - final boolean hasIc2EnergySink = data.readBoolean(); - if (hasIc2EnergySink) { - final int energyStored = data.readVarInt(); - ic2EnergySink.setEnergyStored(energyStored); - } - } - - // / ENERGY CONFIG CHANGE - public void changeEnergyConfig(int euChange, int rfChange, int storageChange) { - euConfig.euForCycle += euChange; - euConfig.rfPerCycle += rfChange; - euConfig.euStorage += storageChange; - - if (ic2EnergySink != null) { - ic2EnergySink.setCapacity(euConfig.euStorage); - } - } - - /* ISocketable */ - @Override - public int getSocketCount() { - return sockets.getSizeInventory(); - } - - @Override - public ItemStack getSocket(int slot) { - return sockets.getStackInSlot(slot); - } - - @Override - public void setSocket(int slot, ItemStack stack) { - - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } - - // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); - } - } - } - - sockets.setInventorySlotContents(slot, stack); - if (stack == null) { - return; - } - - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); - if (chipset != null) { - chipset.onInsertion(this); - } - } - - @Override - public ICircuitSocketType getSocketType() { - return CircuitSocketType.ELECTRIC_ENGINE; - } - - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiEngineElectric(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerEngineElectric(player.inventory, this); - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.tiles; +// +//import javax.annotation.Nonnull; +//import java.io.IOException; +// +//import forestry.api.circuits.ChipsetManager; +//import forestry.api.circuits.CircuitSocketType; +//import forestry.api.circuits.ICircuitBoard; +//import forestry.api.circuits.ICircuitSocketType; +//import forestry.api.core.IErrorLogic; +//import forestry.core.circuits.ISocketable; +//import forestry.core.config.Constants; +//import forestry.core.errors.EnumErrorCode; +//import forestry.core.inventory.InventoryAdapter; +//import forestry.core.network.DataInputStreamForestry; +//import forestry.core.network.DataOutputStreamForestry; +//import forestry.core.network.IStreamableGui; +//import forestry.core.tiles.TemperatureState; +//import forestry.core.tiles.TileEngine; +//import forestry.energy.gui.ContainerEngineElectric; +//import forestry.energy.gui.GuiEngineElectric; +//import forestry.energy.inventory.InventoryEngineElectric; +//import forestry.plugins.compat.PluginIC2; +//import ic2.api.energy.prefab.BasicSink; +//import net.minecraft.entity.player.EntityPlayer; +//import net.minecraft.inventory.IInventory; +//import net.minecraft.item.ItemStack; +//import net.minecraft.nbt.NBTTagCompound; +// +//public class TileEngineElectric extends TileEngine implements ISocketable, IInventory, IStreamableGui { +// protected static class EuConfig { +// +// public int euForCycle; +// public int rfPerCycle; +// public int euStorage; +// +// public EuConfig() { +// this.euForCycle = Constants.ENGINE_TIN_EU_FOR_CYCLE; +// this.rfPerCycle = Constants.ENGINE_TIN_ENERGY_PER_CYCLE; +// this.euStorage = Constants.ENGINE_TIN_MAX_EU_STORED; +// } +// } +// +// private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); +// private final EuConfig euConfig = new EuConfig(); +// +// private BasicSink ic2EnergySink; +// +// public TileEngineElectric() { +// super("engine.tin", Constants.ENGINE_ELECTRIC_HEAT_MAX, 100000); +// +// setInternalInventory(new InventoryEngineElectric(this)); +// +// if (PluginIC2.instance.isAvailable()) { +// ic2EnergySink = new BasicSink(this, euConfig.euStorage, 3); +// } +// } +// +// // / SAVING / LOADING +// @Override +// public void readFromNBT(NBTTagCompound nbttagcompound) { +// super.readFromNBT(nbttagcompound); +// +// if (ic2EnergySink != null) { +// ic2EnergySink.readFromNBT(nbttagcompound); +// } +// sockets.readFromNBT(nbttagcompound); +// +// ItemStack chip = sockets.getStackInSlot(0); +// if (chip != null) { +// ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(chip); +// if (chipset != null) { +// chipset.onLoad(this); +// } +// } +// } +// +// @Nonnull +// @Override +// public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { +// nbttagcompound = super.writeToNBT(nbttagcompound); +// +// if (ic2EnergySink != null) { +// ic2EnergySink.writeToNBT(nbttagcompound); +// } +// sockets.writeToNBT(nbttagcompound); +// return nbttagcompound; +// } +// +// @Override +// public void onChunkUnload() { +// if (ic2EnergySink != null) { +// ic2EnergySink.onChunkUnload(); +// } +// +// super.onChunkUnload(); +// } +// +// @Override +// public void invalidate() { +// if (ic2EnergySink != null) { +// ic2EnergySink.invalidate(); +// } +// +// super.invalidate(); +// } +// +// // / HEAT MANAGEMENT +// @Override +// public int dissipateHeat() { +// if (heat <= 0) { +// return 0; +// } +// +// int loss = 0; +// +// if (!isBurning() || !isRedstoneActivated()) { +// loss += 1; +// } +// +// TemperatureState tempState = getTemperatureState(); +// if (tempState == TemperatureState.OVERHEATING || tempState == TemperatureState.OPERATING_TEMPERATURE) { +// loss += 1; +// } +// +// heat -= loss; +// return loss; +// } +// +// @Override +// public int generateHeat() { +// +// int gain = 0; +// if (isRedstoneActivated() && isBurning()) { +// gain++; +// if (((double) energyManager.getEnergyStored() / (double) energyManager.getMaxEnergyStored()) > 0.5) { +// gain++; +// } +// } +// +// addHeat(gain); +// return gain; +// } +// +// // / WORK +// @Override +// public void updateServerSide() { +// IErrorLogic errorLogic = getErrorLogic(); +// +// // No work to be done if IC2 is unavailable. +// if (errorLogic.setCondition(ic2EnergySink == null, EnumErrorCode.NO_ENERGY_NET)) { +// return; +// } +// +// ic2EnergySink.update(); +// +// super.updateServerSide(); +// +// if (forceCooldown) { +// return; +// } +// +// if (getStackInSlot(InventoryEngineElectric.SLOT_BATTERY) != null) { +// replenishFromBattery(InventoryEngineElectric.SLOT_BATTERY); +// } +// +// // Updating of gui delayed to prevent it from going crazy +// if (!updateOnInterval(80)) { +// return; +// } +// +// boolean canUseEnergy = ic2EnergySink.canUseEnergy(euConfig.euForCycle); +// errorLogic.setCondition(!canUseEnergy, EnumErrorCode.NO_FUEL); +// } +// +// @Override +// public void burn() { +// +// currentOutput = 0; +// +// if (!isRedstoneActivated()) { +// return; +// } +// +// if (ic2EnergySink.useEnergy(euConfig.euForCycle)) { +// currentOutput = euConfig.rfPerCycle; +// energyManager.generateEnergy(euConfig.rfPerCycle); +// } +// +// } +// +// private void replenishFromBattery(int slot) { +// if (!isRedstoneActivated()) { +// return; +// } +// +// ic2EnergySink.discharge(getStackInSlot(slot), euConfig.euForCycle * 3); +// } +// +// // / STATE INFORMATION +// @Override +// protected boolean isBurning() { +// return mayBurn() && ic2EnergySink != null && ic2EnergySink.canUseEnergy(euConfig.euForCycle); +// } +// +// public int getStorageScaled(int i) { +// if (ic2EnergySink == null) { +// return 0; +// } +// +// return Math.min(i, (int) (ic2EnergySink.getEnergyStored() * i) / ic2EnergySink.getCapacity()); +// } +// +// // / SMP GUI +// @Override +// public void writeGuiData(PacketBufferForestry data) { +// super.writeGuiData(data); +// sockets.writeData(data); +// final boolean hasIc2EnergySink = (ic2EnergySink != null); +// data.writeBoolean(hasIc2EnergySink); +// if (hasIc2EnergySink) { +// data.writeVarInt((int) ic2EnergySink.getEnergyStored()); +// } +// } +// +// @Override +// public void readGuiData(PacketBufferForestry data) throws IOException { +// super.readGuiData(data); +// sockets.readData(data); +// final boolean hasIc2EnergySink = data.readBoolean(); +// if (hasIc2EnergySink) { +// final int energyStored = data.readVarInt(); +// ic2EnergySink.setEnergyStored(energyStored); +// } +// } +// +// // / ENERGY CONFIG CHANGE +// public void changeEnergyConfig(int euChange, int rfChange, int storageChange) { +// euConfig.euForCycle += euChange; +// euConfig.rfPerCycle += rfChange; +// euConfig.euStorage += storageChange; +// +// if (ic2EnergySink != null) { +// ic2EnergySink.setCapacity(euConfig.euStorage); +// } +// } +// +// /* ISocketable */ +// @Override +// public int getSocketCount() { +// return sockets.getSizeInventory(); +// } +// +// @Override +// public ItemStack getSocket(int slot) { +// return sockets.getStackInSlot(slot); +// } +// +// @Override +// public void setSocket(int slot, ItemStack stack) { +// +// if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { +// return; +// } +// +// // Dispose correctly of old chipsets +// if (sockets.getStackInSlot(slot) != null) { +// if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { +// ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); +// if (chipset != null) { +// chipset.onRemoval(this); +// } +// } +// } +// +// sockets.setInventorySlotContents(slot, stack); +// if (stack == null) { +// return; +// } +// +// ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); +// if (chipset != null) { +// chipset.onInsertion(this); +// } +// } +// +// @Override +// public ICircuitSocketType getSocketType() { +// return CircuitSocketType.ELECTRIC_ENGINE; +// } +// +// @Override +// public Object getGui(EntityPlayer player, int data) { +// return new GuiEngineElectric(player.inventory, this); +// } +// +// @Override +// public Object getContainer(EntityPlayer player, int data) { +// return new ContainerEngineElectric(player.inventory, this); +// } +//} diff --git a/src/main/java/forestry/energy/tiles/TileEnginePeat.java b/src/main/java/forestry/energy/tiles/TileEnginePeat.java index 9908e66de..66ef16e5c 100644 --- a/src/main/java/forestry/energy/tiles/TileEnginePeat.java +++ b/src/main/java/forestry/energy/tiles/TileEnginePeat.java @@ -12,8 +12,6 @@ package forestry.energy.tiles; import java.io.IOException; -import javax.annotation.Nonnull; - import forestry.api.fuels.FuelManager; import forestry.core.PluginCore; import forestry.core.config.Constants; @@ -21,27 +19,23 @@ import forestry.core.errors.EnumErrorCode; import forestry.core.inventory.AdjacentInventoryCache; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.TemperatureState; import forestry.core.tiles.TileEngine; import forestry.core.utils.InventoryUtil; -import forestry.core.utils.ItemStackUtil; import forestry.energy.gui.ContainerEnginePeat; import forestry.energy.gui.GuiEnginePeat; import forestry.energy.inventory.InventoryEnginePeat; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.wrapper.InvWrapper; public class TileEnginePeat extends TileEngine implements ISidedInventory { - private Item fuelItem; - private int fuelItemMeta; + private ItemStack fuel = ItemStack.EMPTY; private int burnTime; private int totalBurnTime; private int ashProduction; @@ -57,7 +51,7 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { private int getFuelSlot() { IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL) == null) { + if (inventory.getStackInSlot(InventoryEnginePeat.SLOT_FUEL).isEmpty()) { return -1; } @@ -72,7 +66,7 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { IInventoryAdapter inventory = getInternalInventory(); for (int i = InventoryEnginePeat.SLOT_WASTE_1; i <= InventoryEnginePeat.SLOT_WASTE_COUNT; i++) { ItemStack waste = inventory.getStackInSlot(i); - if (waste == null) { + if (waste.isEmpty()) { return i; } @@ -80,7 +74,7 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { continue; } - if (waste.stackSize < 64) { + if (waste.getCount() < waste.getMaxStackSize()) { return i; } } @@ -113,7 +107,7 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { addAsh(1); if (isRedstoneActivated()) { - currentOutput = determineFuelValue(new ItemStack(fuelItem, 1, fuelItemMeta)); + currentOutput = determineFuelValue(fuel); energyManager.generateEnergy(currentOutput); } } else if (isRedstoneActivated()) { @@ -124,8 +118,8 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { IInventoryAdapter inventory = getInternalInventory(); ItemStack fuelStack = inventory.getStackInSlot(fuelSlot); burnTime = totalBurnTime = determineBurnDuration(fuelStack); - if (burnTime > 0 && fuelStack != null) { - fuelItem = fuelStack.getItem(); + if (burnTime > 0 && !fuelStack.isEmpty()) { + fuel = fuelStack.copy(); decrStackSize(fuelSlot, 1); } } @@ -181,10 +175,10 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { if (wasteSlot >= 0) { IInventoryAdapter inventory = getInternalInventory(); ItemStack wasteStack = inventory.getStackInSlot(wasteSlot); - if (wasteStack == null) { + if (wasteStack.isEmpty()) { inventory.setInventorySlotContents(wasteSlot, PluginCore.items.ash.getItemStack()); } else { - wasteStack.stackSize++; + wasteStack.grow(1); } } // Reset @@ -217,19 +211,11 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { /* AUTO-EJECTING */ private IInventory getWasteInventory() { - IInventoryAdapter inventory = getInternalInventory(); - if (inventory == null) { - return null; - } - - return new InventoryMapper(inventory, InventoryEnginePeat.SLOT_WASTE_1, InventoryEnginePeat.SLOT_WASTE_COUNT); + return new InventoryMapper(this, InventoryEnginePeat.SLOT_WASTE_1, InventoryEnginePeat.SLOT_WASTE_COUNT); } private void dumpStash() { IInventory wasteInventory = getWasteInventory(); - if (wasteInventory == null) { - return; - } IItemHandler wasteItemHandler = new InvWrapper(wasteInventory); @@ -261,7 +247,7 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { } IInventoryAdapter inventory = getInternalInventory(); - return (float) inventory.getStackInSlot(fuelSlot).stackSize / (float) inventory.getStackInSlot(fuelSlot).getMaxStackSize() > percentage; + return (float) inventory.getStackInSlot(fuelSlot).getCount() / (float) inventory.getStackInSlot(fuelSlot).getMaxStackSize() > percentage; } // / LOADING AND SAVING @@ -269,13 +255,11 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); - String fuelItemName = nbttagcompound.getString("EngineFuelItem"); - - if (!fuelItemName.isEmpty()) { - fuelItem = ItemStackUtil.getItemFromRegistry(fuelItemName); + if (nbttagcompound.hasKey("EngineFuelItemStack")) { + NBTTagCompound fuelItemNbt = nbttagcompound.getCompoundTag("EngineFuelItemStack"); + fuel = new ItemStack(fuelItemNbt); } - fuelItemMeta = nbttagcompound.getInteger("EngineFuelMeta"); burnTime = nbttagcompound.getInteger("EngineBurnTime"); totalBurnTime = nbttagcompound.getInteger("EngineTotalTime"); if (nbttagcompound.hasKey("AshProduction")) { @@ -283,31 +267,30 @@ public class TileEnginePeat extends TileEngine implements ISidedInventory { } } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); - if (fuelItem != null) { - nbttagcompound.setString("EngineFuelItem", ItemStackUtil.getItemNameFromRegistryAsString(fuelItem)); + if (!fuel.isEmpty()) { + nbttagcompound.setTag("EngineFuelItemStack", fuel.serializeNBT()); } - nbttagcompound.setInteger("EngineFuelMeta", fuelItemMeta); nbttagcompound.setInteger("EngineBurnTime", burnTime); nbttagcompound.setInteger("EngineTotalTime", totalBurnTime); nbttagcompound.setInteger("AshProduction", ashProduction); return nbttagcompound; } - + @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { super.writeGuiData(data); data.writeInt(burnTime); data.writeInt(totalBurnTime); } - + @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { super.readGuiData(data); burnTime = data.readInt(); totalBurnTime = data.readInt(); diff --git a/src/main/java/forestry/energy/tiles/TileEuGenerator.java b/src/main/java/forestry/energy/tiles/TileEuGenerator.java index c044bf333..3dfd9672c 100644 --- a/src/main/java/forestry/energy/tiles/TileEuGenerator.java +++ b/src/main/java/forestry/energy/tiles/TileEuGenerator.java @@ -1,235 +1,235 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.energy.tiles; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.IOException; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - -import forestry.api.core.IErrorLogic; -import forestry.api.fuels.FuelManager; -import forestry.api.fuels.GeneratorFuel; -import forestry.core.config.Constants; -import forestry.core.errors.EnumErrorCode; -import forestry.core.fluids.FluidHelper; -import forestry.core.fluids.ITankManager; -import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamableGui; -import forestry.core.render.TankRenderInfo; -import forestry.core.tiles.ILiquidTankTile; -import forestry.core.tiles.IRenderableTile; -import forestry.core.tiles.TileBase; -import forestry.energy.gui.ContainerGenerator; -import forestry.energy.gui.GuiGenerator; -import forestry.energy.inventory.InventoryGenerator; -import forestry.plugins.compat.PluginIC2; - -import ic2.api.energy.prefab.BasicSource; - -public class TileEuGenerator extends TileBase implements ISidedInventory, ILiquidTankTile, IRenderableTile, IStreamableGui { - private static final int maxEnergy = 30000; - - private final TankManager tankManager; - private final FilteredTank resourceTank; - - private int tickCount = 0; - - private BasicSource ic2EnergySource; - - public TileEuGenerator() { - super("generator"); - - setInternalInventory(new InventoryGenerator(this)); - - resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY); - resourceTank.setFilters(FuelManager.generatorFuel.keySet()); - - tankManager = new TankManager(this, resourceTank); - - if (PluginIC2.instance.isAvailable()) { - ic2EnergySource = new BasicSource(this, maxEnergy, 1); - } - } - - @Nonnull - @Override - public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound = super.writeToNBT(nbttagcompound); - - if (ic2EnergySource != null) { - ic2EnergySource.writeToNBT(nbttagcompound); - } - - tankManager.writeToNBT(nbttagcompound); - return nbttagcompound; - } - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - - if (ic2EnergySource != null) { - ic2EnergySource.readFromNBT(nbttagcompound); - } - - tankManager.readFromNBT(nbttagcompound); - } - - @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - tankManager.writeData(data); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - tankManager.readData(data); - } - - @Override - public void onChunkUnload() { - if (ic2EnergySource != null) { - ic2EnergySource.onChunkUnload(); - } - - super.onChunkUnload(); - } - - @Override - public void invalidate() { - if (ic2EnergySource != null) { - ic2EnergySource.invalidate(); - } - - super.invalidate(); - } - - @Override - public void updateServerSide() { - if (updateOnInterval(20)) { - FluidHelper.drainContainers(tankManager, this, InventoryGenerator.SLOT_CAN); - } - - IErrorLogic errorLogic = getErrorLogic(); - - // No work to be done if IC2 is unavailable. - if (errorLogic.setCondition(ic2EnergySource == null, EnumErrorCode.NO_ENERGY_NET)) { - return; - } - - ic2EnergySource.update(); - - if (resourceTank.getFluidAmount() > 0) { - GeneratorFuel fuel = FuelManager.generatorFuel.get(resourceTank.getFluid().getFluid()); - if (resourceTank.canDrainFluidType(fuel.getFuelConsumed()) && ic2EnergySource.getFreeCapacity() >= fuel.getEu()) { - ic2EnergySource.addEnergy(fuel.getEu()); - this.tickCount++; - - if (tickCount >= fuel.getRate()) { - tickCount = 0; - resourceTank.drain(fuel.getFuelConsumed().amount, true); - } - } - - } - - boolean hasFuel = resourceTank.getFluidAmount() > 0; - errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); - } - - public boolean isWorking() { - return resourceTank.getFluidAmount() > 0; - } - - public int getResourceScaled(int i) { - return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; - } - - public int getStoredScaled(int i) { - if (ic2EnergySource == null) { - return 0; - } - - return (int) (ic2EnergySource.getEnergyStored() * i) / maxEnergy; - } - - @Override - public TankRenderInfo getResourceTankInfo() { - return new TankRenderInfo(resourceTank); - } - - @Override - public TankRenderInfo getProductTankInfo() { - return TankRenderInfo.EMPTY; - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { - if (ic2EnergySource != null) { - data.writeDouble(ic2EnergySource.getEnergyStored()); - } - } - - @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - if (ic2EnergySource != null) { - ic2EnergySource.setEnergyStored(data.readDouble()); - } - } - - @Override - public Object getGui(EntityPlayer player, int data) { - return new GuiGenerator(player.inventory, this); - } - - @Override - public Object getContainer(EntityPlayer player, int data) { - return new ContainerGenerator(player.inventory, this); - } - - @Nonnull - @Override - public ITankManager getTankManager() { - return tankManager; - } - - @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { - if (super.hasCapability(capability, facing)) { - return true; - } - return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY; - } - - @Nonnull - @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { - if (super.hasCapability(capability, facing)) { - return super.getCapability(capability, facing); - } - if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { - return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); - } - return null; - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.energy.tiles; +// +//import javax.annotation.Nonnull; +//import javax.annotation.Nullable; +//import java.io.IOException; +// +//import net.minecraft.entity.player.EntityPlayer; +//import net.minecraft.inventory.ISidedInventory; +//import net.minecraft.nbt.NBTTagCompound; +//import net.minecraft.util.EnumFacing; +// +//import net.minecraftforge.common.capabilities.Capability; +//import net.minecraftforge.fluids.capability.CapabilityFluidHandler; +// +//import forestry.api.core.IErrorLogic; +//import forestry.api.fuels.FuelManager; +//import forestry.api.fuels.GeneratorFuel; +//import forestry.core.config.Constants; +//import forestry.core.errors.EnumErrorCode; +//import forestry.core.fluids.FluidHelper; +//import forestry.core.fluids.ITankManager; +//import forestry.core.fluids.TankManager; +//import forestry.core.fluids.FilteredTank; +//import forestry.core.network.DataInputStreamForestry; +//import forestry.core.network.DataOutputStreamForestry; +//import forestry.core.network.IStreamableGui; +//import forestry.core.render.TankRenderInfo; +//import forestry.core.tiles.ILiquidTankTile; +//import forestry.core.tiles.IRenderableTile; +//import forestry.core.tiles.TileBase; +//import forestry.energy.gui.ContainerGenerator; +//import forestry.energy.gui.GuiGenerator; +//import forestry.energy.inventory.InventoryGenerator; +//import forestry.plugins.compat.PluginIC2; +// +//import ic2.api.energy.prefab.BasicSource; +// +//public class TileEuGenerator extends TileBase implements ISidedInventory, ILiquidTankTile, IRenderableTile, IStreamableGui { +// private static final int maxEnergy = 30000; +// +// private final TankManager tankManager; +// private final FilteredTank resourceTank; +// +// private int tickCount = 0; +// +// private BasicSource ic2EnergySource; +// +// public TileEuGenerator() { +// super("generator"); +// +// setInternalInventory(new InventoryGenerator(this)); +// +// resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY); +// resourceTank.setFilters(FuelManager.generatorFuel.keySet()); +// +// tankManager = new TankManager(this, resourceTank); +// +// if (PluginIC2.instance.isAvailable()) { +// ic2EnergySource = new BasicSource(this, maxEnergy, 1); +// } +// } +// +// @Nonnull +// @Override +// public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { +// nbttagcompound = super.writeToNBT(nbttagcompound); +// +// if (ic2EnergySource != null) { +// ic2EnergySource.writeToNBT(nbttagcompound); +// } +// +// tankManager.writeToNBT(nbttagcompound); +// return nbttagcompound; +// } +// +// @Override +// public void readFromNBT(NBTTagCompound nbttagcompound) { +// super.readFromNBT(nbttagcompound); +// +// if (ic2EnergySource != null) { +// ic2EnergySource.readFromNBT(nbttagcompound); +// } +// +// tankManager.readFromNBT(nbttagcompound); +// } +// +// @Override +// public void writeData(PacketBufferForestry data) { +// super.writeData(data); +// tankManager.writeData(data); +// } +// +// @Override +// public void readData(PacketBufferForestry data) throws IOException { +// super.readData(data); +// tankManager.readData(data); +// } +// +// @Override +// public void onChunkUnload() { +// if (ic2EnergySource != null) { +// ic2EnergySource.onChunkUnload(); +// } +// +// super.onChunkUnload(); +// } +// +// @Override +// public void invalidate() { +// if (ic2EnergySource != null) { +// ic2EnergySource.invalidate(); +// } +// +// super.invalidate(); +// } +// +// @Override +// public void updateServerSide() { +// if (updateOnInterval(20)) { +// FluidHelper.drainContainers(tankManager, this, InventoryGenerator.SLOT_CAN); +// } +// +// IErrorLogic errorLogic = getErrorLogic(); +// +// // No work to be done if IC2 is unavailable. +// if (errorLogic.setCondition(ic2EnergySource == null, EnumErrorCode.NO_ENERGY_NET)) { +// return; +// } +// +// ic2EnergySource.update(); +// +// if (resourceTank.getFluidAmount() > 0) { +// GeneratorFuel fuel = FuelManager.generatorFuel.get(resourceTank.getFluid().getFluid()); +// if (resourceTank.canDrainFluidType(fuel.getFuelConsumed()) && ic2EnergySource.getFreeCapacity() >= fuel.getEu()) { +// ic2EnergySource.addEnergy(fuel.getEu()); +// this.tickCount++; +// +// if (tickCount >= fuel.getRate()) { +// tickCount = 0; +// resourceTank.drain(fuel.getFuelConsumed().amount, true); +// } +// } +// +// } +// +// boolean hasFuel = resourceTank.getFluidAmount() > 0; +// errorLogic.setCondition(!hasFuel, EnumErrorCode.NO_FUEL); +// } +// +// public boolean isWorking() { +// return resourceTank.getFluidAmount() > 0; +// } +// +// public int getResourceScaled(int i) { +// return (resourceTank.getFluidAmount() * i) / Constants.PROCESSOR_TANK_CAPACITY; +// } +// +// public int getStoredScaled(int i) { +// if (ic2EnergySource == null) { +// return 0; +// } +// +// return (int) (ic2EnergySource.getEnergyStored() * i) / maxEnergy; +// } +// +// @Override +// public TankRenderInfo getResourceTankInfo() { +// return new TankRenderInfo(resourceTank); +// } +// +// @Override +// public TankRenderInfo getProductTankInfo() { +// return TankRenderInfo.EMPTY; +// } +// +// @Override +// public void writeGuiData(PacketBufferForestry data) { +// if (ic2EnergySource != null) { +// data.writeDouble(ic2EnergySource.getEnergyStored()); +// } +// } +// +// @Override +// public void readGuiData(PacketBufferForestry data) throws IOException { +// if (ic2EnergySource != null) { +// ic2EnergySource.setEnergyStored(data.readDouble()); +// } +// } +// +// @Override +// public Object getGui(EntityPlayer player, int data) { +// return new GuiGenerator(player.inventory, this); +// } +// +// @Override +// public Object getContainer(EntityPlayer player, int data) { +// return new ContainerGenerator(player.inventory, this); +// } +// +// @Nonnull +// @Override +// public ITankManager getTankManager() { +// return tankManager; +// } +// +// @Override +// public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { +// if (super.hasCapability(capability, facing)) { +// return true; +// } +// return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY; +// } +// +// @Nonnull +// @Override +// public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { +// if (super.hasCapability(capability, facing)) { +// return super.getCapability(capability, facing); +// } +// if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { +// return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); +// } +// return null; +// } +//} diff --git a/src/main/java/forestry/energy/tiles/package-info.java b/src/main/java/forestry/energy/tiles/package-info.java new file mode 100644 index 000000000..69e0727ce --- /dev/null +++ b/src/main/java/forestry/energy/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.energy.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/DummyManagers.java b/src/main/java/forestry/factory/DummyManagers.java index 4173c7d97..0dca0f7c4 100644 --- a/src/main/java/forestry/factory/DummyManagers.java +++ b/src/main/java/forestry/factory/DummyManagers.java @@ -18,6 +18,7 @@ import java.util.Set; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; import forestry.api.recipes.ICarpenterManager; @@ -71,7 +72,7 @@ public class DummyManagers { } @Override - public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object... materials) { + public void addRecipe(int packagingTime, @Nullable FluidStack liquid, ItemStack box, ItemStack product, Object... materials) { } } @@ -125,12 +126,22 @@ public class DummyManagers { public static class DummySqueezerManager extends DummyCraftingProvider implements ISqueezerManager { @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, ItemStack remnants, int chance) { + public void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid, ItemStack remnants, int chance) { } @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) { + public void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid, ItemStack remnants, int chance) { + + } + + @Override + public void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid) { + + } + + @Override + public void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid) { } diff --git a/src/main/java/forestry/factory/PluginFactory.java b/src/main/java/forestry/factory/PluginFactory.java index d12727ddf..73da25c79 100644 --- a/src/main/java/forestry/factory/PluginFactory.java +++ b/src/main/java/forestry/factory/PluginFactory.java @@ -10,16 +10,10 @@ ******************************************************************************/ package forestry.factory; +import javax.annotation.Nullable; import java.util.Set; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - +import com.google.common.base.Preconditions; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuit; @@ -37,8 +31,9 @@ import forestry.apiculture.items.ItemRegistryApiculture; import forestry.core.PluginCore; import forestry.core.PluginFluids; import forestry.core.blocks.BlockBogEarth; -import forestry.core.circuits.Circuit; +import forestry.core.blocks.BlockRegistryCore; import forestry.core.circuits.CircuitLayout; +import forestry.core.circuits.Circuits; import forestry.core.circuits.EnumCircuitBoardType; import forestry.core.circuits.ItemCircuitBoard; import forestry.core.config.Constants; @@ -46,6 +41,7 @@ import forestry.core.fluids.Fluids; import forestry.core.items.EnumElectronTube; import forestry.core.items.ItemElectronTube; import forestry.core.items.ItemRegistryCore; +import forestry.core.items.ItemRegistryFluids; import forestry.core.network.IPacketRegistry; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.datastructures.FluidMap; @@ -66,9 +62,17 @@ import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; import forestry.storage.PluginStorage; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; @ForestryPlugin(pluginID = ForestryPluginUids.FACTORY, name = "Factory", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.factory.description") public class PluginFactory extends BlankForestryPlugin { + @Nullable public static BlockRegistryFactory blocks; @Override @@ -123,6 +127,7 @@ public class PluginFactory extends BlankForestryPlugin { super.preInit(); ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); // Set fuels and resources for the fermenter ItemStack fertilizerCompound = coreItems.fertilizerCompound.getItemStack(); @@ -151,18 +156,38 @@ public class PluginFactory extends BlankForestryPlugin { ItemStack bituminousPeat = coreItems.bituminousPeat.getItemStack(); FuelManager.copperEngineFuel.put(bituminousPeat, new EngineCopperFuel(bituminousPeat, Constants.ENGINE_COPPER_FUEL_VALUE_BITUMINOUS_PEAT, Constants.ENGINE_COPPER_CYCLE_DURATION_BITUMINOUS_PEAT)); - FuelManager.bronzeEngineFuel.put(Fluids.BIOMASS.getFluid(), new EngineBronzeFuel(Fluids.BIOMASS.getFluid(), - Constants.ENGINE_FUEL_VALUE_BIOMASS, (int) (Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")), 1)); + Fluid biomass = Fluids.BIOMASS.getFluid(); + if (biomass != null) { + FuelManager.bronzeEngineFuel.put(biomass, new EngineBronzeFuel(biomass, + Constants.ENGINE_FUEL_VALUE_BIOMASS, (int) (Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")), 1)); + } + FuelManager.bronzeEngineFuel.put(FluidRegistry.WATER, new EngineBronzeFuel(FluidRegistry.WATER, Constants.ENGINE_FUEL_VALUE_WATER, Constants.ENGINE_CYCLE_DURATION_WATER, 3)); - FuelManager.bronzeEngineFuel.put(Fluids.MILK.getFluid(), new EngineBronzeFuel(Fluids.MILK.getFluid(), - Constants.ENGINE_FUEL_VALUE_MILK, Constants.ENGINE_CYCLE_DURATION_MILK, 3)); - FuelManager.bronzeEngineFuel.put(Fluids.SEED_OIL.getFluid(), new EngineBronzeFuel(Fluids.SEED_OIL.getFluid(), - Constants.ENGINE_FUEL_VALUE_SEED_OIL, Constants.ENGINE_CYCLE_DURATION_SEED_OIL, 1)); - FuelManager.bronzeEngineFuel.put(Fluids.FOR_HONEY.getFluid(), new EngineBronzeFuel(Fluids.FOR_HONEY.getFluid(), - Constants.ENGINE_FUEL_VALUE_HONEY, Constants.ENGINE_CYCLE_DURATION_HONEY, 1)); - FuelManager.bronzeEngineFuel.put(Fluids.JUICE.getFluid(), new EngineBronzeFuel(Fluids.JUICE.getFluid(), - Constants.ENGINE_FUEL_VALUE_JUICE, Constants.ENGINE_CYCLE_DURATION_JUICE, 1)); + + Fluid milk = Fluids.MILK.getFluid(); + if (milk != null) { + FuelManager.bronzeEngineFuel.put(milk, new EngineBronzeFuel(milk, + Constants.ENGINE_FUEL_VALUE_MILK, Constants.ENGINE_CYCLE_DURATION_MILK, 3)); + } + + Fluid seedOil = Fluids.SEED_OIL.getFluid(); + if (seedOil != null) { + FuelManager.bronzeEngineFuel.put(seedOil, new EngineBronzeFuel(seedOil, + Constants.ENGINE_FUEL_VALUE_SEED_OIL, Constants.ENGINE_CYCLE_DURATION_SEED_OIL, 1)); + } + + Fluid honey = Fluids.FOR_HONEY.getFluid(); + if (honey != null) { + FuelManager.bronzeEngineFuel.put(honey, new EngineBronzeFuel(honey, + Constants.ENGINE_FUEL_VALUE_HONEY, Constants.ENGINE_CYCLE_DURATION_HONEY, 1)); + } + + Fluid juice = Fluids.JUICE.getFluid(); + if (juice != null) { + FuelManager.bronzeEngineFuel.put(juice, new EngineBronzeFuel(juice, + Constants.ENGINE_FUEL_VALUE_JUICE, Constants.ENGINE_CYCLE_DURATION_JUICE, 1)); + } // Set rain substrates ItemStack iodineCharge = coreItems.iodineCharge.getItemStack(); @@ -183,12 +208,13 @@ public class PluginFactory extends BlankForestryPlugin { @Override public void registerTriggers() { - FactoryTriggers.initialize(); +// FactoryTriggers.initialize(); } @Override public void doInit() { super.doInit(); + Preconditions.checkState(blocks != null); blocks.bottler.init(); blocks.carpenter.init(); @@ -203,47 +229,106 @@ public class PluginFactory extends BlankForestryPlugin { blocks.raintank.init(); blocks.worktable.init(); - Circuit.machineSpeedUpgrade1 = new CircuitSpeedUpgrade("machine.speed.boost.1", 0.125f, 0.05f); - Circuit.machineSpeedUpgrade2 = new CircuitSpeedUpgrade("machine.speed.boost.2", 0.250f, 0.10f); - Circuit.machineEfficiencyUpgrade1 = new CircuitSpeedUpgrade("machine.efficiency.1", 0, -0.10f); + Circuits.machineSpeedUpgrade1 = new CircuitSpeedUpgrade("machine.speed.boost.1", 0.125f, 0.05f); + Circuits.machineSpeedUpgrade2 = new CircuitSpeedUpgrade("machine.speed.boost.2", 0.250f, 0.10f); + Circuits.machineEfficiencyUpgrade1 = new CircuitSpeedUpgrade("machine.efficiency.1", 0, -0.10f); } @Override public void registerRecipes() { // / FABRICATOR - ItemElectronTube electronTube = PluginCore.items.tubes; - - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.COPPER, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "ingotCopper"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.TIN, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "ingotTin"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.BRONZE, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "ingotBronze"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.IRON, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "ingotIron"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.GOLD, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "ingotGold"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.DIAMOND, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "gemDiamond"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.OBSIDIAN, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', Blocks.OBSIDIAN}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.BLAZE, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', Items.BLAZE_POWDER}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.EMERALD, 4), new Object[]{ - " X ", "#X#", "XXX", '#', "dustRedstone", 'X', "gemEmerald"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.APATITE, 4), - new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', "gemApatite"}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.LAPIS, 4), - new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', new ItemStack(Items.DYE, 1, 4)}); - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.ENDER, 4), - new Object[]{" X ", "#X#", "XXX", '#', new ItemStack(Items.ENDER_EYE, 1, 0), 'X', new ItemStack(Blocks.END_STONE, 1, 0)}); + ItemRegistryCore coreItems = PluginCore.items; + BlockRegistryCore coreBlocks = PluginCore.blocks; + ItemRegistryFluids fluidItems = PluginFluids.items; + + Preconditions.checkState(coreItems != null); + Preconditions.checkState(coreBlocks != null); + Preconditions.checkState(fluidItems != null); + Preconditions.checkState(blocks != null); + + ItemElectronTube electronTube = coreItems.tubes; + + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.COPPER, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "ingotCopper"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.TIN, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "ingotTin"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.BRONZE, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "ingotBronze"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.IRON, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "ingotIron"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.GOLD, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "ingotGold"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.DIAMOND, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "gemDiamond"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.OBSIDIAN, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', Blocks.OBSIDIAN}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.BLAZE, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', Items.BLAZE_POWDER}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.EMERALD, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "gemEmerald"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.APATITE, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', "gemApatite"}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.LAPIS, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', "dustRedstone", + 'X', new ItemStack(Items.DYE, 1, 4)}); + RecipeManagers.fabricatorManager.addRecipe(ItemStack.EMPTY, Fluids.GLASS.getFluid(500), electronTube.get(EnumElectronTube.ENDER, 4), new Object[]{ + " X ", + "#X#", + "XXX", + '#', new ItemStack(Items.ENDER_EYE, 1, 0), + 'X', new ItemStack(Blocks.END_STONE, 1, 0)}); String[] dyes = {"dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite"}; if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.APICULTURE)) { ItemRegistryApiculture beeItems = PluginApiculture.items; + Preconditions.checkState(beeItems != null); + FluidStack liquidGlass = Fluids.GLASS.getFluid(Fluid.BUCKET_VOLUME); FluidStack liquidGlassX4 = Fluids.GLASS.getFluid(Fluid.BUCKET_VOLUME * 4); for (int i = 0; i < 16; i++) { @@ -260,20 +345,29 @@ public class PluginFactory extends BlankForestryPlugin { // / SQUEEZER int appleMulchAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple"); int appleJuiceAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple"); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.APPLE)}, Fluids.JUICE.getFluid(appleJuiceAmount), - PluginCore.items.mulch.getItemStack(), appleMulchAmount); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.CARROT)}, Fluids.JUICE.getFluid(appleJuiceAmount), - PluginCore.items.mulch.getItemStack(), appleMulchAmount); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.APPLE), Fluids.JUICE.getFluid(appleJuiceAmount), + coreItems.mulch.getItemStack(), appleMulchAmount); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.CARROT), Fluids.JUICE.getFluid(appleJuiceAmount), + coreItems.mulch.getItemStack(), appleMulchAmount); int seedOilAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); FluidStack seedOil = Fluids.SEED_OIL.getFluid(seedOilAmount); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.WHEAT_SEEDS)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.PUMPKIN_SEEDS)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.MELON_SEEDS)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.BEETROOT_SEEDS)}, seedOil); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{PluginCore.items.phosphor.getItemStack(2), new ItemStack(Blocks.COBBLESTONE)}, new FluidStack(FluidRegistry.LAVA, 1600)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Blocks.CACTUS)}, new FluidStack(FluidRegistry.WATER, 500)); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(Items.SNOWBALL), PluginCore.items.craftingMaterial.getIceShard(4)}, Fluids.ICE.getFluid(4000)); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.WHEAT_SEEDS), seedOil); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.PUMPKIN_SEEDS), seedOil); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.MELON_SEEDS), seedOil); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Items.BEETROOT_SEEDS), seedOil); + + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(Blocks.CACTUS), new FluidStack(FluidRegistry.WATER, 500)); + + NonNullList lavaRecipeResources = NonNullList.create(); + lavaRecipeResources.add(coreItems.phosphor.getItemStack(2)); + lavaRecipeResources.add(new ItemStack(Blocks.COBBLESTONE)); + RecipeManagers.squeezerManager.addRecipe(10, lavaRecipeResources, new FluidStack(FluidRegistry.LAVA, 1600)); + + NonNullList iceRecipeResources = NonNullList.create(); + iceRecipeResources.add(new ItemStack(Items.SNOWBALL)); + iceRecipeResources.add(coreItems.craftingMaterial.getIceShard(4)); + RecipeManagers.squeezerManager.addRecipe(10, iceRecipeResources, Fluids.ICE.getFluid(4000)); // STILL RecipeManagers.stillManager.addRecipe(Constants.STILL_DESTILLATION_DURATION, Fluids.BIOMASS.getFluid(Constants.STILL_DESTILLATION_INPUT), @@ -307,53 +401,53 @@ public class PluginFactory extends BlankForestryPlugin { RecipeManagers.fabricatorSmeltingManager.addSmelting(new ItemStack(Blocks.SANDSTONE, 1, 2), Fluids.GLASS.getFluid(4000), 4800); // / CARPENTER - RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEED_OIL.getFluid(250), null, PluginCore.items.impregnatedCasing.getItemStack(), + RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEED_OIL.getFluid(250), ItemStack.EMPTY, coreItems.impregnatedCasing.getItemStack(), "###", "# #", "###", '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEED_OIL.getFluid(500), null, - new ItemStack(PluginCore.blocks.escritoire), + RecipeManagers.carpenterManager.addRecipe(50, Fluids.SEED_OIL.getFluid(500), ItemStack.EMPTY, + new ItemStack(coreBlocks.escritoire), "# ", "###", "# #", '#', "plankWood"); // RESOURCES - RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEED_OIL.getFluid(100), null, - PluginCore.items.stickImpregnated.getItemStack(2), + RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEED_OIL.getFluid(100), ItemStack.EMPTY, + coreItems.stickImpregnated.getItemStack(2), "#", "#", '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 250), null, - PluginCore.items.woodPulp.getItemStack(4), + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 250), ItemStack.EMPTY, + coreItems.woodPulp.getItemStack(4), "#", '#', "logWood"); - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 250), null, + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 250), ItemStack.EMPTY, new ItemStack(Items.PAPER, 1), "#", "#", '#', "pulpWood"); - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), null, - new ItemStack(PluginCore.blocks.humus, 9), + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, + new ItemStack(coreBlocks.humus, 9), "###", "#X#", "###", '#', Blocks.DIRT, - 'X', PluginCore.items.mulch); - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), null, - PluginCore.blocks.bogEarth.get(BlockBogEarth.SoilType.BOG_EARTH, 8), + 'X', coreItems.mulch); + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, + coreBlocks.bogEarth.get(BlockBogEarth.SoilType.BOG_EARTH, 8), "#X#", "XYX", "#X#", '#', Blocks.DIRT, 'X', "sand", - 'Y', PluginCore.items.mulch); - RecipeManagers.carpenterManager.addRecipe(75, new FluidStack(FluidRegistry.WATER, 5000), null, PluginCore.items.hardenedCasing.getItemStack(), + 'Y', coreItems.mulch); + RecipeManagers.carpenterManager.addRecipe(75, new FluidStack(FluidRegistry.WATER, 5000), ItemStack.EMPTY, coreItems.hardenedCasing.getItemStack(), "# #", " Y ", "# #", '#', "gemDiamond", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); // / CHIPSETS ItemStack basicCircuitboard = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.BASIC, null, new ICircuit[]{}); @@ -361,75 +455,76 @@ public class PluginFactory extends BlankForestryPlugin { ItemStack refinedCircuitboard = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{}); ItemStack intricateCircuitboard = ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.INTRICATE, null, new ICircuit[]{}); - RecipeManagers.carpenterManager.addRecipe(20, new FluidStack(FluidRegistry.WATER, 1000), null, basicCircuitboard, + RecipeManagers.carpenterManager.addRecipe(20, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, basicCircuitboard, "R R", "R#R", "R R", '#', "ingotTin", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(40, new FluidStack(FluidRegistry.WATER, 1000), null, enhancedCircuitboard, + RecipeManagers.carpenterManager.addRecipe(40, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, enhancedCircuitboard, "R#R", "R#R", "R#R", '#', "ingotBronze", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(80, new FluidStack(FluidRegistry.WATER, 1000), null, refinedCircuitboard, + RecipeManagers.carpenterManager.addRecipe(80, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, refinedCircuitboard, "R#R", "R#R", "R#R", '#', "ingotIron", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(80, new FluidStack(FluidRegistry.WATER, 1000), null, intricateCircuitboard, + RecipeManagers.carpenterManager.addRecipe(80, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, intricateCircuitboard, "R#R", "R#R", "R#R", '#', "ingotGold", 'R', "dustRedstone"); - RecipeManagers.carpenterManager.addRecipe(40, new FluidStack(FluidRegistry.WATER, 1000), null, PluginCore.items.solderingIron.getItemStack(), + RecipeManagers.carpenterManager.addRecipe(40, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, coreItems.solderingIron.getItemStack(), " # ", "# #", " B", '#', "ingotIron", 'B', "ingotBronze"); // RAIN SUBSTRATES ItemRegistryApiculture beeItems = PluginApiculture.items; + if (beeItems != null) { - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), null, PluginCore.items.iodineCharge.getItemStack(), + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, coreItems.iodineCharge.getItemStack(), "Z#Z", "#Y#", "X#X", '#', beeItems.pollenCluster.getWildcard(), 'X', Items.GUNPOWDER, - 'Y', PluginFluids.items.canEmpty, + 'Y', fluidItems.canEmpty, 'Z', beeItems.honeyDrop); - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), null, PluginCore.items.craftingMaterial.getDissipationCharge(), + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, coreItems.craftingMaterial.getDissipationCharge(), "Z#Z", "#Y#", "X#X", '#', beeItems.royalJelly, 'X', Items.GUNPOWDER, - 'Y', PluginFluids.items.canEmpty, + 'Y', fluidItems.canEmpty, 'Z', beeItems.honeydew); } // Ender pearl - RecipeManagers.carpenterManager.addRecipe(100, null, new ItemStack(Items.ENDER_PEARL, 1), " # ", "###", " # ", '#', - PluginCore.items.craftingMaterial.getPulsatingMesh()); + RecipeManagers.carpenterManager.addRecipe(100, ItemStack.EMPTY, new ItemStack(Items.ENDER_PEARL, 1), " # ", "###", " # ", '#', + coreItems.craftingMaterial.getPulsatingMesh()); // Woven Silk - RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 500), null, PluginCore.items.craftingMaterial.getWovenSilk(), + RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 500), ItemStack.EMPTY, coreItems.craftingMaterial.getWovenSilk(), "###", "###", "###", - '#', PluginCore.items.craftingMaterial.getSilkWisp()); + '#', coreItems.craftingMaterial.getSilkWisp()); // Boxes - RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), null, PluginCore.items.carton.getItemStack(2), + RecipeManagers.carpenterManager.addRecipe(5, new FluidStack(FluidRegistry.WATER, 1000), ItemStack.EMPTY, coreItems.carton.getItemStack(2), " # ", "# #", " # ", '#', "pulpWood"); // Assembly Kits - RecipeManagers.carpenterManager.addRecipe(20, null, PluginCore.items.carton.getItemStack(), PluginCore.items.kitPickaxe.getItemStack(), new Object[]{ + RecipeManagers.carpenterManager.addRecipe(20, null, coreItems.carton.getItemStack(), coreItems.kitPickaxe.getItemStack(), new Object[]{ "###", " X ", " X ", '#', "ingotBronze", 'X', "stickWood"}); - RecipeManagers.carpenterManager.addRecipe(20, null, PluginCore.items.carton.getItemStack(), PluginCore.items.kitShovel.getItemStack(), + RecipeManagers.carpenterManager.addRecipe(20, null, coreItems.carton.getItemStack(), coreItems.kitShovel.getItemStack(), new Object[]{" # ", " X ", " X ", '#', "ingotBronze", 'X', "stickWood"}); // Reclamation - ItemStack ingotBronze = PluginCore.items.ingotBronze.copy(); - ingotBronze.stackSize = 2; - RecipeManagers.carpenterManager.addRecipe(null, ingotBronze, "#", '#', PluginCore.items.brokenBronzePickaxe); + ItemStack ingotBronze = coreItems.ingotBronze.copy(); + ingotBronze.setCount(2); + RecipeManagers.carpenterManager.addRecipe(ItemStack.EMPTY, ingotBronze, "#", '#', coreItems.brokenBronzePickaxe); ingotBronze = ingotBronze.copy(); - ingotBronze.stackSize = 1; - RecipeManagers.carpenterManager.addRecipe(null, ingotBronze, "#", '#', PluginCore.items.brokenBronzeShovel); + ingotBronze.setCount(1); + RecipeManagers.carpenterManager.addRecipe(ItemStack.EMPTY, ingotBronze, "#", '#', coreItems.brokenBronzeShovel); // Crating and uncrating if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.STORAGE)) { @@ -438,17 +533,17 @@ public class PluginFactory extends BlankForestryPlugin { ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.machine.upgrade"); // / Solder Manager - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.EMERALD, 1), Circuit.machineSpeedUpgrade1); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.machineSpeedUpgrade2); - ChipsetManager.solderManager.addRecipe(layout, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.machineEfficiencyUpgrade1); + ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.EMERALD, 1), Circuits.machineSpeedUpgrade1); + ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.BLAZE, 1), Circuits.machineSpeedUpgrade2); + ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.GOLD, 1), Circuits.machineEfficiencyUpgrade1); RecipeUtil.addRecipe(blocks.bottler, "X#X", "#Y#", "X#X", '#', "blockGlass", - 'X', PluginFluids.items.canEmpty, - 'Y', PluginCore.items.sturdyCasing); + 'X', fluidItems.canEmpty, + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.carpenter, "X#X", @@ -456,7 +551,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "ingotBronze", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.centrifuge, "X#X", @@ -464,7 +559,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "ingotCopper", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.fermenter, "X#X", @@ -472,7 +567,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "gearBronze", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.moistener, "X#X", @@ -480,7 +575,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "gearCopper", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.squeezer, "X#X", @@ -488,7 +583,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "ingotTin", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.still, "X#X", @@ -496,7 +591,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "dustRedstone", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.rainmaker, "X#X", @@ -504,7 +599,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "gearTin", - 'Y', PluginCore.items.hardenedCasing); + 'Y', coreItems.hardenedCasing); RecipeUtil.addRecipe(blocks.fabricator, "X#X", @@ -512,7 +607,7 @@ public class PluginFactory extends BlankForestryPlugin { "XZX", '#', "blockGlass", 'X', "ingotGold", - 'Y', PluginCore.items.sturdyCasing, + 'Y', coreItems.sturdyCasing, 'Z', "chestWood"); RecipeUtil.addRecipe(blocks.raintank, @@ -521,7 +616,7 @@ public class PluginFactory extends BlankForestryPlugin { "X#X", '#', "blockGlass", 'X', "ingotIron", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(blocks.worktable, "B", diff --git a/src/main/java/forestry/factory/blocks/BlockTypeFactoryPlain.java b/src/main/java/forestry/factory/blocks/BlockTypeFactoryPlain.java index 7e896dd60..2b78ba1d5 100644 --- a/src/main/java/forestry/factory/blocks/BlockTypeFactoryPlain.java +++ b/src/main/java/forestry/factory/blocks/BlockTypeFactoryPlain.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.factory.blocks; -import javax.annotation.Nonnull; - import forestry.core.blocks.IBlockType; import forestry.core.blocks.IMachineProperties; import forestry.core.blocks.MachineProperties; @@ -27,14 +25,12 @@ public enum BlockTypeFactoryPlain implements IBlockType { public static final BlockTypeFactoryPlain[] VALUES = values(); - @Nonnull private final IMachineProperties machineProperties; - BlockTypeFactoryPlain(@Nonnull Class teClass, @Nonnull String name) { + BlockTypeFactoryPlain(Class teClass, String name) { this.machineProperties = new MachineProperties<>(teClass, name); } - @Nonnull @Override public IMachineProperties getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java b/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java index 8d1054d0a..b801021ee 100644 --- a/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java +++ b/src/main/java/forestry/factory/blocks/BlockTypeFactoryTesr.java @@ -10,11 +10,8 @@ ******************************************************************************/ package forestry.factory.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; - import forestry.core.blocks.IBlockTypeTesr; import forestry.core.blocks.IMachinePropertiesTesr; import forestry.core.blocks.MachinePropertiesTesr; @@ -29,6 +26,7 @@ import forestry.factory.tiles.TileMillRainmaker; import forestry.factory.tiles.TileMoistener; import forestry.factory.tiles.TileSqueezer; import forestry.factory.tiles.TileStill; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; public enum BlockTypeFactoryTesr implements IBlockTypeTesr { BOTTLER(TileBottler.class, "bottler"), @@ -42,19 +40,17 @@ public enum BlockTypeFactoryTesr implements IBlockTypeTesr { public static final BlockTypeFactoryTesr[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeFactoryTesr(@Nonnull Class teClass, @Nonnull String name) { + BlockTypeFactoryTesr(Class teClass, String name) { TileEntitySpecialRenderer renderer = Proxies.render.getRenderDefaultMachine(Constants.TEXTURE_PATH_BLOCKS + "/" + name + "_"); this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, Constants.MOD_ID + ":blocks/" + name + ".0"); } - BlockTypeFactoryTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer) { + BlockTypeFactoryTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer) { this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, Constants.MOD_ID + ":blocks/" + name + ".0"); } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/factory/blocks/package-info.java b/src/main/java/forestry/factory/blocks/package-info.java new file mode 100644 index 000000000..c0cc911d9 --- /dev/null +++ b/src/main/java/forestry/factory/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/circuits/package-info.java b/src/main/java/forestry/factory/circuits/package-info.java new file mode 100644 index 000000000..9765bc59f --- /dev/null +++ b/src/main/java/forestry/factory/circuits/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.circuits; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/gui/ContainerCarpenter.java b/src/main/java/forestry/factory/gui/ContainerCarpenter.java index 51e1a609e..face474fb 100755 --- a/src/main/java/forestry/factory/gui/ContainerCarpenter.java +++ b/src/main/java/forestry/factory/gui/ContainerCarpenter.java @@ -61,7 +61,7 @@ public class ContainerCarpenter extends ContainerLiquidTanks impl tile.checkRecipe(); } - private ItemStack oldCraftPreview; + private ItemStack oldCraftPreview = ItemStack.EMPTY; @Override public void detectAndSendChanges() { diff --git a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java b/src/main/java/forestry/factory/gui/ContainerCentrifuge.java index 6d7795772..318b07c2e 100755 --- a/src/main/java/forestry/factory/gui/ContainerCentrifuge.java +++ b/src/main/java/forestry/factory/gui/ContainerCentrifuge.java @@ -39,7 +39,7 @@ public class ContainerCentrifuge extends ContainerSocketed { } } - private ItemStack oldCraftPreview; + private ItemStack oldCraftPreview = ItemStack.EMPTY; @Override public void detectAndSendChanges() { diff --git a/src/main/java/forestry/factory/gui/ContainerWorktable.java b/src/main/java/forestry/factory/gui/ContainerWorktable.java index 285d8b792..3ac1c10ef 100755 --- a/src/main/java/forestry/factory/gui/ContainerWorktable.java +++ b/src/main/java/forestry/factory/gui/ContainerWorktable.java @@ -122,10 +122,7 @@ public class ContainerWorktable extends ContainerTile implements } @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { - int primary = packet.getPrimaryIndex(); - int secondary = packet.getSecondaryIndex(); - + public void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary) { switch (primary) { case -1: { // clicked clear button tile.clearCraftMatrix(); @@ -140,7 +137,7 @@ public class ContainerWorktable extends ContainerTile implements break; } case 1: { // right clicked a memorized recipe - long time = player.worldObj.getTotalWorldTime(); + long time = player.world.getTotalWorldTime(); RecipeMemory memory = tile.getMemory(); memory.toggleLock(time, secondary); break; diff --git a/src/main/java/forestry/factory/gui/GuiBottler.java b/src/main/java/forestry/factory/gui/GuiBottler.java index 242042381..e8ee8ac65 100755 --- a/src/main/java/forestry/factory/gui/GuiBottler.java +++ b/src/main/java/forestry/factory/gui/GuiBottler.java @@ -10,15 +10,15 @@ ******************************************************************************/ package forestry.factory.gui; -import net.minecraft.client.renderer.GlStateManager; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Constants; import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.widgets.TankWidget; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; import forestry.factory.tiles.TileBottler; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.InventoryPlayer; public class GuiBottler extends GuiForestryTitled { @@ -50,15 +50,15 @@ public class GuiBottler extends GuiForestryTitled textLayout.line = 5; textLayout.drawCenteredLine(name, 0, ColourProperties.INSTANCE.get("gui.title")); bindTexture(textureFile); - + bindTexture(textureFile); - + TileBottler bottler = inventory; int progressArrow = bottler.getProgressScaled(22); - if(progressArrow > 0){ - if(bottler.isFillRecipe){ + if (progressArrow > 0) { + if (bottler.isFillRecipe) { drawTexturedModalRect(guiLeft + 108, guiTop + 35, 177, 74, progressArrow, 16); - }else{ + } else { drawTexturedModalRect(guiLeft + 46, guiTop + 35, 177, 74, progressArrow, 16); } } diff --git a/src/main/java/forestry/factory/gui/package-info.java b/src/main/java/forestry/factory/gui/package-info.java new file mode 100644 index 000000000..6d832815a --- /dev/null +++ b/src/main/java/forestry/factory/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java b/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java index c7c2dff19..58749b573 100644 --- a/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java +++ b/src/main/java/forestry/factory/gui/widgets/MemorizedRecipeSlot.java @@ -52,7 +52,7 @@ public class MemorizedRecipeSlot extends ItemStackWidgetBase { @Override public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - if (getItemStack() != null) { + if (!getItemStack().isEmpty()) { ContainerWorktable.sendRecipeClick(mouseButton, slotNumber); Proxies.common.playButtonClick(); } diff --git a/src/main/java/forestry/factory/gui/widgets/package-info.java b/src/main/java/forestry/factory/gui/widgets/package-info.java new file mode 100644 index 000000000..3c38d4a82 --- /dev/null +++ b/src/main/java/forestry/factory/gui/widgets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.gui.widgets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java index b1c530773..ed07acbeb 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCarpenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryCarpenter.java @@ -10,16 +10,14 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.factory.recipes.CarpenterRecipeManager; import forestry.factory.tiles.TileCarpenter; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; public class InventoryCarpenter extends InventoryAdapterTile { public final static int SLOT_BOX = 9; @@ -37,7 +35,7 @@ public class InventoryCarpenter extends InventoryAdapterTile { public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { if (slotIndex == SLOT_CAN_INPUT) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); + return fluid != null && tile.getTankManager().canFillFluidType(fluid); } else if (slotIndex == SLOT_BOX) { return CarpenterRecipeManager.isBox(itemStack); } else if (canSlotAccept(SLOT_CAN_INPUT, itemStack) || canSlotAccept(SLOT_BOX, itemStack)) { diff --git a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java index 6343090dc..39f0d64fb 100644 --- a/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java +++ b/src/main/java/forestry/factory/inventory/InventoryCentrifuge.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.factory.recipes.CentrifugeRecipeManager; import forestry.factory.tiles.TileCentrifuge; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryCentrifuge extends InventoryAdapterTile { public static final int SLOT_RESOURCE = 0; diff --git a/src/main/java/forestry/factory/inventory/InventoryFabricator.java b/src/main/java/forestry/factory/inventory/InventoryFabricator.java index 1b583c917..20ee0af07 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFabricator.java +++ b/src/main/java/forestry/factory/inventory/InventoryFabricator.java @@ -10,14 +10,13 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.factory.recipes.FabricatorRecipeManager; import forestry.factory.recipes.FabricatorSmeltingRecipeManager; import forestry.factory.tiles.TileFabricator; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryFabricator extends InventoryAdapterTile { public static final short SLOT_METAL = 0; diff --git a/src/main/java/forestry/factory/inventory/InventoryFermenter.java b/src/main/java/forestry/factory/inventory/InventoryFermenter.java index a428135bc..7e9f1e5ed 100644 --- a/src/main/java/forestry/factory/inventory/InventoryFermenter.java +++ b/src/main/java/forestry/factory/inventory/InventoryFermenter.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import forestry.api.fuels.FuelManager; import forestry.core.fluids.FluidHelper; import forestry.core.inventory.InventoryAdapterTile; import forestry.factory.recipes.FermenterRecipeManager; import forestry.factory.tiles.TileFermenter; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; public class InventoryFermenter extends InventoryAdapterTile { public static final short SLOT_RESOURCE = 0; @@ -39,7 +37,7 @@ public class InventoryFermenter extends InventoryAdapterTile { return FermenterRecipeManager.isResource(itemStack); } else if (slotIndex == SLOT_INPUT) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); + return fluid != null && tile.getTankManager().canFillFluidType(fluid); } else if (slotIndex == SLOT_CAN_INPUT) { return FluidHelper.isFillableContainerWithRoom(itemStack); } else if (slotIndex == SLOT_FUEL) { diff --git a/src/main/java/forestry/factory/inventory/InventoryMoistener.java b/src/main/java/forestry/factory/inventory/InventoryMoistener.java index a23f80c65..6c040da81 100644 --- a/src/main/java/forestry/factory/inventory/InventoryMoistener.java +++ b/src/main/java/forestry/factory/inventory/InventoryMoistener.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import forestry.api.fuels.FuelManager; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.utils.SlotUtil; import forestry.factory.recipes.MoistenerRecipeManager; import forestry.factory.tiles.TileMoistener; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; public class InventoryMoistener extends InventoryAdapterTile { public static final short SLOT_STASH_1 = 0; @@ -47,7 +45,7 @@ public class InventoryMoistener extends InventoryAdapterTile { if (slotIndex == SLOT_PRODUCT) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); + return fluid != null && tile.getTankManager().canFillFluidType(fluid); } return false; diff --git a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java index bddc69593..d63b2eef8 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRainmaker.java +++ b/src/main/java/forestry/factory/inventory/InventoryRainmaker.java @@ -10,12 +10,11 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; - import forestry.api.fuels.FuelManager; import forestry.api.fuels.RainSubstrate; import forestry.core.inventory.InventoryAdapterTile; import forestry.factory.tiles.TileMillRainmaker; +import net.minecraft.item.ItemStack; public class InventoryRainmaker extends InventoryAdapterTile { private static final int SLOT_SUBSTRATE = 0; diff --git a/src/main/java/forestry/factory/inventory/InventoryRaintank.java b/src/main/java/forestry/factory/inventory/InventoryRaintank.java index d7f3d5915..8ccec11c5 100644 --- a/src/main/java/forestry/factory/inventory/InventoryRaintank.java +++ b/src/main/java/forestry/factory/inventory/InventoryRaintank.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.factory.inventory; +import forestry.core.inventory.InventoryAdapterTile; +import forestry.factory.tiles.TileRaintank; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; - import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; import net.minecraftforge.fluids.capability.IFluidHandler; -import forestry.core.inventory.InventoryAdapterTile; -import forestry.factory.tiles.TileRaintank; - public class InventoryRaintank extends InventoryAdapterTile { public static final short SLOT_RESOURCE = 0; public static final short SLOT_PRODUCT = 1; diff --git a/src/main/java/forestry/factory/inventory/InventorySqueezer.java b/src/main/java/forestry/factory/inventory/InventorySqueezer.java index 16c483224..3f07ade70 100644 --- a/src/main/java/forestry/factory/inventory/InventorySqueezer.java +++ b/src/main/java/forestry/factory/inventory/InventorySqueezer.java @@ -10,12 +10,6 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; - import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; import forestry.core.inventory.InventoryAdapterTile; @@ -23,6 +17,11 @@ import forestry.core.inventory.wrappers.InventoryMapper; import forestry.core.utils.InventoryUtil; import forestry.factory.recipes.SqueezerRecipeManager; import forestry.factory.tiles.TileSqueezer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fluids.FluidStack; public class InventorySqueezer extends InventoryAdapterTile { public static final short SLOT_RESOURCE_1 = 0; @@ -64,11 +63,11 @@ public class InventorySqueezer extends InventoryAdapterTile { return !InventoryUtil.isEmpty(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); } - public ItemStack[] getResources() { + public NonNullList getResources() { return InventoryUtil.getStacks(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); } - public boolean removeResources(ItemStack[] stacks) { + public boolean removeResources(NonNullList stacks) { IInventory inventory = new InventoryMapper(this, SLOT_RESOURCE_1, SLOTS_RESOURCE_COUNT); return InventoryUtil.removeSets(inventory, 1, stacks, null, false, true, false, true); } @@ -78,7 +77,7 @@ public class InventorySqueezer extends InventoryAdapterTile { } public void fillContainers(FluidStack fluidStack, TankManager tankManager) { - if (getStackInSlot(SLOT_CAN_INPUT) == null || fluidStack == null) { + if (getStackInSlot(SLOT_CAN_INPUT).isEmpty()) { return; } FluidHelper.fillContainers(tankManager, this, SLOT_CAN_INPUT, SLOT_CAN_OUTPUT, fluidStack.getFluid(), true); diff --git a/src/main/java/forestry/factory/inventory/InventoryStill.java b/src/main/java/forestry/factory/inventory/InventoryStill.java index 38b64efeb..e24b2ac65 100644 --- a/src/main/java/forestry/factory/inventory/InventoryStill.java +++ b/src/main/java/forestry/factory/inventory/InventoryStill.java @@ -10,15 +10,13 @@ ******************************************************************************/ package forestry.factory.inventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; - import forestry.core.fluids.FluidHelper; import forestry.core.inventory.InventoryAdapterTile; import forestry.factory.tiles.TileStill; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; public class InventoryStill extends InventoryAdapterTile { public static final short SLOT_PRODUCT = 0; @@ -35,7 +33,7 @@ public class InventoryStill extends InventoryAdapterTile { return FluidHelper.isFillableEmptyContainer(itemStack); } else if (slotIndex == SLOT_CAN) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return tile.getTankManager().canFillFluidType(fluid); + return fluid != null && tile.getTankManager().canFillFluidType(fluid); } return false; } diff --git a/src/main/java/forestry/factory/inventory/package-info.java b/src/main/java/forestry/factory/inventory/package-info.java new file mode 100644 index 000000000..2f4cb50de --- /dev/null +++ b/src/main/java/forestry/factory/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/network/PacketRegistryFactory.java b/src/main/java/forestry/factory/network/PacketRegistryFactory.java index 1559886ed..91fb2bd1c 100644 --- a/src/main/java/forestry/factory/network/PacketRegistryFactory.java +++ b/src/main/java/forestry/factory/network/PacketRegistryFactory.java @@ -10,22 +10,23 @@ ******************************************************************************/ package forestry.factory.network; -import forestry.core.network.PacketRegistry; +import forestry.core.network.IPacketRegistry; +import forestry.core.network.PacketIdClient; +import forestry.core.network.PacketIdServer; import forestry.factory.network.packets.PacketRecipeTransferRequest; import forestry.factory.network.packets.PacketRecipeTransferUpdate; import forestry.factory.network.packets.PacketWorktableMemoryUpdate; import forestry.factory.network.packets.PacketWorktableRecipeRequest; import forestry.factory.network.packets.PacketWorktableRecipeUpdate; -public class PacketRegistryFactory extends PacketRegistry { +public class PacketRegistryFactory implements IPacketRegistry { @Override public void registerPackets() { + PacketIdClient.WORKTABLE_MEMORY_UPDATE.setPacketHandler(new PacketWorktableMemoryUpdate.Handler()); + PacketIdClient.WORKTABLE_CRAFTING_UPDATE.setPacketHandler(new PacketWorktableRecipeUpdate.Handler()); + PacketIdClient.RECIPE_TRANSFER_UPDATE.setPacketHandler(new PacketRecipeTransferUpdate.Handler()); - registerClientPacket(new PacketWorktableMemoryUpdate()); - registerClientPacket(new PacketWorktableRecipeUpdate()); - registerClientPacket(new PacketRecipeTransferUpdate()); - - registerServerPacket(new PacketWorktableRecipeRequest()); - registerServerPacket(new PacketRecipeTransferRequest()); + PacketIdServer.WORKTABLE_RECIPE_REQUEST.setPacketHandler(new PacketWorktableRecipeRequest.Handler()); + PacketIdServer.RECIPE_TRANSFER_REQUEST.setPacketHandler(new PacketRecipeTransferRequest.Handler()); } } diff --git a/src/main/java/forestry/factory/network/package-info.java b/src/main/java/forestry/factory/network/package-info.java new file mode 100644 index 000000000..94772af3b --- /dev/null +++ b/src/main/java/forestry/factory/network/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.network; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java index 0bca71f34..ab235141c 100644 --- a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java +++ b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferRequest.java @@ -12,68 +12,67 @@ package forestry.factory.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileBase; import forestry.factory.tiles.TileCarpenter; import forestry.factory.tiles.TileFabricator; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; -public class PacketRecipeTransferRequest extends PacketCoordinates implements IForestryPacketServer { - private ItemStack[] craftingInventory; +public class PacketRecipeTransferRequest extends ForestryPacket implements IForestryPacketServer { + private final BlockPos pos; + private final NonNullList craftingInventory; - public PacketRecipeTransferRequest() { - } - - public PacketRecipeTransferRequest(TileBase base, ItemStack[] craftingInventory) { - super(base); + public PacketRecipeTransferRequest(TileBase base, NonNullList craftingInventory) { + this.pos = base.getPos(); this.craftingInventory = craftingInventory; } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeItemStacks(craftingInventory); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - craftingInventory = data.readItemStacks(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if (tile instanceof TileCarpenter) { - TileCarpenter carpenter = (TileCarpenter) tile; - int index = 0; - for(ItemStack stack : craftingInventory){ - carpenter.getCraftingInventory().setInventorySlotContents(index, stack); - index++; - } - - Proxies.net.sendNetworkPacket(new PacketRecipeTransferUpdate(carpenter, craftingInventory), player.worldObj); - }else if(tile instanceof TileFabricator){ - TileFabricator fabricator = (TileFabricator) tile; - int index = 0; - for(ItemStack stack : craftingInventory){ - fabricator.getCraftingInventory().setInventorySlotContents(index, stack); - index++; - } - - Proxies.net.sendNetworkPacket(new PacketRecipeTransferUpdate(fabricator, craftingInventory), player.worldObj); - } - } - @Override public PacketIdServer getPacketId() { return PacketIdServer.RECIPE_TRANSFER_REQUEST; } + + public static class Handler implements IForestryPacketHandlerServer { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + BlockPos pos = data.readBlockPos(); + NonNullList craftingInventory = data.readItemStacks(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileCarpenter) { + TileCarpenter carpenter = (TileCarpenter) tile; + int index = 0; + for (ItemStack stack : craftingInventory) { + carpenter.getCraftingInventory().setInventorySlotContents(index, stack); + index++; + } + + Proxies.net.sendNetworkPacket(new PacketRecipeTransferUpdate(carpenter, craftingInventory), pos, player.world); + } else if (tile instanceof TileFabricator) { + TileFabricator fabricator = (TileFabricator) tile; + int index = 0; + for (ItemStack stack : craftingInventory) { + fabricator.getCraftingInventory().setInventorySlotContents(index, stack); + index++; + } + + Proxies.net.sendNetworkPacket(new PacketRecipeTransferUpdate(fabricator, craftingInventory), pos, player.world); + } + } + } } diff --git a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java index 709c0ee9f..a05314686 100644 --- a/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketRecipeTransferUpdate.java @@ -12,63 +12,62 @@ package forestry.factory.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.tiles.TileBase; import forestry.factory.tiles.TileCarpenter; import forestry.factory.tiles.TileFabricator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; -public class PacketRecipeTransferUpdate extends PacketCoordinates implements IForestryPacketClient { - private ItemStack[] craftingInventory; +public class PacketRecipeTransferUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final NonNullList craftingInventory; - public PacketRecipeTransferUpdate() { - } - - public PacketRecipeTransferUpdate(TileBase base, ItemStack[] craftingInventory) { - super(base); + public PacketRecipeTransferUpdate(TileBase base, NonNullList craftingInventory) { + this.pos = base.getPos(); this.craftingInventory = craftingInventory; } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); data.writeItemStacks(craftingInventory); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - craftingInventory = data.readItemStacks(); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if (tile instanceof TileCarpenter) { - TileCarpenter carpenter = (TileCarpenter) tile; - int index = 0; - for(ItemStack stack : craftingInventory){ - carpenter.getCraftingInventory().setInventorySlotContents(index, stack); - index++; - } - }else if(tile instanceof TileFabricator){ - TileFabricator fabricator = (TileFabricator) tile; - int index = 0; - for(ItemStack stack : craftingInventory){ - fabricator.getCraftingInventory().setInventorySlotContents(index, stack); - index++; - } - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.RECIPE_TRANSFER_UPDATE; } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + NonNullList craftingInventory = data.readItemStacks(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileCarpenter) { + TileCarpenter carpenter = (TileCarpenter) tile; + int index = 0; + for (ItemStack stack : craftingInventory) { + carpenter.getCraftingInventory().setInventorySlotContents(index, stack); + index++; + } + } else if (tile instanceof TileFabricator) { + TileFabricator fabricator = (TileFabricator) tile; + int index = 0; + for (ItemStack stack : craftingInventory) { + fabricator.getCraftingInventory().setInventorySlotContents(index, stack); + index++; + } + } + } + } } diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java b/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java index c71c0ed68..643c84f40 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableMemoryUpdate.java @@ -12,46 +12,46 @@ package forestry.factory.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; import forestry.factory.recipes.RecipeMemory; import forestry.factory.tiles.TileWorktable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -public class PacketWorktableMemoryUpdate extends PacketCoordinates implements IForestryPacketClient { - - private RecipeMemory recipeMemory; - - public PacketWorktableMemoryUpdate() { - } +public class PacketWorktableMemoryUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final RecipeMemory recipeMemory; public PacketWorktableMemoryUpdate(TileWorktable worktable) { - super(worktable); + this.pos = worktable.getPos(); this.recipeMemory = worktable.getMemory(); } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - recipeMemory.writeData(data); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileWorktable) { - ((TileWorktable) tile).getMemory().readData(data); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.WORKTABLE_MEMORY_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + recipeMemory.writeData(data); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileWorktable) { + ((TileWorktable) tile).getMemory().readData(data); + } + } + } } diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeRequest.java b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeRequest.java index d0bf3153c..26cf8f4cd 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeRequest.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeRequest.java @@ -12,63 +12,62 @@ package forestry.factory.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketCoordinates; import forestry.core.proxy.Proxies; import forestry.factory.gui.ContainerWorktable; import forestry.factory.recipes.MemorizedRecipe; import forestry.factory.tiles.TileWorktable; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; /** * Used to sync the worktable crafting grid from Client to Server. */ -public class PacketWorktableRecipeRequest extends PacketCoordinates implements IForestryPacketServer { - private MemorizedRecipe recipe; - - public PacketWorktableRecipeRequest() { - } +public class PacketWorktableRecipeRequest extends ForestryPacket implements IForestryPacketServer { + private final BlockPos pos; + private final MemorizedRecipe recipe; public PacketWorktableRecipeRequest(TileWorktable worktable, MemorizedRecipe recipe) { - super(worktable); + this.pos = worktable.getPos(); this.recipe = recipe; } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeStreamable(recipe); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - recipe = data.readStreamable(MemorizedRecipe.class); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if (tile instanceof TileWorktable) { - TileWorktable worktable = (TileWorktable) tile; - worktable.setCurrentRecipe(recipe); - - if (player.openContainer instanceof ContainerWorktable) { - ContainerWorktable containerWorktable = (ContainerWorktable) player.openContainer; - containerWorktable.updateCraftMatrix(); - } - - Proxies.net.sendNetworkPacket(new PacketWorktableRecipeUpdate(worktable), player.worldObj); - } - } - @Override public PacketIdServer getPacketId() { return PacketIdServer.WORKTABLE_RECIPE_REQUEST; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + recipe.writeData(data); + } + + public static class Handler implements IForestryPacketHandlerServer { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + BlockPos pos = data.readBlockPos(); + MemorizedRecipe recipe = new MemorizedRecipe(); + recipe.readData(data); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileWorktable) { + TileWorktable worktable = (TileWorktable) tile; + worktable.setCurrentRecipe(recipe); + + if (player.openContainer instanceof ContainerWorktable) { + ContainerWorktable containerWorktable = (ContainerWorktable) player.openContainer; + containerWorktable.updateCraftMatrix(); + } + + Proxies.net.sendNetworkPacket(new PacketWorktableRecipeUpdate(worktable), pos, player.world); + } + } + } } diff --git a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java index e36437694..b47d0b1f1 100644 --- a/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java +++ b/src/main/java/forestry/factory/network/packets/PacketWorktableRecipeUpdate.java @@ -12,54 +12,51 @@ package forestry.factory.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.tileentity.TileEntity; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.core.proxy.Proxies; import forestry.factory.recipes.MemorizedRecipe; import forestry.factory.tiles.TileWorktable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; /** * Used to sync the worktable crafting result from Server to Client. */ -public class PacketWorktableRecipeUpdate extends PacketCoordinates implements IForestryPacketClient { - private MemorizedRecipe recipe; - - public PacketWorktableRecipeUpdate() { - } +public class PacketWorktableRecipeUpdate extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final MemorizedRecipe recipe; public PacketWorktableRecipeUpdate(TileWorktable worktable) { - super(worktable); + this.pos = worktable.getPos(); this.recipe = worktable.getCurrentRecipe(); } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeStreamable(recipe); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - recipe = data.readStreamable(MemorizedRecipe.class); - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(Proxies.common.getRenderWorld()); - if (tile instanceof TileWorktable) { - ((TileWorktable) tile).setCurrentRecipe(recipe); - } - } - @Override public PacketIdClient getPacketId() { return PacketIdClient.WORKTABLE_CRAFTING_UPDATE; } + + @Override + protected void writeData(PacketBufferForestry data) { + data.writeBlockPos(pos); + data.writeStreamable(recipe); + } + + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + MemorizedRecipe recipe = new MemorizedRecipe(); + recipe.readData(data); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileWorktable) { + ((TileWorktable) tile).setCurrentRecipe(recipe); + } + } + } } diff --git a/src/main/java/forestry/factory/network/packets/package-info.java b/src/main/java/forestry/factory/network/packets/package-info.java new file mode 100644 index 000000000..e1bba811b --- /dev/null +++ b/src/main/java/forestry/factory/network/packets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.network.packets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/package-info.java b/src/main/java/forestry/factory/package-info.java new file mode 100644 index 000000000..58ace5c6a --- /dev/null +++ b/src/main/java/forestry/factory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/BottlerRecipe.java b/src/main/java/forestry/factory/recipes/BottlerRecipe.java index 292e8205f..62bdd6d6c 100644 --- a/src/main/java/forestry/factory/recipes/BottlerRecipe.java +++ b/src/main/java/forestry/factory/recipes/BottlerRecipe.java @@ -16,46 +16,39 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.fluids.capability.IFluidHandler; +import net.minecraftforge.fluids.capability.IFluidHandlerItem; public class BottlerRecipe { - - public static BottlerRecipe createFilled(ItemStack filled) { - if (filled == null) { - return null; - } - + @Nullable + public static BottlerRecipe createEmptyingRecipe(ItemStack filled) { ItemStack empty = filled.copy(); - empty.stackSize = 1; - IFluidHandler fluidHandler = FluidUtil.getFluidHandler(empty); + empty.setCount(1); + IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(empty); if (fluidHandler == null) { return null; } FluidStack drained = fluidHandler.drain(Integer.MAX_VALUE, true); if (drained != null && drained.amount > 0) { - return new BottlerRecipe(empty, drained, filled, false); + return new BottlerRecipe(fluidHandler.getContainer(), drained, filled, false); } return null; } - - public static BottlerRecipe createEmpty(Fluid res, ItemStack empty) { - if (res == null || empty == null) { - return null; - } + @Nullable + public static BottlerRecipe createFillingRecipe(Fluid res, ItemStack empty) { ItemStack filled = empty.copy(); - filled.stackSize = 1; + filled.setCount(1); - IFluidHandler fluidHandler = FluidUtil.getFluidHandler(filled); + IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(filled); if (fluidHandler == null) { return null; } int fillAmount = fluidHandler.fill(new FluidStack(res, Integer.MAX_VALUE), true); if (fillAmount > 0) { - return new BottlerRecipe(empty, new FluidStack(res, fillAmount), filled, true); + return new BottlerRecipe(empty, new FluidStack(res, fillAmount), fluidHandler.getContainer(), true); } return null; @@ -63,22 +56,21 @@ public class BottlerRecipe { public final FluidStack fluid; public final ItemStack inputStack; - @Nullable public final ItemStack outputStack; public final boolean fillRecipe; - public BottlerRecipe(ItemStack inputStack, FluidStack fluid, @Nullable ItemStack outputStack, boolean fillRecipe) { + public BottlerRecipe(ItemStack inputStack, FluidStack fluid, ItemStack outputStack, boolean fillRecipe) { this.fluid = fluid; this.inputStack = inputStack; this.outputStack = outputStack; this.fillRecipe = fillRecipe; } - + public boolean matchEmpty(ItemStack emptyCan, FluidStack resource) { - return emptyCan != null && resource != null && emptyCan.isItemEqual(inputStack) && resource.isFluidEqual(fluid) && fillRecipe; + return emptyCan.isEmpty() && emptyCan.isItemEqual(inputStack) && resource.isFluidEqual(fluid) && fillRecipe; } public boolean matchFilled(ItemStack filledCan) { - return outputStack != null && !fillRecipe && outputStack.isItemEqual(filledCan); + return !outputStack.isEmpty() && !fillRecipe && outputStack.isItemEqual(filledCan); } } diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java index 939e26761..c4f7ba5e8 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipe.java @@ -12,6 +12,7 @@ package forestry.factory.recipes; import javax.annotation.Nullable; +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; @@ -25,11 +26,12 @@ public class CarpenterRecipe implements ICarpenterRecipe { private final int packagingTime; @Nullable private final FluidStack liquid; - @Nullable private final ItemStack box; private final ShapedRecipeCustom internal; - public CarpenterRecipe(int packagingTime, @Nullable FluidStack liquid, @Nullable ItemStack box, ShapedRecipeCustom internal) { + public CarpenterRecipe(int packagingTime, @Nullable FluidStack liquid, ItemStack box, ShapedRecipeCustom internal) { + Preconditions.checkNotNull(box); + Preconditions.checkNotNull(internal); this.packagingTime = packagingTime; this.liquid = liquid; this.box = box; @@ -42,7 +44,6 @@ public class CarpenterRecipe implements ICarpenterRecipe { } @Override - @Nullable public ItemStack getBox() { return box; } diff --git a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java index 7ffe37439..5f1fca298 100644 --- a/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/CarpenterRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -43,12 +44,13 @@ public class CarpenterRecipeManager implements ICarpenterManager { } @Override - public void addRecipe(int packagingTime, FluidStack liquid, ItemStack box, ItemStack product, Object materials[]) { + public void addRecipe(int packagingTime, @Nullable FluidStack liquid, ItemStack box, ItemStack product, Object materials[]) { ICarpenterRecipe recipe = new CarpenterRecipe(packagingTime, liquid, box, ShapedRecipeCustom.createShapedRecipe(product, materials)); addRecipe(recipe); } - public static ICarpenterRecipe findMatchingRecipe(FluidStack liquid, ItemStack item, IInventory inventorycrafting) { + @Nullable + public static ICarpenterRecipe findMatchingRecipe(@Nullable FluidStack liquid, ItemStack item, IInventory inventorycrafting) { for (ICarpenterRecipe recipe : recipes) { if (matches(recipe, liquid, item, inventorycrafting)) { return recipe; @@ -57,7 +59,7 @@ public class CarpenterRecipeManager implements ICarpenterManager { return null; } - public static boolean matches(ICarpenterRecipe recipe, FluidStack resource, ItemStack item, IInventory inventoryCrafting) { + public static boolean matches(@Nullable ICarpenterRecipe recipe, @Nullable FluidStack resource, ItemStack item, IInventory inventoryCrafting) { if (recipe == null) { return false; } @@ -70,7 +72,7 @@ public class CarpenterRecipeManager implements ICarpenterManager { } ItemStack box = recipe.getBox(); - if (box != null && !ItemStackUtil.isCraftingEquivalent(box, item)) { + if (!box.isEmpty() && !ItemStackUtil.isCraftingEquivalent(box, item)) { return false; } @@ -79,7 +81,7 @@ public class CarpenterRecipeManager implements ICarpenterManager { } public static boolean isBox(ItemStack resource) { - if (resource == null) { + if (resource.isEmpty()) { return false; } diff --git a/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java b/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java index 6efefb6ac..c4dfc01d0 100644 --- a/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/CentrifugeRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Map; @@ -31,8 +32,9 @@ public class CentrifugeRecipeManager implements ICentrifugeManager { addRecipe(recipe); } + @Nullable public static ICentrifugeRecipe findMatchingRecipe(ItemStack itemStack) { - if (itemStack == null) { + if (itemStack.isEmpty()) { return null; } diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java index 5fe7cff45..c8d1fde5e 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipe.java @@ -10,48 +10,46 @@ ******************************************************************************/ package forestry.factory.recipes; -import javax.annotation.Nullable; - +import com.google.common.base.Preconditions; +import forestry.api.recipes.IFabricatorRecipe; import net.minecraft.item.ItemStack; - +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; -import forestry.api.recipes.IFabricatorRecipe; -import forestry.core.recipes.ShapedRecipeCustom; - public class FabricatorRecipe implements IFabricatorRecipe { - private final ItemStack plan; private final FluidStack molten; - private final ShapedRecipeCustom internal; + private final NonNullList> ingredients; + private final ItemStack result; - public FabricatorRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] ingredients) { - this(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, ingredients)); - } - - public FabricatorRecipe(ItemStack plan, FluidStack molten, ShapedRecipeCustom internal) { + public FabricatorRecipe(ItemStack plan, FluidStack molten, ItemStack result, NonNullList> ingredients) { + Preconditions.checkNotNull(plan); + Preconditions.checkNotNull(molten); + Preconditions.checkNotNull(result); + Preconditions.checkArgument(!result.isEmpty()); + Preconditions.checkNotNull(ingredients); this.plan = plan; this.molten = molten; - this.internal = internal; + this.result = result; + this.ingredients = ingredients; } @Override - public Object[] getIngredients() { - return internal.getIngredients(); + public NonNullList> getIngredients() { + return ingredients; } @Override public int getWidth() { - return internal.getWidth(); + return 3; } @Override public int getHeight() { - return internal.getHeight(); + return 3; } @Override - @Nullable public ItemStack getPlan() { return plan; } @@ -63,6 +61,6 @@ public class FabricatorRecipe implements IFabricatorRecipe { @Override public ItemStack getRecipeOutput() { - return internal.getRecipeOutput(); + return result; } } diff --git a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java index 04a554a1d..209e7e187 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FabricatorRecipeManager.java @@ -10,20 +10,20 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fluids.FluidStack; - import forestry.api.recipes.IFabricatorManager; import forestry.api.recipes.IFabricatorRecipe; import forestry.core.recipes.RecipeUtil; import forestry.core.recipes.ShapedRecipeCustom; import forestry.core.utils.ItemStackUtil; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fluids.FluidStack; public class FabricatorRecipeManager implements IFabricatorManager { @@ -31,15 +31,19 @@ public class FabricatorRecipeManager implements IFabricatorManager { @Override public void addRecipe(ItemStack plan, FluidStack molten, ItemStack result, Object[] pattern) { - IFabricatorRecipe recipe = new FabricatorRecipe(plan, molten, ShapedRecipeCustom.createShapedRecipe(result, pattern)); + ShapedRecipeCustom patternRecipe = new ShapedRecipeCustom(result, pattern); + NonNullList> ingredients = patternRecipe.getIngredients(); + + IFabricatorRecipe recipe = new FabricatorRecipe(plan, molten, result, ingredients); addRecipe(recipe); } + @Nullable public static IFabricatorRecipe findMatchingRecipe(ItemStack plan, IInventory resources) { ItemStack[][] gridResources = RecipeUtil.getResources(resources); for (IFabricatorRecipe recipe : recipes) { - if (recipe.getPlan() != null && !ItemStackUtil.isCraftingEquivalent(recipe.getPlan(), plan)) { + if (!recipe.getPlan().isEmpty() && !ItemStackUtil.isCraftingEquivalent(recipe.getPlan(), plan)) { continue; } if (RecipeUtil.matches(recipe.getIngredients(), recipe.getWidth(), recipe.getHeight(), gridResources)) { diff --git a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java index 796c30a47..611fcc812 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java +++ b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipe.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; @@ -23,12 +24,9 @@ public class FabricatorSmeltingRecipe implements IFabricatorSmeltingRecipe { private final int meltingPoint; public FabricatorSmeltingRecipe(ItemStack resource, FluidStack molten, int meltingPoint) { - if (resource == null) { - throw new IllegalArgumentException("Resource cannot be null"); - } - if (molten == null) { - throw new IllegalArgumentException("Molten cannot be null"); - } + Preconditions.checkNotNull(resource); + Preconditions.checkArgument(!resource.isEmpty()); + Preconditions.checkNotNull(molten); this.resource = resource; this.product = molten; diff --git a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java index 475385a6c..96a3b0027 100644 --- a/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FabricatorSmeltingRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.HashSet; @@ -26,8 +27,9 @@ import forestry.core.utils.ItemStackUtil; public class FabricatorSmeltingRecipeManager implements IFabricatorSmeltingManager { public static final Set recipes = new HashSet<>(); + @Nullable public static IFabricatorSmeltingRecipe findMatchingSmelting(ItemStack resource) { - if (resource == null) { + if (resource.isEmpty()) { return null; } @@ -42,9 +44,6 @@ public class FabricatorSmeltingRecipeManager implements IFabricatorSmeltingManag @Override public void addSmelting(ItemStack resource, FluidStack molten, int meltingPoint) { - if (resource == null || molten == null) { - return; - } addRecipe(new FabricatorSmeltingRecipe(resource, molten, meltingPoint)); } diff --git a/src/main/java/forestry/factory/recipes/FermenterRecipe.java b/src/main/java/forestry/factory/recipes/FermenterRecipe.java index 60dfb8e50..466254642 100644 --- a/src/main/java/forestry/factory/recipes/FermenterRecipe.java +++ b/src/main/java/forestry/factory/recipes/FermenterRecipe.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; @@ -26,21 +27,10 @@ public class FermenterRecipe implements IFermenterRecipe { private final FluidStack fluidResource; public FermenterRecipe(ItemStack resource, int fermentationValue, float modifier, Fluid output, FluidStack fluidResource) { - if (resource == null) { - throw new NullPointerException("Fermenter Resource cannot be null!"); - } - - if (resource.getItem() == null) { - throw new NullPointerException("Fermenter Resource item cannot be null!"); - } - - if (output == null) { - throw new NullPointerException("Fermenter Output cannot be null!"); - } - - if (fluidResource == null) { - throw new NullPointerException("Fermenter Liquid cannot be null!"); - } + Preconditions.checkNotNull(resource, "Fermenter Resource cannot be null!"); + Preconditions.checkArgument(!resource.isEmpty(), "Fermenter Resource item cannot be empty!"); + Preconditions.checkNotNull(output, "Fermenter Output cannot be null!"); + Preconditions.checkNotNull(fluidResource, "Fermenter Liquid cannot be null!"); this.resource = resource; this.fermentationValue = fermentationValue; diff --git a/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java b/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java index 67c89335a..d05852f68 100644 --- a/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/FermenterRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -41,6 +42,7 @@ public class FermenterRecipeManager implements IFermenterManager { addRecipe(resource, fermentationValue, modifier, output, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME)); } + @Nullable public static IFermenterRecipe findMatchingRecipe(ItemStack res, FluidStack liqu) { for (IFermenterRecipe recipe : recipes) { if (matches(recipe, res, liqu)) { @@ -57,11 +59,11 @@ public class FermenterRecipeManager implements IFermenterManager { } FluidStack fluid = recipe.getFluidResource(); - return liqu != null && liqu.isFluidEqual(fluid); + return liqu.isFluidEqual(fluid); } public static boolean isResource(ItemStack resource) { - if (resource == null) { + if (resource.isEmpty()) { return false; } diff --git a/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java b/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java index 251032a31..39b98bfa4 100644 --- a/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java +++ b/src/main/java/forestry/factory/recipes/ISqueezerContainerRecipe.java @@ -20,10 +20,10 @@ public interface ISqueezerContainerRecipe { int getProcessingTime(); - @Nullable ItemStack getRemnants(); float getRemnantsChance(); + @Nullable ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer); } diff --git a/src/main/java/forestry/factory/recipes/MemorizedRecipe.java b/src/main/java/forestry/factory/recipes/MemorizedRecipe.java index 9bd0438c1..bc3b1135e 100644 --- a/src/main/java/forestry/factory/recipes/MemorizedRecipe.java +++ b/src/main/java/forestry/factory/recipes/MemorizedRecipe.java @@ -11,26 +11,24 @@ package forestry.factory.recipes; import java.io.IOException; -import java.util.ArrayList; import java.util.List; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.InventoryUtil; import forestry.core.utils.ItemStackUtil; import forestry.factory.inventory.InventoryCraftingForestry; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; public final class MemorizedRecipe implements INbtWritable, INbtReadable, IStreamable { private final InventoryCraftingForestry craftMatrix = new InventoryCraftingForestry(); - private final List recipeOutputs = new ArrayList<>(); + private final NonNullList recipeOutputs = NonNullList.create(); private int selectedRecipe; private long lastUsed; private boolean locked; @@ -87,7 +85,7 @@ public final class MemorizedRecipe implements INbtWritable, INbtReadable, IStrea public ItemStack getRecipeOutput() { if (recipeOutputs.isEmpty()) { - return null; + return ItemStack.EMPTY; } else { return recipeOutputs.get(selectedRecipe); } @@ -136,7 +134,7 @@ public final class MemorizedRecipe implements INbtWritable, INbtReadable, IStrea /* IStreamable */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeInventory(craftMatrix); data.writeBoolean(locked); data.writeItemStacks(recipeOutputs); @@ -144,7 +142,7 @@ public final class MemorizedRecipe implements INbtWritable, INbtReadable, IStrea } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { data.readInventory(craftMatrix); locked = data.readBoolean(); data.readItemStacks(recipeOutputs); diff --git a/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java b/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java index e7eb2ae1f..ed7cba3b2 100644 --- a/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/MoistenerRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -31,7 +32,7 @@ public class MoistenerRecipeManager implements IMoistenerManager { } public static boolean isResource(ItemStack resource) { - if (resource == null) { + if (resource.isEmpty()) { return false; } @@ -44,6 +45,7 @@ public class MoistenerRecipeManager implements IMoistenerManager { return false; } + @Nullable public static IMoistenerRecipe findMatchingRecipe(ItemStack item) { for (IMoistenerRecipe recipe : recipes) { if (ItemStackUtil.isCraftingEquivalent(recipe.getResource(), item)) { diff --git a/src/main/java/forestry/factory/recipes/RecipeMemory.java b/src/main/java/forestry/factory/recipes/RecipeMemory.java index 71358c354..a944ee62f 100644 --- a/src/main/java/forestry/factory/recipes/RecipeMemory.java +++ b/src/main/java/forestry/factory/recipes/RecipeMemory.java @@ -10,13 +10,16 @@ ******************************************************************************/ package forestry.factory.recipes; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import forestry.api.core.INbtWritable; +import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import net.minecraft.item.Item; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; @@ -24,11 +27,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; -import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IStreamable; - public class RecipeMemory implements INbtWritable, IStreamable { private static final int capacity = 9; @@ -46,7 +44,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { memorizedRecipes = new LinkedList<>(); } - public RecipeMemory(@Nonnull NBTTagCompound nbt) { + public RecipeMemory(NBTTagCompound nbt) { memorizedRecipes = new LinkedList<>(); if (!nbt.hasKey("RecipeMemory")) { return; @@ -61,16 +59,16 @@ public class RecipeMemory implements INbtWritable, IStreamable { } } - private static boolean isValid(MemorizedRecipe recipe) { + private static boolean isValid(@Nullable MemorizedRecipe recipe) { if (recipe == null) { return false; } ItemStack recipeOutput = recipe.getRecipeOutput(); - if (recipeOutput == null) { + if (recipeOutput.isEmpty()) { return false; } Item item = recipeOutput.getItem(); - return item != null && !memoryBlacklist.contains(item.getClass()); + return !memoryBlacklist.contains(item.getClass()); } public void validate(World world) { @@ -129,6 +127,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { memorizedRecipes.set(index, updatedRecipe); } + @Nullable private MemorizedRecipe getOldestUnlockedRecipe() { MemorizedRecipe oldest = null; for (MemorizedRecipe existing : memorizedRecipes) { @@ -143,6 +142,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { return oldest; } + @Nullable public MemorizedRecipe getRecipe(int recipeIndex) { if (recipeIndex < 0 || recipeIndex >= memorizedRecipes.size()) { return null; @@ -150,6 +150,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { return memorizedRecipes.get(recipeIndex); } + @Nullable public ItemStack getRecipeDisplayOutput(int recipeIndex) { MemorizedRecipe recipe = getRecipe(recipeIndex); if (recipe == null) { @@ -160,10 +161,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { public boolean isLocked(int recipeIndex) { MemorizedRecipe recipe = getRecipe(recipeIndex); - if (recipe == null) { - return false; - } - return recipe.isLocked(); + return recipe != null && recipe.isLocked(); } public void toggleLock(long worldTime, int recipeIndex) { @@ -173,6 +171,7 @@ public class RecipeMemory implements INbtWritable, IStreamable { } } + @Nullable private MemorizedRecipe getExistingMemorizedRecipe(ItemStack craftingRecipeOutput) { for (MemorizedRecipe memorizedRecipe : memorizedRecipes) { if (memorizedRecipe.hasRecipeOutput(craftingRecipeOutput)) { @@ -198,12 +197,12 @@ public class RecipeMemory implements INbtWritable, IStreamable { } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeStreamables(memorizedRecipes); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { data.readStreamables(memorizedRecipes, MemorizedRecipe.class); } } diff --git a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java index a5031e3bc..a51380769 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerContainerRecipe.java @@ -12,9 +12,11 @@ package forestry.factory.recipes; import javax.annotation.Nullable; +import com.google.common.base.Preconditions; import forestry.api.recipes.ISqueezerRecipe; import forestry.core.utils.ItemStackUtil; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; @@ -22,11 +24,14 @@ public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { private final ItemStack emptyContainer; private final int processingTime; - @Nullable private final ItemStack remnants; private final float remnantsChance; - public SqueezerContainerRecipe(ItemStack emptyContainer, int processingTime, @Nullable ItemStack remnants, float remnantsChance) { + public SqueezerContainerRecipe(ItemStack emptyContainer, int processingTime, ItemStack remnants, float remnantsChance) { + Preconditions.checkNotNull(emptyContainer); + Preconditions.checkArgument(!emptyContainer.isEmpty()); + Preconditions.checkNotNull(remnants); + this.emptyContainer = emptyContainer; this.processingTime = processingTime; this.remnants = remnants; @@ -43,7 +48,6 @@ public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { return processingTime; } - @Nullable @Override public ItemStack getRemnants() { return remnants; @@ -55,16 +59,19 @@ public class SqueezerContainerRecipe implements ISqueezerContainerRecipe { } @Override + @Nullable public ISqueezerRecipe getSqueezerRecipe(ItemStack filledContainer) { - if (filledContainer == null) { + if (filledContainer.isEmpty()) { return null; } FluidStack fluidOutput = FluidUtil.getFluidContained(filledContainer); if (fluidOutput == null) { return null; } - ItemStack filledContainerCopy = ItemStackUtil.createSplitStack(filledContainer, 1); - return new SqueezerRecipe(processingTime, new ItemStack[]{filledContainerCopy}, fluidOutput, remnants, remnantsChance); + ItemStack filledContainerCopy = ItemStackUtil.createCopyWithCount(filledContainer, 1); + NonNullList input = NonNullList.create(); + input.add(filledContainerCopy); + return new SqueezerRecipe(processingTime, input, fluidOutput, remnants, remnantsChance); } } diff --git a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java index 1093b2873..de33d7905 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerRecipe.java +++ b/src/main/java/forestry/factory/recipes/SqueezerRecipe.java @@ -10,10 +10,10 @@ ******************************************************************************/ package forestry.factory.recipes; -import javax.annotation.Nullable; - +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; import forestry.api.recipes.ISqueezerRecipe; @@ -21,13 +21,17 @@ import forestry.api.recipes.ISqueezerRecipe; public class SqueezerRecipe implements ISqueezerRecipe { private final int processingTime; - private final ItemStack[] resources; + private final NonNullList resources; private final FluidStack fluidOutput; - @Nullable private final ItemStack remnants; private final float remnantsChance; - public SqueezerRecipe(int processingTime, ItemStack[] resources, FluidStack fluidOutput, @Nullable ItemStack remnants, float remnantsChance) { + public SqueezerRecipe(int processingTime, NonNullList resources, FluidStack fluidOutput, ItemStack remnants, float remnantsChance) { + Preconditions.checkNotNull(resources); + Preconditions.checkArgument(!resources.isEmpty()); + Preconditions.checkNotNull(fluidOutput); + Preconditions.checkNotNull(remnants); + this.processingTime = processingTime; this.resources = resources; this.fluidOutput = fluidOutput; @@ -36,12 +40,11 @@ public class SqueezerRecipe implements ISqueezerRecipe { } @Override - public ItemStack[] getResources() { + public NonNullList getResources() { return resources; } @Override - @Nullable public ItemStack getRemnants() { return remnants; } diff --git a/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java b/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java index d9b64013b..e5585adb0 100644 --- a/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/SqueezerRecipeManager.java @@ -17,6 +17,7 @@ import java.util.Set; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; import forestry.api.recipes.ISqueezerManager; @@ -31,18 +32,32 @@ public class SqueezerRecipeManager implements ISqueezerManager { public static final ItemStackMap containerRecipes = new ItemStackMap<>(); @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid, @Nullable ItemStack remnants, int chance) { + public void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid, ItemStack remnants, int chance) { ISqueezerRecipe recipe = new SqueezerRecipe(timePerItem, resources, liquid, remnants, chance / 100.0f); addRecipe(recipe); } @Override - public void addRecipe(int timePerItem, ItemStack[] resources, FluidStack liquid) { - addRecipe(timePerItem, resources, liquid, null, 0); + public void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid, ItemStack remnants, int chance) { + NonNullList resourcesList = NonNullList.create(); + resourcesList.add(resources); + addRecipe(timePerItem, resourcesList, liquid, remnants, chance); } @Override - public void addContainerRecipe(int timePerItem, ItemStack emptyContainer, @Nullable ItemStack remnants, float chance) { + public void addRecipe(int timePerItem, NonNullList resources, FluidStack liquid) { + addRecipe(timePerItem, resources, liquid, ItemStack.EMPTY, 0); + } + + @Override + public void addRecipe(int timePerItem, ItemStack resources, FluidStack liquid) { + NonNullList resourcesList = NonNullList.create(); + resourcesList.add(resources); + addRecipe(timePerItem, resourcesList, liquid); + } + + @Override + public void addContainerRecipe(int timePerItem, ItemStack emptyContainer, ItemStack remnants, float chance) { containerRecipes.put(emptyContainer, new SqueezerContainerRecipe(emptyContainer, timePerItem, remnants, chance)); } @@ -55,7 +70,8 @@ public class SqueezerRecipeManager implements ISqueezerManager { return containerRecipes.get(new ItemStack(filledContainer.getItem())); } - public static ISqueezerRecipe findMatchingRecipe(ItemStack[] items) { + @Nullable + public static ISqueezerRecipe findMatchingRecipe(NonNullList items) { // Find container recipes for (ItemStack itemStack : items) { ISqueezerContainerRecipe containerRecipe = findMatchingContainerRecipe(itemStack); diff --git a/src/main/java/forestry/factory/recipes/StillRecipe.java b/src/main/java/forestry/factory/recipes/StillRecipe.java index 183ac6757..825ab6af3 100644 --- a/src/main/java/forestry/factory/recipes/StillRecipe.java +++ b/src/main/java/forestry/factory/recipes/StillRecipe.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import com.google.common.base.Preconditions; import net.minecraftforge.fluids.FluidStack; import forestry.api.recipes.IStillRecipe; @@ -20,13 +21,10 @@ public class StillRecipe implements IStillRecipe { private final FluidStack output; public StillRecipe(int timePerUnit, FluidStack input, FluidStack output) { + Preconditions.checkNotNull(input, "Still recipes need an input. Input was null."); + Preconditions.checkNotNull(output, "Still recipes need an output. Output was null."); + this.timePerUnit = timePerUnit; - if (input == null) { - throw new IllegalArgumentException("Still recipes need an input. Input was null."); - } - if (output == null) { - throw new IllegalArgumentException("Still recipes need an output. Output was null."); - } this.input = input; this.output = output; } diff --git a/src/main/java/forestry/factory/recipes/StillRecipeManager.java b/src/main/java/forestry/factory/recipes/StillRecipeManager.java index b244a275b..22d139111 100644 --- a/src/main/java/forestry/factory/recipes/StillRecipeManager.java +++ b/src/main/java/forestry/factory/recipes/StillRecipeManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.factory.recipes; +import javax.annotation.Nullable; import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -32,7 +33,8 @@ public class StillRecipeManager implements IStillManager { addRecipe(recipe); } - public static IStillRecipe findMatchingRecipe(FluidStack item) { + @Nullable + public static IStillRecipe findMatchingRecipe(@Nullable FluidStack item) { if (item == null) { return null; } @@ -44,7 +46,7 @@ public class StillRecipeManager implements IStillManager { return null; } - public static boolean matches(IStillRecipe recipe, FluidStack item) { + public static boolean matches(@Nullable IStillRecipe recipe, @Nullable FluidStack item) { if (recipe == null || item == null) { return false; } diff --git a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java index 618a7cf17..03f720092 100644 --- a/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java +++ b/src/main/java/forestry/factory/recipes/jei/FactoryJeiPlugin.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.awt.Rectangle; import java.util.List; @@ -61,10 +60,11 @@ import net.minecraft.item.ItemStack; @JEIPlugin public class FactoryJeiPlugin extends BlankModPlugin { + @Nullable public static IJeiHelpers jeiHelpers; @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { jeiHelpers = registry.getJeiHelpers(); IGuiHelper guiHelper = jeiHelpers.getGuiHelper(); @@ -79,7 +79,7 @@ public class FactoryJeiPlugin extends BlankModPlugin { new SqueezerRecipeCategory(guiHelper), new StillRecipeCategory(guiHelper) ); - + registry.addRecipeHandlers( new BottlerRecipeHandler(), new CarpenterRecipeHandler(), @@ -101,7 +101,7 @@ public class FactoryJeiPlugin extends BlankModPlugin { registry.addRecipes(MoistenerRecipeMaker.getMoistenerRecipes()); registry.addRecipes(RainmakerRecipeMaker.getRecipes()); registry.addRecipes(SqueezerRecipeMaker.getSqueezerRecipes()); - registry.addRecipes(SqueezerRecipeMaker.getSqueezerContainerRecipes()); + registry.addRecipes(SqueezerRecipeMaker.getSqueezerContainerRecipes(registry.getIngredientRegistry())); registry.addRecipes(StillRecipeMaker.getStillRecipes()); registry.addRecipeClickArea(GuiBottler.class, 107, 33, 26, 22, ForestryRecipeCategoryUid.BOTTLER); @@ -129,9 +129,9 @@ public class FactoryJeiPlugin extends BlankModPlugin { registry.addRecipeCategoryCraftingItem(new ItemStack(blocks.worktable), VanillaRecipeCategoryUid.CRAFTING); IRecipeTransferRegistry transferRegistry = registry.getRecipeTransferRegistry(); - transferRegistry.addRecipeTransferHandler(new WorktableRecipeTransferHandler()); - transferRegistry.addRecipeTransferHandler(new CarpenterRecipeTransferHandler()); - transferRegistry.addRecipeTransferHandler(new FabricatorRecipeTransferHandler()); + transferRegistry.addRecipeTransferHandler(new WorktableRecipeTransferHandler(), VanillaRecipeCategoryUid.CRAFTING); + transferRegistry.addRecipeTransferHandler(new CarpenterRecipeTransferHandler(), ForestryRecipeCategoryUid.CARPENTER); + transferRegistry.addRecipeTransferHandler(new FabricatorRecipeTransferHandler(), ForestryRecipeCategoryUid.FABRICATOR); registry.addAdvancedGuiHandlers(new ForestryAdvancedGuiHandler()); @@ -142,7 +142,7 @@ public class FactoryJeiPlugin extends BlankModPlugin { } private static class ForestryAdvancedGuiHandler extends BlankAdvancedGuiHandler { - @Nonnull + @Override public Class getGuiContainerClass() { return GuiForestry.class; @@ -151,8 +151,7 @@ public class FactoryJeiPlugin extends BlankModPlugin { @Nullable @Override public List getGuiExtraAreas(GuiForestry guiContainer) { - GuiForestry guiForestry = guiContainer; - return guiForestry.getExtraGuiAreas(); + return ((GuiForestry) guiContainer).getExtraGuiAreas(); } @Nullable diff --git a/src/main/java/forestry/factory/recipes/jei/WorktableRecipeTransferHandler.java b/src/main/java/forestry/factory/recipes/jei/WorktableRecipeTransferHandler.java index fa91fd4b0..8a875ec09 100644 --- a/src/main/java/forestry/factory/recipes/jei/WorktableRecipeTransferHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/WorktableRecipeTransferHandler.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.List; @@ -11,7 +10,6 @@ import forestry.factory.inventory.InventoryCraftingForestry; import forestry.factory.recipes.MemorizedRecipe; import mezz.jei.api.gui.IGuiIngredient; import mezz.jei.api.gui.IRecipeLayout; -import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import mezz.jei.api.recipe.transfer.IRecipeTransferError; import mezz.jei.api.recipe.transfer.IRecipeTransferHandler; import net.minecraft.entity.player.EntityPlayer; @@ -23,14 +21,9 @@ class WorktableRecipeTransferHandler implements IRecipeTransferHandler> guiIngredients = recipeLayout.getItemStacks().getGuiIngredients(); InventoryCraftingForestry inventory = new InventoryCraftingForestry(container); diff --git a/src/main/java/forestry/factory/recipes/jei/bottler/BottlerRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/bottler/BottlerRecipeHandler.java index 89678b346..ce177e259 100644 --- a/src/main/java/forestry/factory/recipes/jei/bottler/BottlerRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/bottler/BottlerRecipeHandler.java @@ -11,11 +11,6 @@ public class BottlerRecipeHandler implements IRecipeHandler getBottlerRecipes(IIngredientRegistry ingredientRegistry) { List recipes = new ArrayList<>(); + for (ItemStack stack : ingredientRegistry.getIngredients(ItemStack.class)) { + if (stack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null)) { + IFluidHandlerItem fluidHandler = stack.copy().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); + if (fluidHandler != null) { + final boolean canDrain = canDrain(fluidHandler); + final boolean canFill = canFill(fluidHandler); - ImmutableList ingredients = ingredientRegistry.getIngredients(ItemStack.class); - - for (ItemStack ingredient : ingredients) { - if (ingredient.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null)) { - FluidStack drain; - - ItemStack emptyStack = ingredient.copy(); - IFluidHandler emptyCapability = emptyStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null); - drain = emptyCapability.drain(Constants.PROCESSOR_TANK_CAPACITY, true); - if (drain != null) { - if (emptyStack.stackSize == 0) { - emptyStack = null; + if (canDrain) { + FluidStack drainedFluid = fluidHandler.drain(Integer.MAX_VALUE, true); + if (drainedFluid != null) { + ItemStack drained = fluidHandler.getContainer(); + recipes.add(new BottlerRecipeWrapper(stack, drainedFluid, drained, false)); + } } - recipes.add(new BottlerRecipeWrapper(ingredient, drain, emptyStack, false)); - addFillRecipe(ingredient, drain.getFluid(), recipes); - } else { - for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { - addFillRecipe(ingredient, fluid, recipes); + + if (canFill) { + for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { + IFluidHandlerItem fillingCapability = stack.copy().getCapability(CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null); + if (fillingCapability != null) { + int fill = fillingCapability.fill(new FluidStack(fluid, Integer.MAX_VALUE), true); + if (fill > 0) { + FluidStack filledFluid = new FluidStack(fluid, fill); + ItemStack filled = fluidHandler.getContainer(); + recipes.add(new BottlerRecipeWrapper(stack, filledFluid, filled, true)); + } + } else { + break; + } + } } } } @@ -46,13 +56,21 @@ public class BottlerRecipeMaker { return recipes; } - private static void addFillRecipe(ItemStack ingredient, Fluid fluid, List recipes) { - ItemStack fillStack = ingredient.copy(); - IFluidHandler fillCapability = fillStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null); - int fill = fillCapability.fill(new FluidStack(fluid, Constants.PROCESSOR_TANK_CAPACITY), true); - if (fill > 0) { - FluidStack filledFluid = new FluidStack(fluid, fill); - recipes.add(new BottlerRecipeWrapper(ingredient, filledFluid, fillStack, true)); + private static boolean canDrain(IFluidHandler fluidHandler) { + for (IFluidTankProperties properties : fluidHandler.getTankProperties()) { + if (properties.canDrain()) { + return true; + } } + return false; + } + + private static boolean canFill(IFluidHandler fluidHandler) { + for (IFluidTankProperties properties : fluidHandler.getTankProperties()) { + if (properties.canFill()) { + return true; + } + } + return false; } } diff --git a/src/main/java/forestry/factory/recipes/jei/bottler/package-info.java b/src/main/java/forestry/factory/recipes/jei/bottler/package-info.java index 50968bada..22a0cbf39 100644 --- a/src/main/java/forestry/factory/recipes/jei/bottler/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/bottler/package-info.java @@ -1,7 +1,9 @@ @ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault @MethodsReturnNonnullByDefault package forestry.factory.recipes.jei.bottler; import javax.annotation.ParametersAreNonnullByDefault; +import forestry.core.utils.FieldsAreNonnullByDefault; import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java index f9760b33a..d072468a2 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeCategory.java @@ -1,7 +1,6 @@ package forestry.factory.recipes.jei.carpenter; -import javax.annotation.Nonnull; -import java.util.Arrays; +import java.util.ArrayList; import java.util.List; import forestry.api.recipes.ICarpenterRecipe; @@ -9,7 +8,6 @@ import forestry.api.recipes.IDescriptiveRecipe; import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.core.render.ForestryResource; -import forestry.factory.recipes.jei.FactoryJeiPlugin; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.ICraftingGridHelper; import mezz.jei.api.gui.IDrawable; @@ -19,9 +17,9 @@ import mezz.jei.api.gui.IGuiFluidStackGroup; import mezz.jei.api.gui.IGuiItemStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IStackHelper; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; @@ -30,70 +28,70 @@ public class CarpenterRecipeCategory extends ForestryRecipeCategory outputs = ingredients.getOutputs(ItemStack.class); - craftingGridHelper.setOutput(guiItemStacks, outputs); + List> outputs = ingredients.getOutputs(ItemStack.class); + guiItemStacks.set(craftOutputSlot, outputs.get(0)); IDescriptiveRecipe craftingGridRecipe = recipe.getCraftingGridRecipe(); - List inputs = Arrays.asList(craftingGridRecipe.getIngredients()); - IStackHelper stackHelper = FactoryJeiPlugin.jeiHelpers.getStackHelper(); - List> craftInputs = stackHelper.expandRecipeItemStackInputs(inputs); - craftingGridHelper.setInputStacks(guiItemStacks, craftInputs, craftingGridRecipe.getWidth(), craftingGridRecipe.getHeight()); + NonNullList> inputs = craftingGridRecipe.getIngredients(); + List> inputStacks = new ArrayList<>(); + for (List stacks : inputs) { + List copy = new ArrayList<>(); + copy.addAll(stacks); + inputStacks.add(copy); + } + craftingGridHelper.setInputs(guiItemStacks, inputStacks, craftingGridRecipe.getWidth(), craftingGridRecipe.getHeight()); List> fluidInputs = ingredients.getInputs(FluidStack.class); if (!fluidInputs.isEmpty()) { diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeHandler.java index 5bb7be15b..6277317fb 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeHandler.java @@ -1,7 +1,5 @@ package forestry.factory.recipes.jei.carpenter; -import javax.annotation.Nonnull; - import forestry.api.recipes.ICarpenterRecipe; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; @@ -9,44 +7,29 @@ import mezz.jei.api.recipe.IRecipeHandler; import mezz.jei.api.recipe.IRecipeWrapper; public class CarpenterRecipeHandler implements IRecipeHandler { - - @Nonnull + @Override public Class getRecipeClass() { return CarpenterRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid( CarpenterRecipeWrapper recipe) { return ForestryRecipeCategoryUid.CARPENTER; } - - @Nonnull + @Override - public String getRecipeCategoryUid(@Nonnull CarpenterRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.CARPENTER; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull CarpenterRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper( CarpenterRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull CarpenterRecipeWrapper wrapper) { + public boolean isRecipeValid( CarpenterRecipeWrapper wrapper) { ICarpenterRecipe recipe = wrapper.getRecipe(); if (recipe.getPackagingTime() <= 0) { return false; } - if (recipe.getCraftingGridRecipe() == null || recipe.getCraftingGridRecipe().getIngredients() == null) { - return false; - } - int inputCount = 0; - for (Object ingredient : recipe.getCraftingGridRecipe().getIngredients()) { - inputCount++; - } + int inputCount = recipe.getCraftingGridRecipe().getIngredients().size(); return inputCount > 0; } diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java index 29a3d1fde..cf896651c 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeTransferHandler.java @@ -3,7 +3,6 @@ package forestry.factory.recipes.jei.carpenter; import java.util.Map.Entry; import forestry.core.proxy.Proxies; -import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.factory.gui.ContainerCarpenter; import forestry.factory.network.packets.PacketRecipeTransferRequest; import mezz.jei.api.gui.IGuiIngredient; @@ -13,6 +12,7 @@ import mezz.jei.api.recipe.transfer.IRecipeTransferHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public class CarpenterRecipeTransferHandler implements IRecipeTransferHandler { @@ -21,24 +21,19 @@ public class CarpenterRecipeTransferHandler implements IRecipeTransferHandler items = NonNullList.withSize(9, ItemStack.EMPTY); for(Entry> guiIngredientEntry : recipeLayout.getItemStacks().getGuiIngredients().entrySet()){ IGuiIngredient guiIngredient = guiIngredientEntry.getValue(); - if(guiIngredientEntry != null && guiIngredient.getDisplayedIngredient() != null){ + if(guiIngredient != null && guiIngredient.getDisplayedIngredient() != null){ int index = guiIngredientEntry.getKey(); if (index >= 2) { ItemStack ingredient = guiIngredient.getDisplayedIngredient().copy(); craftingInventory.setInventorySlotContents(index - 2, ingredient); - items[index - 2] = ingredient; + items.set(index - 2, ingredient); } } } diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeWrapper.java index b27abdd54..86ef8a707 100644 --- a/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/CarpenterRecipeWrapper.java @@ -1,35 +1,38 @@ package forestry.factory.recipes.jei.carpenter; -import javax.annotation.Nonnull; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import forestry.api.recipes.ICarpenterRecipe; import forestry.api.recipes.IDescriptiveRecipe; import forestry.core.recipes.jei.ForestryRecipeWrapper; -import forestry.factory.recipes.jei.FactoryJeiPlugin; import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IStackHelper; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; public class CarpenterRecipeWrapper extends ForestryRecipeWrapper { - - public CarpenterRecipeWrapper(@Nonnull ICarpenterRecipe recipe) { + + public CarpenterRecipeWrapper(ICarpenterRecipe recipe) { super(recipe); } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { ICarpenterRecipe recipe = getRecipe(); IDescriptiveRecipe craftingGridRecipe = recipe.getCraftingGridRecipe(); - Object[] inputs = craftingGridRecipe.getIngredients(); - IStackHelper stackHelper = FactoryJeiPlugin.jeiHelpers.getStackHelper(); + NonNullList> inputs = craftingGridRecipe.getIngredients(); + + List> inputStacks = new ArrayList<>(); + for (List stacks : inputs) { + List copy = new ArrayList<>(); + copy.addAll(stacks); + inputStacks.add(copy); + } - List> inputStacks = stackHelper.expandRecipeItemStackInputs(Arrays.asList(inputs)); ItemStack box = recipe.getBox(); - if (box != null) { + if (!box.isEmpty()) { inputStacks.add(Collections.singletonList(box)); } ingredients.setInputLists(ItemStack.class, inputStacks); diff --git a/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java b/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java new file mode 100644 index 000000000..02bc7798f --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/carpenter/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.carpenter; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java index 0d57230cc..c7aeaff94 100644 --- a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeCategory.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.centrifuge; -import javax.annotation.Nonnull; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -26,44 +25,38 @@ import net.minecraft.util.ResourceLocation; public class CentrifugeRecipeCategory extends ForestryRecipeCategory { private static final int[][] OUTPUTS = new int[][]{{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; - - private static final Comparator> highestChanceComparator = new Comparator>() { - @Override - public int compare(Entry o1, Entry o2) { - return o2.getValue().compareTo(o1.getValue()); - } - }; - + + private static final Comparator> highestChanceComparator = (o1, o2) -> o2.getValue().compareTo(o1.getValue()); + private static final int inputSlot = 0; private static final int outputSlot = 1; - + private final static ResourceLocation guiTexture = new ForestryResource("textures/gui/centrifugesocket2.png"); - @Nonnull private final IDrawableAnimated arrow; public CentrifugeRecipeCategory(IGuiHelper guiHelper) { super(guiHelper.createDrawable(guiTexture, 11, 18, 154, 54), "tile.for.centrifuge.name"); - + IDrawableStatic arrowDrawable = guiHelper.createDrawable(guiTexture, 176, 0, 4, 17); this.arrow = guiHelper.createAnimatedDrawable(arrowDrawable, 80, IDrawableAnimated.StartDirection.BOTTOM, false); } - - @Nonnull + + @Override public String getUid() { return ForestryRecipeCategoryUid.CENTRIFUGE; } @Override - public void drawAnimations(@Nonnull Minecraft minecraft) { + public void drawExtras(Minecraft minecraft) { arrow.draw(minecraft, 32, 18); arrow.draw(minecraft, 56, 18); } @Override - public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull CentrifugeRecipeWrapper recipeWrapper, @Nonnull IIngredients ingredients) { + public void setRecipe(IRecipeLayout recipeLayout, CentrifugeRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks(); - + guiItemStacks.init(inputSlot, true, 4, 18); List> inputs = ingredients.getInputs(ItemStack.class); guiItemStacks.set(inputSlot, inputs.get(0)); @@ -73,7 +66,7 @@ public class CentrifugeRecipeCategory extends ForestryRecipeCategory outputs, IGuiItemStackGroup guiItemStacks) { Set> entrySet = outputs.entrySet(); if (entrySet.isEmpty()) { diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeHandler.java index 8b5d517f8..e536d644c 100644 --- a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeHandler.java @@ -1,54 +1,37 @@ package forestry.factory.recipes.jei.centrifuge; -import javax.annotation.Nonnull; - -import net.minecraft.item.ItemStack; - import forestry.api.recipes.ICentrifugeRecipe; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; - import mezz.jei.api.recipe.IRecipeHandler; import mezz.jei.api.recipe.IRecipeWrapper; public class CentrifugeRecipeHandler implements IRecipeHandler { - - @Nonnull + @Override public Class getRecipeClass() { return CentrifugeRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(CentrifugeRecipeWrapper recipe) { return ForestryRecipeCategoryUid.CENTRIFUGE; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull CentrifugeRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.CENTRIFUGE; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull CentrifugeRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper(CentrifugeRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull CentrifugeRecipeWrapper wrapper) { + public boolean isRecipeValid(CentrifugeRecipeWrapper wrapper) { ICentrifugeRecipe recipe = wrapper.getRecipe(); if (recipe.getProcessingTime() <= 0) { return false; } - if (recipe.getInput() == null) { + if (recipe.getInput().isEmpty()) { return false; } - int inputCount = 0; - for (ItemStack ingredient : recipe.getAllProducts().keySet()) { - inputCount++; - } + int inputCount = recipe.getAllProducts().keySet().size(); return inputCount > 0; } diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeWrapper.java index 02afc7387..5ef13afb8 100644 --- a/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/CentrifugeRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.centrifuge; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.Set; @@ -11,13 +10,12 @@ import mezz.jei.api.ingredients.IIngredients; import net.minecraft.item.ItemStack; public class CentrifugeRecipeWrapper extends ForestryRecipeWrapper { - - public CentrifugeRecipeWrapper(@Nonnull ICentrifugeRecipe recipe) { + public CentrifugeRecipeWrapper(ICentrifugeRecipe recipe) { super(recipe); } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { ICentrifugeRecipe recipe = getRecipe(); ingredients.setInputs(ItemStack.class, Collections.singletonList(recipe.getInput())); diff --git a/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java b/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java new file mode 100644 index 000000000..e71fae646 --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/centrifuge/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.centrifuge; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java index 24f563e28..eae72317f 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeCategory.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.fabricator; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -29,49 +28,47 @@ public class FabricatorRecipeCategory extends ForestryRecipeCategory itemOutputs = ingredients.getOutputs(ItemStack.class); - craftingGridHelper.setOutput(guiItemStacks, itemOutputs); + List> itemOutputs = ingredients.getOutputs(ItemStack.class); + guiItemStacks.set(craftOutputSlot, itemOutputs.get(0)); List> itemStackInputs = ingredients.getInputs(ItemStack.class); - craftingGridHelper.setInputStacks(guiItemStacks, itemStackInputs, recipe.getWidth(), recipe.getHeight()); + craftingGridHelper.setInputs(guiItemStacks, itemStackInputs, recipe.getWidth(), recipe.getHeight()); List> fluidInputs = ingredients.getInputs(FluidStack.class); if (!fluidInputs.isEmpty()) { guiFluidStacks.set(inputTank, fluidInputs.get(0)); } } - + private static Map> getSmeltingInputs() { Map> smeltingInputs = new HashMap<>(); for (IFabricatorSmeltingRecipe smelting : FabricatorSmeltingRecipeManager.recipes) { diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeHandler.java index 79348c860..755733178 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeHandler.java @@ -1,55 +1,30 @@ package forestry.factory.recipes.jei.fabricator; -import javax.annotation.Nonnull; - import forestry.api.recipes.IFabricatorRecipe; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; - import mezz.jei.api.recipe.IRecipeHandler; import mezz.jei.api.recipe.IRecipeWrapper; public class FabricatorRecipeHandler implements IRecipeHandler { - - @Nonnull @Override public Class getRecipeClass() { return FabricatorRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(FabricatorRecipeWrapper recipe) { return ForestryRecipeCategoryUid.FABRICATOR; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull FabricatorRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.FABRICATOR; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull FabricatorRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper(FabricatorRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull FabricatorRecipeWrapper wrapper) { + public boolean isRecipeValid(FabricatorRecipeWrapper wrapper) { IFabricatorRecipe recipe = wrapper.getRecipe(); - if (recipe.getIngredients() == null) { - return false; - } - if (recipe.getLiquid() == null) { - return false; - } - if (recipe.getRecipeOutput() == null) { - return false; - } - int inputCount = 0; - for (Object ingredient : recipe.getIngredients()) { - inputCount++; - } + int inputCount = recipe.getIngredients().size(); return inputCount > 0; } diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java index 663bd9dd6..be16e5579 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeTransferHandler.java @@ -3,7 +3,6 @@ package forestry.factory.recipes.jei.fabricator; import java.util.Map.Entry; import forestry.core.proxy.Proxies; -import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.factory.gui.ContainerFabricator; import forestry.factory.network.packets.PacketRecipeTransferRequest; import mezz.jei.api.gui.IGuiIngredient; @@ -13,6 +12,7 @@ import mezz.jei.api.recipe.transfer.IRecipeTransferHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; public class FabricatorRecipeTransferHandler implements IRecipeTransferHandler { @@ -21,24 +21,19 @@ public class FabricatorRecipeTransferHandler implements IRecipeTransferHandler> guiIngredientEntry : recipeLayout.getItemStacks().getGuiIngredients().entrySet()){ + NonNullList items = NonNullList.withSize(9, ItemStack.EMPTY); + for (Entry> guiIngredientEntry : recipeLayout.getItemStacks().getGuiIngredients().entrySet()) { IGuiIngredient guiIngredient = guiIngredientEntry.getValue(); int index = guiIngredientEntry.getKey(); - if (index >= 3 && guiIngredientEntry != null && guiIngredient.getDisplayedIngredient() != null) { - ItemStack ingredient =guiIngredient.getDisplayedIngredient().copy(); - craftingInventory.setInventorySlotContents(index - 3, ingredient); - items[index - 3] = ingredient; - } + if (index >= 3 && guiIngredient.getDisplayedIngredient() != null) { + ItemStack ingredient = guiIngredient.getDisplayedIngredient().copy(); + craftingInventory.setInventorySlotContents(index - 3, ingredient); + items.set(index - 3, ingredient); + } } Proxies.net.sendToServer(new PacketRecipeTransferRequest(container.getFabricator(), items)); } diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeWrapper.java index 13e27c5cf..b97de4cd9 100644 --- a/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/FabricatorRecipeWrapper.java @@ -1,32 +1,35 @@ package forestry.factory.recipes.jei.fabricator; -import javax.annotation.Nonnull; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import forestry.api.recipes.IFabricatorRecipe; import forestry.core.recipes.jei.ForestryRecipeWrapper; -import forestry.factory.recipes.jei.FactoryJeiPlugin; import mezz.jei.api.ingredients.IIngredients; -import mezz.jei.api.recipe.IStackHelper; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; public class FabricatorRecipeWrapper extends ForestryRecipeWrapper { - - public FabricatorRecipeWrapper(@Nonnull IFabricatorRecipe recipe) { + + public FabricatorRecipeWrapper(IFabricatorRecipe recipe) { super(recipe); } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { IFabricatorRecipe recipe = getRecipe(); - IStackHelper stackHelper = FactoryJeiPlugin.jeiHelpers.getStackHelper(); - Object[] itemInputs = recipe.getIngredients(); - List> itemStackInputs = stackHelper.expandRecipeItemStackInputs(Arrays.asList(itemInputs)); - ingredients.setInputLists(ItemStack.class, itemStackInputs); + NonNullList> itemInputs = recipe.getIngredients(); + List> inputStacks = new ArrayList<>(); + for (List stacks : itemInputs) { + List copy = new ArrayList<>(); + copy.addAll(stacks); + inputStacks.add(copy); + } + + ingredients.setInputLists(ItemStack.class, inputStacks); ingredients.setInputs(FluidStack.class, Collections.singletonList(getRecipe().getLiquid())); diff --git a/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java b/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java new file mode 100644 index 000000000..e85191ce8 --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/fabricator/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.fabricator; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java index dd2c0d911..898a999ba 100644 --- a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeCategory.java @@ -1,7 +1,5 @@ package forestry.factory.recipes.jei.fermenter; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.core.render.ForestryResource; @@ -20,48 +18,45 @@ public class FermenterRecipeCategory extends ForestryRecipeCategory { - - @Nonnull @Override public Class getRecipeClass() { return FermenterRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(FermenterRecipeWrapper recipe) { return ForestryRecipeCategoryUid.FERMENTER; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull FermenterRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.FERMENTER; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull FermenterRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper(FermenterRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull FermenterRecipeWrapper wrapper) { + public boolean isRecipeValid(FermenterRecipeWrapper wrapper) { IFermenterRecipe recipe = wrapper.getRecipe(); - if (recipe.getFermentationValue() <= 0) { - return false; - } - if (recipe.getModifier() <= 0) { - return false; - } - if (recipe.getFluidResource() == null) { - return false; - } - if (recipe.getResource() == null) { - return false; - } - return recipe.getOutput() != null; + return recipe.getFermentationValue() > 0 && + !(recipe.getModifier() <= 0); } - } diff --git a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeMaker.java b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeMaker.java index 859076dd7..2f02d38ea 100644 --- a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeMaker.java +++ b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeMaker.java @@ -19,7 +19,7 @@ public class FermenterRecipeMaker { public static List getFermenterRecipes(IStackHelper stackHelper) { List recipes = new ArrayList<>(); for (IFermenterRecipe recipe : RecipeManagers.fermenterManager.recipes()) { - if (recipe.getResource() != null) { + if (!recipe.getResource().isEmpty()) { if (recipe.getResource().getItem() instanceof IVariableFermentable) { for (ItemStack stack : stackHelper.getSubtypes(recipe.getResource())) { recipes.add(new FermenterRecipeWrapper(recipe, stack)); @@ -28,7 +28,7 @@ public class FermenterRecipeMaker { recipes.add(new FermenterRecipeWrapper(recipe, recipe.getResource())); } } else { - Log.error("Null resource for recipe"); + Log.error("Empty resource for recipe"); } } return recipes; diff --git a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeWrapper.java index 87ea66d21..356142140 100644 --- a/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/fermenter/FermenterRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.fermenter; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -16,17 +15,15 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; public class FermenterRecipeWrapper extends ForestryRecipeWrapper { - - @Nonnull private final ItemStack fermentable; - - public FermenterRecipeWrapper(@Nonnull IFermenterRecipe recipe, @Nonnull ItemStack fermentable) { + + public FermenterRecipeWrapper(IFermenterRecipe recipe, ItemStack fermentable) { super(recipe); this.fermentable = fermentable; } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { List fuelInputs = new ArrayList<>(); for (FermenterFuel fuel : FuelManager.fermenterFuel.values()) { fuelInputs.add(fuel.getItem()); @@ -48,9 +45,4 @@ public class FermenterRecipeWrapper extends ForestryRecipeWrapper { - - @Nonnull @Override public Class getRecipeClass() { return MoistenerRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid( MoistenerRecipeWrapper recipe) { return ForestryRecipeCategoryUid.MOISTENER; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull MoistenerRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.MOISTENER; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull MoistenerRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper( MoistenerRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull MoistenerRecipeWrapper wrapper) { + public boolean isRecipeValid( MoistenerRecipeWrapper wrapper) { IMoistenerRecipe recipe = wrapper.getRecipe(); - if (recipe.getTimePerItem() <= 0) { - return false; - } - if (recipe.getResource() == null) { - return false; - } - if (recipe.getProduct() == null) { - return false; - } - return wrapper.getFuel() != null || wrapper.getFuel().getItem() != null || wrapper.getFuel().getProduct() != null; + return recipe.getTimePerItem() > 0; } - } diff --git a/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeWrapper.java index 0f3b562cf..d27f741c2 100644 --- a/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/moistener/MoistenerRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.moistener; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -13,41 +12,33 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; public class MoistenerRecipeWrapper extends ForestryRecipeWrapper { - - @Nonnull private final MoistenerFuel fuel; - public MoistenerRecipeWrapper(@Nonnull IMoistenerRecipe recipe, @Nonnull MoistenerFuel fuel) { + public MoistenerRecipeWrapper( IMoistenerRecipe recipe, MoistenerFuel fuel) { super(recipe); this.fuel = fuel; } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients( IIngredients ingredients) { IMoistenerRecipe recipe = getRecipe(); List itemStackInputs = new ArrayList<>(); itemStackInputs.add(recipe.getResource()); ItemStack fuelItem = fuel.getItem(); - if (fuelItem != null) { - itemStackInputs.add(fuelItem); - } + itemStackInputs.add(fuelItem); ingredients.setInputs(ItemStack.class, itemStackInputs); List itemStackOutputs = new ArrayList<>(); itemStackOutputs.add(recipe.getProduct()); ItemStack fuelProduct = fuel.getProduct(); - if (fuelProduct != null) { - itemStackOutputs.add(fuelProduct); - } + itemStackOutputs.add(fuelProduct); ingredients.setOutputs(ItemStack.class, itemStackOutputs); ingredients.setInput(FluidStack.class, new FluidStack(FluidRegistry.WATER, recipe.getTimePerItem() / 4)); } - - @Nonnull + public MoistenerFuel getFuel() { return fuel; } - } diff --git a/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java b/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java new file mode 100644 index 000000000..efdc04f26 --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/moistener/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.moistener; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/package-info.java b/src/main/java/forestry/factory/recipes/jei/package-info.java index 3c50ec58f..5356db3d8 100644 --- a/src/main/java/forestry/factory/recipes/jei/package-info.java +++ b/src/main/java/forestry/factory/recipes/jei/package-info.java @@ -1,7 +1,9 @@ @ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault @MethodsReturnNonnullByDefault package forestry.factory.recipes.jei; import javax.annotation.ParametersAreNonnullByDefault; +import forestry.core.utils.FieldsAreNonnullByDefault; import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java index ba10af716..a52f8ce2f 100644 --- a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeCategory.java @@ -1,7 +1,5 @@ package forestry.factory.recipes.jei.rainmaker; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import mezz.jei.api.IGuiHelper; @@ -15,25 +13,24 @@ public class RainmakerRecipeCategory extends ForestryRecipeCategory { - @Nonnull @Override public Class getRecipeClass() { return RainmakerRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(RainmakerRecipeWrapper recipe) { return ForestryRecipeCategoryUid.RAINMAKER; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull RainmakerRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.RAINMAKER; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull RainmakerRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper(RainmakerRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull RainmakerRecipeWrapper wrapper) { + public boolean isRecipeValid(RainmakerRecipeWrapper wrapper) { return true; } } diff --git a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeWrapper.java index 12c94dbbd..e75bf0ee6 100644 --- a/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/rainmaker/RainmakerRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.rainmaker; -import javax.annotation.Nonnull; import java.awt.Color; import java.util.Collections; @@ -12,20 +11,19 @@ import net.minecraft.client.Minecraft; import net.minecraft.item.ItemStack; public class RainmakerRecipeWrapper extends BlankRecipeWrapper { - @Nonnull private final RainSubstrate substrate; - public RainmakerRecipeWrapper(@Nonnull RainSubstrate substrate) { + public RainmakerRecipeWrapper(RainSubstrate substrate) { this.substrate = substrate; } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { ingredients.setInputs(ItemStack.class, Collections.singletonList(substrate.getItem())); } @Override - public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { + public void drawInfo(Minecraft minecraft, int recipeWidth, int recipeHeight, int mouseX, int mouseY) { super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY); minecraft.fontRendererObj.drawString(getEffectString(), 24, 0, Color.darkGray.getRGB()); diff --git a/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java b/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java new file mode 100644 index 000000000..747836864 --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/rainmaker/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.rainmaker; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/AbstractSqueezerRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/squeezer/AbstractSqueezerRecipeWrapper.java index 0894f5b12..639595711 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/AbstractSqueezerRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/AbstractSqueezerRecipeWrapper.java @@ -1,11 +1,9 @@ package forestry.factory.recipes.jei.squeezer; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeWrapper; public abstract class AbstractSqueezerRecipeWrapper extends ForestryRecipeWrapper { - public AbstractSqueezerRecipeWrapper(@Nonnull R recipe) { + public AbstractSqueezerRecipeWrapper(R recipe) { super(recipe); } diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerContainerRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerContainerRecipeWrapper.java index ec6e351ba..c450b6658 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerContainerRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerContainerRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.squeezer; -import javax.annotation.Nonnull; import java.util.Collections; import forestry.factory.recipes.ISqueezerContainerRecipe; @@ -10,21 +9,19 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidUtil; public class SqueezerContainerRecipeWrapper extends AbstractSqueezerRecipeWrapper { - - @Nonnull private final ItemStack filledContainer; - - public SqueezerContainerRecipeWrapper(@Nonnull ISqueezerContainerRecipe recipe, @Nonnull ItemStack filledContainer) { + + public SqueezerContainerRecipeWrapper(ISqueezerContainerRecipe recipe, ItemStack filledContainer) { super(recipe); this.filledContainer = filledContainer; } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { ingredients.setInputs(ItemStack.class, Collections.singletonList(filledContainer)); ItemStack remnants = getRecipe().getRemnants(); - if (remnants != null) { + if (!remnants.isEmpty()) { ingredients.setOutput(ItemStack.class, remnants); } diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java index f3247f662..1906a9759 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeCategory.java @@ -1,7 +1,5 @@ package forestry.factory.recipes.jei.squeezer; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.core.recipes.jei.ForestryTooltipCallback; @@ -18,41 +16,39 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; public class SqueezerRecipeCategory extends ForestryRecipeCategory { - + private static final int[][] INPUTS = new int[][]{{0, 0}, {1, 0}, {2, 0}, {0, 1}, {1, 1}, {2, 1}, {0, 2}, {1, 2}, {2, 2}}; - + private static final int craftOutputSlot = 0; private static final int craftInputSlot = 1; - + private static final int outputTank = 0; - - private final static ResourceLocation guiTexture = new ForestryResource("textures/gui/squeezersocket.png"); - @Nonnull + + private static final ResourceLocation guiTexture = new ForestryResource("textures/gui/squeezersocket.png"); + private final IDrawableAnimated arrow; - @Nonnull private final IDrawable tankOverlay; - public SqueezerRecipeCategory(@Nonnull IGuiHelper guiHelper) { + public SqueezerRecipeCategory(IGuiHelper guiHelper) { super(guiHelper.createDrawable(guiTexture, 9, 16, 158, 62), "tile.for.squeezer.name"); - + IDrawableStatic arrowDrawable = guiHelper.createDrawable(guiTexture, 176, 60, 43, 18); this.arrow = guiHelper.createAnimatedDrawable(arrowDrawable, 200, IDrawableAnimated.StartDirection.LEFT, false); this.tankOverlay = guiHelper.createDrawable(guiTexture, 176, 0, 16, 58); } - - @Nonnull + @Override public String getUid() { return ForestryRecipeCategoryUid.SQUEEZER; } @Override - public void drawAnimations(@Nonnull Minecraft minecraft) { + public void drawExtras(Minecraft minecraft) { arrow.draw(minecraft, 67, 25); } @Override - public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull AbstractSqueezerRecipeWrapper recipeWrapper, @Nonnull IIngredients ingredients) { + public void setRecipe(IRecipeLayout recipeLayout, AbstractSqueezerRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiItemStackGroup guiItemStacks = recipeLayout.getItemStacks(); IGuiFluidStackGroup guiFluidStacks = recipeLayout.getFluidStacks(); diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeHandler.java index fff9b2a53..fe5cfa240 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeHandler.java @@ -1,46 +1,33 @@ package forestry.factory.recipes.jei.squeezer; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import mezz.jei.api.recipe.IRecipeHandler; import mezz.jei.api.recipe.IRecipeWrapper; public class SqueezerRecipeHandler implements IRecipeHandler { - - @Nonnull private final Class recipeClass; - - public SqueezerRecipeHandler(@Nonnull Class recipeClass) { + + public SqueezerRecipeHandler(Class recipeClass) { this.recipeClass = recipeClass; } - - @Nonnull + @Override public Class getRecipeClass() { return recipeClass; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(R recipe) { return ForestryRecipeCategoryUid.SQUEEZER; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull R recipe) { - return ForestryRecipeCategoryUid.SQUEEZER; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull R recipe) { + public IRecipeWrapper getRecipeWrapper(R recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull R wrapper) { + public boolean isRecipeValid(R wrapper) { return true; } diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeMaker.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeMaker.java index 07d3dbecf..29602bb93 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeMaker.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeMaker.java @@ -3,19 +3,18 @@ package forestry.factory.recipes.jei.squeezer; import java.util.ArrayList; import java.util.List; -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; - import forestry.api.recipes.ISqueezerRecipe; import forestry.api.recipes.RecipeManagers; import forestry.factory.recipes.ISqueezerContainerRecipe; import forestry.factory.recipes.SqueezerRecipeManager; +import mezz.jei.api.ingredients.IIngredientRegistry; +import net.minecraft.item.ItemStack; public class SqueezerRecipeMaker { private SqueezerRecipeMaker() { } - + public static List getSqueezerRecipes() { List recipes = new ArrayList<>(); for (ISqueezerRecipe recipe : RecipeManagers.squeezerManager.recipes()) { @@ -23,16 +22,15 @@ public class SqueezerRecipeMaker { } return recipes; } - - public static List getSqueezerContainerRecipes() { + + public static List getSqueezerContainerRecipes(IIngredientRegistry ingredientRegistry) { List recipes = new ArrayList<>(); - for (FluidContainerData data : FluidContainerRegistry.getRegisteredFluidContainerData()) { - ISqueezerContainerRecipe containerRecipe = SqueezerRecipeManager.findMatchingContainerRecipe(data.filledContainer); + for (ItemStack stack : ingredientRegistry.getIngredients(ItemStack.class)) { + ISqueezerContainerRecipe containerRecipe = SqueezerRecipeManager.findMatchingContainerRecipe(stack); if (containerRecipe != null) { - recipes.add(new SqueezerContainerRecipeWrapper(containerRecipe, data.filledContainer)); + recipes.add(new SqueezerContainerRecipeWrapper(containerRecipe, stack)); } } return recipes; } - } diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeWrapper.java index b2e847906..fb663bbbf 100644 --- a/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/SqueezerRecipeWrapper.java @@ -1,26 +1,23 @@ package forestry.factory.recipes.jei.squeezer; -import javax.annotation.Nonnull; -import java.util.Arrays; - import forestry.api.recipes.ISqueezerRecipe; import mezz.jei.api.ingredients.IIngredients; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraftforge.fluids.FluidStack; public class SqueezerRecipeWrapper extends AbstractSqueezerRecipeWrapper { - - public SqueezerRecipeWrapper(@Nonnull ISqueezerRecipe recipe) { + public SqueezerRecipeWrapper(ISqueezerRecipe recipe) { super(recipe); } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { - ItemStack[] resources = getRecipe().getResources(); - ingredients.setInputs(ItemStack.class, Arrays.asList(resources)); + public void getIngredients(IIngredients ingredients) { + NonNullList resources = getRecipe().getResources(); + ingredients.setInputs(ItemStack.class, resources); ItemStack remnants = getRecipe().getRemnants(); - if (remnants != null) { + if (!remnants.isEmpty()) { ingredients.setOutput(ItemStack.class, remnants); } diff --git a/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java b/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java new file mode 100644 index 000000000..4f717447a --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/squeezer/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.squeezer; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeCategory.java b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeCategory.java index 4d72f36bf..b4298b662 100644 --- a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeCategory.java +++ b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeCategory.java @@ -1,7 +1,5 @@ package forestry.factory.recipes.jei.still; -import javax.annotation.Nonnull; - import forestry.core.recipes.jei.ForestryRecipeCategory; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; import forestry.core.render.ForestryResource; @@ -17,38 +15,34 @@ import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; public class StillRecipeCategory extends ForestryRecipeCategory { - private static final int inputTank = 0; private static final int outputTank = 1; - - private final static ResourceLocation guiTexture = new ForestryResource("textures/gui/still.png"); - - @Nonnull + + private static final ResourceLocation guiTexture = new ForestryResource("textures/gui/still.png"); + private final IDrawable tankOverlay; - @Nonnull private final IDrawableAnimated progressBar; - + public StillRecipeCategory(IGuiHelper guiHelper) { super(guiHelper.createDrawable(guiTexture, 34, 14, 108, 60), "tile.for.still.name"); this.tankOverlay = guiHelper.createDrawable(guiTexture, 176, 0, 16, 58); - + IDrawableStatic progressBarDrawable0 = guiHelper.createDrawable(guiTexture, 176, 74, 4, 18); this.progressBar = guiHelper.createAnimatedDrawable(progressBarDrawable0, 20, IDrawableAnimated.StartDirection.BOTTOM, false); } - - @Nonnull + @Override public String getUid() { return ForestryRecipeCategoryUid.STILL; } @Override - public void drawAnimations(@Nonnull Minecraft minecraft) { + public void drawExtras(Minecraft minecraft) { progressBar.draw(minecraft, 50, 3); } @Override - public void setRecipe(@Nonnull IRecipeLayout recipeLayout, @Nonnull IRecipeWrapper recipeWrapper, @Nonnull IIngredients ingredients) { + public void setRecipe(IRecipeLayout recipeLayout, IRecipeWrapper recipeWrapper, IIngredients ingredients) { IGuiFluidStackGroup guiFluidStacks = recipeLayout.getFluidStacks(); guiFluidStacks.init(inputTank, true, 1, 1, 16, 58, 10000, false, tankOverlay); diff --git a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeHandler.java b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeHandler.java index 582cad2a9..9c212a2e2 100644 --- a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeHandler.java +++ b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeHandler.java @@ -1,49 +1,27 @@ package forestry.factory.recipes.jei.still; -import javax.annotation.Nonnull; - -import forestry.api.recipes.IStillRecipe; import forestry.core.recipes.jei.ForestryRecipeCategoryUid; - import mezz.jei.api.recipe.IRecipeHandler; import mezz.jei.api.recipe.IRecipeWrapper; public class StillRecipeHandler implements IRecipeHandler { - - @Nonnull @Override public Class getRecipeClass() { return StillRecipeWrapper.class; } - @Nonnull @Override - public String getRecipeCategoryUid() { + public String getRecipeCategoryUid(StillRecipeWrapper recipe) { return ForestryRecipeCategoryUid.STILL; } - @Nonnull @Override - public String getRecipeCategoryUid(@Nonnull StillRecipeWrapper recipe) { - return ForestryRecipeCategoryUid.STILL; - } - - @Nonnull - @Override - public IRecipeWrapper getRecipeWrapper(@Nonnull StillRecipeWrapper recipe) { + public IRecipeWrapper getRecipeWrapper(StillRecipeWrapper recipe) { return recipe; } @Override - public boolean isRecipeValid(@Nonnull StillRecipeWrapper wrapper) { - IStillRecipe recipe = wrapper.getRecipe(); - if (recipe.getInput() == null) { - return false; - } - if (recipe.getOutput() == null) { - return false; - } + public boolean isRecipeValid(StillRecipeWrapper wrapper) { return true; } - } diff --git a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeWrapper.java b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeWrapper.java index 2908abed8..9a47fb633 100644 --- a/src/main/java/forestry/factory/recipes/jei/still/StillRecipeWrapper.java +++ b/src/main/java/forestry/factory/recipes/jei/still/StillRecipeWrapper.java @@ -1,6 +1,5 @@ package forestry.factory.recipes.jei.still; -import javax.annotation.Nonnull; import java.util.Collections; import forestry.api.recipes.IStillRecipe; @@ -9,13 +8,13 @@ import mezz.jei.api.ingredients.IIngredients; import net.minecraftforge.fluids.FluidStack; public class StillRecipeWrapper extends ForestryRecipeWrapper { - - public StillRecipeWrapper(@Nonnull IStillRecipe recipe) { + + public StillRecipeWrapper(IStillRecipe recipe) { super(recipe); } @Override - public void getIngredients(@Nonnull IIngredients ingredients) { + public void getIngredients(IIngredients ingredients) { ingredients.setInputs(FluidStack.class, Collections.singletonList(getRecipe().getInput())); ingredients.setOutput(FluidStack.class, getRecipe().getOutput()); } diff --git a/src/main/java/forestry/factory/recipes/jei/still/package-info.java b/src/main/java/forestry/factory/recipes/jei/still/package-info.java new file mode 100644 index 000000000..00f0f99e9 --- /dev/null +++ b/src/main/java/forestry/factory/recipes/jei/still/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes.jei.still; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/recipes/package-info.java b/src/main/java/forestry/factory/recipes/package-info.java new file mode 100644 index 000000000..658b365be --- /dev/null +++ b/src/main/java/forestry/factory/recipes/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.recipes; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/tiles/TileBottler.java b/src/main/java/forestry/factory/tiles/TileBottler.java index 523931aec..3bf5f6ac2 100644 --- a/src/main/java/forestry/factory/tiles/TileBottler.java +++ b/src/main/java/forestry/factory/tiles/TileBottler.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.EnumMap; @@ -20,12 +19,11 @@ import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.FluidHelper.FillStatus; +import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.StandardTank; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.watchers.ISlotPickupWatcher; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; @@ -39,7 +37,7 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; @@ -57,9 +55,9 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid private final StandardTank resourceTank; private final TankManager tankManager; - private EnumMap canDump; + private final EnumMap canDump; private boolean dumpingFluid = false; - + @Nullable private BottlerRecipe currentRecipe; @SideOnly(Side.CLIENT) public boolean isFillRecipe; @@ -71,12 +69,12 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid resourceTank = new StandardTank(Constants.PROCESSOR_TANK_CAPACITY); tankManager = new TankManager(this, resourceTank); - + canDump = new EnumMap<>(EnumFacing.class); } /* SAVING & LOADING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -93,13 +91,13 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -111,16 +109,16 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid if (updateOnInterval(20)) { ItemStack leftProcessingStack = getStackInSlot(InventoryBottler.SLOT_EMPTYING_PROCESSING); ItemStack rightProcessingStack = getStackInSlot(InventoryBottler.SLOT_FILLING_PROCESSING); - if (leftProcessingStack == null) { + if (leftProcessingStack.isEmpty()) { ItemStack inputStack = getStackInSlot(InventoryBottler.SLOT_INPUT_FULL_CONTAINER); - if (inputStack != null) { + if (!inputStack.isEmpty()) { leftProcessingStack = decrStackSize(InventoryBottler.SLOT_INPUT_FULL_CONTAINER, 1); setInventorySlotContents(InventoryBottler.SLOT_EMPTYING_PROCESSING, leftProcessingStack); } } - if (rightProcessingStack == null) { + if (rightProcessingStack.isEmpty()) { ItemStack inputStack = getStackInSlot(InventoryBottler.SLOT_INPUT_EMPTY_CONTAINER); - if (inputStack != null) { + if (!inputStack.isEmpty()) { rightProcessingStack = decrStackSize(InventoryBottler.SLOT_INPUT_EMPTY_CONTAINER, 1); setInventorySlotContents(InventoryBottler.SLOT_FILLING_PROCESSING, rightProcessingStack); } @@ -133,13 +131,13 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid } } } - + private boolean canDump() { FluidStack fluid = tankManager.getFluid(0); if (fluid != null) { if (canDump.isEmpty()) { for (EnumFacing facing : EnumFacing.VALUES) { - canDump.put(facing, FluidHelper.canAcceptFluid(worldObj, pos.offset(facing), facing.getOpposite(), fluid)); + canDump.put(facing, FluidHelper.canAcceptFluid(world, pos.offset(facing), facing.getOpposite(), fluid)); } } @@ -154,9 +152,9 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid private boolean dumpFluid() { if (!resourceTank.isEmpty()) { - for(EnumFacing facing : EnumFacing.VALUES){ - if(canDump.get(facing)){ - IFluidHandler fluidDestination = FluidUtil.getFluidHandler(worldObj, pos.offset(facing), facing.getOpposite()); + for (EnumFacing facing : EnumFacing.VALUES) { + if (canDump.get(facing)) { + IFluidHandler fluidDestination = FluidUtil.getFluidHandler(world, pos.offset(facing), facing.getOpposite()); if (fluidDestination != null) { if (FluidUtil.tryFluidTransfer(fluidDestination, tankManager, Fluid.BUCKET_VOLUME / 20, true) != null) { return true; @@ -171,35 +169,40 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid @Override public boolean workCycle() { FluidHelper.FillStatus status; - if(currentRecipe.fillRecipe){ - status = FluidHelper.fillContainers(tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, currentRecipe.fluid.getFluid(), true); - }else{ - status = FluidHelper.drainContainers(tankManager, this, InventoryBottler.SLOT_EMPTYING_PROCESSING, InventoryBottler.SLOT_OUTPUT_EMPTY_CONTAINER, true); + if (currentRecipe != null) { + if (currentRecipe.fillRecipe) { + status = FluidHelper.fillContainers(tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, currentRecipe.fluid.getFluid(), true); + } else { + status = FluidHelper.drainContainers(tankManager, this, InventoryBottler.SLOT_EMPTYING_PROCESSING, InventoryBottler.SLOT_OUTPUT_EMPTY_CONTAINER, true); + } + } else { + return true; } - if(status == FluidHelper.FillStatus.SUCCESS){ + + if (status == FluidHelper.FillStatus.SUCCESS) { currentRecipe = null; return true; } return false; } - + @Override - public void onNeighborTileChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { + public void onNeighborTileChange(World world, BlockPos pos, BlockPos neighbor) { super.onNeighborTileChange(world, pos, neighbor); canDump.clear(); } - - private void checkFillRecipe(){ + + private void checkFillRecipe() { ItemStack emptyCan = getStackInSlot(InventoryBottler.SLOT_FILLING_PROCESSING); - if(emptyCan != null){ + if (!emptyCan.isEmpty()) { FluidStack resource = resourceTank.getFluid(); if (resource == null) { return; } //Fill Container if (currentRecipe == null || !currentRecipe.matchEmpty(emptyCan, resource)) { - currentRecipe = BottlerRecipe.createEmpty(resource.getFluid(), emptyCan); + currentRecipe = BottlerRecipe.createFillingRecipe(resource.getFluid(), emptyCan); if (currentRecipe != null) { float viscosityMultiplier = resource.getFluid().getViscosity(resource) / 1000.0f; viscosityMultiplier = (viscosityMultiplier - 1f) / 20f + 1f; // scale down the effect @@ -214,13 +217,13 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid } } } - - private void checkEmptyRecipe(){ + + private void checkEmptyRecipe() { ItemStack filledCan = getStackInSlot(InventoryBottler.SLOT_EMPTYING_PROCESSING); - if(filledCan != null){ + if (!filledCan.isEmpty()) { //Empty Container if (currentRecipe == null || !currentRecipe.matchFilled(filledCan) && !currentRecipe.fillRecipe) { - currentRecipe = BottlerRecipe.createFilled(filledCan); + currentRecipe = BottlerRecipe.createEmptyingRecipe(filledCan); if (currentRecipe != null) { FluidStack resource = currentRecipe.fluid; float viscosityMultiplier = resource.getFluid().getViscosity(resource) / 1000.0f; @@ -236,47 +239,47 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid } } } - + @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { - if(slotIndex == InventoryBottler.SLOT_EMPTYING_PROCESSING){ - if(currentRecipe != null && !currentRecipe.fillRecipe){ + public void onTake(int slotIndex, EntityPlayer player) { + if (slotIndex == InventoryBottler.SLOT_EMPTYING_PROCESSING) { + if (currentRecipe != null && !currentRecipe.fillRecipe) { currentRecipe = null; setTicksPerWorkCycle(0); } - }else if(slotIndex == InventoryBottler.SLOT_FILLING_PROCESSING){ - if(currentRecipe != null && currentRecipe.fillRecipe){ + } else if (slotIndex == InventoryBottler.SLOT_FILLING_PROCESSING) { + if (currentRecipe != null && currentRecipe.fillRecipe) { currentRecipe = null; setTicksPerWorkCycle(0); } } } - + @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { - super.readGuiData(data); - isFillRecipe = data.readBoolean(); - } - - @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { super.writeGuiData(data); - if(currentRecipe == null){ + if (currentRecipe == null) { data.writeBoolean(false); - }else{ + } else { data.writeBoolean(currentRecipe.fillRecipe); } } + @Override + public void readGuiData(PacketBufferForestry data) throws IOException { + super.readGuiData(data); + isFillRecipe = data.readBoolean(); + } + @Override public boolean hasResourcesMin(float percentage) { IInventoryAdapter inventory = getInternalInventory(); ItemStack emptyCan = inventory.getStackInSlot(InventoryBottler.SLOT_FILLING_PROCESSING); - if (emptyCan == null) { + if (emptyCan.isEmpty()) { return false; } - return (float) emptyCan.stackSize / (float) emptyCan.getMaxStackSize() > percentage; + return (float) emptyCan.getCount() / (float) emptyCan.getMaxStackSize() > percentage; } @Override @@ -285,37 +288,37 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid FluidHelper.FillStatus fillStatus; IErrorLogic errorLogic = getErrorLogic(); errorLogic.clearErrors(); - + checkEmptyRecipe(); if (currentRecipe != null) { IFluidTankProperties properties = tankManager.getTankProperties()[0]; - if(properties != null){ + if (properties != null) { emptyStatus = FluidHelper.drainContainers(tankManager, this, InventoryBottler.SLOT_EMPTYING_PROCESSING, InventoryBottler.SLOT_OUTPUT_EMPTY_CONTAINER, false); - }else{ + } else { emptyStatus = FillStatus.SUCCESS; } - }else{ + } else { emptyStatus = null; } - if(emptyStatus == null || emptyStatus != FillStatus.SUCCESS){ + if (emptyStatus == null || emptyStatus != FillStatus.SUCCESS) { checkFillRecipe(); if (currentRecipe == null) { return false; - }else{ + } else { fillStatus = FluidHelper.fillContainers(tankManager, this, InventoryBottler.SLOT_FILLING_PROCESSING, InventoryBottler.SLOT_OUTPUT_FULL_CONTAINER, currentRecipe.fluid.getFluid(), false); } - }else{ + } else { return true; } - - if(fillStatus == FillStatus.SUCCESS){ + + if (fillStatus == FillStatus.SUCCESS) { return true; } errorLogic.setCondition(fillStatus == FluidHelper.FillStatus.NO_FLUID, EnumErrorCode.NO_RESOURCE_LIQUID); errorLogic.setCondition(fillStatus == FluidHelper.FillStatus.NO_SPACE, EnumErrorCode.NO_SPACE_INVENTORY); errorLogic.setCondition(emptyStatus == FluidHelper.FillStatus.NO_SPACE_FLUID, EnumErrorCode.NO_SPACE_TANK); - if(emptyStatus == FillStatus.INVALID_INPUT || fillStatus == FillStatus.INVALID_INPUT || errorLogic.hasErrors()){ + if (emptyStatus == FillStatus.INVALID_INPUT || fillStatus == FillStatus.INVALID_INPUT || errorLogic.hasErrors()) { currentRecipe = null; return false; } @@ -328,20 +331,20 @@ public class TileBottler extends TilePowered implements ISidedInventory, ILiquid } /* ILIQUIDCONTAINER */ - @Nonnull + @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileCarpenter.java b/src/main/java/forestry/factory/tiles/TileCarpenter.java index a042edcc0..325e1d2fc 100644 --- a/src/main/java/forestry/factory/tiles/TileCarpenter.java +++ b/src/main/java/forestry/factory/tiles/TileCarpenter.java @@ -10,33 +10,19 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCraftResult; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.recipes.ICarpenterRecipe; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.IItemStackDisplay; import forestry.core.tiles.ILiquidTankTile; @@ -47,6 +33,17 @@ import forestry.factory.gui.GuiCarpenter; import forestry.factory.inventory.InventoryCarpenter; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.recipes.CarpenterRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.inventory.InventoryCraftResult; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileCarpenter extends TilePowered implements ISidedInventory, ILiquidTankTile, IItemStackDisplay { private static final int TICKS_PER_RECIPE_TIME = 1; @@ -55,7 +52,7 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu private final FilteredTank resourceTank; private final TankManager tankManager; - private final InventoryAdapterTile craftingInventory; + private final InventoryAdapterTile craftingInventory; private final InventoryCraftResult craftPreviewInventory; @Nullable @@ -78,7 +75,7 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu } /* LOADING & SAVING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -96,19 +93,19 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } public void checkRecipe() { - if (worldObj.isRemote) { + if (world.isRemote) { return; } @@ -123,7 +120,7 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu ItemStack craftingResult = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); craftPreviewInventory.setInventorySlotContents(0, craftingResult); } else { - craftPreviewInventory.setInventorySlotContents(0, null); + craftPreviewInventory.setInventorySlotContents(0, ItemStack.EMPTY); } } } @@ -146,9 +143,10 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu return false; } - ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); - InventoryUtil.tryAddStack(this, pendingProduct, InventoryCarpenter.SLOT_PRODUCT, InventoryCarpenter.SLOT_PRODUCT_COUNT, true); - + if (currentRecipe != null) { + ItemStack pendingProduct = currentRecipe.getCraftingGridRecipe().getRecipeOutput(); + InventoryUtil.tryAddStack(this, pendingProduct, InventoryCarpenter.SLOT_PRODUCT, InventoryCarpenter.SLOT_PRODUCT_COUNT, true); + } return true; } @@ -160,7 +158,7 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu FluidStack fluid = currentRecipe.getFluidResource(); if (fluid != null) { FluidStack drained = resourceTank.drainInternal(fluid, false); - if (!FluidHelper.areFluidStacksEqual(drained, fluid)) { + if (!drained.isFluidStackIdentical(fluid)) { return false; } if (doRemove) { @@ -176,9 +174,9 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu return true; } - if (currentRecipe.getBox() != null) { + if (!currentRecipe.getBox().isEmpty()) { ItemStack box = getStackInSlot(InventoryCarpenter.SLOT_BOX); - if (box == null || box.stackSize == 0) { + if (box.isEmpty()) { return false; } if (doRemove) { @@ -186,7 +184,7 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu } } - ItemStack[] craftingSets = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + NonNullList craftingSets = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); IInventory inventory = new InventoryMapper(getInternalInventory(), InventoryCarpenter.SLOT_INVENTORY_1, InventoryCarpenter.SLOT_INVENTORY_COUNT); return InventoryUtil.removeSets(inventory, 1, craftingSets, null, true, true, false, doRemove); } @@ -241,20 +239,20 @@ public class TileCarpenter extends TilePowered implements ISidedInventory, ILiqu craftPreviewInventory.setInventorySlotContents(0, itemStack); } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileCentrifuge.java b/src/main/java/forestry/factory/tiles/TileCentrifuge.java index b4c536e7c..b22359828 100644 --- a/src/main/java/forestry/factory/tiles/TileCentrifuge.java +++ b/src/main/java/forestry/factory/tiles/TileCentrifuge.java @@ -10,18 +10,11 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.Collection; import java.util.Stack; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCraftResult; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitBoard; @@ -33,8 +26,7 @@ import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.IItemStackDisplay; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; @@ -42,6 +34,13 @@ import forestry.factory.gui.ContainerCentrifuge; import forestry.factory.gui.GuiCentrifuge; import forestry.factory.inventory.InventoryCentrifuge; import forestry.factory.recipes.CentrifugeRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.inventory.InventoryCraftResult; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; public class TileCentrifuge extends TilePowered implements ISocketable, ISidedInventory, IItemStackDisplay { private static final int TICKS_PER_RECIPE_TIME = 1; @@ -50,7 +49,7 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn private final InventoryAdapter sockets = new InventoryAdapter(1, "sockets"); private final InventoryCraftResult craftPreviewInventory; - + @Nullable private ICentrifugeRecipe currentRecipe; private final Stack pendingProducts = new Stack<>(); @@ -62,7 +61,7 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn } /* LOADING & SAVING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -90,12 +89,12 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn NBTTagList nbttaglist = nbttagcompound.getTagList("PendingProducts", 10); for (int i = 0; i < nbttaglist.tagCount(); i++) { NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - pendingProducts.add(ItemStack.loadItemStackFromNBT(nbttagcompound1)); + pendingProducts.add(new ItemStack(nbttagcompound1)); } sockets.readFromNBT(nbttagcompound); ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { + if (!chip.isEmpty()) { ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(chip); if (chipset != null) { chipset.onLoad(this); @@ -104,13 +103,13 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { super.writeGuiData(data); sockets.writeData(data); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { super.readGuiData(data); sockets.readData(data); } @@ -122,7 +121,7 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn } if (!pendingProducts.isEmpty()) { - craftPreviewInventory.setInventorySlotContents(0, null); + craftPreviewInventory.setInventorySlotContents(0, ItemStack.EMPTY); return false; } @@ -131,14 +130,14 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn } // We are done, add products to queue - Collection products = currentRecipe.getProducts(worldObj.rand); + Collection products = currentRecipe.getProducts(world.rand); pendingProducts.addAll(products); - + //Add Item to preview slot. ItemStack previewStack = getInternalInventory().getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).copy(); - previewStack.stackSize=1; + previewStack.setCount(1); craftPreviewInventory.setInventorySlotContents(0, previewStack); - + getInternalInventory().decrStackSize(InventoryCentrifuge.SLOT_RESOURCE, 1); return true; } @@ -168,8 +167,8 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn if (added) { pendingProducts.pop(); - if(pendingProducts.isEmpty()){ - craftPreviewInventory.setInventorySlotContents(0, null); + if (pendingProducts.isEmpty()) { + craftPreviewInventory.setInventorySlotContents(0, ItemStack.EMPTY); } } @@ -180,21 +179,21 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn @Override public boolean hasResourcesMin(float percentage) { IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) == null) { + if (inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).isEmpty()) { return false; } - return (float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).stackSize / (float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).getMaxStackSize() > percentage; + return (float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).getCount() / (float) inventory.getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).getMaxStackSize() > percentage; } @Override public boolean hasWork() { - if(!pendingProducts.isEmpty()){ + if (!pendingProducts.isEmpty()) { return true; } checkRecipe(); - boolean hasResource = getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE) != null; + boolean hasResource = !getStackInSlot(InventoryCentrifuge.SLOT_RESOURCE).isEmpty(); IErrorLogic errorLogic = getErrorLogic(); errorLogic.setCondition(!hasResource, EnumErrorCode.NO_RESOURCE); @@ -227,12 +226,12 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn @Override public void setSocket(int slot, ItemStack stack) { - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { + if (!stack.isEmpty() && !ChipsetManager.circuitRegistry.isChipset(stack)) { return; } // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { + if (!sockets.getStackInSlot(slot).isEmpty()) { if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); if (chipset != null) { @@ -242,7 +241,7 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn } sockets.setInventorySlotContents(slot, stack); - if (stack == null) { + if (stack.isEmpty()) { return; } @@ -266,7 +265,7 @@ public class TileCentrifuge extends TilePowered implements ISocketable, ISidedIn public Object getContainer(EntityPlayer player, int data) { return new ContainerCentrifuge(player.inventory, this); } - + public IInventory getCraftPreviewInventory() { return craftPreviewInventory; } diff --git a/src/main/java/forestry/factory/tiles/TileFabricator.java b/src/main/java/forestry/factory/tiles/TileFabricator.java index fdf21351f..011a74f34 100644 --- a/src/main/java/forestry/factory/tiles/TileFabricator.java +++ b/src/main/java/forestry/factory/tiles/TileFabricator.java @@ -10,41 +10,23 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.recipes.IFabricatorRecipe; import forestry.api.recipes.IFabricatorSmeltingRecipe; import forestry.core.errors.EnumErrorCode; -import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.Fluids; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.inventory.watchers.ISlotPickupWatcher; import forestry.core.inventory.wrappers.InventoryMapper; import forestry.core.items.ICraftingPlan; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; import forestry.core.utils.InventoryUtil; @@ -54,6 +36,20 @@ import forestry.factory.inventory.InventoryFabricator; import forestry.factory.inventory.InventoryGhostCrafting; import forestry.factory.recipes.FabricatorRecipeManager; import forestry.factory.recipes.FabricatorSmeltingRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileFabricator extends TilePowered implements ISlotPickupWatcher, ILiquidTankTile, ISidedInventory { private static final int MAX_HEAT = 5000; @@ -76,7 +72,7 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I } /* SAVING & LOADING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -97,13 +93,13 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -135,7 +131,7 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I IInventoryAdapter inventory = getInternalInventory(); ItemStack smeltResource = inventory.getStackInSlot(InventoryFabricator.SLOT_METAL); - if (smeltResource == null) { + if (smeltResource.isEmpty()) { return; } @@ -164,12 +160,13 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I return true; } + @Nullable private IFabricatorRecipe getRecipe() { IInventoryAdapter inventory = getInternalInventory(); ItemStack plan = inventory.getStackInSlot(InventoryFabricator.SLOT_PLAN); FluidStack liquid = moltenTank.getFluid(); IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); - if (liquid != null && !liquid.containsFluid(recipe.getLiquid())) { + if (liquid != null && recipe != null && !liquid.containsFluid(recipe.getLiquid())) { return null; } return recipe; @@ -179,7 +176,7 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I IFabricatorRecipe myRecipe = getRecipe(); if (myRecipe == null) { - return null; + return ItemStack.EMPTY; } return myRecipe.getRecipeOutput().copy(); @@ -187,7 +184,7 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I /* ISlotPickupWatcher */ @Override - public void onPickupFromSlot(int slotIndex, EntityPlayer player) { + public void onTake(int slotIndex, EntityPlayer player) { if (slotIndex == InventoryFabricator.SLOT_RESULT) { decrStackSize(InventoryFabricator.SLOT_RESULT, 1); } @@ -195,49 +192,36 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I private void craftResult() { IFabricatorRecipe myRecipe = getRecipe(); - if (myRecipe == null) { - return; - } + ItemStack craftResult = getResult(); + if (myRecipe != null && !craftResult.isEmpty() && getStackInSlot(InventoryFabricator.SLOT_RESULT).isEmpty()) { + FluidStack liquid = myRecipe.getLiquid(); - ItemStack result = getResult(); - if (result == null) { - return; - } + // Remove resources + NonNullList crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + if (removeFromInventory(crafting, false)) { + FluidStack drained = moltenTank.drainInternal(liquid, false); + if (drained.isFluidStackIdentical(liquid)) { + removeFromInventory(crafting, true); + moltenTank.drain(liquid.amount, true); - if (getStackInSlot(InventoryFabricator.SLOT_RESULT) != null) { - return; - } + // Damage plan + if (!getStackInSlot(InventoryFabricator.SLOT_PLAN).isEmpty()) { + Item planItem = getStackInSlot(InventoryFabricator.SLOT_PLAN).getItem(); + if (planItem instanceof ICraftingPlan) { + ItemStack planUsed = ((ICraftingPlan) planItem).planUsed(getStackInSlot(InventoryFabricator.SLOT_PLAN), craftResult); + setInventorySlotContents(InventoryFabricator.SLOT_PLAN, planUsed); + } + } - FluidStack liquid = myRecipe.getLiquid(); - - // Remove resources - ItemStack[] crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - if (!removeFromInventory(crafting, null, false)) { - return; - } - - FluidStack drained = moltenTank.drainInternal(liquid, false); - if (!FluidHelper.areFluidStacksEqual(drained, liquid)) { - return; - } - - removeFromInventory(crafting, null, true); - moltenTank.drain(liquid.amount, true); - - // Damage plan - if (getStackInSlot(InventoryFabricator.SLOT_PLAN) != null) { - Item planItem = getStackInSlot(InventoryFabricator.SLOT_PLAN).getItem(); - if (planItem instanceof ICraftingPlan) { - setInventorySlotContents(InventoryFabricator.SLOT_PLAN, ((ICraftingPlan) planItem).planUsed(getStackInSlot(InventoryFabricator.SLOT_PLAN), result)); + setInventorySlotContents(InventoryFabricator.SLOT_RESULT, craftResult); + } } } - - setInventorySlotContents(InventoryFabricator.SLOT_RESULT, result); } - private boolean removeFromInventory(ItemStack[] set, EntityPlayer player, boolean doRemove) { + private boolean removeFromInventory(NonNullList set, boolean doRemove) { IInventory inventory = new InventoryMapper(this, InventoryFabricator.SLOT_INVENTORY_1, InventoryFabricator.SLOT_INVENTORY_COUNT); - return InventoryUtil.removeSets(inventory, 1, set, player, true, true, false, doRemove); + return InventoryUtil.removeSets(inventory, 1, set, null, true, true, false, doRemove); } @Override @@ -249,11 +233,11 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I ItemStack plan = getStackInSlot(InventoryFabricator.SLOT_PLAN); IFabricatorRecipe recipe = FabricatorRecipeManager.findMatchingRecipe(plan, craftingInventory); if (recipe != null) { - ItemStack[] crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); - hasResources = removeFromInventory(crafting, null, false); + NonNullList crafting = InventoryUtil.getStacks(craftingInventory, InventoryGhostCrafting.SLOT_CRAFTING_1, InventoryGhostCrafting.SLOT_CRAFTING_COUNT); + hasResources = removeFromInventory(crafting, false); FluidStack toDrain = recipe.getLiquid(); FluidStack drained = moltenTank.drainInternal(toDrain, false); - hasLiquidResources = FluidHelper.areFluidStacksEqual(drained, toDrain); + hasLiquidResources = drained.isFluidStackIdentical(toDrain); } else { hasRecipe = false; } @@ -271,7 +255,7 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I } private int getMeltingPoint() { - if (this.getStackInSlot(InventoryFabricator.SLOT_METAL) != null) { + if (!this.getStackInSlot(InventoryFabricator.SLOT_METAL).isEmpty()) { IFabricatorSmeltingRecipe smelt = FabricatorSmeltingRecipeManager.findMatchingSmelting(this.getStackInSlot(InventoryFabricator.SLOT_METAL)); if (smelt != null) { return smelt.getMeltingPoint(); @@ -314,20 +298,19 @@ public class TileFabricator extends TilePowered implements ISlotPickupWatcher, I return craftingInventory; } - @Nonnull @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { - return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileFermenter.java b/src/main/java/forestry/factory/tiles/TileFermenter.java index d03e4eb7b..8fc911195 100644 --- a/src/main/java/forestry/factory/tiles/TileFermenter.java +++ b/src/main/java/forestry/factory/tiles/TileFermenter.java @@ -10,23 +10,9 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.FermenterFuel; import forestry.api.fuels.FuelManager; @@ -34,11 +20,10 @@ import forestry.api.recipes.IFermenterRecipe; import forestry.api.recipes.IVariableFermentable; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; @@ -46,12 +31,24 @@ import forestry.factory.gui.ContainerFermenter; import forestry.factory.gui.GuiFermenter; import forestry.factory.inventory.InventoryFermenter; import forestry.factory.recipes.FermenterRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileFermenter extends TilePowered implements ISidedInventory, ILiquidTankTile { private final FilteredTank resourceTank; private final FilteredTank productTank; private final TankManager tankManager; + @Nullable private IFermenterRecipe currentRecipe; private float currentResourceModifier; private int fermentationTime = 0; @@ -74,7 +71,6 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu tankManager = new TankManager(this, resourceTank, productTank); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -103,13 +99,13 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -130,6 +126,10 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu @Override public boolean workCycle() { + if (currentRecipe == null) { + return false; + } + int fermented = Math.min(fermentationTime, fuelCurrentFerment); int productAmount = Math.round(fermented * currentRecipe.getModifier() * currentResourceModifier); productTank.fillInternal(new FluidStack(currentRecipe.getOutput(), productAmount), true); @@ -155,7 +155,9 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu ItemStack resource = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); FluidStack fluid = resourceTank.getFluid(); - currentRecipe = FermenterRecipeManager.findMatchingRecipe(resource, fluid); + if (fluid != null) { + currentRecipe = FermenterRecipeManager.findMatchingRecipe(resource, fluid); + } fermentationTotalTime = fermentationTime = currentRecipe == null ? 0 : currentRecipe.getFermentationValue(); @@ -166,24 +168,18 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu } private void checkFuel() { - if (fuelBurnTime > 0) { - return; + if (fuelBurnTime <= 0) { + ItemStack fuel = getStackInSlot(InventoryFermenter.SLOT_FUEL); + if (!fuel.isEmpty()) { + FermenterFuel fermenterFuel = FuelManager.fermenterFuel.get(fuel); + if (fermenterFuel != null) { + fuelBurnTime = fuelTotalTime = fermenterFuel.getBurnDuration(); + fuelCurrentFerment = fermenterFuel.getFermentPerCycle(); + + decrStackSize(InventoryFermenter.SLOT_FUEL, 1); + } + } } - - ItemStack fuel = getStackInSlot(InventoryFermenter.SLOT_FUEL); - if (fuel == null) { - return; - } - - FermenterFuel fermenterFuel = FuelManager.fermenterFuel.get(fuel); - if (fermenterFuel == null) { - return; - } - - fuelBurnTime = fuelTotalTime = fermenterFuel.getBurnDuration(); - fuelCurrentFerment = fermenterFuel.getFermentPerCycle(); - - decrStackSize(InventoryFermenter.SLOT_FUEL, 1); } private static float determineResourceMod(ItemStack itemstack) { @@ -198,21 +194,21 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu @Override public boolean hasResourcesMin(float percentage) { ItemStack fermentationStack = getStackInSlot(InventoryFermenter.SLOT_RESOURCE); - if (fermentationStack == null) { + if (fermentationStack.isEmpty()) { return false; } - return (float) fermentationStack.stackSize / (float) fermentationStack.getMaxStackSize() > percentage; + return (float) fermentationStack.getCount() / (float) fermentationStack.getMaxStackSize() > percentage; } @Override public boolean hasFuelMin(float percentage) { ItemStack fuelStack = getStackInSlot(InventoryFermenter.SLOT_FUEL); - if (fuelStack == null) { + if (fuelStack.isEmpty()) { return false; } - return (float) fuelStack.stackSize / (float) fuelStack.getMaxStackSize() > percentage; + return (float) fuelStack.getCount() / (float) fuelStack.getMaxStackSize() > percentage; } @Override @@ -224,7 +220,7 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu boolean hasRecipe = currentRecipe != null; boolean hasFuel = fuelBurnTime > 0; - boolean hasResource = fermentationTime > 0 || getStackInSlot(InventoryFermenter.SLOT_RESOURCE) != null; + boolean hasResource = fermentationTime > 0 || !getStackInSlot(InventoryFermenter.SLOT_RESOURCE).isEmpty(); FluidStack drained = resourceTank.drain(fermented, false); boolean hasFluidResource = drained != null && drained.amount == fermented; boolean hasFluidSpace = true; @@ -297,7 +293,7 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu iCrafting.sendProgressBarUpdate(container, 3, fermentationTotalTime); } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; @@ -325,13 +321,13 @@ public class TileFermenter extends TilePowered implements ISidedInventory, ILiqu } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java index 3dad33d8b..c9bcebccf 100644 --- a/src/main/java/forestry/factory/tiles/TileMillRainmaker.java +++ b/src/main/java/forestry/factory/tiles/TileMillRainmaker.java @@ -10,19 +10,18 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.SoundEvents; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.SoundCategory; +import javax.annotation.Nullable; import forestry.api.fuels.FuelManager; import forestry.api.fuels.RainSubstrate; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileMill; import forestry.factory.inventory.InventoryRainmaker; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.SoundEvents; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.SoundCategory; public class TileMillRainmaker extends TileMill { private int duration; @@ -36,23 +35,17 @@ public class TileMillRainmaker extends TileMill { @Override public void openGui(EntityPlayer player, ItemStack heldItem) { - if (player.worldObj.isRemote) { - return; - } - - if (heldItem == null) { - return; - } - - // We don't have a gui, but we can be activated - if (FuelManager.rainSubstrate.containsKey(heldItem) && charge == 0) { - RainSubstrate substrate = FuelManager.rainSubstrate.get(heldItem); - if (substrate.getItem().isItemEqual(heldItem)) { - addCharge(substrate); - heldItem.stackSize--; + if (!player.world.isRemote && !heldItem.isEmpty()) { + // We don't have a gui, but we can be activated + if (FuelManager.rainSubstrate.containsKey(heldItem) && charge == 0) { + RainSubstrate substrate = FuelManager.rainSubstrate.get(heldItem); + if (substrate.getItem().isItemEqual(heldItem)) { + addCharge(substrate); + heldItem.shrink(1); + } } + sendNetworkUpdate(); } - sendNetworkUpdate(); } @Override @@ -66,7 +59,7 @@ public class TileMillRainmaker extends TileMill { reverse = nbttagcompound.getBoolean("Reverse"); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -90,26 +83,26 @@ public class TileMillRainmaker extends TileMill { @Override public void activate() { if (Proxies.render.hasRendering()) { - worldObj.playSound(null, getPos(), SoundEvents.ENTITY_LIGHTNING_THUNDER, SoundCategory.WEATHER, 10000.0F, 0.8F + worldObj.rand.nextFloat() * 0.2F); + world.playSound(null, getPos(), SoundEvents.ENTITY_LIGHTNING_THUNDER, SoundCategory.WEATHER, 10000.0F, 0.8F + world.rand.nextFloat() * 0.2F); float f = getPos().getX() + 0.5F; - float f1 = getPos().getY() + 0.0F + worldObj.rand.nextFloat() * 6F / 16F; + float f1 = getPos().getY() + 0.0F + world.rand.nextFloat() * 6F / 16F; float f2 = getPos().getZ() + 0.5F; float f3 = 0.52F; - float f4 = worldObj.rand.nextFloat() * 0.6F - 0.3F; + float f4 = world.rand.nextFloat() * 0.6F - 0.3F; - Proxies.render.addEntityExplodeFX(worldObj, f - f3, f1, f2 + f4); - Proxies.render.addEntityExplodeFX(worldObj, f + f3, f1, f2 + f4); - Proxies.render.addEntityExplodeFX(worldObj, f + f4, f1, f2 - f3); - Proxies.render.addEntityExplodeFX(worldObj, f + f4, f1, f2 + f3); + Proxies.render.addEntityExplodeFX(world, f - f3, f1, f2 + f4); + Proxies.render.addEntityExplodeFX(world, f + f3, f1, f2 + f4); + Proxies.render.addEntityExplodeFX(world, f + f4, f1, f2 - f3); + Proxies.render.addEntityExplodeFX(world, f + f4, f1, f2 + f3); } - if (!worldObj.isRemote) { + if (!world.isRemote) { if (reverse) { - worldObj.getWorldInfo().setRaining(false); + world.getWorldInfo().setRaining(false); } else { - worldObj.getWorldInfo().setRaining(true); - worldObj.getWorldInfo().setRainTime(duration); + world.getWorldInfo().setRaining(true); + world.getWorldInfo().setRainTime(duration); } charge = 0; duration = 0; @@ -119,11 +112,13 @@ public class TileMillRainmaker extends TileMill { } @Override + @Nullable public Object getGui(EntityPlayer player, int data) { return null; } @Override + @Nullable public Object getContainer(EntityPlayer player, int data) { return null; } diff --git a/src/main/java/forestry/factory/tiles/TileMoistener.java b/src/main/java/forestry/factory/tiles/TileMoistener.java index 0d6c3e6ad..17816f188 100644 --- a/src/main/java/forestry/factory/tiles/TileMoistener.java +++ b/src/main/java/forestry/factory/tiles/TileMoistener.java @@ -10,35 +10,21 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IContainerListener; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - import forestry.api.core.IErrorLogic; import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; import forestry.api.recipes.IMoistenerRecipe; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.IRenderableTile; @@ -49,17 +35,30 @@ import forestry.factory.gui.ContainerMoistener; import forestry.factory.gui.GuiMoistener; import forestry.factory.inventory.InventoryMoistener; import forestry.factory.recipes.MoistenerRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IContainerListener; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileMoistener extends TileBase implements ISidedInventory, ILiquidTankTile, IRenderableTile { private final FilteredTank resourceTank; private final TankManager tankManager; + @Nullable private IMoistenerRecipe currentRecipe; private int burnTime = 0; private int totalTime = 0; private int productionTime = 0; private int timePerItem = 0; + @Nullable private ItemStack currentProduct; + @Nullable private ItemStack pendingProduct; public TileMoistener() { @@ -70,7 +69,6 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT } /* LOADING & SAVING */ - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -108,24 +106,24 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT // Load pending product if (nbttagcompound.hasKey("PendingProduct")) { NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("PendingProduct"); - pendingProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); + pendingProduct = new ItemStack(nbttagcompoundP); } if (nbttagcompound.hasKey("CurrentProduct")) { NBTTagCompound nbttagcompoundP = nbttagcompound.getCompoundTag("CurrentProduct"); - currentProduct = ItemStack.loadItemStackFromNBT(nbttagcompoundP); + currentProduct = new ItemStack(nbttagcompoundP); } checkRecipe(); } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -139,7 +137,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT } // Let's get to work - int lightvalue = worldObj.getLightFromNeighbors(getPos().up()); + int lightvalue = world.getLightFromNeighbors(getPos().up()); IErrorLogic errorLogic = getErrorLogic(); @@ -195,7 +193,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT checkRecipe(); // Let's see if we have a valid resource in the working slot - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) == null) { + if (getStackInSlot(InventoryMoistener.SLOT_WORKING).isEmpty()) { return; } @@ -254,7 +252,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT for (int i = startSlot; i < endSlot; i++) { ItemStack slotStack = getStackInSlot(i); // Empty slots are okay. - if (slotStack == null) { + if (slotStack.isEmpty()) { if (slot < 0) { slot = i; } @@ -266,7 +264,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT } // Wrong item or full - if (!slotStack.isItemEqual(deposit) || slotStack.stackSize >= slotStack.getMaxStackSize()) { + if (!slotStack.isItemEqual(deposit) || slotStack.getCount() >= slotStack.getMaxStackSize()) { continue; } @@ -293,7 +291,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT IInventoryAdapter inventory = getInternalInventory(); for (int i = startSlot; i < endSlot; i++) { ItemStack slotStack = inventory.getStackInSlot(i); - if (slotStack == null) { + if (slotStack.isEmpty()) { continue; } @@ -315,7 +313,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT IErrorLogic errorLogic = getErrorLogic(); // Put working slot contents into inventory if space is available - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { + if (!getStackInSlot(InventoryMoistener.SLOT_WORKING).isEmpty()) { // Get the result of the consumed item in the working slot ItemStack deposit; if (FuelManager.moistenerResource.containsKey(getStackInSlot(InventoryMoistener.SLOT_WORKING))) { @@ -331,16 +329,16 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT return false; } - if (getStackInSlot(targetSlot) == null) { + if (getStackInSlot(targetSlot).isEmpty()) { setInventorySlotContents(targetSlot, deposit); } else { - getStackInSlot(targetSlot).stackSize++; + getStackInSlot(targetSlot).grow(1); } decrStackSize(InventoryMoistener.SLOT_WORKING, 1); } - if (getStackInSlot(InventoryMoistener.SLOT_WORKING) != null) { + if (!getStackInSlot(InventoryMoistener.SLOT_WORKING).isEmpty()) { return true; } @@ -359,7 +357,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT ArrayList slotsToShift = new ArrayList<>(); for (int i = InventoryMoistener.SLOT_RESERVOIR_1; i < InventoryMoistener.SLOT_RESERVOIR_1 + InventoryMoistener.SLOT_RESERVOIR_COUNT; i++) { - if (getStackInSlot(i) == null) { + if (getStackInSlot(i).isEmpty()) { continue; } @@ -378,7 +376,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT } setInventorySlotContents(targetSlot, slotStack); - setInventorySlotContents(slot, null); + setInventorySlotContents(slot, ItemStack.EMPTY); shiftedSlots++; } @@ -395,14 +393,11 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT break; } // Else shift - if (getStackInSlot(targetSlot) == null) { + if (getStackInSlot(targetSlot).isEmpty()) { setInventorySlotContents(targetSlot, getStackInSlot(resourceSlot)); - setInventorySlotContents(resourceSlot, null); + setInventorySlotContents(resourceSlot, ItemStack.EMPTY); } else { ItemStackUtil.mergeStacks(getStackInSlot(resourceSlot), getStackInSlot(targetSlot)); - if (getStackInSlot(resourceSlot) != null && getStackInSlot(resourceSlot).stackSize <= 0) { - setInventorySlotContents(resourceSlot, null); - } } } } @@ -417,7 +412,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT IInventoryAdapter inventory = getInternalInventory(); for (int i = InventoryMoistener.SLOT_STASH_1; i < InventoryMoistener.SLOT_RESERVOIR_1; i++) { - if (inventory.getStackInSlot(i) == null) { + if (inventory.getStackInSlot(i).isEmpty()) { max += 64; continue; } @@ -425,7 +420,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT MoistenerFuel res = FuelManager.moistenerResource.get(inventory.getStackInSlot(i)); if (res.getItem().isItemEqual(inventory.getStackInSlot(i))) { max += 64; - avail += inventory.getStackInSlot(i).stackSize; + avail += inventory.getStackInSlot(i).getCount(); } } } @@ -435,11 +430,11 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT public boolean hasResourcesMin(float percentage) { IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE) == null) { + if (inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).isEmpty()) { return false; } - return (float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).stackSize / (float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).getMaxStackSize() > percentage; + return (float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).getCount() / (float) inventory.getStackInSlot(InventoryMoistener.SLOT_RESOURCE).getMaxStackSize() > percentage; } public boolean isProducing() { @@ -479,7 +474,7 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT return TankRenderInfo.EMPTY; } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; @@ -521,13 +516,13 @@ public class TileMoistener extends TileBase implements ISidedInventory, ILiquidT } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileRaintank.java b/src/main/java/forestry/factory/tiles/TileRaintank.java index 04fb50e48..f60bac979 100644 --- a/src/main/java/forestry/factory/tiles/TileRaintank.java +++ b/src/main/java/forestry/factory/tiles/TileRaintank.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -19,11 +18,10 @@ import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; import forestry.core.fluids.ContainerFiller; import forestry.core.fluids.DrainOnlyFluidHandlerWrapper; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TileBase; import forestry.factory.gui.ContainerRaintank; @@ -36,7 +34,7 @@ import net.minecraft.inventory.ISidedInventory; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.Fluid; @@ -50,13 +48,11 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa private static final FluidStack STACK_WATER = new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME); private static final FluidStack WATER_PER_UPDATE = new FluidStack(FluidRegistry.WATER, Constants.RAINTANK_AMOUNT_PER_UPDATE); - @Nonnull private final FilteredTank resourceTank; - @Nonnull private final TankManager tankManager; - @Nonnull private final ContainerFiller containerFiller; + @Nullable private Boolean canDumpBelow = null; private boolean dumpingFluid = false; @@ -74,7 +70,6 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa containerFiller = new ContainerFiller(resourceTank, Constants.RAINTANK_FILLING_TIME, this, InventoryRaintank.SLOT_RESOURCE, InventoryRaintank.SLOT_PRODUCT); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -89,13 +84,13 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -106,14 +101,14 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa IErrorLogic errorLogic = getErrorLogic(); BlockPos pos = getPos(); - Biome biome = worldObj.getBiome(pos); + Biome biome = world.getBiome(pos); errorLogic.setCondition(!biome.canRain(), EnumErrorCode.NO_RAIN_BIOME); BlockPos posAbove = pos.up(); - boolean hasSky = worldObj.canBlockSeeSky(posAbove); + boolean hasSky = world.canBlockSeeSky(posAbove); errorLogic.setCondition(!hasSky, EnumErrorCode.NO_SKY_RAIN_TANK); - errorLogic.setCondition(!worldObj.isRainingAt(posAbove), EnumErrorCode.NOT_RAINING); + errorLogic.setCondition(!world.isRainingAt(posAbove), EnumErrorCode.NOT_RAINING); if (!errorLogic.hasErrors()) { resourceTank.fillInternal(WATER_PER_UPDATE, true); @@ -123,7 +118,7 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa } if (canDumpBelow == null) { - canDumpBelow = FluidHelper.canAcceptFluid(worldObj, getPos().down(), EnumFacing.UP, STACK_WATER); + canDumpBelow = FluidHelper.canAcceptFluid(world, getPos().down(), EnumFacing.UP, STACK_WATER); } if (canDumpBelow) { @@ -135,7 +130,7 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa private boolean dumpFluidBelow() { if (!resourceTank.isEmpty()) { - IFluidHandler fluidDestination = FluidUtil.getFluidHandler(worldObj, pos.down(), EnumFacing.UP); + IFluidHandler fluidDestination = FluidUtil.getFluidHandler(world, pos.down(), EnumFacing.UP); if (fluidDestination != null) { if (FluidUtil.tryFluidTransfer(fluidDestination, tankManager, Fluid.BUCKET_VOLUME / 20, true) != null) { return true; @@ -166,29 +161,28 @@ public class TileRaintank extends TileBase implements ISidedInventory, ILiquidTa iCrafting.sendProgressBarUpdate(container, 0, containerFiller.getFillingProgress()); } - @Nonnull @Override public TankManager getTankManager() { return tankManager; } @Override - public void onNeighborTileChange(IBlockAccess world, BlockPos pos, BlockPos neighbor) { + public void onNeighborTileChange(World world, BlockPos pos, BlockPos neighbor) { super.onNeighborTileChange(world, pos, neighbor); if (neighbor.equals(pos.down())) { - canDumpBelow = FluidHelper.canAcceptFluid(worldObj, neighbor, EnumFacing.UP, STACK_WATER); + canDumpBelow = FluidHelper.canAcceptFluid(world, neighbor, EnumFacing.UP, STACK_WATER); } } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { final IFluidHandler fluidHandler; if (facing == EnumFacing.DOWN) { diff --git a/src/main/java/forestry/factory/tiles/TileSqueezer.java b/src/main/java/forestry/factory/tiles/TileSqueezer.java index 65ffae61f..0e8d9ea4b 100644 --- a/src/main/java/forestry/factory/tiles/TileSqueezer.java +++ b/src/main/java/forestry/factory/tiles/TileSqueezer.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; @@ -24,11 +23,10 @@ import forestry.core.circuits.ISocketable; import forestry.core.circuits.ISpeedUpgradable; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.StandardTank; import forestry.core.inventory.InventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; @@ -42,6 +40,7 @@ import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; @@ -56,7 +55,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve private final TankManager tankManager; private final StandardTank productTank; private final InventorySqueezer inventory; - + @Nullable private ISqueezerRecipe currentRecipe; public TileSqueezer() { @@ -68,7 +67,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve } /* LOADING & SAVING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -84,7 +83,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve sockets.readFromNBT(nbttagcompound); ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { + if (!chip.isEmpty()) { ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(chip); if (chipset != null) { chipset.onLoad(this); @@ -93,25 +92,25 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { super.writeGuiData(data); sockets.writeData(data); } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { super.readGuiData(data); sockets.readData(data); } @@ -122,12 +121,18 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve super.updateServerSide(); if (updateOnInterval(20)) { - inventory.fillContainers(productTank.getFluid(), tankManager); + FluidStack fluid = productTank.getFluid(); + if (fluid != null) { + inventory.fillContainers(fluid, tankManager); + } } } @Override public boolean workCycle() { + if (currentRecipe == null) { + return false; + } if (!inventory.removeResources(currentRecipe.getResources())) { return false; } @@ -135,7 +140,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve FluidStack resultFluid = currentRecipe.getFluidOutput(); productTank.fillInternal(resultFluid, true); - if (currentRecipe.getRemnants() != null && worldObj.rand.nextFloat() < currentRecipe.getRemnantsChance()) { + if (!currentRecipe.getRemnants().isEmpty() && world.rand.nextFloat() < currentRecipe.getRemnantsChance()) { ItemStack remnant = currentRecipe.getRemnants().copy(); inventory.addRemnant(remnant, true); } @@ -146,7 +151,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve private boolean checkRecipe() { ISqueezerRecipe matchingRecipe = null; if (inventory.hasResources()) { - ItemStack[] resources = inventory.getResources(); + NonNullList resources = inventory.getResources(); if (currentRecipe != null && ItemStackUtil.containsSets(currentRecipe.getResources(), resources, true, false) > 0) { matchingRecipe = currentRecipe; @@ -183,7 +188,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve FluidStack resultFluid = currentRecipe.getFluidOutput(); canFill = productTank.fillInternal(resultFluid, false) == resultFluid.amount; - if (currentRecipe.getRemnants() != null) { + if (!currentRecipe.getRemnants().isEmpty()) { canAdd = inventory.addRemnant(currentRecipe.getRemnants(), false); } } @@ -203,7 +208,7 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve return new TankRenderInfo(productTank); } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; @@ -222,29 +227,24 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve @Override public void setSocket(int slot, ItemStack stack) { - - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } - - // Dispose correctly of old chipsets - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); + if (stack.isEmpty() || ChipsetManager.circuitRegistry.isChipset(stack)) { + // Dispose correctly of old chipsets + if (!sockets.getStackInSlot(slot).isEmpty()) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } } } - } - sockets.setInventorySlotContents(slot, stack); - if (stack == null) { - return; - } - - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); - if (chipset != null) { - chipset.onInsertion(this); + sockets.setInventorySlotContents(slot, stack); + if (!stack.isEmpty()) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } } } @@ -254,13 +254,13 @@ public class TileSqueezer extends TilePowered implements ISocketable, ISidedInve } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileStill.java b/src/main/java/forestry/factory/tiles/TileStill.java index cceaedd37..9387fde4e 100644 --- a/src/main/java/forestry/factory/tiles/TileStill.java +++ b/src/main/java/forestry/factory/tiles/TileStill.java @@ -10,28 +10,18 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.EnumFacing; - -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.capability.CapabilityFluidHandler; - +import com.google.common.base.Preconditions; import forestry.api.core.IErrorLogic; import forestry.api.recipes.IStillRecipe; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; +import forestry.core.fluids.FilteredTank; import forestry.core.fluids.FluidHelper; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.render.TankRenderInfo; import forestry.core.tiles.ILiquidTankTile; import forestry.core.tiles.TilePowered; @@ -39,6 +29,13 @@ import forestry.factory.gui.ContainerStill; import forestry.factory.gui.GuiStill; import forestry.factory.inventory.InventoryStill; import forestry.factory.recipes.StillRecipeManager; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.capabilities.Capability; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.capability.CapabilityFluidHandler; public class TileStill extends TilePowered implements ISidedInventory, ILiquidTankTile { private static final int ENERGY_PER_RECIPE_TIME = 200; @@ -47,7 +44,9 @@ public class TileStill extends TilePowered implements ISidedInventory, ILiquidTa private final FilteredTank productTank; private final TankManager tankManager; + @Nullable private IStillRecipe currentRecipe; + @Nullable private FluidStack bufferedLiquid; public TileStill() { @@ -62,7 +61,6 @@ public class TileStill extends TilePowered implements ISidedInventory, ILiquidTa tankManager = new TankManager(this, resourceTank, productTank); } - @Nonnull @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -88,13 +86,13 @@ public class TileStill extends TilePowered implements ISidedInventory, ILiquidTa } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); tankManager.writeData(data); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); tankManager.readData(data); } @@ -115,7 +113,7 @@ public class TileStill extends TilePowered implements ISidedInventory, ILiquidTa @Override public boolean workCycle() { - + Preconditions.checkState(currentRecipe != null); int cycles = currentRecipe.getCyclesPerUnit(); FluidStack output = currentRecipe.getOutput(); @@ -181,20 +179,20 @@ public class TileStill extends TilePowered implements ISidedInventory, ILiquidTa return new TankRenderInfo(productTank); } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(tankManager); } diff --git a/src/main/java/forestry/factory/tiles/TileWorktable.java b/src/main/java/forestry/factory/tiles/TileWorktable.java index a14b7f482..6d5a707e6 100644 --- a/src/main/java/forestry/factory/tiles/TileWorktable.java +++ b/src/main/java/forestry/factory/tiles/TileWorktable.java @@ -10,14 +10,14 @@ ******************************************************************************/ package forestry.factory.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.IOException; import java.util.List; +import com.google.common.base.Preconditions; import forestry.core.inventory.InventoryAdapterTile; import forestry.core.inventory.wrappers.InventoryMapper; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.recipes.RecipeUtil; import forestry.core.tiles.TileBase; import forestry.core.utils.InventoryUtil; @@ -35,11 +35,13 @@ import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraftforge.common.ForgeHooks; public class TileWorktable extends TileBase implements ICrafterWorktable { private RecipeMemory recipeMemory; private final InventoryAdapterTile craftingDisplay; + @Nullable private MemorizedRecipe currentRecipe; public TileWorktable() { @@ -51,7 +53,7 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } /* LOADING & SAVING */ - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); @@ -71,7 +73,7 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { /* NETWORK */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); craftingDisplay.writeData(data); @@ -79,7 +81,7 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); craftingDisplay.readData(data); @@ -89,7 +91,7 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { @Override public void validate() { super.validate(); - recipeMemory.validate(worldObj); + recipeMemory.validate(world); } /* Recipe Conflicts */ @@ -132,9 +134,9 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { return false; } - ItemStack[] recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); - ItemStack[] inventoryStacks = InventoryUtil.getStacks(this); - InventoryCraftingForestry crafting = RecipeUtil.getCraftRecipe(recipeItems, inventoryStacks, worldObj, currentRecipe.getRecipeOutput()); + NonNullList recipeItems = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); + NonNullList inventoryStacks = InventoryUtil.getStacks(this); + InventoryCraftingForestry crafting = RecipeUtil.getCraftRecipe(recipeItems, inventoryStacks, world, currentRecipe.getRecipeOutput()); if (crafting == null) { return false; } @@ -150,7 +152,7 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } // craft recipe should exactly match ingredients here, so no oreDict or tool matching - ItemStack[] removed = InventoryUtil.removeSets(inventory, 1, recipeItems, null, false, false, false); + NonNullList removed = InventoryUtil.removeSets(inventory, 1, recipeItems, null, false, false, false); if (removed == null) { return false; } @@ -165,8 +167,10 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { @Override public void onCraftingComplete(EntityPlayer player) { + Preconditions.checkState(currentRecipe != null); + ForgeHooks.setCraftingPlayer(player); - ItemStack[] remainingItems = CraftingManager.getInstance().getRemainingItems(currentRecipe.getCraftMatrix(), player.worldObj); + NonNullList remainingItems = CraftingManager.getInstance().getRemainingItems(currentRecipe.getCraftMatrix(), player.world); ForgeHooks.setCraftingPlayer(null); for (ItemStack remainingItem : remainingItems) { @@ -176,20 +180,20 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } } } - - if (!worldObj.isRemote) { - recipeMemory.memorizeRecipe(worldObj.getTotalWorldTime(), currentRecipe); + + if (!world.isRemote) { + recipeMemory.memorizeRecipe(world.getTotalWorldTime(), currentRecipe); } } @Override public ItemStack getResult() { if (currentRecipe == null) { - return null; + return ItemStack.EMPTY; } ItemStack result = currentRecipe.getRecipeOutput(); - if (result != null) { + if (!result.isEmpty()) { result = result.copy(); } return result; @@ -206,10 +210,6 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } private void setCraftingDisplay(IInventory craftMatrix) { - if (craftMatrix == null) { - return; - } - for (int slot = 0; slot < craftMatrix.getSizeInventory(); slot++) { craftingDisplay.setInventorySlotContents(slot, craftMatrix.getStackInSlot(slot)); } @@ -221,18 +221,18 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { public void clearCraftMatrix() { for (int slot = 0; slot < craftingDisplay.getSizeInventory(); slot++) { - craftingDisplay.setInventorySlotContents(slot, null); + craftingDisplay.setInventorySlotContents(slot, ItemStack.EMPTY); } } public void setCurrentRecipe(InventoryCraftingForestry crafting) { - List recipeOutputs = RecipeUtil.findMatchingRecipes(crafting, worldObj); + List recipeOutputs = RecipeUtil.findMatchingRecipes(crafting, world); MemorizedRecipe recipe = recipeOutputs.isEmpty() ? null : new MemorizedRecipe(crafting, recipeOutputs); if (currentRecipe != null && recipe != null) { if (recipe.hasRecipeOutput(currentRecipe.getRecipeOutput())) { - ItemStack[] stacks = InventoryUtil.getStacks(crafting); - ItemStack[] currentStacks = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); + NonNullList stacks = InventoryUtil.getStacks(crafting); + NonNullList currentStacks = InventoryUtil.getStacks(currentRecipe.getCraftMatrix()); if (ItemStackUtil.equalSets(stacks, currentStacks)) { return; } @@ -243,11 +243,12 @@ public class TileWorktable extends TileBase implements ICrafterWorktable { } /* Network Sync with PacketWorktableRecipeUpdate */ + @Nullable public MemorizedRecipe getCurrentRecipe() { return currentRecipe; } - public void setCurrentRecipe(MemorizedRecipe recipe) { + public void setCurrentRecipe(@Nullable MemorizedRecipe recipe) { this.currentRecipe = recipe; if (currentRecipe != null) { setCraftingDisplay(currentRecipe.getCraftMatrix()); diff --git a/src/main/java/forestry/factory/tiles/package-info.java b/src/main/java/forestry/factory/tiles/package-info.java new file mode 100644 index 000000000..a92bdbb2b --- /dev/null +++ b/src/main/java/forestry/factory/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/factory/triggers/FactoryTriggers.java b/src/main/java/forestry/factory/triggers/FactoryTriggers.java index d6c90c5cd..cb8c6bb8e 100644 --- a/src/main/java/forestry/factory/triggers/FactoryTriggers.java +++ b/src/main/java/forestry/factory/triggers/FactoryTriggers.java @@ -13,15 +13,15 @@ package forestry.factory.triggers; import forestry.core.triggers.Trigger; public class FactoryTriggers { - public static Trigger lowResource25; - public static Trigger lowResource10; - public static Trigger lowFuel25; - public static Trigger lowFuel10; - - public static void initialize() { - lowResource25 = new TriggerLowResource("lowResources.25", 0.25f); - lowResource10 = new TriggerLowResource("lowResources.10", 0.1f); - lowFuel25 = new TriggerLowFuel("lowFuel.25", 0.25f); - lowFuel10 = new TriggerLowFuel("lowFuel.10", 0.1f); - } +// public static Trigger lowResource25; +// public static Trigger lowResource10; +// public static Trigger lowFuel25; +// public static Trigger lowFuel10; +// +// public static void initialize() { +// lowResource25 = new TriggerLowResource("lowResources.25", 0.25f); +// lowResource10 = new TriggerLowResource("lowResources.10", 0.1f); +// lowFuel25 = new TriggerLowFuel("lowFuel.25", 0.25f); +// lowFuel10 = new TriggerLowFuel("lowFuel.10", 0.1f); +// } } diff --git a/src/main/java/forestry/factory/triggers/package-info.java b/src/main/java/forestry/factory/triggers/package-info.java new file mode 100644 index 000000000..cf52d29dd --- /dev/null +++ b/src/main/java/forestry/factory/triggers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.factory.triggers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/PluginFarming.java b/src/main/java/forestry/farming/PluginFarming.java index de306a4e6..3e3adbdd5 100644 --- a/src/main/java/forestry/farming/PluginFarming.java +++ b/src/main/java/forestry/farming/PluginFarming.java @@ -10,36 +10,19 @@ ******************************************************************************/ package forestry.farming; + +import javax.annotation.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import javax.annotation.Nonnull; - -import net.minecraft.block.BlockBeetroot; -import net.minecraft.block.BlockCrops; -import net.minecraft.block.BlockNetherWart; -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.oredict.OreDictionary; +import com.google.common.base.Preconditions; import forestry.Forestry; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; @@ -47,12 +30,13 @@ import forestry.api.circuits.ICircuitLayout; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.core.PluginCore; -import forestry.core.circuits.Circuit; import forestry.core.circuits.CircuitLayout; +import forestry.core.circuits.Circuits; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.config.LocalizedConfiguration; import forestry.core.items.EnumElectronTube; +import forestry.core.items.ItemRegistryCore; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.Log; @@ -90,14 +74,32 @@ import forestry.farming.triggers.FarmingTriggers; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.block.BlockBeetroot; +import net.minecraft.block.BlockCrops; +import net.minecraft.block.BlockNetherWart; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.oredict.OreDictionary; @ForestryPlugin(pluginID = ForestryPluginUids.FARMING, name = "Farming", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.farming.description") public class PluginFarming extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.farming.proxy.ProxyFarmingClient", serverSide = "forestry.farming.proxy.ProxyFarming") public static ProxyFarming proxy; - public static int modelIdFarmBlock; + @Nullable public static BlockRegistryFarming blocks; @Override @@ -107,8 +109,10 @@ public class PluginFarming extends BlankForestryPlugin { @Override public void preInit() { + Preconditions.checkState(blocks != null); + MinecraftForge.EVENT_BUS.register(this); - + Farmables.farmables.put("farmArboreal", new FarmableVanillaSapling()); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ARBORICULTURE)) { Farmables.farmables.put("farmArboreal", new FarmableGE()); @@ -144,7 +148,7 @@ public class PluginFarming extends BlankForestryPlugin { //Foretsry fertilizer Farmables.fertilizers.put(new ItemStack(PluginCore.items.fertilizerCompound, 1, OreDictionary.WILDCARD_VALUE), 500); - + proxy.initializeModels(); // Layouts @@ -153,8 +157,8 @@ public class PluginFarming extends BlankForestryPlugin { ICircuitLayout layoutManual = new CircuitLayout("farms.manual", CircuitSocketType.FARM); ChipsetManager.circuitRegistry.registerLayout(layoutManual); } - - private void loadConfig(LocalizedConfiguration config){ + + private void loadConfig(LocalizedConfiguration config) { List defaultFertilizers = new ArrayList<>(getItemStrings(Farmables.fertilizers)); Collections.sort(defaultFertilizers); String[] defaultSortedFertilizers = defaultFertilizers.toArray(new String[defaultFertilizers.size()]); @@ -162,21 +166,20 @@ public class PluginFarming extends BlankForestryPlugin { Farmables.fertilizers.clear(); String[] fertilizerList = fertilizerConf.getStringList(); - for(int i = 0;i < fertilizerList.length;i++){ - try{ + for (int i = 0; i < fertilizerList.length; i++) { + try { String fertilizer = fertilizerList[i]; String[] fertilizers = fertilizer.split(";"); ItemStack fertilizerItem = ItemStackUtil.parseItemStackString(fertilizers[0], OreDictionary.WILDCARD_VALUE); int fertilizerValue = Integer.parseInt(fertilizers[1]); Farmables.fertilizers.put(fertilizerItem, fertilizerValue); - }catch(Exception e){ + } catch (Exception e) { Log.error("Forestry failed to parse a fertilizer entry at the farm config, at the position " + i + ".", e); } } } - @Nonnull - private static Set getItemStrings(LinkedHashMap itemStacks) { + private static Set getItemStrings(Map itemStacks) { Set itemStrings = new HashSet<>(itemStacks.size()); for (Entry itemStack : itemStacks.entrySet()) { String itemString = ItemStackUtil.getStringForItemStack(itemStack.getKey()); @@ -185,7 +188,7 @@ public class PluginFarming extends BlankForestryPlugin { } return itemStrings; } - + @Override public void registerTriggers() { FarmingTriggers.initialize(); @@ -194,7 +197,7 @@ public class PluginFarming extends BlankForestryPlugin { @Override public void doInit() { super.doInit(); - + //Load config File configFile = new File(Forestry.instance.getConfigFolder(), Config.CATEGORY_FARM + ".cfg"); LocalizedConfiguration config = new LocalizedConfiguration(configFile, "1.0.0"); @@ -207,27 +210,30 @@ public class PluginFarming extends BlankForestryPlugin { GameRegistry.registerTileEntity(TileFarmValve.class, "forestry.FarmValve"); GameRegistry.registerTileEntity(TileFarmControl.class, "forestry.FarmControl"); - Circuit.farmArborealManaged = new CircuitFarmLogic("managedArboreal", new FarmLogicArboreal()); - Circuit.farmShroomManaged = new CircuitFarmLogic("managedShroom", new FarmLogicMushroom()); - Circuit.farmPeatManaged = new CircuitFarmLogic("managedPeat", new FarmLogicPeat()); - Circuit.farmCerealManaged = new CircuitFarmLogic("managedCereal", new FarmLogicCereal()); - Circuit.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", new FarmLogicVegetable()); - Circuit.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", new FarmLogicInfernal()); + Circuits.farmArborealManaged = new CircuitFarmLogic("managedArboreal", new FarmLogicArboreal()); + Circuits.farmShroomManaged = new CircuitFarmLogic("managedShroom", new FarmLogicMushroom()); + Circuits.farmPeatManaged = new CircuitFarmLogic("managedPeat", new FarmLogicPeat()); + Circuits.farmCerealManaged = new CircuitFarmLogic("managedCereal", new FarmLogicCereal()); + Circuits.farmVegetableManaged = new CircuitFarmLogic("managedVegetable", new FarmLogicVegetable()); + Circuits.farmInfernalManaged = new CircuitFarmLogic("managedInfernal", new FarmLogicInfernal()); - Circuit.farmPeatManual = new CircuitFarmLogic("manualPeat", new FarmLogicPeat()).setManual(); - Circuit.farmShroomManual = new CircuitFarmLogic("manualShroom", new FarmLogicMushroom()).setManual(); - Circuit.farmCerealManual = new CircuitFarmLogic("manualCereal", new FarmLogicCereal()).setManual(); - Circuit.farmVegetableManual = new CircuitFarmLogic("manualVegetable", new FarmLogicVegetable()).setManual(); - Circuit.farmSucculentManual = new CircuitFarmLogic("manualSucculent", new FarmLogicSucculent()).setManual(); - Circuit.farmPoalesManual = new CircuitFarmLogic("manualPoales", new FarmLogicReeds()).setManual(); - Circuit.farmGourdManual = new CircuitFarmLogic("manualGourd", new FarmLogicGourd()).setManual(); - Circuit.farmCocoaManual = new CircuitFarmLogic("manualCocoa", new FarmLogicCocoa()).setManual(); + Circuits.farmPeatManual = new CircuitFarmLogic("manualPeat", new FarmLogicPeat()).setManual(); + Circuits.farmShroomManual = new CircuitFarmLogic("manualShroom", new FarmLogicMushroom()).setManual(); + Circuits.farmCerealManual = new CircuitFarmLogic("manualCereal", new FarmLogicCereal()).setManual(); + Circuits.farmVegetableManual = new CircuitFarmLogic("manualVegetable", new FarmLogicVegetable()).setManual(); + Circuits.farmSucculentManual = new CircuitFarmLogic("manualSucculent", new FarmLogicSucculent()).setManual(); + Circuits.farmPoalesManual = new CircuitFarmLogic("manualPoales", new FarmLogicReeds()).setManual(); + Circuits.farmGourdManual = new CircuitFarmLogic("manualGourd", new FarmLogicGourd()).setManual(); + Circuits.farmCocoaManual = new CircuitFarmLogic("manualCocoa", new FarmLogicCocoa()).setManual(); - Circuit.farmOrchardManual = new CircuitFarmLogic("manualOrchard", new FarmLogicOrchard()); + Circuits.farmOrchardManual = new CircuitFarmLogic("manualOrchard", new FarmLogicOrchard()); } @Override public void registerRecipes() { + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(blocks != null); + Preconditions.checkState(coreItems != null); ItemStack basic = blocks.farm.get(EnumFarmBlockType.PLAIN, 1); ItemStack gearbox = blocks.farm.get(EnumFarmBlockType.GEARBOX, 1); @@ -235,6 +241,7 @@ public class PluginFarming extends BlankForestryPlugin { ItemStack valve = blocks.farm.get(EnumFarmBlockType.VALVE, 1); ItemStack control = blocks.farm.get(EnumFarmBlockType.CONTROL, 1); + for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { NBTTagCompound compound = new NBTTagCompound(); block.saveToCompound(compound); @@ -250,7 +257,7 @@ public class PluginFarming extends BlankForestryPlugin { "WCW", '#', block.getBase(), 'W', "slabWood", - 'C', PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), + 'C', coreItems.tubes.get(EnumElectronTube.TIN, 1), 'I', "ingotCopper"); RecipeUtil.addRecipe(gearbox, @@ -277,7 +284,7 @@ public class PluginFarming extends BlankForestryPlugin { " # ", "XTX", '#', basic, - 'T', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), + 'T', coreItems.tubes.get(EnumElectronTube.GOLD, 1), 'X', "dustRedstone"); } @@ -285,26 +292,28 @@ public class PluginFarming extends BlankForestryPlugin { ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmArborealManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1), Circuit.farmInfernalManaged); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.COPPER, 1), Circuits.farmArborealManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.TIN, 1), Circuits.farmPeatManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.BRONZE, 1), Circuits.farmCerealManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.IRON, 1), Circuits.farmVegetableManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.BLAZE, 1), Circuits.farmInfernalManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, coreItems.tubes.get(EnumElectronTube.APATITE, 1), Circuits.farmShroomManaged); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.COPPER, 1), Circuit.farmOrchardManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.TIN, 1), Circuit.farmPeatManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.farmCerealManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), Circuit.farmVegetableManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1), Circuit.farmSucculentManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.DIAMOND, 1), Circuit.farmPoalesManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.OBSIDIAN, 1), Circuit.farmGourdManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.APATITE, 1), Circuit.farmShroomManual); - ChipsetManager.solderManager.addRecipe(layoutManual, PluginCore.items.tubes.get(EnumElectronTube.LAPIS, 1), Circuit.farmCocoaManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.COPPER, 1), Circuits.farmOrchardManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.TIN, 1), Circuits.farmPeatManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.BRONZE, 1), Circuits.farmCerealManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.IRON, 1), Circuits.farmVegetableManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.GOLD, 1), Circuits.farmSucculentManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.DIAMOND, 1), Circuits.farmPoalesManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.OBSIDIAN, 1), Circuits.farmGourdManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.APATITE, 1), Circuits.farmShroomManual); + ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.LAPIS, 1), Circuits.farmCocoaManual); } - + @Override public void getHiddenItems(List hiddenItems) { + Preconditions.checkState(blocks != null); + // mushrooms are a workaround for the farm and should not be obtainable hiddenItems.add(new ItemStack(blocks.mushroom, 1, OreDictionary.WILDCARD_VALUE)); } diff --git a/src/main/java/forestry/farming/blocks/BlockFarm.java b/src/main/java/forestry/farming/blocks/BlockFarm.java index 10ee8b1ee..f732e5627 100644 --- a/src/main/java/forestry/farming/blocks/BlockFarm.java +++ b/src/main/java/forestry/farming/blocks/BlockFarm.java @@ -10,9 +10,11 @@ ******************************************************************************/ package forestry.farming.blocks; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import forestry.core.tiles.TileUtil; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -28,6 +30,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; @@ -43,8 +46,8 @@ import net.minecraftforge.fml.relauncher.SideOnly; import forestry.api.core.IModelManager; import forestry.api.core.Tabs; import forestry.core.blocks.BlockStructure; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.utils.ItemStackUtil; import forestry.farming.models.EnumFarmBlockTexture; import forestry.farming.tiles.TileFarm; @@ -90,15 +93,14 @@ public class BlockFarm extends BlockStructure { } @Override - @SideOnly(Side.CLIENT) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { for (int i = 0; i < 6; i++) { if (i == 1) { continue; } for (EnumFarmBlockTexture block : EnumFarmBlockTexture.values()) { - ItemStack stack = new ItemStack(item, 1, i); + ItemStack stack = new ItemStack(itemIn, 1, i); NBTTagCompound compound = new NBTTagCompound(); block.saveToCompound(compound); stack.setTagCompound(compound); @@ -120,12 +122,14 @@ public class BlockFarm extends BlockStructure { public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { super.onBlockPlacedBy(world, pos, state, placer, stack); - if (!stack.hasTagCompound()) { + if (stack.getTagCompound() == null) { return; } - TileFarm tile = (TileFarm) world.getTileEntity(pos); - tile.setFarmBlockTexture(EnumFarmBlockTexture.getFromCompound(stack.getTagCompound())); + TileFarm tile = TileUtil.getTile(world, pos, TileFarm.class); + if (tile != null) { + tile.setFarmBlockTexture(EnumFarmBlockTexture.getFromCompound(stack.getTagCompound())); + } } @Override @@ -191,7 +195,7 @@ public class BlockFarm extends BlockStructure { } @Override - public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { + public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable EnumFacing side) { return state.getValue(META) == EnumFarmBlockType.CONTROL; } diff --git a/src/main/java/forestry/farming/blocks/BlockMushroom.java b/src/main/java/forestry/farming/blocks/BlockMushroom.java index 2c7894f91..71e4d56c5 100644 --- a/src/main/java/forestry/farming/blocks/BlockMushroom.java +++ b/src/main/java/forestry/farming/blocks/BlockMushroom.java @@ -29,6 +29,7 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; @@ -158,12 +159,10 @@ public class BlockMushroom extends BlockBush implements IItemModelRegister, IGro this.generateGiantMushroom(worldIn, pos, state, rand); } - /* ICONS */ - @SideOnly(Side.CLIENT) @Override - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - list.add(new ItemStack(item, 1, 0)); - list.add(new ItemStack(item, 1, 1)); + public void getSubBlocks(Item itemIn, CreativeTabs tab, NonNullList list) { + list.add(new ItemStack(itemIn, 1, 0)); + list.add(new ItemStack(itemIn, 1, 1)); } @Override diff --git a/src/main/java/forestry/farming/blocks/package-info.java b/src/main/java/forestry/farming/blocks/package-info.java new file mode 100644 index 000000000..7e6a2e1e4 --- /dev/null +++ b/src/main/java/forestry/farming/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java index 5bab2ae76..4e556230b 100755 --- a/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java +++ b/src/main/java/forestry/farming/circuits/CircuitFarmLogic.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.farming.circuits; +import javax.annotation.Nullable; + import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmLogic; @@ -35,6 +37,7 @@ public class CircuitFarmLogic extends Circuit { return tile instanceof IFarmHousing; } + @Nullable private IFarmHousing getCircuitable(Object tile) { if (!isCircuitable(tile)) { return null; diff --git a/src/main/java/forestry/farming/circuits/package-info.java b/src/main/java/forestry/farming/circuits/package-info.java new file mode 100644 index 000000000..9b2f8e787 --- /dev/null +++ b/src/main/java/forestry/farming/circuits/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.circuits; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java b/src/main/java/forestry/farming/gui/FarmLogicSlot.java similarity index 90% rename from src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java rename to src/main/java/forestry/farming/gui/FarmLogicSlot.java index deb19d1d1..d8f64991b 100644 --- a/src/main/java/forestry/farming/gui/widgets/FarmLogicSlot.java +++ b/src/main/java/forestry/farming/gui/FarmLogicSlot.java @@ -1,76 +1,70 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.gui.widgets; - -import net.minecraft.client.renderer.RenderItem; -import net.minecraft.item.ItemStack; - -import forestry.api.farming.FarmDirection; -import forestry.api.farming.IFarmLogic; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.farming.multiblock.IFarmControllerInternal; - -public class FarmLogicSlot extends Widget { - - private final IFarmControllerInternal farmController; - private final FarmDirection farmDirection; - - public FarmLogicSlot(IFarmControllerInternal farmController, WidgetManager manager, int xPos, int yPos, FarmDirection farmDirection) { - super(manager, xPos, yPos); - this.farmController = farmController; - this.farmDirection = farmDirection; - } - - private IFarmLogic getLogic() { - return farmController.getFarmLogic(farmDirection); - } - - private ItemStack getStackIndex() { - if (getLogic() == null) { - return null; - } - return getLogic().getIconItemStack(); - } - - @Override - public void draw(int startX, int startY) { - if (getStackIndex() != null) { - Proxies.render.bindTexture(getLogic().getTextureMap()); - RenderItem renderItem = Proxies.common.getClientInstance().getRenderItem(); - renderItem.renderItemIntoGUI(getStackIndex(), startX + xPos, startY + yPos); - } - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - if (isMouseOver(mouseX, mouseY)) { - return toolTip; - } else { - return null; - } - } - - protected final ToolTip toolTip = new ToolTip(250) { - @Override - public void refresh() { - toolTip.clear(); - if (getLogic() == null) { - return; - } - toolTip.add(getLogic().getName()); - toolTip.add("Fertilizer: " + getLogic().getFertilizerConsumption()); - toolTip.add("Water: " + getLogic().getWaterConsumption(farmController.getFarmLedgerDelegate().getHydrationModifier())); - } - }; -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.farming.gui; + +import net.minecraft.client.renderer.RenderItem; +import net.minecraft.item.ItemStack; + +import forestry.api.farming.FarmDirection; +import forestry.api.farming.IFarmLogic; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.farming.multiblock.IFarmControllerInternal; + +public class FarmLogicSlot extends Widget { + + private final IFarmControllerInternal farmController; + private final FarmDirection farmDirection; + + public FarmLogicSlot(IFarmControllerInternal farmController, WidgetManager manager, int xPos, int yPos, FarmDirection farmDirection) { + super(manager, xPos, yPos); + this.farmController = farmController; + this.farmDirection = farmDirection; + } + + private IFarmLogic getLogic() { + return farmController.getFarmLogic(farmDirection); + } + + private ItemStack getStackIndex() { + return getLogic().getIconItemStack(); + } + + @Override + public void draw(int startX, int startY) { + if (!getStackIndex().isEmpty()) { + Proxies.render.bindTexture(getLogic().getTextureMap()); + RenderItem renderItem = Proxies.common.getClientInstance().getRenderItem(); + renderItem.renderItemIntoGUI(getStackIndex(), startX + xPos, startY + yPos); + } + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + if (isMouseOver(mouseX, mouseY)) { + return toolTip; + } else { + return null; + } + } + + protected final ToolTip toolTip = new ToolTip(250) { + @Override + public void refresh() { + toolTip.clear(); + toolTip.add(getLogic().getName()); + toolTip.add("Fertilizer: " + getLogic().getFertilizerConsumption()); + toolTip.add("Water: " + getLogic().getWaterConsumption(farmController.getFarmLedgerDelegate().getHydrationModifier())); + } + }; +} diff --git a/src/main/java/forestry/farming/gui/GuiFarm.java b/src/main/java/forestry/farming/gui/GuiFarm.java index 1bf15fe14..4724f6265 100755 --- a/src/main/java/forestry/farming/gui/GuiFarm.java +++ b/src/main/java/forestry/farming/gui/GuiFarm.java @@ -18,7 +18,6 @@ import forestry.core.gui.GuiForestryTitled; import forestry.core.gui.ledgers.ClimateLedger; import forestry.core.gui.widgets.SocketWidget; import forestry.core.gui.widgets.TankWidget; -import forestry.farming.gui.widgets.FarmLogicSlot; import forestry.farming.multiblock.IFarmControllerInternal; import forestry.farming.tiles.TileFarm; diff --git a/src/main/java/forestry/farming/gui/package-info.java b/src/main/java/forestry/farming/gui/package-info.java new file mode 100644 index 000000000..c11ae457e --- /dev/null +++ b/src/main/java/forestry/farming/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/items/ItemBlockFarm.java b/src/main/java/forestry/farming/items/ItemBlockFarm.java index 24b880a1c..2d7b7c167 100644 --- a/src/main/java/forestry/farming/items/ItemBlockFarm.java +++ b/src/main/java/forestry/farming/items/ItemBlockFarm.java @@ -33,7 +33,7 @@ public class ItemBlockFarm extends ItemBlock { @Override public void addInformation(ItemStack itemstack, EntityPlayer player, List info, boolean par4) { - if (!itemstack.hasTagCompound()) { + if (itemstack.getTagCompound() == null) { return; } diff --git a/src/main/java/forestry/farming/items/package-info.java b/src/main/java/forestry/farming/items/package-info.java new file mode 100644 index 000000000..e1ef8c84d --- /dev/null +++ b/src/main/java/forestry/farming/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/logic/Crop.java b/src/main/java/forestry/farming/logic/Crop.java index 4ebe6658f..560ea19e8 100755 --- a/src/main/java/forestry/farming/logic/Crop.java +++ b/src/main/java/forestry/farming/logic/Crop.java @@ -10,33 +10,30 @@ ******************************************************************************/ package forestry.farming.logic; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Collection; +import forestry.api.farming.ICrop; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.api.farming.ICrop; - public abstract class Crop implements ICrop { - private final World world; protected final BlockPos position; - protected Crop(@Nonnull World world, @Nonnull BlockPos position) { + protected Crop(World world, BlockPos position) { this.world = world; this.position = position; } protected abstract boolean isCrop(World world, BlockPos pos); - protected abstract Collection harvestBlock(World world, BlockPos pos); + protected abstract NonNullList harvestBlock(World world, BlockPos pos); @Nullable @Override - public Collection harvest() { + public NonNullList harvest() { if (!isCrop(world, position)) { return null; } @@ -44,7 +41,6 @@ public abstract class Crop implements ICrop { return harvestBlock(world, position); } - @Nonnull @Override public BlockPos getPosition() { return position; diff --git a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java index e174fc28c..c7758e68f 100644 --- a/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java +++ b/src/main/java/forestry/farming/logic/CropBasicAgriCraft.java @@ -10,12 +10,10 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -36,9 +34,10 @@ public class CropBasicAgriCraft extends Crop { } @Override - protected Collection harvestBlock(World world, BlockPos pos) { + protected NonNullList harvestBlock(World world, BlockPos pos) { Block block = blockState.getBlock(); - List harvest = block.getDrops(world, pos, blockState, 0); + NonNullList harvest = NonNullList.create(); + harvest.addAll(block.getDrops(world, pos, blockState, 0)); if (harvest.size() > 1) { harvest.remove(1); //AgriCraft returns cropsticks in 0, seeds in 1 in getDrops, removing since harvesting doesn't return them. } diff --git a/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java b/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java index 925503f0e..fff12e9c9 100644 --- a/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java +++ b/src/main/java/forestry/farming/logic/CropBasicGrowthCraft.java @@ -10,12 +10,10 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.List; - import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -42,15 +40,16 @@ public class CropBasicGrowthCraft extends Crop { } @Override - protected Collection harvestBlock(World world, BlockPos pos) { + protected NonNullList harvestBlock(World world, BlockPos pos) { Block block = blockState.getBlock(); - List harvest = block.getDrops(world, pos, blockState, 0); + NonNullList harvest = NonNullList.create(); + harvest.addAll(block.getDrops(world, pos, blockState, 0)); if (harvest.size() > 1) { harvest.remove(0); //Hops have rope as first drop. } PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); if (isGrape) { world.setBlockToAir(pos); diff --git a/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java b/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java index 4c7ea4889..07858d26c 100644 --- a/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java +++ b/src/main/java/forestry/farming/logic/CropBasicIC2Crop.java @@ -1,83 +1,83 @@ -package forestry.farming.logic; - -import javax.annotation.Nonnull; - -import java.util.Collection; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import net.minecraftforge.fml.common.Optional; - -import forestry.plugins.compat.PluginIC2; - -import ic2.api.crops.ICropTile; - -public class CropBasicIC2Crop extends Crop { - private final TileEntity tileEntity; - - public CropBasicIC2Crop(@Nonnull World world, @Nonnull TileEntity tileEntity, @Nonnull BlockPos position) { - super(world, position); - this.tileEntity = tileEntity; - } - - @Override - protected boolean isCrop(World world, BlockPos pos) { - return canHarvestCrop(this.tileEntity); - } - - @Override - protected Collection harvestBlock(World world, BlockPos pos) { - return getCropDrops(this.tileEntity); - } - - /** - * Check if there is an instance of ICropTile. - * @param tileEntity tile entity to be checked. - * @return true if there is an IC2 crop and false otherwise. - */ - @Optional.Method(modid = PluginIC2.modId) - public static boolean isIC2Crop(TileEntity tileEntity) { - if (tileEntity instanceof ICropTile) { - return true; - } - return false; - } - - /** - * Check if an IC2 crop is ready to be harvested. - * @param tileEntity tile entity to be checked. - * @return true if crop size is optimal for harvest and false otherwise. - */ - @Optional.Method(modid = PluginIC2.modId) - public static boolean canHarvestCrop(TileEntity tileEntity) { - if (isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile) tileEntity; - if (crop.getCrop() == null) { - return false; - } - if (crop.getCurrentSize() == crop.getCrop().getOptimalHarvestSize(crop)) { - return true; - } - } - return false; - } - - /** - * This function takes care of everything related to the harvesting of the - * crop meaning it will calculate the drops and also do setSizeAfterHarvest(). - * @param tileEntity tile entity to be checked. - * @return list containing the drops. - */ - @Optional.Method(modid = PluginIC2.modId) - private static List getCropDrops(TileEntity tileEntity) { - if (isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile) tileEntity; - return crop.performHarvest(); - } - return null; - } -} +//package forestry.farming.logic; +// +//import javax.annotation.Nonnull; +// +//import java.util.Collection; +//import java.util.List; +// +//import net.minecraft.item.ItemStack; +//import net.minecraft.tileentity.TileEntity; +//import net.minecraft.util.math.BlockPos; +//import net.minecraft.world.World; +// +//import net.minecraftforge.fml.common.Optional; +// +//import forestry.plugins.compat.PluginIC2; +// +//import ic2.api.crops.ICropTile; +// +//public class CropBasicIC2Crop extends Crop { +// private final TileEntity tileEntity; +// +// public CropBasicIC2Crop(@Nonnull World world, @Nonnull TileEntity tileEntity, @Nonnull BlockPos position) { +// super(world, position); +// this.tileEntity = tileEntity; +// } +// +// @Override +// protected boolean isCrop(World world, BlockPos pos) { +// return canHarvestCrop(this.tileEntity); +// } +// +// @Override +// protected Collection harvestBlock(World world, BlockPos pos) { +// return getCropDrops(this.tileEntity); +// } +// +// /** +// * Check if there is an instance of ICropTile. +// * @param tileEntity tile entity to be checked. +// * @return true if there is an IC2 crop and false otherwise. +// */ +// @Optional.Method(modid = PluginIC2.modId) +// public static boolean isIC2Crop(TileEntity tileEntity) { +// if (tileEntity instanceof ICropTile) { +// return true; +// } +// return false; +// } +// +// /** +// * Check if an IC2 crop is ready to be harvested. +// * @param tileEntity tile entity to be checked. +// * @return true if crop size is optimal for harvest and false otherwise. +// */ +// @Optional.Method(modid = PluginIC2.modId) +// public static boolean canHarvestCrop(TileEntity tileEntity) { +// if (isIC2Crop(tileEntity)) { +// ICropTile crop = (ICropTile) tileEntity; +// if (crop.getCrop() == null) { +// return false; +// } +// if (crop.getCurrentSize() == crop.getCrop().getOptimalHarvestSize(crop)) { +// return true; +// } +// } +// return false; +// } +// +// /** +// * This function takes care of everything related to the harvesting of the +// * crop meaning it will calculate the drops and also do setSizeAfterHarvest(). +// * @param tileEntity tile entity to be checked. +// * @return list containing the drops. +// */ +// @Optional.Method(modid = PluginIC2.modId) +// private static List getCropDrops(TileEntity tileEntity) { +// if (isIC2Crop(tileEntity)) { +// ICropTile crop = (ICropTile) tileEntity; +// return crop.performHarvest(); +// } +// return null; +// } +//} diff --git a/src/main/java/forestry/farming/logic/CropDestroy.java b/src/main/java/forestry/farming/logic/CropDestroy.java index 169aae206..2422b7ff3 100644 --- a/src/main/java/forestry/farming/logic/CropDestroy.java +++ b/src/main/java/forestry/farming/logic/CropDestroy.java @@ -11,11 +11,11 @@ package forestry.farming.logic; import javax.annotation.Nullable; -import java.util.Collection; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -41,12 +41,13 @@ public class CropDestroy extends Crop { } @Override - protected Collection harvestBlock(World world, BlockPos pos) { + protected NonNullList harvestBlock(World world, BlockPos pos) { Block block = blockState.getBlock(); - Collection harvested = block.getDrops(world, pos, blockState, 0); + NonNullList harvested = NonNullList.create(); + harvested.addAll(block.getDrops(world, pos, blockState, 0)); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); if (replantState != null) { world.setBlockState(pos, replantState, Constants.FLAG_BLOCK_SYNC); diff --git a/src/main/java/forestry/farming/logic/CropFruit.java b/src/main/java/forestry/farming/logic/CropFruit.java index 6d06f96f8..e460a09b4 100755 --- a/src/main/java/forestry/farming/logic/CropFruit.java +++ b/src/main/java/forestry/farming/logic/CropFruit.java @@ -10,12 +10,10 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.Collection; -import java.util.Collections; - import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -47,16 +45,16 @@ public class CropFruit extends Crop { } @Override - protected Collection harvestBlock(World world, BlockPos pos) { + protected NonNullList harvestBlock(World world, BlockPos pos) { TileEntity tile = world.getTileEntity(pos); if (!(tile instanceof IFruitBearer)) { - return Collections.emptySet(); + return NonNullList.create(); } IBlockState blockState = world.getBlockState(pos); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); - return ((IFruitBearer) tile).pickFruit(null); + Proxies.net.sendNetworkPacket(packet, pos, world); + return ((IFruitBearer) tile).pickFruit(ItemStack.EMPTY); } } diff --git a/src/main/java/forestry/farming/logic/CropPeat.java b/src/main/java/forestry/farming/logic/CropPeat.java index 679da9484..6a591b2ac 100755 --- a/src/main/java/forestry/farming/logic/CropPeat.java +++ b/src/main/java/forestry/farming/logic/CropPeat.java @@ -10,22 +10,18 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.core.PluginCore; import forestry.core.blocks.BlockBogEarth; import forestry.core.config.Constants; import forestry.core.network.packets.PacketFXSignal; import forestry.core.proxy.Proxies; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class CropPeat extends Crop { @@ -46,14 +42,14 @@ public class CropPeat extends Crop { } @Override - protected Collection harvestBlock(World world, BlockPos pos) { - List drops = new ArrayList<>(); + protected NonNullList harvestBlock(World world, BlockPos pos) { + NonNullList drops = NonNullList.create(); drops.add(PluginCore.items.peat.getItemStack()); IBlockState blockState = world.getBlockState(pos); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); world.setBlockState(pos, Blocks.DIRT.getDefaultState(), Constants.FLAG_BLOCK_SYNC); return drops; diff --git a/src/main/java/forestry/farming/logic/CropRubber.java b/src/main/java/forestry/farming/logic/CropRubber.java index c7a606e46..814138229 100755 --- a/src/main/java/forestry/farming/logic/CropRubber.java +++ b/src/main/java/forestry/farming/logic/CropRubber.java @@ -1,94 +1,94 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.logic; - -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; - -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableCollection; -import forestry.core.config.Constants; -import forestry.core.network.packets.PacketFXSignal; -import forestry.core.proxy.Proxies; -import forestry.core.utils.ItemStackUtil; -import forestry.plugins.compat.PluginIC2; -import net.minecraft.block.Block; -import net.minecraft.block.properties.IProperty; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -public class CropRubber extends CropDestroy { - - public CropRubber(World world, IBlockState blockState, BlockPos position) { - super(world, blockState, position, getReplantState(blockState)); - } - - /** - * Convert a "wet" rubber log blockstate into the dry version. - * Total hack since we don't have access to the blockstates. - */ - private static > IBlockState getReplantState(IBlockState sappyState) { - if (hasRubberToHarvest(sappyState)) { - for (Map.Entry, Comparable> wetPropertyEntry : sappyState.getProperties().entrySet()) { - String valueWetString = wetPropertyEntry.getValue().toString(); - String valueDryString = valueWetString.replace("wet", "dry"); - IProperty property = wetPropertyEntry.getKey(); - - IBlockState baseState = sappyState.getBlock().getBlockState().getBaseState(); - IBlockState dryState = getStateWithValue(baseState, property, valueDryString); - if (dryState != null) { - return dryState; - } - } - } - - return sappyState.getBlock().getDefaultState(); - } - - public static boolean hasRubberToHarvest(IBlockState blockState) { - Block block = blockState.getBlock(); - if (ItemStackUtil.equals(block, PluginIC2.rubberWood)) { - ImmutableCollection> propertyValues = blockState.getProperties().values(); - for (Comparable propertyValue : propertyValues) { - if (propertyValue.toString().contains("wet")) { - return true; - } - } - } - return false; - } - - @Nullable - private static > IBlockState getStateWithValue(IBlockState baseState, IProperty property, String valueString) { - Optional value = property.parseValue(valueString); - if (value.isPresent()) { - return baseState.withProperty(property, value.get()); - } - return null; - } - - @Override - protected Collection harvestBlock(World world, BlockPos pos) { - Collection harvested = new ArrayList<>(); - harvested.add(PluginIC2.resin.copy()); - - PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, world); - - world.setBlockState(pos, replantState, Constants.FLAG_BLOCK_SYNC); - return harvested; - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.farming.logic; +// +//import javax.annotation.Nullable; +//import java.util.ArrayList; +//import java.util.Collection; +//import java.util.Map; +// +//import com.google.common.base.Optional; +//import com.google.common.collect.ImmutableCollection; +//import forestry.core.config.Constants; +//import forestry.core.network.packets.PacketFXSignal; +//import forestry.core.proxy.Proxies; +//import forestry.core.utils.ItemStackUtil; +//import forestry.plugins.compat.PluginIC2; +//import net.minecraft.block.Block; +//import net.minecraft.block.properties.IProperty; +//import net.minecraft.block.state.IBlockState; +//import net.minecraft.item.ItemStack; +//import net.minecraft.util.math.BlockPos; +//import net.minecraft.world.World; +// +//public class CropRubber extends CropDestroy { +// +// public CropRubber(World world, IBlockState blockState, BlockPos position) { +// super(world, blockState, position, getReplantState(blockState)); +// } +// +// /** +// * Convert a "wet" rubber log blockstate into the dry version. +// * Total hack since we don't have access to the blockstates. +// */ +// private static > IBlockState getReplantState(IBlockState sappyState) { +// if (hasRubberToHarvest(sappyState)) { +// for (Map.Entry, Comparable> wetPropertyEntry : sappyState.getProperties().entrySet()) { +// String valueWetString = wetPropertyEntry.getValue().toString(); +// String valueDryString = valueWetString.replace("wet", "dry"); +// IProperty property = wetPropertyEntry.getKey(); +// +// IBlockState baseState = sappyState.getBlock().getBlockState().getBaseState(); +// IBlockState dryState = getStateWithValue(baseState, property, valueDryString); +// if (dryState != null) { +// return dryState; +// } +// } +// } +// +// return sappyState.getBlock().getDefaultState(); +// } +// +// public static boolean hasRubberToHarvest(IBlockState blockState) { +// Block block = blockState.getBlock(); +// if (ItemStackUtil.equals(block, PluginIC2.rubberWood)) { +// ImmutableCollection> propertyValues = blockState.getProperties().values(); +// for (Comparable propertyValue : propertyValues) { +// if (propertyValue.toString().contains("wet")) { +// return true; +// } +// } +// } +// return false; +// } +// +// @Nullable +// private static > IBlockState getStateWithValue(IBlockState baseState, IProperty property, String valueString) { +// Optional value = property.parseValue(valueString); +// if (value.isPresent()) { +// return baseState.withProperty(property, value.get()); +// } +// return null; +// } +// +// @Override +// protected Collection harvestBlock(World world, BlockPos pos) { +// Collection harvested = new ArrayList<>(); +// harvested.add(PluginIC2.resin.copy()); +// +// PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); +// Proxies.net.sendNetworkPacket(packet, world); +// +// world.setBlockState(pos, replantState, Constants.FLAG_BLOCK_SYNC); +// return harvested; +// } +// +//} diff --git a/src/main/java/forestry/farming/logic/FarmLogic.java b/src/main/java/forestry/farming/logic/FarmLogic.java index 2cd81f799..2f64b6713 100755 --- a/src/main/java/forestry/farming/logic/FarmLogic.java +++ b/src/main/java/forestry/farming/logic/FarmLogic.java @@ -10,8 +10,7 @@ ******************************************************************************/ package forestry.farming.logic; -import javax.annotation.Nonnull; -import java.util.ArrayList; +import javax.annotation.Nullable; import java.util.List; import com.google.common.base.Predicate; @@ -25,6 +24,7 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; @@ -48,23 +48,18 @@ public abstract class FarmLogic implements IFarmLogic { public ResourceLocation getTextureMap() { return TextureMap.LOCATION_BLOCKS_TEXTURE; } - + @Override public abstract ItemStack getIconItemStack(); public abstract boolean isAcceptedWindfall(ItemStack stack); - @Deprecated - protected final boolean isAirBlock(@Nonnull Block block, @Nonnull IBlockState blockState, @Nonnull World world, @Nonnull BlockPos blockPos) { - return block.isAir(blockState, world, blockPos); - } - protected final boolean isWaterSourceBlock(World world, BlockPos position) { IBlockState blockState = world.getBlockState(position); Block block = blockState.getBlock(); return block == Blocks.WATER; } - + protected final BlockPos translateWithOffset(BlockPos pos, FarmDirection farmDirection, int step) { return VectUtil.scale(farmDirection.getFacing().getDirectionVec(), step).add(pos); } @@ -85,11 +80,11 @@ public abstract class FarmLogic implements IFarmLogic { return new AxisAlignedBB(min.getX(), min.getY(), min.getZ(), max.getX(), maxY, max.getZ()); } - protected List collectEntityItems(World world, IFarmHousing farmHousing, boolean toWorldHeight) { + protected NonNullList collectEntityItems(World world, IFarmHousing farmHousing, boolean toWorldHeight) { AxisAlignedBB harvestBox = getHarvestBox(world, farmHousing, toWorldHeight); List entityItems = world.getEntitiesWithinAABB(EntityItem.class, harvestBox, entitySelectorFarm); - List stacks = new ArrayList<>(); + NonNullList stacks = NonNullList.create(); for (EntityItem entity : entityItems) { ItemStack contained = entity.getEntityItem(); stacks.add(contained.copy()); @@ -106,8 +101,8 @@ public abstract class FarmLogic implements IFarmLogic { } @Override - public boolean apply(EntityItem entity) { - if (entity.isDead) { + public boolean apply(@Nullable EntityItem entity) { + if (entity == null || entity.isDead) { return false; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java index 62ae06109..a962ada95 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicArboreal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicArboreal.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.farming.logic; +import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -21,6 +22,7 @@ import java.util.Stack; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -61,8 +63,8 @@ public class FarmLogicArboreal extends FarmLogicHomogeneous { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - Collection products = produce; + public NonNullList collect(World world, IFarmHousing farmHousing) { + NonNullList products = produce; produce = collectEntityItems(world, farmHousing, true); return products; } @@ -122,6 +124,7 @@ public class FarmLogicArboreal extends FarmLogicHomogeneous { return crops; } + @Nullable private static IFarmable getFarmableForBlock(World world, BlockPos position, Collection farmables) { IBlockState blockState = world.getBlockState(position); for (IFarmable farmable : farmables) { diff --git a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java index 390e73c1a..8332f0959 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCocoa.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCocoa.java @@ -27,6 +27,7 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -74,8 +75,8 @@ public class FarmLogicCocoa extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } private final Map lastExtentsCultivation = new HashMap<>(); @@ -146,10 +147,7 @@ public class FarmLogicCocoa extends FarmLogic { private static boolean isJungleTreeTrunk(IBlockState blockState) { Block block = blockState.getBlock(); - if (block == Blocks.LOG && blockState.getValue(BlockOldLog.VARIANT) == BlockPlanks.EnumType.JUNGLE) { - return true; - } - return false; + return block == Blocks.LOG && blockState.getValue(BlockOldLog.VARIANT) == BlockPlanks.EnumType.JUNGLE; } private Collection getHarvestBlocks(World world, BlockPos position) { diff --git a/src/main/java/forestry/farming/logic/FarmLogicCrops.java b/src/main/java/forestry/farming/logic/FarmLogicCrops.java index 8b568eaa4..0dfa2399f 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicCrops.java +++ b/src/main/java/forestry/farming/logic/FarmLogicCrops.java @@ -17,6 +17,7 @@ import java.util.Stack; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -61,8 +62,8 @@ public abstract class FarmLogicCrops extends FarmLogicWatered { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - Collection products = produce; + public NonNullList collect(World world, IFarmHousing farmHousing) { + NonNullList products = produce; produce = collectEntityItems(world, farmHousing, false); return products; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicEnder.java b/src/main/java/forestry/farming/logic/FarmLogicEnder.java index 48b03b15b..bbb636df1 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicEnder.java +++ b/src/main/java/forestry/farming/logic/FarmLogicEnder.java @@ -17,6 +17,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -54,8 +55,8 @@ public class FarmLogicEnder extends FarmLogicHomogeneous { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmLogicGourd.java b/src/main/java/forestry/farming/logic/FarmLogicGourd.java index b50f99ddd..55d408c3d 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicGourd.java +++ b/src/main/java/forestry/farming/logic/FarmLogicGourd.java @@ -16,6 +16,7 @@ import java.util.Stack; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -70,8 +71,8 @@ public class FarmLogicGourd extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java index 63fa46a0c..8945cbba3 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java +++ b/src/main/java/forestry/farming/logic/FarmLogicHomogeneous.java @@ -10,21 +10,20 @@ ******************************************************************************/ package forestry.farming.logic; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmHousing; import forestry.api.farming.IFarmable; import forestry.core.utils.BlockUtil; import forestry.farming.FarmHelper; +import net.minecraft.block.state.IBlockState; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public abstract class FarmLogicHomogeneous extends FarmLogic { @@ -32,15 +31,15 @@ public abstract class FarmLogicHomogeneous extends FarmLogic { private final IBlockState soilState; protected final List farmables; - List produce = new ArrayList<>(); + protected NonNullList produce = NonNullList.create(); - protected FarmLogicHomogeneous(ItemStack resource, @Nonnull IBlockState soilState, Collection farmables) { + protected FarmLogicHomogeneous(ItemStack resource, IBlockState soilState, Collection farmables) { this.resource = resource; this.soilState = soilState; this.farmables = new ArrayList<>(farmables); } - protected boolean isAcceptedSoil(@Nonnull IBlockState blockState) { + protected boolean isAcceptedSoil(IBlockState blockState) { return soilState.getBlock() == blockState.getBlock(); } @@ -71,16 +70,13 @@ public abstract class FarmLogicHomogeneous extends FarmLogic { @Override public boolean cultivate(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent) { - - if (maintainSoil(world, farmHousing, pos, direction, extent)) { - return true; - } - - return maintainGermlings(world, farmHousing, pos.up(), direction, extent); + return maintainSoil(world, farmHousing, pos, direction, extent) || + maintainGermlings(world, farmHousing, pos.up(), direction, extent); } private boolean maintainSoil(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent) { - ItemStack[] resources = new ItemStack[]{resource}; + NonNullList resources = NonNullList.create(); + resources.add(resource); if (!farmHousing.getFarmInventory().hasResources(resources)) { return false; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java index ed0cbcdb3..ba5a94dc8 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicInfernal.java +++ b/src/main/java/forestry/farming/logic/FarmLogicInfernal.java @@ -17,6 +17,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -54,8 +55,8 @@ public class FarmLogicInfernal extends FarmLogicHomogeneous { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmLogicMushroom.java b/src/main/java/forestry/farming/logic/FarmLogicMushroom.java index 843962a79..15c43c7c4 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicMushroom.java +++ b/src/main/java/forestry/farming/logic/FarmLogicMushroom.java @@ -10,15 +10,12 @@ ******************************************************************************/ package forestry.farming.logic; -import java.util.ArrayList; -import java.util.Collection; - -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - import forestry.api.farming.Farmables; import forestry.api.farming.IFarmHousing; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; public class FarmLogicMushroom extends FarmLogicArboreal { @@ -51,9 +48,9 @@ public class FarmLogicMushroom extends FarmLogicArboreal { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - Collection products = produce; - produce = new ArrayList<>(); + public NonNullList collect(World world, IFarmHousing farmHousing) { + NonNullList products = produce; + produce = NonNullList.create(); return products; } diff --git a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java index 94866036d..0854cda77 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicOrchard.java +++ b/src/main/java/forestry/farming/logic/FarmLogicOrchard.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.farming.logic; +import javax.annotation.Nullable; + import com.google.common.collect.ImmutableList; import java.util.ArrayList; @@ -24,6 +26,7 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -92,8 +95,8 @@ public class FarmLogicOrchard extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override @@ -138,7 +141,7 @@ public class FarmLogicOrchard extends FarmLogic { // Determine what type we want to harvest. IBlockState blockState = world.getBlockState(position); Block block = blockState.getBlock(); - if (!block.isWood(world, position) && !isBlockTraversable(blockState, world, position, traversalBlocks) && !isFruitBearer(world, position)) { + if (!block.isWood(world, position) && !isBlockTraversable(blockState, traversalBlocks) && !isFruitBearer(world, position)) { return crops; } @@ -181,7 +184,7 @@ public class FarmLogicOrchard extends FarmLogic { IBlockState blockState = world.getBlockState(candidate); Block block = blockState.getBlock(); - if (block.isWood(world, candidate) || isBlockTraversable(blockState, world, candidate, traversalBlocks)) { + if (block.isWood(world, candidate) || isBlockTraversable(blockState, traversalBlocks)) { candidates.add(candidate); seen.add(candidate); } @@ -217,7 +220,7 @@ public class FarmLogicOrchard extends FarmLogic { return false; } - private static boolean isBlockTraversable(IBlockState blockState, World world, BlockPos position, ImmutableList traversalBlocks) { + private static boolean isBlockTraversable(IBlockState blockState, ImmutableList traversalBlocks) { Block candidate = blockState.getBlock(); for (Block block : traversalBlocks) { if (block == candidate) { @@ -227,6 +230,7 @@ public class FarmLogicOrchard extends FarmLogic { return false; } + @Nullable private ICrop getCrop(World world, BlockPos position) { TileEntity tile = world.getTileEntity(position); diff --git a/src/main/java/forestry/farming/logic/FarmLogicReeds.java b/src/main/java/forestry/farming/logic/FarmLogicReeds.java index 1e1126ce9..a551fc073 100644 --- a/src/main/java/forestry/farming/logic/FarmLogicReeds.java +++ b/src/main/java/forestry/farming/logic/FarmLogicReeds.java @@ -17,6 +17,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -78,8 +79,8 @@ public class FarmLogicReeds extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmLogicRubber.java b/src/main/java/forestry/farming/logic/FarmLogicRubber.java index f8e53b86a..8313377a0 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicRubber.java +++ b/src/main/java/forestry/farming/logic/FarmLogicRubber.java @@ -1,132 +1,132 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.farming.logic; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; - -import forestry.api.farming.FarmDirection; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmHousing; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.Log; -import forestry.plugins.compat.PluginIC2; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -public class FarmLogicRubber extends FarmLogic { - - private boolean active = true; - - public FarmLogicRubber() { - if (PluginIC2.rubberWood == null || PluginIC2.resin == null) { - Log.warning("Failed to init a farm logic {} since IC2 rubber wood or resin were not found", getClass().getName()); - active = false; - } - } - - @Override - public ItemStack getIconItemStack() { - return PluginIC2.resin; - } - - @Override - public String getName() { - return "Rubber Plantation"; - } - - @Override - public int getFertilizerConsumption() { - return 40; - } - - @Override - public int getWaterConsumption(float hydrationModifier) { - return (int) (5 * hydrationModifier); - } - - @Override - public boolean isAcceptedResource(ItemStack itemstack) { - return false; - } - - @Override - public boolean isAcceptedGermling(ItemStack itemstack) { - return false; - } - - @Override - public boolean isAcceptedWindfall(ItemStack stack) { - return false; - } - - @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; - } - - @Override - public boolean cultivate(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent) { - return false; - } - - private final Map lastExtents = new HashMap<>(); - - @Override - public Collection harvest(World world, BlockPos pos, FarmDirection direction, int extent) { - if (!active) { - return null; - } - - if (!lastExtents.containsKey(pos)) { - lastExtents.put(pos, 0); - } - - int lastExtent = lastExtents.get(pos); - if (lastExtent > extent) { - lastExtent = 0; - } - - BlockPos position = translateWithOffset(pos.up(), direction, lastExtent); - Collection crops = getHarvestBlocks(world, position); - lastExtent++; - lastExtents.put(pos, lastExtent); - - return crops; - } - - private Collection getHarvestBlocks(World world, BlockPos position) { - Stack crops = new Stack<>(); - - for (int j = 0; j < 10; j++) { - BlockPos candidate = position.add(0, j, 0); - - IBlockState blockState = world.getBlockState(candidate); - Block block = blockState.getBlock(); - if (!ItemStackUtil.equals(block, PluginIC2.rubberWood)) { - break; - } - - if (CropRubber.hasRubberToHarvest(blockState)) { - crops.push(new CropRubber(world, blockState, candidate)); - break; - } - } - - return crops; - } - -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.farming.logic; +// +//import java.util.Collection; +//import java.util.HashMap; +//import java.util.Map; +//import java.util.Stack; +// +//import forestry.api.farming.FarmDirection; +//import forestry.api.farming.ICrop; +//import forestry.api.farming.IFarmHousing; +//import forestry.core.utils.ItemStackUtil; +//import forestry.core.utils.Log; +//import forestry.plugins.compat.PluginIC2; +//import net.minecraft.block.Block; +//import net.minecraft.block.state.IBlockState; +//import net.minecraft.item.ItemStack; +//import net.minecraft.util.math.BlockPos; +//import net.minecraft.world.World; +// +//public class FarmLogicRubber extends FarmLogic { +// +// private boolean active = true; +// +// public FarmLogicRubber() { +// if (PluginIC2.rubberWood == null || PluginIC2.resin == null) { +// Log.warning("Failed to init a farm logic {} since IC2 rubber wood or resin were not found", getClass().getName()); +// active = false; +// } +// } +// +// @Override +// public ItemStack getIconItemStack() { +// return PluginIC2.resin; +// } +// +// @Override +// public String getName() { +// return "Rubber Plantation"; +// } +// +// @Override +// public int getFertilizerConsumption() { +// return 40; +// } +// +// @Override +// public int getWaterConsumption(float hydrationModifier) { +// return (int) (5 * hydrationModifier); +// } +// +// @Override +// public boolean isAcceptedResource(ItemStack itemstack) { +// return false; +// } +// +// @Override +// public boolean isAcceptedGermling(ItemStack itemstack) { +// return false; +// } +// +// @Override +// public boolean isAcceptedWindfall(ItemStack stack) { +// return false; +// } +// +// @Override +// public Collection collect(World world, IFarmHousing farmHousing) { +// return null; +// } +// +// @Override +// public boolean cultivate(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent) { +// return false; +// } +// +// private final Map lastExtents = new HashMap<>(); +// +// @Override +// public Collection harvest(World world, BlockPos pos, FarmDirection direction, int extent) { +// if (!active) { +// return null; +// } +// +// if (!lastExtents.containsKey(pos)) { +// lastExtents.put(pos, 0); +// } +// +// int lastExtent = lastExtents.get(pos); +// if (lastExtent > extent) { +// lastExtent = 0; +// } +// +// BlockPos position = translateWithOffset(pos.up(), direction, lastExtent); +// Collection crops = getHarvestBlocks(world, position); +// lastExtent++; +// lastExtents.put(pos, lastExtent); +// +// return crops; +// } +// +// private Collection getHarvestBlocks(World world, BlockPos position) { +// Stack crops = new Stack<>(); +// +// for (int j = 0; j < 10; j++) { +// BlockPos candidate = position.add(0, j, 0); +// +// IBlockState blockState = world.getBlockState(candidate); +// Block block = blockState.getBlock(); +// if (!ItemStackUtil.equals(block, PluginIC2.rubberWood)) { +// break; +// } +// +// if (CropRubber.hasRubberToHarvest(blockState)) { +// crops.push(new CropRubber(world, blockState, candidate)); +// break; +// } +// } +// +// return crops; +// } +// +//} diff --git a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java index fc1d2dd6a..3f43d4f03 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicSucculent.java +++ b/src/main/java/forestry/farming/logic/FarmLogicSucculent.java @@ -17,6 +17,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -78,8 +79,8 @@ public class FarmLogicSucculent extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - return null; + public NonNullList collect(World world, IFarmHousing farmHousing) { + return NonNullList.create(); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmLogicWatered.java b/src/main/java/forestry/farming/logic/FarmLogicWatered.java index 11d476e29..43c6152c3 100755 --- a/src/main/java/forestry/farming/logic/FarmLogicWatered.java +++ b/src/main/java/forestry/farming/logic/FarmLogicWatered.java @@ -10,36 +10,30 @@ ******************************************************************************/ package forestry.farming.logic; -import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - import forestry.api.farming.FarmDirection; import forestry.api.farming.IFarmHousing; import forestry.core.utils.BlockUtil; import forestry.farming.FarmHelper; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; public abstract class FarmLogicWatered extends FarmLogic { protected final IBlockState ground; private final ItemStack resource; - + private static final FluidStack STACK_WATER = new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME); - protected List produce = new ArrayList<>(); + protected NonNullList produce = NonNullList.create(); - protected FarmLogicWatered(ItemStack resource, @Nonnull IBlockState ground) { + protected FarmLogicWatered(ItemStack resource, IBlockState ground) { this.ground = ground; this.resource = resource; } @@ -64,9 +58,9 @@ public abstract class FarmLogicWatered extends FarmLogic { } @Override - public Collection collect(World world, IFarmHousing farmHousing) { - Collection products = produce; - produce = new ArrayList<>(); + public NonNullList collect(World world, IFarmHousing farmHousing) { + NonNullList products = produce; + produce = NonNullList.create(); return products; } @@ -89,7 +83,8 @@ public abstract class FarmLogicWatered extends FarmLogic { } private boolean maintainSoil(World world, IFarmHousing farmHousing, BlockPos pos, FarmDirection direction, int extent) { - ItemStack[] resources = new ItemStack[]{resource}; + NonNullList resources = NonNullList.create(); + resources.add(resource); for (int i = 0; i < extent; i++) { BlockPos position = translateWithOffset(pos, direction, i); @@ -146,7 +141,8 @@ public abstract class FarmLogicWatered extends FarmLogic { } private boolean trySetSoil(World world, IFarmHousing farmHousing, BlockPos position) { - ItemStack[] resources = new ItemStack[]{resource}; + NonNullList resources = NonNullList.create(); + resources.add(resource); if (!farmHousing.getFarmInventory().hasResources(resources)) { return false; } diff --git a/src/main/java/forestry/farming/logic/FarmableAgingCrop.java b/src/main/java/forestry/farming/logic/FarmableAgingCrop.java index 7462fa388..222dec7a8 100644 --- a/src/main/java/forestry/farming/logic/FarmableAgingCrop.java +++ b/src/main/java/forestry/farming/logic/FarmableAgingCrop.java @@ -1,8 +1,11 @@ package forestry.farming.logic; -import javax.annotation.Nonnull; import javax.annotation.Nullable; +import com.google.common.base.Preconditions; +import forestry.api.farming.ICrop; +import forestry.api.farming.IFarmable; +import forestry.core.utils.BlockUtil; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; @@ -11,10 +14,6 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmable; -import forestry.core.utils.BlockUtil; - /** * For blocks that are harvestable once they are a certain age. */ @@ -26,11 +25,15 @@ public class FarmableAgingCrop implements IFarmable { @Nullable protected final Integer replantAge; - public FarmableAgingCrop(@Nonnull ItemStack germling, @Nonnull Block cropBlock, @Nonnull IProperty ageProperty, int minHarvestAge) { + public FarmableAgingCrop(ItemStack germling, Block cropBlock, IProperty ageProperty, int minHarvestAge) { this(germling, cropBlock, ageProperty, minHarvestAge, null); } public FarmableAgingCrop(ItemStack germling, Block cropBlock, IProperty ageProperty, int minHarvestAge, @Nullable Integer replantAge) { + Preconditions.checkNotNull(germling); + Preconditions.checkNotNull(cropBlock); + Preconditions.checkNotNull(ageProperty); + this.germling = germling; this.cropBlock = cropBlock; this.ageProperty = ageProperty; @@ -45,6 +48,7 @@ public class FarmableAgingCrop implements IFarmable { } @Override + @Nullable public ICrop getCropAt(World world, BlockPos pos, IBlockState blockState) { if (blockState.getBlock() != cropBlock) { return null; @@ -54,15 +58,15 @@ public class FarmableAgingCrop implements IFarmable { return null; } - if (replantAge != null) { - IBlockState replantState = getReplantState(world, pos, blockState); - return new CropDestroy(world, blockState, pos, replantState); - } else { - return new CropDestroy(world, blockState, pos, null); - } + IBlockState replantState = getReplantState(blockState); + return new CropDestroy(world, blockState, pos, replantState); } - protected IBlockState getReplantState(World world, BlockPos pos, IBlockState blockState) { + @Nullable + protected IBlockState getReplantState(IBlockState blockState) { + if (replantAge == null) { + return null; + } return blockState.withProperty(ageProperty, replantAge); } diff --git a/src/main/java/forestry/farming/logic/FarmableBase.java b/src/main/java/forestry/farming/logic/FarmableBase.java index c871a18c9..1be4e7839 100644 --- a/src/main/java/forestry/farming/logic/FarmableBase.java +++ b/src/main/java/forestry/farming/logic/FarmableBase.java @@ -35,11 +35,8 @@ public abstract class FarmableBase implements IFarmable { return null; } - if (replant) { - return new CropDestroy(world, blockState, pos, plantedState); - } else { - return new CropDestroy(world, blockState, pos, null); - } + IBlockState replantState = replant ? plantedState : null; + return new CropDestroy(world, blockState, pos, replantState); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java b/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java index 8700f63da..9a78601ca 100644 --- a/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java +++ b/src/main/java/forestry/farming/logic/FarmableBasicIC2Crop.java @@ -1,85 +1,85 @@ -package forestry.farming.logic; - -import javax.annotation.Nullable; - -import net.minecraft.block.state.IBlockState; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import net.minecraftforge.fml.common.Optional; - -import forestry.api.farming.ICrop; -import forestry.api.farming.IFarmable; -import forestry.plugins.compat.PluginIC2; - -import ic2.api.crops.ICropTile; - -public class FarmableBasicIC2Crop implements IFarmable { - - /** - * Perform some of the actions of the crop-matron. - */ - @Optional.Method(modid = PluginIC2.modId) - public static void babysitCrop(TileEntity tileEntity) { - if (CropBasicIC2Crop.isIC2Crop(tileEntity)) { - ICropTile crop = (ICropTile) tileEntity; - /* - This part might be unbalanced until a custom farm logic is added and makes use of weed-ex. - if (crop.getCrop() != null) { - if (crop.getCrop().isWeed(crop)) { - crop.reset(); - } - }*/ - if (crop.getStorageWater() <= 200) { - crop.setStorageWater(200); - } - if (crop.getStorageNutrient() <= 100) { - crop.setStorageNutrient(crop.getStorageNutrient() + 100); - } - } - } - - @Override - public boolean isSaplingAt(World world, BlockPos pos) { - TileEntity crop = world.getTileEntity(pos); - if (CropBasicIC2Crop.isIC2Crop(crop)) { - babysitCrop(crop); - return true; - } - return false; - } - - @Nullable - @Override - public ICrop getCropAt(World world, BlockPos pos, IBlockState blockState) { - TileEntity crop = world.getTileEntity(pos); - if (crop == null) { - return null; - } - if (!CropBasicIC2Crop.isIC2Crop(crop)) { - return null; - } - if (!CropBasicIC2Crop.canHarvestCrop(crop)) { - return null; - } - return new CropBasicIC2Crop(world, crop, pos); - } - - @Override - public boolean isGermling(ItemStack itemstack) { - return false; - } - - @Override - public boolean isWindfall(ItemStack itemstack) { - return false; - } - - @Override - public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, BlockPos pos) { - return false; - } -} +//package forestry.farming.logic; +// +//import javax.annotation.Nullable; +// +//import net.minecraft.block.state.IBlockState; +//import net.minecraft.entity.player.EntityPlayer; +//import net.minecraft.item.ItemStack; +//import net.minecraft.tileentity.TileEntity; +//import net.minecraft.util.math.BlockPos; +//import net.minecraft.world.World; +// +//import net.minecraftforge.fml.common.Optional; +// +//import forestry.api.farming.ICrop; +//import forestry.api.farming.IFarmable; +//import forestry.plugins.compat.PluginIC2; +// +//import ic2.api.crops.ICropTile; +// +//public class FarmableBasicIC2Crop implements IFarmable { +// +// /** +// * Perform some of the actions of the crop-matron. +// */ +// @Optional.Method(modid = PluginIC2.modId) +// public static void babysitCrop(TileEntity tileEntity) { +// if (CropBasicIC2Crop.isIC2Crop(tileEntity)) { +// ICropTile crop = (ICropTile) tileEntity; +// /* +// This part might be unbalanced until a custom farm logic is added and makes use of weed-ex. +// if (crop.getCrop() != null) { +// if (crop.getCrop().isWeed(crop)) { +// crop.reset(); +// } +// }*/ +// if (crop.getStorageWater() <= 200) { +// crop.setStorageWater(200); +// } +// if (crop.getStorageNutrient() <= 100) { +// crop.setStorageNutrient(crop.getStorageNutrient() + 100); +// } +// } +// } +// +// @Override +// public boolean isSaplingAt(World world, BlockPos pos) { +// TileEntity crop = world.getTileEntity(pos); +// if (CropBasicIC2Crop.isIC2Crop(crop)) { +// babysitCrop(crop); +// return true; +// } +// return false; +// } +// +// @Nullable +// @Override +// public ICrop getCropAt(World world, BlockPos pos, IBlockState blockState) { +// TileEntity crop = world.getTileEntity(pos); +// if (crop == null) { +// return null; +// } +// if (!CropBasicIC2Crop.isIC2Crop(crop)) { +// return null; +// } +// if (!CropBasicIC2Crop.canHarvestCrop(crop)) { +// return null; +// } +// return new CropBasicIC2Crop(world, crop, pos); +// } +// +// @Override +// public boolean isGermling(ItemStack itemstack) { +// return false; +// } +// +// @Override +// public boolean isWindfall(ItemStack itemstack) { +// return false; +// } +// +// @Override +// public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, BlockPos pos) { +// return false; +// } +//} diff --git a/src/main/java/forestry/farming/logic/FarmableGE.java b/src/main/java/forestry/farming/logic/FarmableGE.java index 0030df222..4d7017fa4 100755 --- a/src/main/java/forestry/farming/logic/FarmableGE.java +++ b/src/main/java/forestry/farming/logic/FarmableGE.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.farming.logic; +import forestry.api.arboriculture.ITreeRoot; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; @@ -50,11 +51,15 @@ public class FarmableGE implements IFarmable { @Override public boolean plantSaplingAt(EntityPlayer player, ItemStack germling, World world, BlockPos pos) { - ITree tree = TreeManager.treeRoot.getMember(germling); - if (tree == null) { + ITreeRoot treeRoot = TreeManager.treeRoot; + + germling = GeneticsUtil.convertToGeneticEquivalent(germling); + if (treeRoot.isMember(germling)) { + ITree tree = treeRoot.getMember(germling); + return treeRoot.plantSapling(world, tree, player.getGameProfile(), pos); + } else { return false; } - return TreeManager.treeRoot.plantSapling(world, tree, player.getGameProfile(), pos); } @Override diff --git a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java index 54f5e1806..74bccb456 100755 --- a/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java +++ b/src/main/java/forestry/farming/logic/FarmableVanillaSapling.java @@ -56,7 +56,7 @@ public class FarmableVanillaSapling implements IFarmable { EnumActionResult actionResult = germling.copy().onItemUse(player, world, pos.down(), EnumHand.MAIN_HAND, EnumFacing.UP, 0, 0, 0); if (actionResult == EnumActionResult.SUCCESS) { PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.SoundFXType.BLOCK_PLACE, pos, Blocks.SAPLING.getDefaultState()); - Proxies.net.sendNetworkPacket(packet, world); + Proxies.net.sendNetworkPacket(packet, pos, world); return true; } return false; diff --git a/src/main/java/forestry/farming/logic/package-info.java b/src/main/java/forestry/farming/logic/package-info.java new file mode 100644 index 000000000..4f11ab53c --- /dev/null +++ b/src/main/java/forestry/farming/logic/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.logic; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/models/EnumFarmBlockTexture.java b/src/main/java/forestry/farming/models/EnumFarmBlockTexture.java index dfe4e0d12..b10f281ba 100644 --- a/src/main/java/forestry/farming/models/EnumFarmBlockTexture.java +++ b/src/main/java/forestry/farming/models/EnumFarmBlockTexture.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.farming.models; +import javax.annotation.Nullable; + import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.init.Blocks; @@ -107,7 +109,7 @@ public enum EnumFarmBlockTexture { return base; } - public static EnumFarmBlockTexture getFromCompound(NBTTagCompound compound) { + public static EnumFarmBlockTexture getFromCompound(@Nullable NBTTagCompound compound) { if (compound != null) { int farmBlockOrdinal = compound.getInteger("FarmBlock"); if (farmBlockOrdinal < EnumFarmBlockTexture.values().length) { diff --git a/src/main/java/forestry/farming/models/ModelFarmBlock.java b/src/main/java/forestry/farming/models/ModelFarmBlock.java index 947b6abc4..2cf9bbb7c 100644 --- a/src/main/java/forestry/farming/models/ModelFarmBlock.java +++ b/src/main/java/forestry/farming/models/ModelFarmBlock.java @@ -1,11 +1,10 @@ package forestry.farming.models; -import javax.annotation.Nonnull; import java.util.Objects; import forestry.api.core.IModelBaker; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.models.ModelBlockCached; import forestry.core.tiles.TileUtil; import forestry.farming.blocks.BlockFarm; @@ -52,7 +51,7 @@ public class ModelFarmBlock extends ModelBlockCached resources) { return false; } @Override - public void removeResources(ItemStack[] resources) { + public void removeResources(NonNullList resources) { } diff --git a/src/main/java/forestry/farming/multiblock/FarmController.java b/src/main/java/forestry/farming/multiblock/FarmController.java index d2b2cb232..cb77e2332 100644 --- a/src/main/java/forestry/farming/multiblock/FarmController.java +++ b/src/main/java/forestry/farming/multiblock/FarmController.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.farming.multiblock; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.ArrayList; @@ -28,6 +27,7 @@ import java.util.Set; import java.util.Stack; import com.google.common.base.Objects; +import com.google.common.base.Preconditions; import forestry.api.circuits.ChipsetManager; import forestry.api.circuits.CircuitSocketType; import forestry.api.circuits.ICircuitBoard; @@ -48,18 +48,16 @@ import forestry.api.multiblock.IMultiblockComponent; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.errors.EnumErrorCode; -import forestry.core.fluids.FluidHelper; +import forestry.core.fluids.FilteredTank; +import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.fluids.tanks.StandardTank; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.inventory.InventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.ILiquidTankTile; import forestry.core.utils.PlayerUtil; import forestry.core.utils.TopDownBlockPosComparator; @@ -74,6 +72,7 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3i; import net.minecraft.world.World; @@ -110,7 +109,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private final Map> targets = new EnumMap<>(FarmDirection.class); private int allowedExtent = 0; - + @Nullable private IFarmLogic harvestProvider; // The farm logic which supplied the pending crops. private final List pendingCrops = new LinkedList<>(); private final Stack pendingProduce = new Stack<>(); @@ -136,6 +135,11 @@ public class FarmController extends RectangularMultiblockControllerBase implemen // tick updates can come from multiple gearboxes so keep track of them here private int farmWorkTicks = 0; + @Nullable + private Vec3i offset; + @Nullable + private Vec3i area; + public FarmController(World world) { super(world, FarmMultiblockSizeLimits.instance); @@ -156,7 +160,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen return hydrationManager; } - @Nonnull + @Override public IInventoryAdapter getInternalInventory() { if (isAssembled()) { @@ -166,7 +170,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } } - @Nonnull + @Override public TankManager getTankManager() { return tankManager; @@ -185,7 +189,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } if (newPart instanceof IFarmComponent.Active) { - farmActiveComponents.put((IFarmComponent.Active) newPart, worldObj.rand.nextInt(256)); + farmActiveComponents.put((IFarmComponent.Active) newPart, world.rand.nextInt(256)); } } @@ -250,7 +254,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override protected boolean updateServer(int tickCount) { - hydrationManager.updateServer(worldObj, getTopCenterCoord()); + hydrationManager.updateServer(world, getTopCenterCoord()); if (updateOnInterval(20)) { inventory.drainCan(tankManager); @@ -334,12 +338,11 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public BlockPos getCoordinates() { - BlockPos coord = getReferenceCoord(); - return new BlockPos(coord); + return getReferenceCoord(); } @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { tankManager.writeData(data); hydrationManager.writeData(data); fertilizerManager.writeData(data); @@ -347,7 +350,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { tankManager.readData(data); hydrationManager.readData(data); fertilizerManager.readData(data); @@ -363,7 +366,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen // See whether we have socketed stuff. ItemStack chip = sockets.getStackInSlot(0); - if (chip != null) { + if (!chip.isEmpty()) { ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(chip); if (chipset != null) { chipset.onLoad(this); @@ -383,19 +386,16 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public float getExactTemperature() { - BlockPos coords = getReferenceCoord(); + BlockPos coords = getCoordinates(); return ForestryAPI.climateManager.getTemperature(getWorldObj(), coords); } @Override public float getExactHumidity() { - BlockPos coords = getReferenceCoord(); + BlockPos coords = getCoordinates(); return ForestryAPI.climateManager.getHumidity(getWorldObj(), coords); } - private Vec3i offset; - private Vec3i area; - @Override public BlockPos getCoords() { return getCenterCoord(); @@ -444,7 +444,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } // Cull queued crops. - if (!pendingCrops.isEmpty()) { + if (!pendingCrops.isEmpty() && harvestProvider != null) { ICrop first = pendingCrops.get(0); if (cullCrop(first, harvestProvider)) { pendingCrops.remove(0); @@ -458,12 +458,9 @@ public class FarmController extends RectangularMultiblockControllerBase implemen FarmWorkStatus farmWorkStatus = new FarmWorkStatus(); List farmDirections = Arrays.asList(FarmDirection.values()); - Collections.shuffle(farmDirections, worldObj.rand); + Collections.shuffle(farmDirections, world.rand); for (FarmDirection farmSide : farmDirections) { IFarmLogic logic = getFarmLogic(farmSide); - if (logic == null) { - continue; - } // Always try to collect windfall. if (collectWindfall(logic)) { @@ -473,11 +470,11 @@ public class FarmController extends RectangularMultiblockControllerBase implemen List farmTargets = targets.get(farmSide); if (stage == Stage.HARVEST) { - Collection harvested = harvestTargets(worldObj, farmTargets, logic, farmListeners); + Collection harvested = harvestTargets(world, farmTargets, logic, farmListeners); farmWorkStatus.didWork = !harvested.isEmpty(); if (!harvested.isEmpty()) { pendingCrops.addAll(harvested); - Collections.sort(pendingCrops, TopDownICropComparator.INSTANCE); + pendingCrops.sort(TopDownICropComparator.INSTANCE); harvestProvider = logic; } } else if (stage == Stage.CULTIVATE) { @@ -513,8 +510,8 @@ public class FarmController extends RectangularMultiblockControllerBase implemen // Set the maximum allowed extent. allowedExtent = Math.max(sizeNorthSouth, sizeEastWest) * Config.farmSize + 1; - createTargets(worldObj, targets, targetStart, allowedExtent, sizeNorthSouth, sizeEastWest, min, max); - setExtents(worldObj, targets); + createTargets(world, targets, targetStart, allowedExtent, sizeNorthSouth, sizeEastWest, min, max); + setExtents(world, targets); } private static void createTargets(World world, Map> targets, BlockPos targetStart, final int allowedExtent, final int farmSizeNorthSouth, final int farmSizeEastWest, BlockPos minFarmCoord, BlockPos maxFarmCoord) { @@ -594,13 +591,13 @@ public class FarmController extends RectangularMultiblockControllerBase implemen return false; } - private static void setExtents(World worldObj, Map> targets) { + private static void setExtents(World world, Map> targets) { for (List targetsList : targets.values()) { if (!targetsList.isEmpty()) { - BlockPos groundPosition = getGroundPosition(worldObj, targetsList.get(0).getStart()); + BlockPos groundPosition = getGroundPosition(world, targetsList.get(0).getStart()); for (FarmTarget target : targetsList) { - target.setExtentAndYOffset(worldObj, groundPosition); + target.setExtentAndYOffset(world, groundPosition); } } } @@ -615,13 +612,11 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private FarmWorkStatus cultivateTargets(FarmWorkStatus farmWorkStatus, List farmTargets, IFarmLogic logic, FarmDirection farmSide) { boolean hasFarmland = false; - if (farmTargets != null) { - for (FarmTarget target : farmTargets) { - if (target.getExtent() > 0) { - hasFarmland = true; - farmWorkStatus.hasFarmland = true; - break; - } + for (FarmTarget target : farmTargets) { + if (target.getExtent() > 0) { + hasFarmland = true; + farmWorkStatus.hasFarmland = true; + break; } } @@ -643,7 +638,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen continue; } - if (cultivateTarget(worldObj, this, target, logic, farmListeners)) { + if (cultivateTarget(world, this, target, logic, farmListeners)) { // Remove fertilizer and water fertilizerManager.removeFertilizer(inventory, fertilizerConsumption); removeLiquid(liquid); @@ -669,12 +664,10 @@ public class FarmController extends RectangularMultiblockControllerBase implemen } private static Collection harvestTargets(World world, List farmTargets, IFarmLogic logic, Iterable farmListeners) { - if (farmTargets != null) { - for (FarmTarget target : farmTargets) { - Collection harvested = harvestTarget(world, target, logic, farmListeners); - if (!harvested.isEmpty()) { - return harvested; - } + for (FarmTarget target : farmTargets) { + Collection harvested = harvestTarget(world, target, logic, farmListeners); + if (!harvested.isEmpty()) { + return harvested; } } @@ -684,21 +677,18 @@ public class FarmController extends RectangularMultiblockControllerBase implemen private static Collection harvestTarget(World world, FarmTarget target, IFarmLogic logic, Iterable farmListeners) { BlockPos pos = target.getStart().add(0, target.getYOffset(), 0); Collection harvested = logic.harvest(world, pos, target.getDirection(), target.getExtent()); - if (harvested == null || harvested.isEmpty()) { - return Collections.emptyList(); + if (!harvested.isEmpty()) { + // Let event handlers know. + for (IFarmListener listener : farmListeners) { + listener.hasScheduledHarvest(harvested, logic, pos, target.getDirection(), target.getExtent()); + } } - - // Let event handlers know. - for (IFarmListener listener : farmListeners) { - listener.hasScheduledHarvest(harvested, logic, pos, target.getDirection(), target.getExtent()); - } - return harvested; } private boolean collectWindfall(IFarmLogic logic) { - Collection collected = logic.collect(worldObj, this); - if (collected == null || collected.size() <= 0) { + NonNullList collected = logic.collect(world, this); + if (collected.isEmpty()) { return false; } @@ -744,22 +734,19 @@ public class FarmController extends RectangularMultiblockControllerBase implemen return false; } - Collection harvested = crop.harvest(); - if (harvested == null) { - return true; + NonNullList harvested = crop.harvest(); + if (harvested != null) { + // Remove fertilizer and water + fertilizerManager.removeFertilizer(inventory, fertilizerConsumption); + removeLiquid(requiredLiquid); + + // Let event handlers handle the harvest first. + for (IFarmListener listener : farmListeners) { + listener.afterCropHarvest(harvested, crop); + } + + inventory.stowHarvest(harvested, pendingProduce); } - - // Remove fertilizer and water - fertilizerManager.removeFertilizer(inventory, fertilizerConsumption); - removeLiquid(requiredLiquid); - - // Let event handlers handle the harvest first. - for (IFarmListener listener : farmListeners) { - listener.afterCropHarvest(harvested, crop); - } - - inventory.stowHarvest(harvested, pendingProduce); - return true; } @@ -771,7 +758,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public boolean hasLiquid(FluidStack liquid) { FluidStack drained = resourceTank.drainInternal(liquid, false); - return FluidHelper.areFluidStacksEqual(drained, liquid); + return drained.isFluidStackIdentical(liquid); } @Override @@ -782,7 +769,7 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public boolean plantGermling(IFarmable germling, World world, BlockPos pos) { EntityPlayer player = PlayerUtil.getPlayer(world, getOwnerHandler().getOwner()); - return inventory.plantGermling(germling, player, pos); + return player != null && inventory.plantGermling(germling, player, pos); } @Override @@ -792,9 +779,8 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public void setFarmLogic(FarmDirection direction, IFarmLogic logic) { - if (logic == null) { - throw new NullPointerException("logic must not be null"); - } + Preconditions.checkNotNull(direction); + Preconditions.checkNotNull(logic, "logic must not be null"); farmLogics.put(direction, logic); } @@ -820,30 +806,26 @@ public class FarmController extends RectangularMultiblockControllerBase implemen @Override public void setSocket(int slot, ItemStack stack) { - if (stack != null && !ChipsetManager.circuitRegistry.isChipset(stack)) { - return; - } - - // Dispose old chipsets correctly - if (sockets.getStackInSlot(slot) != null) { - if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); - if (chipset != null) { - chipset.onRemoval(this); + if (ChipsetManager.circuitRegistry.isChipset(stack)) { + // Dispose old chipsets correctly + if (!sockets.getStackInSlot(slot).isEmpty()) { + if (ChipsetManager.circuitRegistry.isChipset(sockets.getStackInSlot(slot))) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(sockets.getStackInSlot(slot)); + if (chipset != null) { + chipset.onRemoval(this); + } } } - } - sockets.setInventorySlotContents(slot, stack); - refreshFarmLogics(); + sockets.setInventorySlotContents(slot, stack); + refreshFarmLogics(); - if (stack == null) { - return; - } - - ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); - if (chipset != null) { - chipset.onInsertion(this); + if (!stack.isEmpty()) { + ICircuitBoard chipset = ChipsetManager.circuitRegistry.getCircuitBoard(stack); + if (chipset != null) { + chipset.onInsertion(this); + } + } } } diff --git a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java index d84dfb6cf..2f2a9dfe4 100644 --- a/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmFertilizerManager.java @@ -12,12 +12,11 @@ package forestry.farming.multiblock; import java.io.IOException; +import forestry.core.network.PacketBufferForestry; import net.minecraft.nbt.NBTTagCompound; import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; public class FarmFertilizerManager implements INbtWritable, INbtReadable, IStreamable { @@ -80,12 +79,12 @@ public class FarmFertilizerManager implements INbtWritable, INbtReadable, IStrea } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeVarInt(storedFertilizer); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { storedFertilizer = data.readVarInt(); } } diff --git a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java index ea1d8ec7a..1d11e0af1 100644 --- a/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java +++ b/src/main/java/forestry/farming/multiblock/FarmHydrationManager.java @@ -10,32 +10,28 @@ ******************************************************************************/ package forestry.farming.multiblock; -import javax.annotation.Nonnull; import java.io.IOException; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - import forestry.api.core.INbtReadable; import forestry.api.core.INbtWritable; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.tiles.IClimatised; import forestry.farming.gui.IFarmLedgerDelegate; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class FarmHydrationManager implements IFarmLedgerDelegate, INbtWritable, INbtReadable, IStreamable { private static final int DELAY_HYDRATION = 100; private static final float RAINFALL_MODIFIER_MAX = 15f; private static final float RAINFALL_MODIFIER_MIN = 0.5f; - @Nonnull private final IClimatised climatised; private int hydrationDelay = 0; private int ticksSinceRainfall = 0; - public FarmHydrationManager(@Nonnull IClimatised climatised) { + public FarmHydrationManager(IClimatised climatised) { this.climatised = climatised; } @@ -96,13 +92,13 @@ public class FarmHydrationManager implements IFarmLedgerDelegate, INbtWritable, } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { data.writeVarInt(hydrationDelay); data.writeVarInt(ticksSinceRainfall); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { hydrationDelay = data.readVarInt(); ticksSinceRainfall = data.readVarInt(); } diff --git a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java index ffa9720c9..33e3205de 100644 --- a/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java +++ b/src/main/java/forestry/farming/multiblock/IFarmControllerInternal.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.farming.multiblock; -import javax.annotation.Nonnull; - import forestry.api.multiblock.IFarmController; import forestry.core.owner.IOwnedTile; import forestry.core.circuits.ISocketable; @@ -27,6 +25,5 @@ public interface IFarmControllerInternal extends IFarmController, IMultiblockCon IInventoryAdapter getInternalInventory(); - @Nonnull ITankManager getTankManager(); } diff --git a/src/main/java/forestry/farming/multiblock/InventoryFarm.java b/src/main/java/forestry/farming/multiblock/InventoryFarm.java index 6277eae35..0cfeb18d4 100644 --- a/src/main/java/forestry/farming/multiblock/InventoryFarm.java +++ b/src/main/java/forestry/farming/multiblock/InventoryFarm.java @@ -10,18 +10,9 @@ ******************************************************************************/ package forestry.farming.multiblock; -import java.util.Stack; import java.util.Map.Entry; +import java.util.Stack; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; - -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidUtil; -import net.minecraftforge.oredict.OreDictionary; import forestry.api.core.ForestryAPI; import forestry.api.farming.FarmDirection; import forestry.api.farming.Farmables; @@ -35,6 +26,15 @@ import forestry.core.inventory.wrappers.InventoryMapper; import forestry.core.utils.InventoryUtil; import forestry.core.utils.PlayerUtil; import forestry.core.utils.SlotUtil; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidUtil; +import net.minecraftforge.oredict.OreDictionary; public class InventoryFarm extends InventoryAdapterRestricted implements IFarmInventory { public static final int SLOT_RESOURCES_1 = 0; @@ -50,7 +50,7 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn public static final int SLOT_CAN_COUNT = 1; public static final int SLOT_COUNT = SLOT_RESOURCES_COUNT + SLOT_GERMLINGS_COUNT + SLOT_PRODUCTION_COUNT + SLOT_FERTILIZER_COUNT + SLOT_CAN_COUNT; - + private static final int FERTILIZER_MODIFIER = ForestryAPI.activeMode.getIntegerSetting("farms.fertilizer.modifier"); private final FarmController farmController; @@ -80,7 +80,7 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn return acceptsAsResource(itemStack); } else if (SlotUtil.isSlotInRange(slotIndex, SLOT_CAN, SLOT_CAN_COUNT)) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return farmController.getTankManager().canFillFluidType(fluid); + return fluid != null && farmController.getTankManager().canFillFluidType(fluid); } return false; } @@ -91,19 +91,19 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn } @Override - public boolean hasResources(ItemStack[] resources) { + public boolean hasResources(NonNullList resources) { return InventoryUtil.contains(resourcesInventory, resources); } @Override - public void removeResources(ItemStack[] resources) { + public void removeResources(NonNullList resources) { EntityPlayer player = PlayerUtil.getPlayer(farmController.getWorldObj(), farmController.getOwnerHandler().getOwner()); InventoryUtil.removeSets(resourcesInventory, 1, resources, player, false, true, false, true); } @Override public boolean acceptsAsGermling(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return false; } @@ -119,7 +119,7 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn @Override public boolean acceptsAsResource(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return false; } @@ -135,17 +135,17 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn @Override public boolean acceptsAsFertilizer(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return false; } - - for(Entry fertilizer : Farmables.fertilizers.entrySet()){ - ItemStack fertilizerItem = fertilizer.getKey(); - if(itemstack.getItem() == fertilizerItem.getItem() && (fertilizerItem.getItemDamage() == itemstack.getItemDamage() || fertilizerItem.getItemDamage() == OreDictionary.WILDCARD_VALUE)){ - return true; - } - } - return false; + + for (Entry fertilizer : Farmables.fertilizers.entrySet()) { + ItemStack fertilizerItem = fertilizer.getKey(); + if (itemstack.getItem() == fertilizerItem.getItem() && (fertilizerItem.getItemDamage() == itemstack.getItemDamage() || fertilizerItem.getItemDamage() == OreDictionary.WILDCARD_VALUE)) { + return true; + } + } + return false; } @Override @@ -175,11 +175,11 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn public boolean plantGermling(IFarmable germling, EntityPlayer player, BlockPos pos) { for (int i = 0; i < germlingsInventory.getSizeInventory(); i++) { ItemStack germlingStack = germlingsInventory.getStackInSlot(i); - if (germlingStack == null || !germling.isGermling(germlingStack)) { + if (germlingStack.isEmpty() || !germling.isGermling(germlingStack)) { continue; } - if (germling.plantSaplingAt(player, germlingStack, player.worldObj, pos)) { + if (germling.plantSaplingAt(player, germlingStack, player.world, pos)) { germlingsInventory.decrStackSize(i, 1); return true; } @@ -188,13 +188,15 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn } public void addProduce(ItemStack produce) { - produce.stackSize -= InventoryUtil.addStack(productInventory, produce, true); + int added = InventoryUtil.addStack(productInventory, produce, true); + produce.shrink(added); } public void stowHarvest(Iterable harvested, Stack pendingProduce) { for (ItemStack harvest : harvested) { - harvest.stackSize -= InventoryUtil.addStack(productInventory, harvest, true); - if (harvest.stackSize > 0) { + int added = InventoryUtil.addStack(productInventory, harvest, true); + harvest.shrink(added); + if (!harvest.isEmpty()) { pendingProduce.push(harvest); } } @@ -212,33 +214,28 @@ public class InventoryFarm extends InventoryAdapterRestricted implements IFarmIn return added; } - + public int getFertilizerValue() { ItemStack fertilizerStack = getStackInSlot(SLOT_FERTILIZER); - if (fertilizerStack == null || fertilizerStack.stackSize <= 0) { - return 0; - } - - for(Entry fertilizer : Farmables.fertilizers.entrySet()){ - ItemStack fertilizerItem = fertilizer.getKey(); - if(fertilizerStack.getItem() == fertilizerItem.getItem() && (fertilizerItem.getItemDamage() == fertilizerStack.getItemDamage() || fertilizerItem.getItemDamage() == OreDictionary.WILDCARD_VALUE)){ - return fertilizer.getValue() * FERTILIZER_MODIFIER; - } - } - return 0; - } + if (fertilizerStack.isEmpty()) { + return 0; + } + + for (Entry fertilizer : Farmables.fertilizers.entrySet()) { + ItemStack fertilizerItem = fertilizer.getKey(); + if (fertilizerStack.getItem() == fertilizerItem.getItem() && (fertilizerItem.getItemDamage() == fertilizerStack.getItemDamage() || fertilizerItem.getItemDamage() == OreDictionary.WILDCARD_VALUE)) { + return fertilizer.getValue() * FERTILIZER_MODIFIER; + } + } + return 0; + } public boolean useFertilizer() { ItemStack fertilizer = getStackInSlot(SLOT_FERTILIZER); - if (fertilizer == null || fertilizer.stackSize <= 0) { - return false; + if (acceptsAsFertilizer(fertilizer)) { + decrStackSize(SLOT_FERTILIZER, 1); + return true; } - - if (!acceptsAsFertilizer(fertilizer)) { - return false; - } - - decrStackSize(SLOT_FERTILIZER, 1); - return true; + return false; } } \ No newline at end of file diff --git a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java index 4a535bd95..8ce35e8fd 100644 --- a/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java +++ b/src/main/java/forestry/farming/multiblock/MultiblockLogicFarm.java @@ -22,7 +22,7 @@ public class MultiblockLogicFarm extends MultiblockLogic implements IFarmComponent, IHintSource, ISocketable, IStreamableGui, IErrorLogicSource, IOwnedTile, ITitled { - private EnumFarmBlockTexture farmBlockTexture = EnumFarmBlockTexture.BRICK_STONE; protected TileFarm() { super(new MultiblockLogicFarm()); } - + @Override public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) { return oldState.getBlock() != newState.getBlock(); @@ -58,13 +54,13 @@ public abstract class TileFarm extends MultiblockTileEntityForestry capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return energyManager.hasCapability(capability) || super.hasCapability(capability, facing); } - @Nonnull + @Nullable @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability(Capability capability, @Nullable EnumFacing facing) { T energyCapability = energyManager.getCapability(capability); if (energyCapability != null) { return energyCapability; diff --git a/src/main/java/forestry/farming/tiles/TileFarmHatch.java b/src/main/java/forestry/farming/tiles/TileFarmHatch.java index afa963d6d..1241d2b7b 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmHatch.java +++ b/src/main/java/forestry/farming/tiles/TileFarmHatch.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.farming.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import forestry.api.multiblock.IFarmComponent; import forestry.core.inventory.AdjacentInventoryCache; @@ -18,7 +18,6 @@ import forestry.core.tiles.AdjacentTileCache; import forestry.core.utils.InventoryUtil; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; -import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.items.CapabilityItemHandler; @@ -37,12 +36,7 @@ public class TileFarmHatch extends TileFarm implements ISidedInventory, IFarmCom public TileFarmHatch() { this.tileCache = new AdjacentTileCache(this); - this.inventoryCache = new AdjacentInventoryCache(this, tileCache, new AdjacentInventoryCache.ITileFilter() { - @Override - public boolean matches(TileEntity tile) { - return !(tile instanceof TileFarm) && tile.getPos().getY() < getPos().getY(); - } - }); + this.inventoryCache = new AdjacentInventoryCache(this, tileCache, tile -> !(tile instanceof TileFarm) && tile.getPos().getY() < getPos().getY()); } @Override @@ -68,12 +62,13 @@ public class TileFarmHatch extends TileFarm implements ISidedInventory, IFarmCom } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nonnull EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing); } @Override - public T getCapability(@Nonnull Capability capability, @Nonnull EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { SidedInvWrapper sidedInvWrapper = new SidedInvWrapper(this, facing); return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(sidedInvWrapper); diff --git a/src/main/java/forestry/farming/tiles/TileFarmPlain.java b/src/main/java/forestry/farming/tiles/TileFarmPlain.java index 0fc282ea9..b191305fd 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmPlain.java +++ b/src/main/java/forestry/farming/tiles/TileFarmPlain.java @@ -22,7 +22,7 @@ public class TileFarmPlain extends TileFarm { // set band block meta int bandY = maxCoord.getY() - 1; if (getPos().getY() == bandY) { - this.worldObj.setBlockState(getPos(), getBlockType().getStateFromMeta(1), 2); + this.world.setBlockState(getPos(), getBlockType().getStateFromMeta(1), 2); } } @@ -31,6 +31,6 @@ public class TileFarmPlain extends TileFarm { super.onMachineBroken(); // set band block meta back to normal - this.worldObj.setBlockState(getPos(), getBlockType().getDefaultState(), 2); + this.world.setBlockState(getPos(), getBlockType().getDefaultState(), 2); } } diff --git a/src/main/java/forestry/farming/tiles/TileFarmValve.java b/src/main/java/forestry/farming/tiles/TileFarmValve.java index 913fef0f0..17f048921 100644 --- a/src/main/java/forestry/farming/tiles/TileFarmValve.java +++ b/src/main/java/forestry/farming/tiles/TileFarmValve.java @@ -11,6 +11,7 @@ package forestry.farming.tiles; import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.util.EnumFacing; @@ -28,7 +29,7 @@ public class TileFarmValve extends TileFarm implements ILiquidTankTile { } @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { return true; } @@ -36,7 +37,8 @@ public class TileFarmValve extends TileFarm implements ILiquidTankTile { } @Override - public T getCapability(Capability capability, EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { return super.getCapability(capability, facing); } diff --git a/src/main/java/forestry/farming/tiles/package-info.java b/src/main/java/forestry/farming/tiles/package-info.java new file mode 100644 index 000000000..7bb16e0bb --- /dev/null +++ b/src/main/java/forestry/farming/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java index cbe72944a..f55b00df9 100755 --- a/src/main/java/forestry/farming/triggers/TriggerLowSoil.java +++ b/src/main/java/forestry/farming/triggers/TriggerLowSoil.java @@ -56,7 +56,7 @@ public class TriggerLowSoil extends Trigger { // return InventoryUtil.containsPercent(resourcesInventory, threshold); // } else { // ItemStack filter = parameter.getItemStack().copy(); -// filter.stackSize = threshold; +// filter.setCount(threshold); // return farmInventory.hasResources(new ItemStack[]{filter}); // } // } diff --git a/src/main/java/forestry/farming/triggers/package-info.java b/src/main/java/forestry/farming/triggers/package-info.java new file mode 100644 index 000000000..39e60fe47 --- /dev/null +++ b/src/main/java/forestry/farming/triggers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.farming.triggers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/food/BeverageEffect.java b/src/main/java/forestry/food/BeverageEffect.java index 24f9abdc5..518f90b98 100755 --- a/src/main/java/forestry/food/BeverageEffect.java +++ b/src/main/java/forestry/food/BeverageEffect.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.food; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -42,6 +43,7 @@ public abstract class BeverageEffect implements IBeverageEffect { return this.id; } + @Nullable protected String getLevel() { return null; } diff --git a/src/main/java/forestry/food/InfuserIngredientManager.java b/src/main/java/forestry/food/InfuserIngredientManager.java index 43edf4a02..c674024c1 100644 --- a/src/main/java/forestry/food/InfuserIngredientManager.java +++ b/src/main/java/forestry/food/InfuserIngredientManager.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.food; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -26,8 +27,9 @@ public class InfuserIngredientManager implements IIngredientManager { } @Override + @Nullable public String getDescription(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return null; } diff --git a/src/main/java/forestry/food/InfuserMixture.java b/src/main/java/forestry/food/InfuserMixture.java index afb9834ea..b5acaf74e 100644 --- a/src/main/java/forestry/food/InfuserMixture.java +++ b/src/main/java/forestry/food/InfuserMixture.java @@ -13,26 +13,23 @@ package forestry.food; import net.minecraft.item.ItemStack; import forestry.api.food.IBeverageEffect; +import net.minecraft.util.NonNullList; /** * describes the itemstacks required to achieve a certain effect. */ public class InfuserMixture { private final int meta; - private final ItemStack[] ingredients; + private final NonNullList ingredients; private final IBeverageEffect effect; - public InfuserMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { - this(meta, new ItemStack[]{ingredient}, effect); - } - - public InfuserMixture(int meta, ItemStack ingredients[], IBeverageEffect effect) { + public InfuserMixture(int meta, NonNullList ingredients, IBeverageEffect effect) { this.meta = meta; this.ingredients = ingredients; this.effect = effect; } - public ItemStack[] getIngredients() { + public NonNullList getIngredients() { return ingredients; } @@ -48,10 +45,10 @@ public class InfuserMixture { return false; } - public boolean matches(ItemStack[] res) { + public boolean matches(NonNullList res) { // No recipe without resource! - if (res == null || res.length <= 0) { + if (res.isEmpty()) { return false; } @@ -66,12 +63,12 @@ public class InfuserMixture { // Check item matching if (stack.getItemDamage() < 0 && stack.getItem() == matchStack.getItem()) { - if (stack.stackSize <= matchStack.stackSize) { + if (stack.getCount() <= matchStack.getCount()) { matched = true; break; } } else if (stack.getItemDamage() >= 0 && stack.isItemEqual(matchStack)) { - if (stack.stackSize <= matchStack.stackSize) { + if (stack.getCount() <= matchStack.getCount()) { matched = true; break; } @@ -94,6 +91,6 @@ public class InfuserMixture { } public int getWeight() { - return ingredients.length; + return ingredients.size(); } } diff --git a/src/main/java/forestry/food/InfuserMixtureManager.java b/src/main/java/forestry/food/InfuserMixtureManager.java index 9c2ca5f50..3b3876813 100644 --- a/src/main/java/forestry/food/InfuserMixtureManager.java +++ b/src/main/java/forestry/food/InfuserMixtureManager.java @@ -11,13 +11,12 @@ package forestry.food; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import net.minecraft.item.ItemStack; - import forestry.api.food.IBeverageEffect; import forestry.api.food.IInfuserManager; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; /** * contains the available mixtures. @@ -28,11 +27,13 @@ public class InfuserMixtureManager implements IInfuserManager { @Override public void addMixture(int meta, ItemStack ingredient, IBeverageEffect effect) { - this.mixtures.add(new InfuserMixture(meta, ingredient, effect)); + NonNullList ingredients = NonNullList.create(); + ingredients.add(ingredient); + this.mixtures.add(new InfuserMixture(meta, ingredients, effect)); } @Override - public void addMixture(int meta, ItemStack[] ingredients, IBeverageEffect effect) { + public void addMixture(int meta, NonNullList ingredients, IBeverageEffect effect) { this.mixtures.add(new InfuserMixture(meta, ingredients, effect)); } @@ -47,9 +48,9 @@ public class InfuserMixtureManager implements IInfuserManager { return false; } - private InfuserMixture[] getMatchingMixtures(ItemStack[] ingredients) { + private List getMatchingMixtures(NonNullList ingredients) { - ArrayList matches = new ArrayList<>(); + List matches = new ArrayList<>(); for (InfuserMixture mixture : mixtures) { if (mixture.matches(ingredients)) { @@ -57,29 +58,29 @@ public class InfuserMixtureManager implements IInfuserManager { } } - return matches.toArray(new InfuserMixture[matches.size()]); + return matches; } @Override - public boolean hasMixtures(ItemStack[] ingredients) { - return getMatchingMixtures(ingredients).length > 0; + public boolean hasMixtures(NonNullList ingredients) { + return !getMatchingMixtures(ingredients).isEmpty(); } @Override - public ItemStack[] getRequired(ItemStack[] ingredients) { - InfuserMixture[] mixtures = getMatchingMixtures(ingredients); - ArrayList required = new ArrayList<>(); + public NonNullList getRequired(NonNullList ingredients) { + List mixtures = getMatchingMixtures(ingredients); + NonNullList required = NonNullList.create(); for (InfuserMixture mixture : mixtures) { - required.addAll(Arrays.asList(mixture.getIngredients())); + required.addAll(mixture.getIngredients()); } - return required.toArray(new ItemStack[required.size()]); + return required; } @Override - public ItemStack getSeasoned(ItemStack base, ItemStack[] ingredients) { - InfuserMixture[] mixtures = getMatchingMixtures(ingredients); + public ItemStack getSeasoned(ItemStack base, NonNullList ingredients) { + List mixtures = getMatchingMixtures(ingredients); List effects = BeverageEffect.loadEffects(base); int weight = 0; diff --git a/src/main/java/forestry/food/PluginFood.java b/src/main/java/forestry/food/PluginFood.java index f8837887d..ef4fac3cf 100644 --- a/src/main/java/forestry/food/PluginFood.java +++ b/src/main/java/forestry/food/PluginFood.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.food; +import javax.annotation.Nullable; + +import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import forestry.api.food.BeverageManager; @@ -25,7 +28,7 @@ import forestry.plugins.ForestryPluginUids; @ForestryPlugin(pluginID = ForestryPluginUids.FOOD, name = "Food", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.food.description") public class PluginFood extends BlankForestryPlugin { - + @Nullable public static ItemRegistryFood items; @Override @@ -60,6 +63,8 @@ public class PluginFood extends BlankForestryPlugin { @Override public void registerRecipes() { + Preconditions.checkState(items != null); + // INFUSER RecipeUtil.addRecipe(items.infuser.getItemStack(), "X", "#", "X", diff --git a/src/main/java/forestry/food/compat/FoodJeiPlugin.java b/src/main/java/forestry/food/compat/FoodJeiPlugin.java index 0fe7d3f22..26fa3dc56 100644 --- a/src/main/java/forestry/food/compat/FoodJeiPlugin.java +++ b/src/main/java/forestry/food/compat/FoodJeiPlugin.java @@ -1,7 +1,5 @@ package forestry.food.compat; -import javax.annotation.Nonnull; - import forestry.core.utils.JeiUtil; import forestry.food.PluginFood; import forestry.food.items.ItemRegistryFood; @@ -12,7 +10,7 @@ import mezz.jei.api.JEIPlugin; @JEIPlugin public class FoodJeiPlugin extends BlankModPlugin { @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { ItemRegistryFood items = PluginFood.items; JeiUtil.addDescription(registry, items.infuser diff --git a/src/main/java/forestry/food/compat/package-info.java b/src/main/java/forestry/food/compat/package-info.java new file mode 100644 index 000000000..0140a644c --- /dev/null +++ b/src/main/java/forestry/food/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.food.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/food/gui/package-info.java b/src/main/java/forestry/food/gui/package-info.java new file mode 100644 index 000000000..a66696734 --- /dev/null +++ b/src/main/java/forestry/food/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.food.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java b/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java index 254e3debc..7a78cf9c7 100644 --- a/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java +++ b/src/main/java/forestry/food/inventory/ItemInventoryInfuser.java @@ -10,12 +10,13 @@ ******************************************************************************/ package forestry.food.inventory; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - import forestry.api.food.BeverageManager; import forestry.core.inventory.ItemInventory; import forestry.food.PluginFood; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.oredict.OreDictionary; public class ItemInventoryInfuser extends ItemInventory { private static final short inputSlot = 0; @@ -32,61 +33,43 @@ public class ItemInventoryInfuser extends ItemInventory { // Need input ItemStack input = getStackInSlot(inputSlot); - if (input == null) { - return; - } + if (!input.isEmpty() && + getStackInSlot(outputSlot).isEmpty() && + PluginFood.items.beverage == input.getItem()) { - // Output slot may not be occupied - if (getStackInSlot(outputSlot) != null) { - return; - } + // Create the seasoned item + NonNullList ingredients = NonNullList.create(); + for (int i = 0; i < ingredientSlotCount; i++) { + ingredients.add(getStackInSlot(i + ingredientSlot1)); + } - // Need a valid base - if (PluginFood.items.beverage != input.getItem()) { - return; - } + // Only continue if there is anything to season + if (BeverageManager.infuserManager.hasMixtures(ingredients)) { - // Create the seasoned item - ItemStack[] ingredients = new ItemStack[4]; - for (int i = 0; i < 4; i++) { - ingredients[i] = getStackInSlot(i + ingredientSlot1); - } + ItemStack seasoned = BeverageManager.infuserManager.getSeasoned(input, ingredients); + if (!seasoned.isEmpty()) { - // Only continue if there is anything to season - if (!BeverageManager.infuserManager.hasMixtures(ingredients)) { - return; - } + // Remove required ingredients. + NonNullList toRemove = BeverageManager.infuserManager.getRequired(ingredients); + for (ItemStack templ : toRemove) { + ItemStack ghost = templ.copy(); - ItemStack seasoned = BeverageManager.infuserManager.getSeasoned(input, ingredients); - if (seasoned == null) { - return; - } - - // Remove required ingredients. - ItemStack[] toRemove = BeverageManager.infuserManager.getRequired(ingredients); - for (ItemStack templ : toRemove) { - ItemStack ghost = templ.copy(); - - for (int i = ingredientSlot1; i < this.getSizeInventory(); i++) { - ItemStack ingredient = getStackInSlot(i); - if (ingredient == null) { - continue; - } - if (ghost.stackSize <= 0) { - break; - } - - if (ghost.getItemDamage() >= 0 && ingredient.isItemEqual(ghost) - || ghost.getItemDamage() < 0 && ghost.getItem() == ingredient.getItem()) { - ItemStack removed = decrStackSize(i, 1); - ghost.stackSize -= removed.stackSize; + for (int i = ingredientSlot1; i < this.getSizeInventory() && !ghost.isEmpty(); i++) { + ItemStack ingredient = getStackInSlot(i); + if (!ingredient.isEmpty() && OreDictionary.itemMatches(ghost, ingredient, false)) { + ItemStack removed = decrStackSize(i, 1); + ghost.shrink(removed.getCount()); + } + } + } + decrStackSize(inputSlot, 1); + setInventorySlotContents(outputSlot, seasoned); } } } - decrStackSize(inputSlot, 1); - setInventorySlotContents(outputSlot, seasoned); } + @Override public String getName() { return "Infuser"; diff --git a/src/main/java/forestry/food/inventory/package-info.java b/src/main/java/forestry/food/inventory/package-info.java new file mode 100644 index 000000000..6cd60d925 --- /dev/null +++ b/src/main/java/forestry/food/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.food.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/food/items/ItemBeverage.java b/src/main/java/forestry/food/items/ItemBeverage.java index 9adc33678..4434dbd76 100755 --- a/src/main/java/forestry/food/items/ItemBeverage.java +++ b/src/main/java/forestry/food/items/ItemBeverage.java @@ -12,6 +12,13 @@ package forestry.food.items; import java.util.List; +import forestry.api.core.IModelManager; +import forestry.api.food.IBeverageEffect; +import forestry.core.config.Config; +import forestry.core.items.IColoredItem; +import forestry.core.items.ItemForestryFood; +import forestry.core.items.ItemOverlay; +import forestry.food.BeverageEffect; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; @@ -23,20 +30,12 @@ import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.SoundCategory; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; -import forestry.api.food.IBeverageEffect; -import forestry.core.config.Config; -import forestry.core.items.IColoredItem; -import forestry.core.items.ItemForestryFood; -import forestry.core.items.ItemOverlay; -import forestry.food.BeverageEffect; - public class ItemBeverage extends ItemForestryFood implements IColoredItem { public interface IBeverageInfo extends ItemOverlay.IOverlayInfo { int getHeal(); @@ -68,7 +67,7 @@ public class ItemBeverage extends ItemForestryFood implements IColoredItem { public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityLivingBase entityLiving) { List effects = BeverageEffect.loadEffects(stack); - stack.stackSize--; + stack.shrink(1); if (entityLiving instanceof EntityPlayer) { EntityPlayer entityplayer = (EntityPlayer) entityLiving; @@ -114,23 +113,23 @@ public class ItemBeverage extends ItemForestryFood implements IColoredItem { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) - { - int meta = itemStackIn.getItemDamage(); + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand hand) { + ItemStack itemStack = playerIn.getHeldItem(hand); + int meta = itemStack.getItemDamage(); IBeverageInfo beverage = beverages[meta]; if (playerIn.canEat(beverage.isAlwaysEdible())) { playerIn.setActiveHand(hand); - return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn); + return new ActionResult<>(EnumActionResult.SUCCESS, itemStack); } else { - return new ActionResult<>(EnumActionResult.FAIL, itemStackIn); + return new ActionResult<>(EnumActionResult.FAIL, itemStack); } } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { for (int i = 0; i < beverages.length; i++) { if (Config.isDebug || !beverages[i].isSecret()) { - itemList.add(new ItemStack(this, 1, i)); + subItems.add(new ItemStack(this, 1, i)); } } } @@ -140,12 +139,11 @@ public class ItemBeverage extends ItemForestryFood implements IColoredItem { List effects = BeverageEffect.loadEffects(itemstack); for (IBeverageEffect effect : effects) { - if (effect.getDescription() != null) { - list.add(effect.getDescription()); - } + list.add(effect.getDescription()); } } + @Override public String getUnlocalizedName(ItemStack stack) { return super.getUnlocalizedName(stack) + "." + beverages[stack.getItemDamage()].getUid(); diff --git a/src/main/java/forestry/food/items/package-info.java b/src/main/java/forestry/food/items/package-info.java new file mode 100644 index 000000000..4f4f607ff --- /dev/null +++ b/src/main/java/forestry/food/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.food.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/food/package-info.java b/src/main/java/forestry/food/package-info.java new file mode 100644 index 000000000..c2ad90142 --- /dev/null +++ b/src/main/java/forestry/food/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.food; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/GreenhouseClimateSource.java b/src/main/java/forestry/greenhouse/GreenhouseClimateSource.java index 1379ebf3e..c52725f97 100644 --- a/src/main/java/forestry/greenhouse/GreenhouseClimateSource.java +++ b/src/main/java/forestry/greenhouse/GreenhouseClimateSource.java @@ -22,25 +22,26 @@ import forestry.core.climate.ClimateSource; import forestry.greenhouse.multiblock.IGreenhouseControllerInternal; import forestry.greenhouse.tiles.TileGreenhouseClimatiser; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; public class GreenhouseClimateSource

extends ClimateSource

{ public GreenhouseClimateSource(int ticksForChange) { super(ticksForChange); } - + @Override public boolean changeClimate(int tickCount, IClimateRegion region) { - World world = region.getWorld(); + if (provider == null) { + return false; + } IClimatiserDefinition definition = provider.getDefinition(); IMultiblockLogic logic = provider.getMultiblockLogic(); IMultiblockController controller = logic.getController(); Iterable positionsInRange = provider.getPositionsInRange(); - + boolean hasChange = false; boolean isActive = false; - if(logic.isConnected() && controller.isAssembled() && controller instanceof IGreenhouseControllerInternal && positionsInRange != null && positionsInRange.iterator().hasNext() && region != null){ + if (logic.isConnected() && controller.isAssembled() && controller instanceof IGreenhouseControllerInternal && positionsInRange.iterator().hasNext()) { IGreenhouseControllerInternal greenhouseInternal = (IGreenhouseControllerInternal) controller; IClimateControl climateControl = getClimateControl(greenhouseInternal); float controlTemp = climateControl.getControlTemperature(); @@ -49,63 +50,63 @@ public class GreenhouseClimateSource

extends EnumClimatiserTypes type = definition.getType(); EnumClimatiserModes mode = definition.getMode(); float maxChange = definition.getChange(); - if(isActive){ - if(canChange(type, EnumClimatiserTypes.TEMPERATURE)){ - if(region.getTemperature() < controlTemp) { - if(!canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (isActive) { + if (canChange(type, EnumClimatiserTypes.TEMPERATURE)) { + if (region.getTemperature() < controlTemp) { + if (!canChange(mode, EnumClimatiserModes.POSITIVE)) { isActive = false; } - }else if(region.getTemperature() > controlTemp){ - if(!canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (region.getTemperature() > controlTemp) { + if (!canChange(mode, EnumClimatiserModes.NEGATIVE)) { isActive = false; } } } if (canChange(type, EnumClimatiserTypes.HUMIDITY)) { - if(region.getTemperature() < controlHum) { - if(!canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (region.getTemperature() < controlHum) { + if (!canChange(mode, EnumClimatiserModes.POSITIVE)) { isActive = false; } - }else if(region.getTemperature() > controlHum){ - if(!canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (region.getTemperature() > controlHum) { + if (!canChange(mode, EnumClimatiserModes.NEGATIVE)) { isActive = false; } } } } - - if (isActive) { - for(BlockPos pos : positionsInRange){ + + if (isActive) { + for (BlockPos pos : positionsInRange) { IClimatePosition position = region.getPositions().get(pos); - if(position != null){ + if (position != null) { double distance = pos.distanceSq(provider.getCoordinates()); double range = definition.getRange(); - if(distance <= range){ + if (distance <= range) { float change = maxChange; - if(distance > 0){ + if (distance > 0) { change = (float) (maxChange / distance); } if (canChange(type, EnumClimatiserTypes.TEMPERATURE)) { - if(position.getTemperature() < controlTemp) { - if(canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (position.getTemperature() < controlTemp) { + if (canChange(mode, EnumClimatiserModes.POSITIVE)) { position.addTemperature(Math.min(change, controlTemp - position.getTemperature())); hasChange = true; } - }else if(position.getTemperature() > controlTemp){ - if(canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (position.getTemperature() > controlTemp) { + if (canChange(mode, EnumClimatiserModes.NEGATIVE)) { position.addTemperature(-Math.min(position.getTemperature() - controlTemp, change)); hasChange = true; } } } if (canChange(type, EnumClimatiserTypes.HUMIDITY)) { - if(position.getHumidity() < controlHum) { - if(canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (position.getHumidity() < controlHum) { + if (canChange(mode, EnumClimatiserModes.POSITIVE)) { position.addHumidity(Math.min(change, controlHum - position.getHumidity())); hasChange = true; } - }else if(position.getHumidity() > controlHum){ - if(canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (position.getHumidity() > controlHum) { + if (canChange(mode, EnumClimatiserModes.NEGATIVE)) { position.addHumidity(-Math.min(position.getHumidity() - controlHum, change)); hasChange = true; } @@ -116,27 +117,21 @@ public class GreenhouseClimateSource

extends } } } - if(provider.isActive() != isActive){ + if (provider.isActive() != isActive) { provider.setActive(isActive); } return hasChange; } - - protected boolean canChange(EnumClimatiserTypes climatiserType, EnumClimatiserTypes type){ - if(type == climatiserType || climatiserType == EnumClimatiserTypes.NONE){ - return true; - } - return false; + + protected boolean canChange(EnumClimatiserTypes climatiserType, EnumClimatiserTypes type) { + return type == climatiserType || climatiserType == EnumClimatiserTypes.NONE; } - - protected boolean canChange(EnumClimatiserModes climatiserMode, EnumClimatiserModes mode){ - if(mode == climatiserMode || climatiserMode == EnumClimatiserModes.NONE){ - return true; - } - return false; + + protected boolean canChange(EnumClimatiserModes climatiserMode, EnumClimatiserModes mode) { + return mode == climatiserMode || climatiserMode == EnumClimatiserModes.NONE; } - - protected IClimateControl getClimateControl(IGreenhouseControllerInternal greenhouseInternal){ + + protected IClimateControl getClimateControl(IGreenhouseControllerInternal greenhouseInternal) { return greenhouseInternal.getClimateControl(); } diff --git a/src/main/java/forestry/greenhouse/GreenhouseClimateWindow.java b/src/main/java/forestry/greenhouse/GreenhouseClimateWindow.java index e786ca6d6..ace8e4617 100644 --- a/src/main/java/forestry/greenhouse/GreenhouseClimateWindow.java +++ b/src/main/java/forestry/greenhouse/GreenhouseClimateWindow.java @@ -1,5 +1,7 @@ package forestry.greenhouse; +import javax.annotation.Nullable; + import forestry.api.climate.EnumClimatiserModes; import forestry.api.climate.EnumClimatiserTypes; import forestry.api.climate.IClimateControl; @@ -16,75 +18,77 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; -public class GreenhouseClimateWindow extends GreenhouseClimateSource{ - +public class GreenhouseClimateWindow extends GreenhouseClimateSource { + @Nullable private Biome biome; - + public GreenhouseClimateWindow(int ticksForChange) { super(ticksForChange); } - + @Override public boolean changeClimate(int tickCount, IClimateRegion region) { + if (provider == null) { + return false; + } World world = region.getWorld(); IClimatiserDefinition definition = provider.getDefinition(); IMultiblockLogic logic = provider.getMultiblockLogic(); IMultiblockController controller = logic.getController(); Iterable positionsInRange = provider.getPositionsInRange(); - + boolean hasChange = false; WindowMode windowMode = provider.getMode(); - if(logic.isConnected() && controller.isAssembled() && controller instanceof IGreenhouseControllerInternal && positionsInRange != null && positionsInRange.iterator().hasNext() && region != null){ + if (logic.isConnected() && controller.isAssembled() && controller instanceof IGreenhouseControllerInternal && positionsInRange.iterator().hasNext()) { IGreenhouseControllerInternal greenhouseInternal = (IGreenhouseControllerInternal) controller; IClimateControl climateControl = getClimateControl(greenhouseInternal); float controlTemp = climateControl.getControlTemperature(); float controlHum = climateControl.getControlHumidity(); - if(!greenhouseInternal.canWork()){ - if(windowMode == WindowMode.OPEN){ + if (!greenhouseInternal.canWork()) { + if (windowMode == WindowMode.OPEN) { provider.setMode(windowMode = WindowMode.CONTROL); } - }else{ - if(windowMode == WindowMode.CONTROL){ + } else { + if (windowMode == WindowMode.CONTROL) { provider.setMode(windowMode = WindowMode.OPEN); } } - if(windowMode == WindowMode.OPEN){ - int dimensionID = world.provider.getDimension(); + if (windowMode == WindowMode.OPEN) { EnumClimatiserTypes type = definition.getType(); EnumClimatiserModes mode = definition.getMode(); float maxChange = definition.getChange(); - - for(BlockPos pos : positionsInRange){ + + for (BlockPos pos : positionsInRange) { IClimatePosition position = region.getPositions().get(pos); - if(position != null){ + if (position != null) { double distance = pos.distanceSq(provider.getCoordinates()); double range = definition.getRange(); - if(distance <= range){ + if (distance <= range) { float change = maxChange; - if(distance > 0){ + if (distance > 0) { change = (float) (maxChange / distance); } if (canChange(type, EnumClimatiserTypes.TEMPERATURE)) { - if(position.getTemperature() < controlTemp) { - if(canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (position.getTemperature() < controlTemp) { + if (canChange(mode, EnumClimatiserModes.POSITIVE)) { position.addTemperature(Math.min(change, controlTemp - position.getTemperature())); hasChange = true; } - }else if(position.getTemperature() > controlTemp){ - if(canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (position.getTemperature() > controlTemp) { + if (canChange(mode, EnumClimatiserModes.NEGATIVE)) { position.addTemperature(-Math.min(position.getTemperature() - controlTemp, change)); hasChange = true; } } } if (canChange(type, EnumClimatiserTypes.HUMIDITY)) { - if(position.getHumidity() < controlHum) { - if(canChange(mode, EnumClimatiserModes.POSITIVE)){ + if (position.getHumidity() < controlHum) { + if (canChange(mode, EnumClimatiserModes.POSITIVE)) { position.addHumidity(Math.min(change, controlHum - position.getHumidity())); hasChange = true; } - }else if(position.getHumidity() > controlHum){ - if(canChange(mode, EnumClimatiserModes.NEGATIVE)){ + } else if (position.getHumidity() > controlHum) { + if (canChange(mode, EnumClimatiserModes.NEGATIVE)) { position.addHumidity(-Math.min(position.getHumidity() - controlHum, change)); hasChange = true; } @@ -97,10 +101,10 @@ public class GreenhouseClimateWindow extends GreenhouseClimateSource> greenhouseLogics = new ArrayList<>(); - + @Override + @Nullable public IGreenhouseController getGreenhouseController(World world, BlockPos pos) { - if (MultiblockRegistry.getControllersFromWorld(world) != null) { - for (IMultiblockControllerInternal controllerInternal : MultiblockRegistry.getControllersFromWorld(world)) { - if (controllerInternal instanceof IGreenhouseControllerInternal) { - if (controllerInternal.isAssembled()) { - if (isPositionInGreenhouse((IGreenhouseControllerInternal) controllerInternal, pos)) { - return (IGreenhouseController) controllerInternal; - } - } - } + for (IMultiblockControllerInternal controllerInternal : MultiblockRegistry.getControllersFromWorld(world)) { + if (controllerInternal instanceof IGreenhouseControllerInternal && + controllerInternal.isAssembled() && + isPositionInGreenhouse((IGreenhouseControllerInternal) controllerInternal, pos)) { + return (IGreenhouseController) controllerInternal; } } return null; } - + private static boolean isPositionInGreenhouse(IGreenhouseControllerInternal controller, BlockPos pos) { IInternalBlock checkBlock = new InternalBlockCheck(pos); return controller.getInternalBlocks().contains(checkBlock); } - + @Override public void addGreenhouseLogic(Class logic) { - if(!greenhouseLogics.contains(logic)){ + if (!greenhouseLogics.contains(logic)) { greenhouseLogics.add(logic); } } - + @Override public List> getGreenhouseLogics() { return greenhouseLogics; diff --git a/src/main/java/forestry/greenhouse/PluginGreenhouse.java b/src/main/java/forestry/greenhouse/PluginGreenhouse.java index 91a6c9537..6129260a3 100644 --- a/src/main/java/forestry/greenhouse/PluginGreenhouse.java +++ b/src/main/java/forestry/greenhouse/PluginGreenhouse.java @@ -10,17 +10,15 @@ ******************************************************************************/ package forestry.greenhouse; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.registry.GameRegistry; +import javax.annotation.Nullable; +import com.google.common.base.Preconditions; import forestry.api.core.ForestryAPI; import forestry.api.greenhouse.GreenhouseManager; import forestry.core.PluginCore; import forestry.core.config.Constants; import forestry.core.items.EnumElectronTube; +import forestry.core.items.ItemRegistryCore; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.OreDictUtil; import forestry.greenhouse.blocks.BlockGreenhouseType; @@ -44,35 +42,45 @@ import forestry.greenhouse.tiles.TileGreenhouseWindow; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.registry.GameRegistry; @ForestryPlugin(pluginID = ForestryPluginUids.GREENHOUSE, name = "Greenhouse", author = "Nedelosk", url = Constants.URL, unlocalizedDescription = "for.plugin.greenhouse.description") public class PluginGreenhouse extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.greenhouse.proxy.ProxyGreenhouseClient", serverSide = "forestry.greenhouse.proxy.ProxyGreenhouse") public static ProxyGreenhouse proxy; - + + @Nullable public static BlockRegistryGreenhouse blocks; - + @Override public void setupAPI() { GreenhouseManager.greenhouseHelper = new GreenhouseHelper(); } - + @Override public void registerItemsAndBlocks() { blocks = new BlockRegistryGreenhouse(); } - + @Override public void registerRecipes() { - + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); + Preconditions.checkState(blocks != null); + Block greenhousePlainBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN); RecipeUtil.addRecipe(greenhousePlainBlock, "###", "#X#", "###", 'X', Blocks.BRICK_BLOCK, - '#', PluginCore.items.craftingMaterial.getCamouflagedPaneling()); + '#', coreItems.craftingMaterial.getCamouflagedPaneling()); Block greenhouseGlassBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.GLASS); RecipeUtil.addRecipe(greenhouseGlassBlock, @@ -80,7 +88,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "#X#", "###", 'X', "blockGlass", - '#', PluginCore.items.craftingMaterial.getCamouflagedPaneling()); + '#', coreItems.craftingMaterial.getCamouflagedPaneling()); Block greenhouseHatchInputBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.HATCH_INPUT); RecipeUtil.addRecipe(greenhouseHatchInputBlock, @@ -89,7 +97,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), 'H', OreDictUtil.TRAPDOOR_WOOD, '#', "gearTin", - 'T', PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.BRONZE, 1)); Block greenhouseHatchOutputBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.HATCH_OUTPUT); RecipeUtil.addRecipe(greenhouseHatchOutputBlock, @@ -98,7 +106,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), 'H', OreDictUtil.TRAPDOOR_WOOD, '#', "gearTin", - 'T', PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.BRONZE, 1)); Block greenhouseControlBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.CONTROL); RecipeUtil.addRecipe(greenhouseControlBlock, @@ -106,7 +114,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "#T#", 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), '#', OreDictUtil.DUST_REDSTONE, - 'T', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.GOLD, 1)); Block greenhouseGearBoxBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.GEARBOX); RecipeUtil.addRecipe(greenhouseGearBoxBlock, @@ -130,7 +138,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "T#T", 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), '#', OreDictUtil.INGOT_TIN, - 'T', PluginCore.items.tubes.get(EnumElectronTube.GOLD, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.GOLD, 1)); Block greenhouseFanlock = blocks.getGreenhouseBlock(BlockGreenhouseType.FAN); RecipeUtil.addRecipe(greenhouseFanlock, @@ -139,7 +147,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "T#T", 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), '#', OreDictUtil.INGOT_IRON, - 'T', PluginCore.items.tubes.get(EnumElectronTube.TIN, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.TIN, 1)); Block greenhouseDryerBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.DRYER); RecipeUtil.addRecipe(greenhouseDryerBlock, @@ -148,7 +156,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "T#T", 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), '#', OreDictUtil.INGOT_TIN, - 'T', PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.BLAZE, 1)); Block greenhouseSprinklerBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.SPRINKLER); RecipeUtil.addRecipe(greenhouseSprinklerBlock, @@ -156,9 +164,9 @@ public class PluginGreenhouse extends BlankForestryPlugin { "GIG", " I ", 'X', blocks.getGreenhouseBlock(BlockGreenhouseType.GLASS), - 'I', OreDictUtil.INGOT_IRON, + 'I', OreDictUtil.INGOT_IRON, 'G', OreDictUtil.GEAR_TIN, - 'T', PluginCore.items.tubes.get(EnumElectronTube.LAPIS, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.LAPIS, 1)); Block greenhouseDoorBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.DOOR); RecipeUtil.addRecipe(greenhouseDoorBlock, @@ -167,7 +175,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "GG ", "GG ", 'G', blocks.getGreenhouseBlock(BlockGreenhouseType.GLASS)); - + Block greenhouseWindowBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.WINDOW); RecipeUtil.addRecipe(greenhouseWindowBlock, true, @@ -176,7 +184,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "GGS", 'G', blocks.getGreenhouseBlock(BlockGreenhouseType.GLASS), 'S', OreDictUtil.STICK_WOOD); - + Block greenhouseWindowRoofBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.WINDOW_UP); RecipeUtil.addRecipe(greenhouseWindowRoofBlock, true, @@ -185,7 +193,7 @@ public class PluginGreenhouse extends BlankForestryPlugin { "GGG", 'G', blocks.getGreenhouseBlock(BlockGreenhouseType.GLASS), 'S', OreDictUtil.STICK_WOOD); - + Block greenhouseClimateControlBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.CLIMATE_CONTROL); RecipeUtil.addRecipe(greenhouseClimateControlBlock, true, @@ -196,10 +204,10 @@ public class PluginGreenhouse extends BlankForestryPlugin { 'I', OreDictUtil.INGOT_BRONZE, 'G', OreDictUtil.GEAR_TIN, 'R', OreDictUtil.DUST_REDSTONE, - 'T', PluginCore.items.tubes.get(EnumElectronTube.LAPIS, 1), - 'E', PluginCore.items.tubes.get(EnumElectronTube.BLAZE, 1)); + 'T', coreItems.tubes.get(EnumElectronTube.LAPIS, 1), + 'E', coreItems.tubes.get(EnumElectronTube.BLAZE, 1)); - if(ForestryAPI.enabledPlugins.contains(ForestryPluginUids.LEPIDOPTEROLOGY)){ + if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.LEPIDOPTEROLOGY)) { Block greenhouseButterflyHatchBlock = blocks.getGreenhouseBlock(BlockGreenhouseType.BUTTERFLY_HATCH); RecipeUtil.addRecipe(greenhouseButterflyHatchBlock, true, @@ -210,14 +218,14 @@ public class PluginGreenhouse extends BlankForestryPlugin { 'I', OreDictUtil.INGOT_IRON, 'G', OreDictUtil.GEAR_COPPER, 'B', blocks.getGreenhouseBlock(BlockGreenhouseType.PLAIN), - 'S', PluginCore.items.craftingMaterial.getSilkWisp()); + 'S', coreItems.craftingMaterial.getSilkWisp()); } } - + @Override public void doInit() { super.doInit(); - + GameRegistry.registerTileEntity(TileGreenhouseFan.class, "forestry.GreenhouseFan"); GameRegistry.registerTileEntity(TileGreenhouseHeater.class, "forestry.GreenhouseHeater"); GameRegistry.registerTileEntity(TileGreenhouseDryer.class, "forestry.GreenhouseDryer"); @@ -234,15 +242,15 @@ public class PluginGreenhouse extends BlankForestryPlugin { GameRegistry.registerTileEntity(TileGreenhouseButterflyHatch.class, "forestry.GreenhouseButterflyHatch"); } } - + @Override public void preInit() { MinecraftForge.EVENT_BUS.register(new EventHandlerGreenhouse()); - + proxy.initializeModels(); - + GreenhouseManager.greenhouseHelper.addGreenhouseLogic(GreenhouseLogicGreenhouseEffect.class); GreenhouseManager.greenhouseHelper.addGreenhouseLogic(GreenhouseLogicGreenhouseDoor.class); } - + } diff --git a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouse.java b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouse.java index b9bfdaf84..39ad0dd7b 100644 --- a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouse.java +++ b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouse.java @@ -10,50 +10,11 @@ ******************************************************************************/ package forestry.greenhouse.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.EnumMap; -import java.util.List; import java.util.Locale; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.block.SoundType; -import net.minecraft.block.material.Material; -import net.minecraft.block.properties.IProperty; -import net.minecraft.block.properties.PropertyBool; -import net.minecraft.block.properties.PropertyDirection; -import net.minecraft.block.properties.PropertyEnum; -import net.minecraft.block.state.BlockStateContainer; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.BlockRenderLayer; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumFacing.Plane; -import net.minecraft.util.EnumHand; -import net.minecraft.util.IStringSerializable; -import net.minecraft.util.Rotation; -import net.minecraft.util.math.AxisAlignedBB; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.util.text.TextComponentTranslation; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -import net.minecraftforge.client.model.ModelLoader; -import net.minecraftforge.common.property.ExtendedBlockState; -import net.minecraftforge.common.property.IExtendedBlockState; -import net.minecraftforge.common.property.IUnlistedProperty; -import net.minecraftforge.common.property.Properties; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.core.ForestryAPI; import forestry.api.core.ICamouflagedTile; import forestry.api.core.IModelManager; @@ -66,8 +27,8 @@ import forestry.core.CreativeTabForestry; import forestry.core.blocks.BlockStructure; import forestry.core.blocks.IBlockRotatable; import forestry.core.blocks.IColoredBlock; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.multiblock.MultiblockTileEntityForestry; import forestry.core.tiles.IActivatable; import forestry.core.utils.CamouflageUtil; @@ -87,13 +48,48 @@ import forestry.greenhouse.tiles.TileGreenhouseValve; import forestry.greenhouse.tiles.TileGreenhouseWindow; import forestry.greenhouse.tiles.TileGreenhouseWindow.WindowMode; import forestry.plugins.ForestryPluginUids; +import net.minecraft.block.Block; +import net.minecraft.block.SoundType; +import net.minecraft.block.material.Material; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.properties.PropertyBool; +import net.minecraft.block.properties.PropertyDirection; +import net.minecraft.block.properties.PropertyEnum; +import net.minecraft.block.state.BlockStateContainer; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockRenderLayer; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumFacing.Plane; +import net.minecraft.util.EnumHand; +import net.minecraft.util.IStringSerializable; +import net.minecraft.util.Rotation; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.IBlockAccess; +import net.minecraft.world.World; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.common.property.ExtendedBlockState; +import net.minecraftforge.common.property.IExtendedBlockState; +import net.minecraftforge.common.property.IUnlistedProperty; +import net.minecraftforge.common.property.Properties; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BlockGreenhouse extends BlockStructure implements ISpriteRegister, IColoredBlock, IBlockRotatable { private static final AxisAlignedBB SPRINKLER_BOUNDS = new AxisAlignedBB(0.3125F, 0.25F, 0.3125F, 0.6875F, 1F, 0.6875F); public static final PropertyEnum STATE = PropertyEnum.create("state", State.class); public static final PropertyBool BLOCKED = PropertyBool.create("blocked"); public static final PropertyDirection FACING = PropertyDirection.create("facing", Plane.HORIZONTAL); - + public enum State implements IStringSerializable { ON, OFF; @@ -102,7 +98,7 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR return name().toLowerCase(Locale.ENGLISH); } } - + public static Map create() { Map blockMap = new EnumMap<>(BlockGreenhouseType.class); for (final BlockGreenhouseType type : BlockGreenhouseType.VALUES) { @@ -111,22 +107,22 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR continue; } } - + BlockGreenhouse block; if (type == BlockGreenhouseType.DOOR) { block = new BlockGreenhouseDoor(); } else { block = new BlockGreenhouse() { - @Nonnull + @Override public BlockGreenhouseType getGreenhouseType() { return type; } - - @Nonnull + + @Override public SoundType getSoundType() { - if(type == BlockGreenhouseType.SPRINKLER || type == BlockGreenhouseType.GLASS || type == BlockGreenhouseType.WINDOW || type == BlockGreenhouseType.WINDOW_UP){ + if (type == BlockGreenhouseType.SPRINKLER || type == BlockGreenhouseType.GLASS || type == BlockGreenhouseType.WINDOW || type == BlockGreenhouseType.WINDOW_UP) { return SoundType.GLASS; } return super.getSoundType(); @@ -137,7 +133,7 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR } return blockMap; } - + public BlockGreenhouse() { super(Material.ROCK); BlockGreenhouseType greenhouseType = getGreenhouseType(); @@ -145,11 +141,11 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR if (greenhouseType.activatable && greenhouseType != BlockGreenhouseType.SPRINKLER) { defaultState = defaultState.withProperty(STATE, State.OFF); } - if(greenhouseType == BlockGreenhouseType.WINDOW || greenhouseType == BlockGreenhouseType.WINDOW_UP){ + if (greenhouseType == BlockGreenhouseType.WINDOW || greenhouseType == BlockGreenhouseType.WINDOW_UP) { defaultState = defaultState.withProperty(FACING, EnumFacing.NORTH); } setDefaultState(defaultState); - + setHardness(1.0f); setHarvestLevel("pickaxe", 0); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)) { @@ -158,10 +154,10 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR setCreativeTab(CreativeTabForestry.tabForestry); } } - + @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { - if (player.isSneaking()) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + if (playerIn.isSneaking()) { return false; } @@ -169,67 +165,62 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR if (!(tile instanceof MultiblockTileEntityForestry)) { return false; } - + MultiblockTileEntityForestry part = (MultiblockTileEntityForestry) tile; IMultiblockController controller = part.getMultiblockLogic().getController(); - if(player.getHeldItemMainhand() == null){ - if(tile instanceof TileGreenhouseWindow){ + if (playerIn.getHeldItemMainhand().isEmpty()) { + if (tile instanceof TileGreenhouseWindow) { TileGreenhouseWindow window = (TileGreenhouseWindow) tile; - if(window.getMode() != WindowMode.CONTROL){ + if (window.getMode() != WindowMode.CONTROL) { if (!worldIn.isRemote) { - if(window.isBlocked() == WindowMode.OPEN){ - if(window.getMode() == WindowMode.OPEN){ + if (window.isBlocked() == WindowMode.OPEN) { + if (window.getMode() == WindowMode.OPEN) { window.setMode(WindowMode.PLAYER); - }else{ - window.setMode(WindowMode.OPEN); + } else { + window.setMode(WindowMode.OPEN); } } } - worldIn.playEvent(player, getPlaySound(!window.isActive()), pos, 0); + worldIn.playEvent(playerIn, getPlaySound(!window.isActive()), pos, 0); return true; } } - - if (player.getHeldItemOffhand() == null) { + + if (playerIn.getHeldItemOffhand().isEmpty()) { // If the player's hands are empty and they right-click on a multiblock, they get a // multiblock-debugging message if the machine is not assembled. - if (controller != null) { - if (!controller.isAssembled()) { - String validationError = controller.getLastValidationError(); - if (validationError != null) { - long tick = worldIn.getTotalWorldTime(); - if (tick > previousMessageTick + 20) { - player.addChatMessage(new TextComponentString(validationError)); - previousMessageTick = tick; - } - return true; + if (!controller.isAssembled()) { + String validationError = controller.getLastValidationError(); + if (validationError != null) { + long tick = worldIn.getTotalWorldTime(); + if (tick > previousMessageTick + 20) { + playerIn.sendMessage(new TextComponentString(validationError)); + previousMessageTick = tick; } + return true; } - } else { - player.addChatMessage(new TextComponentTranslation("for.multiblock.error.notConnected")); - return true; } } } // Don't open the GUI if the multiblock isn't assembled - if (controller == null || !controller.isAssembled()) { + if (!controller.isAssembled()) { return false; } if (!worldIn.isRemote) { - part.openGui(player); + part.openGui(playerIn); } return true; } - - protected int getPlaySound(boolean open){ - if (open){ - return 1007; - }else{ - return 1013; - } - } + + protected int getPlaySound(boolean open) { + if (open) { + return 1007; + } else { + return 1013; + } + } @Override @SideOnly(Side.CLIENT) @@ -240,8 +231,9 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR return super.getSelectedBoundingBox(state, worldIn, pos); } + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { if (getGreenhouseType() == BlockGreenhouseType.SPRINKLER) { return SPRINKLER_BOUNDS; } @@ -261,64 +253,65 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR protected BlockStateContainer createBlockState() { if (getGreenhouseType() == BlockGreenhouseType.SPRINKLER) { return new ExtendedBlockState(this, new IProperty[]{Properties.StaticProperty}, new IUnlistedProperty[]{Properties.AnimationProperty}); - }else if (getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP) { + } else if (getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP) { return new BlockStateContainer(this, STATE, FACING); - } else if (getGreenhouseType().activatable) { + } else if (getGreenhouseType().activatable) { return new ExtendedBlockState(this, new IProperty[]{STATE}, new IUnlistedProperty[]{UnlistedBlockPos.POS, UnlistedBlockAccess.BLOCKACCESS}); } else { return new ExtendedBlockState(this, new IProperty[0], new IUnlistedProperty[]{UnlistedBlockPos.POS, UnlistedBlockAccess.BLOCKACCESS}); } } - + @Override public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { if (getGreenhouseType() == BlockGreenhouseType.SPRINKLER) { return state.withProperty(Properties.StaticProperty, true); } else { TileEntity tile = worldIn.getTileEntity(pos); - if(tile instanceof IActivatable){ + if (tile instanceof IActivatable) { state = state.withProperty(STATE, ((IActivatable) tile).isActive() ? State.ON : State.OFF); } - if(tile instanceof TileGreenhouseWindow){ + if (tile instanceof TileGreenhouseWindow) { TileGreenhouseWindow window = (TileGreenhouseWindow) tile; } return super.getActualState(state, worldIn, pos); } } - + @Override public IBlockState withRotation(IBlockState state, Rotation rot) { EnumFacing facing = state.getValue(FACING); return state.withProperty(FACING, rot.rotate(facing)); } - + @Override public IBlockState getStateFromMeta(int meta) { - if(getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP){ + if (getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP) { return getDefaultState().withProperty(FACING, EnumFacing.VALUES[meta + 2]); } return super.getStateFromMeta(meta); } - + @Override public int getMetaFromState(IBlockState state) { - if(getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP){ + if (getGreenhouseType() == BlockGreenhouseType.WINDOW || getGreenhouseType() == BlockGreenhouseType.WINDOW_UP) { return state.getValue(FACING).ordinal() - 2; } return 0; } - + @Override public void rotateAfterPlacement(EntityPlayer player, World world, BlockPos pos, EnumFacing side) { IBlockState state = world.getBlockState(pos); - if(state.getProperties().containsKey(FACING)){ + if (state.getProperties().containsKey(FACING)) { world.setBlockState(pos, state.withProperty(FACING, player.getHorizontalFacing().getOpposite())); } } - + @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { + @Deprecated + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { try { TileEntity tile = worldIn.getTileEntity(pos); if (tile instanceof TileGreenhouseWindow) { @@ -329,12 +322,6 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR throw error; } } - - @Override - @SideOnly(Side.CLIENT) - public void getSubBlocks(Item item, CreativeTabs tab, List list) { - list.add(new ItemStack(item)); - } @Override public TileEntity createNewTileEntity(World world, int meta) { @@ -372,21 +359,21 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR } @Override - public int colorMultiplier(IBlockState state, IBlockAccess worldIn, BlockPos pos, int tintIndex) { - if(pos == null){ + public int colorMultiplier(IBlockState state, @Nullable IBlockAccess worldIn, @Nullable BlockPos pos, int tintIndex) { + if (pos == null || worldIn == null) { return 0xffffff; } TileEntity tile = worldIn.getTileEntity(pos); if (tile instanceof ICamouflagedTile) { ItemStack camouflageStack = CamouflageUtil.getCamouflageBlock(worldIn, pos); - if (tintIndex < 100 && camouflageStack != null) { + if (tintIndex < 100 && !camouflageStack.isEmpty()) { Block block = Block.getBlockFromItem(camouflageStack.getItem()); - if(block != null){ + if (block != Blocks.AIR) { IBlockState camouflageState = block.getStateFromMeta(camouflageStack.getItemDamage()); - + int color = Minecraft.getMinecraft().getBlockColors().colorMultiplier(camouflageState, worldIn, pos, tintIndex); - if(color != -1){ + if (color != -1) { return color; } } @@ -415,7 +402,7 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR public boolean isOpaqueCube(IBlockState state) { return getGreenhouseType() != BlockGreenhouseType.GLASS && getGreenhouseType() != BlockGreenhouseType.SPRINKLER && getGreenhouseType() != BlockGreenhouseType.WINDOW && getGreenhouseType() != BlockGreenhouseType.WINDOW_UP; } - + @Override public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { if (getGreenhouseType() == BlockGreenhouseType.SPRINKLER) { @@ -428,14 +415,14 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR } return super.canPlaceBlockAt(worldIn, pos); } - + @Override public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) { super.onBlockPlacedBy(world, pos, state, placer, stack); TileEntity tile = world.getTileEntity(pos); - if(tile instanceof TileGreenhouseWindow){ + if (tile instanceof TileGreenhouseWindow) { TileGreenhouseWindow window = (TileGreenhouseWindow) tile; - if(!window.getWorld().isRemote){ + if (!window.getWorld().isRemote) { window.setMode(window.isBlocked()); } } @@ -454,15 +441,12 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR } TileEntity tile = blockAccess.getTileEntity(pos); TileEntity tileSide = blockAccess.getTileEntity(posSide); - if(tile instanceof TileGreenhousePlain && tileSide instanceof TileGreenhousePlain){ - if(((TileGreenhousePlain)tile).getCamouflageType().equals(((TileGreenhousePlain)tileSide).getCamouflageType())){ + if (tile instanceof TileGreenhousePlain && tileSide instanceof TileGreenhousePlain) { + if (((TileGreenhousePlain) tile).getCamouflageType().equals(((TileGreenhousePlain) tileSide).getCamouflageType())) { ItemStack camouflage = CamouflageUtil.getCamouflageBlock(blockAccess, pos); ItemStack camouflageSide = CamouflageUtil.getCamouflageBlock(blockAccess, posSide); - if(camouflage != null && camouflageSide != null){ - if(ItemStackUtil.isIdenticalItem(camouflage, camouflageSide)){ - return false; - } - return true; + if (!camouflage.isEmpty() && !camouflageSide.isEmpty()) { + return !ItemStackUtil.isIdenticalItem(camouflage, camouflageSide); } } } @@ -473,7 +457,7 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR return super.shouldSideBeRendered(blockState, blockAccess, pos, side); } - + @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { @@ -483,11 +467,11 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation("forestry:greenhouse.window", "inventory")); } else if (getGreenhouseType() == BlockGreenhouseType.WINDOW_UP) { ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation("forestry:greenhouse.window_up", "inventory")); - } else { + } else { ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation("forestry:greenhouse", "inventory")); } } - + @SideOnly(Side.CLIENT) @Override public void registerSprites(ITextureManager manager) { @@ -495,10 +479,10 @@ public abstract class BlockGreenhouse extends BlockStructure implements ISpriteR } @Override - public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) { + public boolean canConnectRedstone(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable EnumFacing side) { return getGreenhouseType() == BlockGreenhouseType.CONTROL; } - - @Nonnull + + public abstract BlockGreenhouseType getGreenhouseType(); } diff --git a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseDoor.java b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseDoor.java index fb0d010b8..58bc4a725 100644 --- a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseDoor.java +++ b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseDoor.java @@ -10,9 +10,17 @@ ******************************************************************************/ package forestry.greenhouse.blocks; -import javax.annotation.Nonnull; import java.util.Random; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; +import forestry.core.proxy.Proxies; +import forestry.core.utils.CamouflageUtil; +import forestry.core.utils.Translator; +import forestry.greenhouse.models.GreenhouseDoorStateMapper; +import forestry.greenhouse.tiles.TileGreenhouse; import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.block.SoundType; @@ -26,7 +34,6 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumFacing; @@ -35,21 +42,11 @@ import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; -import forestry.core.proxy.Proxies; -import forestry.core.utils.CamouflageUtil; -import forestry.core.utils.Translator; -import forestry.greenhouse.models.GreenhouseDoorStateMapper; -import forestry.greenhouse.tiles.TileGreenhouse; public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapperRegister { @@ -98,8 +95,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper boolean flag = !state.getValue(OPEN); boolean flag1 = state.getValue(HINGE) == BlockDoor.EnumHingePosition.RIGHT; - switch (enumfacing) - { + switch (enumfacing) { case EAST: default: return flag ? EAST_AABB : (flag1 ? NORTH_AABB : SOUTH_AABB); @@ -113,14 +109,14 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper } @Override - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ) { + public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { TileEntity tile = worldIn.getTileEntity(pos); if (!(tile instanceof TileGreenhouse)) { return false; } - + TileGreenhouse door = (TileGreenhouse) tile; - if(playerIn.isSneaking() && playerIn.getHeldItem(hand) == null){ + if (playerIn.isSneaking() && playerIn.getHeldItem(hand).isEmpty()) { if (!worldIn.isRemote) { door.openGui(playerIn); } @@ -142,7 +138,8 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper } @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { + @Deprecated + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { if (state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { BlockPos blockpos = pos.down(); IBlockState iblockstate = worldIn.getBlockState(blockpos); @@ -150,7 +147,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper if (iblockstate.getBlock() != this) { worldIn.setBlockToAir(pos); } else if (blockIn != this) { - iblockstate.neighborChanged(worldIn, blockpos, blockIn); + iblockstate.neighborChanged(worldIn, blockpos, blockIn, fromPos); } } else { boolean flag1 = false; @@ -162,7 +159,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper flag1 = true; } - if (!worldIn.getBlockState(pos.down()).isFullyOpaque()) { + if (!worldIn.getBlockState(pos.down()).isSideSolid(worldIn, pos.down(), EnumFacing.UP)) { worldIn.setBlockToAir(pos); flag1 = true; @@ -202,8 +199,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper } @Override - public EnumPushReaction getMobilityFlag(IBlockState state) - { + public EnumPushReaction getMobilityFlag(IBlockState state) { return EnumPushReaction.DESTROY; } @@ -246,7 +242,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper state = state.withProperty(FACING, iblockstate1.getValue(FACING)).withProperty(OPEN, iblockstate1.getValue(OPEN)); } } - state = state.withProperty(CAMOUFLAGED, CamouflageUtil.getCamouflageBlock(worldIn, pos) != null); + state = state.withProperty(CAMOUFLAGED, !CamouflageUtil.getCamouflageBlock(worldIn, pos).isEmpty()); return state; } @@ -292,7 +288,7 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper public void registerModel(Item item, IModelManager manager) { ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation("forestry:greenhouse.door", "inventory")); } - + @SideOnly(Side.CLIENT) @Override public void registerStateMapper() { @@ -332,7 +328,6 @@ public class BlockGreenhouseDoor extends BlockGreenhouse implements IStateMapper return new ExtendedBlockState(this, new IProperty[]{HALF, FACING, OPEN, HINGE, POWERED, CAMOUFLAGED}, new IUnlistedProperty[]{UnlistedBlockPos.POS, UnlistedBlockAccess.BLOCKACCESS}); } - @Nonnull @Override public BlockGreenhouseType getGreenhouseType() { return BlockGreenhouseType.DOOR; diff --git a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseType.java b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseType.java index 5b29d9c81..c35fe3ec3 100644 --- a/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseType.java +++ b/src/main/java/forestry/greenhouse/blocks/BlockGreenhouseType.java @@ -91,7 +91,7 @@ public enum BlockGreenhouseType { * @return The texture sprite from the type and the {@link IBlockState} of the greenhouse block */ @SideOnly(Side.CLIENT) - public static TextureAtlasSprite getSprite(BlockGreenhouseType type, EnumFacing facing, @Nullable IBlockState state, @Nullable IBlockAccess world, @Nullable BlockPos pos) { + public static TextureAtlasSprite getSprite(BlockGreenhouseType type, @Nullable EnumFacing facing, @Nullable IBlockState state, @Nullable IBlockAccess world, @Nullable BlockPos pos) { TileEntity tile = null; if (world != null && pos != null) { tile = world.getTileEntity(pos); @@ -136,15 +136,15 @@ public enum BlockGreenhouseType { } else if (hatch.getOutwardsDir().getOpposite() == facing) { return sprites.get(BlockGreenhouseSprites.HATCH_INPUT); } - return null; + return Minecraft.getMinecraft().getTextureMapBlocks().missingImage; case CLIMATE_CONTROL: if (facing == EnumFacing.DOWN || facing == EnumFacing.UP) { - return null; + return Minecraft.getMinecraft().getTextureMapBlocks().missingImage; } return sprites.get(BlockGreenhouseSprites.CLIMATE_CONTROL); case BUTTERFLY_HATCH: if (facing == EnumFacing.DOWN || facing == EnumFacing.UP) { - return null; + return Minecraft.getMinecraft().getTextureMapBlocks().missingImage; } return sprites.get(BlockGreenhouseSprites.BUTTERFLY_HATCH); default: diff --git a/src/main/java/forestry/greenhouse/blocks/BlockRegistryGreenhouse.java b/src/main/java/forestry/greenhouse/blocks/BlockRegistryGreenhouse.java index 59f09839f..21702ecb4 100644 --- a/src/main/java/forestry/greenhouse/blocks/BlockRegistryGreenhouse.java +++ b/src/main/java/forestry/greenhouse/blocks/BlockRegistryGreenhouse.java @@ -2,16 +2,15 @@ package forestry.greenhouse.blocks; import java.util.Map; -import net.minecraft.item.ItemBlock; - import forestry.core.blocks.BlockRegistry; import forestry.core.items.ItemBlockForestry; import forestry.greenhouse.items.ItemBlockGreenhouseDoor; +import net.minecraft.item.ItemBlock; public class BlockRegistryGreenhouse extends BlockRegistry { - + private final Map greenhouseBlockMap; - + public BlockRegistryGreenhouse() { greenhouseBlockMap = BlockGreenhouse.create(); for (BlockGreenhouse block : greenhouseBlockMap.values()) { @@ -26,5 +25,5 @@ public class BlockRegistryGreenhouse extends BlockRegistry { public BlockGreenhouse getGreenhouseBlock(BlockGreenhouseType type) { return greenhouseBlockMap.get(type); } - + } diff --git a/src/main/java/forestry/greenhouse/blocks/package-info.java b/src/main/java/forestry/greenhouse/blocks/package-info.java new file mode 100644 index 000000000..b9cf96ae9 --- /dev/null +++ b/src/main/java/forestry/greenhouse/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/entities/package-info.java b/src/main/java/forestry/greenhouse/entities/package-info.java new file mode 100644 index 000000000..add00cfff --- /dev/null +++ b/src/main/java/forestry/greenhouse/entities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.entities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/gui/GuiGreenhouse.java b/src/main/java/forestry/greenhouse/gui/GuiGreenhouse.java index 871985f30..0eb8d4075 100644 --- a/src/main/java/forestry/greenhouse/gui/GuiGreenhouse.java +++ b/src/main/java/forestry/greenhouse/gui/GuiGreenhouse.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.greenhouse.gui; -import javax.annotation.Nullable; import java.io.IOException; import com.google.common.base.Predicate; @@ -38,144 +37,145 @@ import net.minecraft.entity.player.EntityPlayer; public class GuiGreenhouse extends GuiForestryTitled { - private static final Predicate numberFilter = new Predicate(){ - @Override - public boolean apply(@Nullable String text){ - if(!text.isEmpty() && text.length() > 1){ - if(!text.contains(".")){ - return false; - } - } - if(text.length() > 7){ - return false; - } - Float f = Floats.tryParse(text); - return text.isEmpty() || f != null && Floats.isFinite(f.floatValue()) && f.floatValue() >= 0.0F; - } - }; - + private static final Predicate numberFilter = text -> { + if (text == null) { + return false; + } + if (!text.isEmpty() && text.length() > 1) { + if (!text.contains(".")) { + return false; + } + } + if (text.length() > 7) { + return false; + } + Float f = Floats.tryParse(text); + return text.isEmpty() || f != null && Floats.isFinite(f) && f >= 0.0F; + }; private GuiTextField humidityField; private GuiTextField temperatureField; private boolean fieldsEnabeled; - + public GuiGreenhouse(EntityPlayer player, TileGreenhouse tile) { super(Constants.TEXTURE_PATH_GUI + "/greenhouse.png", new ContainerGreenhouse(player.inventory, tile), tile); //Add the water tank widgetManager.add(new TankWidget(widgetManager, 152, 16, 0).setOverlayOrigin(176, 0)); - + //Add the multiblock camouflage slots widgetManager.add(new WidgetCamouflageSlot(widgetManager, 8, 16, inventory.getMultiblockLogic().getController(), CamouflageManager.DEFAULT)); widgetManager.add(new WidgetCamouflageSlot(widgetManager, 8, 37, inventory.getMultiblockLogic().getController(), CamouflageManager.GLASS)); widgetManager.add(new WidgetCamouflageSlot(widgetManager, 8, 58, inventory.getMultiblockLogic().getController(), CamouflageManager.DOOR)); - + //Add the tile camouflage slots widgetManager.add(new WidgetCamouflageSlot(widgetManager, 35, 37, inventory, tile.getCamouflageType())); fieldsEnabeled = true; - + + temperatureField = new GuiTextField(0, fontRendererObj, guiLeft + 63, guiTop + 30, 50, 10); + humidityField = new GuiTextField(1, fontRendererObj, guiLeft + 63, guiTop + 60, 50, 10); } - + @Override public void initGui() { super.initGui(); - + temperatureField = new GuiTextField(0, fontRendererObj, guiLeft + 63, guiTop + 30, 50, 10); humidityField = new GuiTextField(1, fontRendererObj, guiLeft + 63, guiTop + 60, 50, 10); - + temperatureField.setValidator(numberFilter); humidityField.setValidator(numberFilter); - + IGreenhouseController controller = inventory.getMultiblockLogic().getController(); - if(controller == null || controller.getClimateControl() == null || controller.getClimateControl() == DefaultClimateControl.instance){ + if (controller == null || controller.getClimateControl() == DefaultClimateControl.instance) { temperatureField.setEnabled(false); temperatureField.setVisible(false); humidityField.setEnabled(false); humidityField.setVisible(false); fieldsEnabeled = false; - }else{ + } else { IClimateControl control = controller.getClimateControl(); temperatureField.setText(Float.toString(control.getControlTemperature())); humidityField.setText(Float.toString(control.getControlHumidity())); } } - - @Override - protected void keyTyped(char typedChar, int keyCode) throws IOException{ - if(fieldsEnabeled){ - if(!humidityField.textboxKeyTyped(typedChar, keyCode) && !temperatureField.textboxKeyTyped(typedChar, keyCode)){ - super.keyTyped(typedChar, keyCode); - } - }else{ - super.keyTyped(typedChar, keyCode); - } - } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException{ - super.mouseClicked(mouseX, mouseY, mouseButton); - if(fieldsEnabeled){ - boolean temperatureWasFocused = temperatureField.isFocused(); - boolean humidityWasFocused = humidityField.isFocused(); - temperatureField.mouseClicked(mouseX, mouseY, mouseButton); - humidityField.mouseClicked(mouseX, mouseY, mouseButton); - IClimateControlProvider provider = inventory.getMultiblockLogic().getController(); - IClimateControl control = provider.getClimateControl(); - if(temperatureWasFocused && !temperatureField.isFocused()){ - float temp = parseField(temperatureField); - temperatureField.setText(Float.toString(temp)); - control.setControlTemperature(temp); - }else if(humidityWasFocused && !humidityField.isFocused()){ - float hum = parseField(humidityField); - humidityField.setText(Float.toString(hum)); - control.setControlHumidity(parseField(humidityField)); - } - Proxies.net.sendToServer(new PacketUpdateClimateControl(provider)); - } - } - - private float parseField(GuiTextField field){ - String text = field.getText(); - if(text.isEmpty()){ - return 2.0F; - } - try{ - float f = Float.parseFloat(text); - if(f >= 2){ - f = 2.0F; - } - return f; - }catch (NumberFormatException var5){ - return 2.0F; - } - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { - super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); - - if(temperatureField.getVisible()){ + @Override + protected void keyTyped(char typedChar, int keyCode) throws IOException { + if (fieldsEnabeled) { + if (!humidityField.textboxKeyTyped(typedChar, keyCode) && !temperatureField.textboxKeyTyped(typedChar, keyCode)) { + super.keyTyped(typedChar, keyCode); + } + } else { + super.keyTyped(typedChar, keyCode); + } + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + super.mouseClicked(mouseX, mouseY, mouseButton); + if (fieldsEnabeled) { + boolean temperatureWasFocused = temperatureField.isFocused(); + boolean humidityWasFocused = humidityField.isFocused(); + temperatureField.mouseClicked(mouseX, mouseY, mouseButton); + humidityField.mouseClicked(mouseX, mouseY, mouseButton); + IClimateControlProvider provider = inventory.getMultiblockLogic().getController(); + IClimateControl control = provider.getClimateControl(); + if (temperatureWasFocused && !temperatureField.isFocused()) { + float temp = parseField(temperatureField); + temperatureField.setText(Float.toString(temp)); + control.setControlTemperature(temp); + } else if (humidityWasFocused && !humidityField.isFocused()) { + float hum = parseField(humidityField); + humidityField.setText(Float.toString(hum)); + control.setControlHumidity(parseField(humidityField)); + } + Proxies.net.sendToServer(new PacketUpdateClimateControl(provider)); + } + } + + private float parseField(GuiTextField field) { + String text = field.getText(); + if (text.isEmpty()) { + return 2.0F; + } + try { + float f = Float.parseFloat(text); + if (f >= 2) { + f = 2.0F; + } + return f; + } catch (NumberFormatException var5) { + return 2.0F; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + super.drawGuiContainerBackgroundLayer(f, mouseX, mouseY); + + if (temperatureField.getVisible()) { textLayout.line = 20; textLayout.drawCenteredLine(Translator.translateToLocal("for.gui.temperature"), 0, ColourProperties.INSTANCE.get("gui.greenhouse.temperature.text")); - temperatureField.drawTextBox(); - } - if(humidityField.getVisible()){ + temperatureField.drawTextBox(); + } + if (humidityField.getVisible()) { textLayout.line = 50; textLayout.drawCenteredLine(Translator.translateToLocal("for.gui.humidity"), 0, ColourProperties.INSTANCE.get("gui.greenhouse.humidity.text")); - - humidityField.drawTextBox(); - } + + humidityField.drawTextBox(); + } bindTexture(textureFile); - } + } @Override protected void addLedgers() { IGreenhouseControllerInternal greenhouseController = inventory.getMultiblockLogic().getController(); - + ledgerManager.add(new ClimateLedger(ledgerManager, greenhouseController)); ledgerManager.add(new EnergyLedger()); super.addLedgers(); } - + protected class EnergyLedger extends Ledger { public EnergyLedger() { diff --git a/src/main/java/forestry/greenhouse/gui/package-info.java b/src/main/java/forestry/greenhouse/gui/package-info.java new file mode 100644 index 000000000..11eccc55d --- /dev/null +++ b/src/main/java/forestry/greenhouse/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/inventory/InventoryGreenhouse.java b/src/main/java/forestry/greenhouse/inventory/InventoryGreenhouse.java index 7a84beb8a..78bf0de47 100644 --- a/src/main/java/forestry/greenhouse/inventory/InventoryGreenhouse.java +++ b/src/main/java/forestry/greenhouse/inventory/InventoryGreenhouse.java @@ -32,7 +32,7 @@ public class InventoryGreenhouse extends InventoryAdapterRestricted { @Override public boolean canSlotAccept(int slotIndex, ItemStack itemStack) { FluidStack fluid = FluidUtil.getFluidContained(itemStack); - return greenhouseController.getTankManager().canFillFluidType(fluid); + return fluid != null && greenhouseController.getTankManager().canFillFluidType(fluid); } public void drainCan(TankManager tankManager) { diff --git a/src/main/java/forestry/greenhouse/inventory/package-info.java b/src/main/java/forestry/greenhouse/inventory/package-info.java new file mode 100644 index 000000000..6594e95f5 --- /dev/null +++ b/src/main/java/forestry/greenhouse/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/items/ItemBlockGreenhouseDoor.java b/src/main/java/forestry/greenhouse/items/ItemBlockGreenhouseDoor.java index f9cce89db..40613d0e3 100644 --- a/src/main/java/forestry/greenhouse/items/ItemBlockGreenhouseDoor.java +++ b/src/main/java/forestry/greenhouse/items/ItemBlockGreenhouseDoor.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.greenhouse.items; +import forestry.core.items.ItemBlockForestry; +import forestry.greenhouse.blocks.BlockGreenhouseDoor; import net.minecraft.block.Block; import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; @@ -23,9 +25,6 @@ import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; -import forestry.core.items.ItemBlockForestry; -import forestry.greenhouse.blocks.BlockGreenhouseDoor; - public class ItemBlockGreenhouseDoor extends ItemBlockForestry { public ItemBlockGreenhouseDoor(Block block) { @@ -33,10 +32,10 @@ public class ItemBlockGreenhouseDoor extends ItemBlockForestry 0 && hitZ > 0.5F || j < 0 && hitX > 0.5F || j > 0 && hitX < 0.5F; ItemDoor.placeDoor(worldIn, pos, enumfacing, this.block, flag); - SoundType soundtype = this.block.getSoundType(); - worldIn.playSound(playerIn, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); - --stack.stackSize; + SoundType soundtype = worldIn.getBlockState(pos).getBlock().getSoundType(worldIn.getBlockState(pos), worldIn, pos, player); + worldIn.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F); + itemstack.shrink(1); return EnumActionResult.SUCCESS; } else { return EnumActionResult.FAIL; diff --git a/src/main/java/forestry/greenhouse/items/package-info.java b/src/main/java/forestry/greenhouse/items/package-info.java new file mode 100644 index 000000000..c51910d37 --- /dev/null +++ b/src/main/java/forestry/greenhouse/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/logics/GreenhouseLogicGreenhouseEffect.java b/src/main/java/forestry/greenhouse/logics/GreenhouseLogicGreenhouseEffect.java index 8416ac39a..e735eaf73 100644 --- a/src/main/java/forestry/greenhouse/logics/GreenhouseLogicGreenhouseEffect.java +++ b/src/main/java/forestry/greenhouse/logics/GreenhouseLogicGreenhouseEffect.java @@ -10,9 +10,6 @@ ******************************************************************************/ package forestry.greenhouse.logics; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageItemHandler; import forestry.api.core.ICamouflagedTile; @@ -22,17 +19,20 @@ import forestry.api.greenhouse.IGreenhouseClimaLogic; import forestry.api.multiblock.IGreenhouseController; import forestry.api.multiblock.IMultiblockComponent; import forestry.core.utils.CamouflageUtil; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class GreenhouseLogicGreenhouseEffect extends DefaultGreenhouseLogic implements IGreenhouseClimaLogic { private float lightTransmittance; private int workTimer; - + public GreenhouseLogicGreenhouseEffect(IGreenhouseController controller) { super(controller, "GreenhouseEffect"); - + } - + @Override public void work() { /*if (controller == null || !controller.isAssembled()) { @@ -62,25 +62,26 @@ public class GreenhouseLogicGreenhouseEffect extends DefaultGreenhouseLogic impl @Override public void onEvent(EnumGreenhouseEventType type, Object event) { if (type == EnumGreenhouseEventType.CAMOUFLAGE) { - if (controller == null || !controller.isAssembled()) { + if (!controller.isAssembled()) { return; } float lightTransmittance = 0F; int i = 0; - + World world = controller.getWorldObj(); for (IMultiblockComponent component : controller.getComponents()) { if (component instanceof ICamouflagedTile) { ICamouflagedTile block = (ICamouflagedTile) component; - if (block.getCamouflageType() == CamouflageManager.GLASS) { + if (block.getCamouflageType().equals(CamouflageManager.GLASS)) { if (world.canBlockSeeSky(component.getCoordinates())) { ItemStack camouflageStack = CamouflageUtil.getCamouflageBlock(world, component.getCoordinates()); ICamouflageItemHandler handler = CamouflageManager.camouflageAccess.getHandlerFromItem(camouflageStack); - float camouflageLightTransmittance = handler.getLightTransmittance(camouflageStack, controller); - - if (camouflageLightTransmittance < 1 && camouflageLightTransmittance > 0) { - lightTransmittance = lightTransmittance + camouflageLightTransmittance; - i++; + if (handler != null) { + float camouflageLightTransmittance = handler.getLightTransmittance(camouflageStack, controller); + if (camouflageLightTransmittance < 1 && camouflageLightTransmittance > 0) { + lightTransmittance = lightTransmittance + camouflageLightTransmittance; + i++; + } } } } diff --git a/src/main/java/forestry/greenhouse/logics/package-info.java b/src/main/java/forestry/greenhouse/logics/package-info.java new file mode 100644 index 000000000..a74d68291 --- /dev/null +++ b/src/main/java/forestry/greenhouse/logics/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.logics; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/models/GreenhouseDoorStateMapper.java b/src/main/java/forestry/greenhouse/models/GreenhouseDoorStateMapper.java index 9fb22effd..556efe5d2 100644 --- a/src/main/java/forestry/greenhouse/models/GreenhouseDoorStateMapper.java +++ b/src/main/java/forestry/greenhouse/models/GreenhouseDoorStateMapper.java @@ -4,7 +4,6 @@ import java.util.LinkedHashMap; import java.util.Map; import com.google.common.collect.Maps; - import forestry.core.render.ForestryStateMapper; import forestry.greenhouse.blocks.BlockGreenhouseDoor; import net.minecraft.block.Block; @@ -17,10 +16,10 @@ public class GreenhouseDoorStateMapper extends ForestryStateMapper { @Override public Map putStateModelLocations(Block block) { - for(IBlockState state : block.getBlockState().getValidStates()){ - if(state.getValue(BlockGreenhouseDoor.CAMOUFLAGED)){ + for (IBlockState state : block.getBlockState().getValidStates()) { + if (state.getValue(BlockGreenhouseDoor.CAMOUFLAGED)) { mapStateModelLocations.put(state, new ModelResourceLocation(block.getRegistryName(), "camouflage")); - }else{ + } else { LinkedHashMap, Comparable> linkedhashmap = Maps.newLinkedHashMap(state.getProperties()); linkedhashmap.remove(BlockGreenhouseDoor.CAMOUFLAGED); linkedhashmap.remove(BlockDoor.POWERED); diff --git a/src/main/java/forestry/greenhouse/models/ModelGreenhouse.java b/src/main/java/forestry/greenhouse/models/ModelGreenhouse.java index e4e8537dc..e1648a68e 100644 --- a/src/main/java/forestry/greenhouse/models/ModelGreenhouse.java +++ b/src/main/java/forestry/greenhouse/models/ModelGreenhouse.java @@ -10,15 +10,15 @@ ******************************************************************************/ package forestry.greenhouse.models; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflageItemHandler; import forestry.api.core.ICamouflagedTile; import forestry.api.core.IModelBaker; -import forestry.core.blocks.propertys.UnlistedBlockAccess; -import forestry.core.blocks.propertys.UnlistedBlockPos; +import forestry.core.blocks.properties.UnlistedBlockAccess; +import forestry.core.blocks.properties.UnlistedBlockPos; import forestry.core.models.ModelBlockDefault; import forestry.core.utils.CamouflageUtil; import forestry.greenhouse.blocks.BlockGreenhouse; @@ -37,11 +37,14 @@ import org.apache.commons.lang3.tuple.Pair; // DO NOT CACHE THIS. PLEASE. I BEG YOU. NOT IN THE CURRENT STATE. public class ModelGreenhouse extends ModelBlockDefault { public static class Key { + @Nullable public final IExtendedBlockState state; + @Nullable public final IBlockAccess world; + @Nullable public final BlockPos pos; - public Key(IExtendedBlockState state, IBlockAccess world, BlockPos pos) { + public Key(@Nullable IExtendedBlockState state, @Nullable IBlockAccess world, @Nullable BlockPos pos) { this.state = state; this.world = world; this.pos = pos; @@ -53,12 +56,12 @@ public class ModelGreenhouse extends ModelBlockDefault model = itemHandler.getModel(camouflageStack, camouflageHandler, camouflageTile); - if(model != null){ - baker.addBakedModel(model.getLeft(), model.getRight()); - baker.setParticleSprite(model.getRight().getParticleTexture()); - } + baker.addBakedModel(model.getLeft(), model.getRight()); + baker.setParticleSprite(model.getRight().getParticleTexture()); } } diff --git a/src/main/java/forestry/greenhouse/models/package-info.java b/src/main/java/forestry/greenhouse/models/package-info.java new file mode 100644 index 000000000..5645d19ce --- /dev/null +++ b/src/main/java/forestry/greenhouse/models/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.models; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/multiblock/FakeGreenhouseController.java b/src/main/java/forestry/greenhouse/multiblock/FakeGreenhouseController.java index 55cdf56fe..71f750ece 100644 --- a/src/main/java/forestry/greenhouse/multiblock/FakeGreenhouseController.java +++ b/src/main/java/forestry/greenhouse/multiblock/FakeGreenhouseController.java @@ -10,12 +10,11 @@ ******************************************************************************/ package forestry.greenhouse.multiblock; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Set; -import javax.annotation.Nonnull; - import forestry.api.climate.IClimateControl; import forestry.api.climate.IClimateRegion; import forestry.api.greenhouse.EnumGreenhouseEventType; @@ -29,7 +28,6 @@ import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.FakeMultiblockController; import forestry.energy.EnergyManager; - import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; @@ -39,13 +37,11 @@ public class FakeGreenhouseController extends FakeMultiblockController implement private FakeGreenhouseController() { } - @Nonnull @Override public IInventoryAdapter getInternalInventory() { return FakeInventoryAdapter.instance(); } - @Nonnull @Override public ITankManager getTankManager() { return FakeTankManager.instance; @@ -58,12 +54,12 @@ public class FakeGreenhouseController extends FakeMultiblockController implement @Override public ItemStack getCamouflageBlock(String type) { - return null; + return ItemStack.EMPTY; } @Override public ItemStack getDefaultCamouflageBlock(String type) { - return null; + return ItemStack.EMPTY; } @Override @@ -78,7 +74,7 @@ public class FakeGreenhouseController extends FakeMultiblockController implement @Override public BlockPos getCoordinates() { - return null; + return BlockPos.ORIGIN; } @Override @@ -125,6 +121,7 @@ public class FakeGreenhouseController extends FakeMultiblockController implement } @Override + @Nullable public ButterflyHatch getButterflyHatch() { return null; } diff --git a/src/main/java/forestry/greenhouse/multiblock/GreenhouseController.java b/src/main/java/forestry/greenhouse/multiblock/GreenhouseController.java index eee0aab15..480535729 100644 --- a/src/main/java/forestry/greenhouse/multiblock/GreenhouseController.java +++ b/src/main/java/forestry/greenhouse/multiblock/GreenhouseController.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.greenhouse.multiblock; +import javax.annotation.Nullable; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -20,8 +21,6 @@ import java.util.Map; import java.util.Set; import java.util.Stack; -import javax.annotation.Nonnull; - import forestry.api.climate.IClimateControl; import forestry.api.climate.IClimatePosition; import forestry.api.climate.IClimateRegion; @@ -48,16 +47,15 @@ import forestry.api.multiblock.IMultiblockComponent; import forestry.core.climate.ClimatePosition; import forestry.core.climate.ClimateRoom; import forestry.core.config.Constants; +import forestry.core.fluids.FilteredTank; +import forestry.core.fluids.StandardTank; import forestry.core.fluids.TankManager; -import forestry.core.fluids.tanks.FilteredTank; -import forestry.core.fluids.tanks.StandardTank; import forestry.core.inventory.FakeInventoryAdapter; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.multiblock.MultiblockValidationException; import forestry.core.multiblock.RectangularMultiblockControllerBase; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.CamouflageSelectionType; import forestry.core.network.packets.PacketCamouflageSelectServer; import forestry.core.proxy.Proxies; @@ -71,7 +69,6 @@ import forestry.greenhouse.blocks.BlockGreenhouse; import forestry.greenhouse.blocks.BlockGreenhouseType; import forestry.greenhouse.inventory.InventoryGreenhouse; import forestry.greenhouse.tiles.TileGreenhouseSprinkler; - import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; @@ -80,7 +77,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; - import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fluids.FluidRegistry; @@ -91,11 +87,12 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im private final Set activeComponents = new HashSet<>(); private final Set climatiserComponents = new HashSet<>(); private final List logics = new ArrayList<>(); + @Nullable protected ClimateControl climateControl; + @Nullable protected ButterflyHatch butterflyHatch; - + private final TankManager tankManager; - private final StandardTank resourceTank; private final EnergyManager energyManager; private final InventoryGreenhouse inventory; private final boolean needRenderUpdate = false; @@ -104,12 +101,13 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im private ItemStack camouflagePlainBlock; private ItemStack camouflageGlassBlock; private ItemStack camouflageDoorBlock; + @Nullable private ClimateRoom region; public GreenhouseController(World world) { super(world, GreenhouseMultiblockSizeLimits.instance); - this.resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilters(FluidRegistry.WATER); + StandardTank resourceTank = new FilteredTank(Constants.PROCESSOR_TANK_CAPACITY).setFilters(FluidRegistry.WATER); this.tankManager = new TankManager(this, resourceTank); this.energyManager = new EnergyManager(200, 100000); this.inventory = new InventoryGreenhouse(this); @@ -122,7 +120,6 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im /* CLIMATE */ @Override public EnumTemperature getTemperature() { - BlockPos coords = getReferenceCoord(); return EnumTemperature.getFromValue(getExactTemperature()); } @@ -133,7 +130,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override public float getExactTemperature() { - if(region == null){ + if (region == null) { return 0; } return region.getTemperature(); @@ -141,7 +138,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override public float getExactHumidity() { - if(region == null){ + if (region == null) { return 0; } return region.getHumidity(); @@ -154,8 +151,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override public BlockPos getCoordinates() { - BlockPos coord = getReferenceCoord(); - return new BlockPos(coord); + return getReferenceCoord(); } /* SAVING & LOADING */ @@ -177,7 +173,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im data.setTag("logic" + logic.getName(), nbtTag); } - if(region != null){ + if (region != null) { data.setTag("Region", region.writeToNBT(new NBTTagCompound())); } @@ -204,11 +200,11 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im logic.readFromNBT(data.getCompoundTag("logic" + logic.getName())); } - if(data.hasKey("Region")){ + if (data.hasKey("Region")) { NBTTagCompound nbtTag = data.getCompoundTag("Region"); - if(region != null){ + if (region != null) { region.readFromNBT(nbtTag); - }else{ + } else { region = new ClimateRoom(this, getWallPositions(), nbtTag); } } @@ -231,30 +227,30 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im /* GUI DATA */ @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { tankManager.writeData(data); energyManager.writeData(data); inventory.writeData(data); CamouflageUtil.writeCamouflageBlockToData(data, this, CamouflageManager.DEFAULT); CamouflageUtil.writeCamouflageBlockToData(data, this, CamouflageManager.GLASS); CamouflageUtil.writeCamouflageBlockToData(data, this, CamouflageManager.DOOR); - if(region != null){ + if (region != null) { data.writeBoolean(true); region.writeData(data); - }else{ + } else { data.writeBoolean(false); } } @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { tankManager.readData(data); energyManager.readData(data); inventory.readData(data); CamouflageUtil.readCamouflageBlockFromData(data, this); CamouflageUtil.readCamouflageBlockFromData(data, this); CamouflageUtil.readCamouflageBlockFromData(data, this); - if(data.readBoolean()){ + if (data.readBoolean()) { region.readData(data); } } @@ -269,20 +265,20 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im public boolean setCamouflageBlock(String type, ItemStack camouflageBlock, boolean sendClientUpdate) { ItemStack oldCamouflageBlock; switch (type) { - case CamouflageManager.DEFAULT: - oldCamouflageBlock = camouflagePlainBlock; - break; - case CamouflageManager.GLASS: - oldCamouflageBlock = camouflageGlassBlock; - break; - case CamouflageManager.DOOR: - oldCamouflageBlock = camouflageDoorBlock; - break; - default: - return false; + case CamouflageManager.DEFAULT: + oldCamouflageBlock = camouflagePlainBlock; + break; + case CamouflageManager.GLASS: + oldCamouflageBlock = camouflageGlassBlock; + break; + case CamouflageManager.DOOR: + oldCamouflageBlock = camouflageDoorBlock; + break; + default: + return false; } - if(!ItemStackUtil.isIdenticalItem(camouflageBlock, oldCamouflageBlock)){ + if (!ItemStackUtil.isIdenticalItem(camouflageBlock, oldCamouflageBlock)) { switch (type) { case CamouflageManager.DEFAULT: camouflagePlainBlock = camouflageBlock; @@ -296,7 +292,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im default: return false; } - if (sendClientUpdate && worldObj != null && worldObj.isRemote) { + if (sendClientUpdate && world.isRemote) { Proxies.net.sendToServer(new PacketCamouflageSelectServer(this, type, CamouflageSelectionType.MULTIBLOCK)); } MinecraftForge.EVENT_BUS.post(new CamouflageChangeEvent(this, null, this, type)); @@ -315,7 +311,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im case CamouflageManager.DOOR: return camouflageDoorBlock; default: - return null; + return ItemStack.EMPTY; } } @@ -327,9 +323,9 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im case CamouflageManager.GLASS: return new ItemStack(Blocks.STAINED_GLASS, 1, 13); case CamouflageManager.DOOR: - return null; + return ItemStack.EMPTY; default: - return null; + return ItemStack.EMPTY; } } @@ -352,6 +348,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im } } + @Nullable private IGreenhouseLogic createLogic(Class logicClass) { try { return logicClass.getConstructor(IGreenhouseController.class).newInstance(this); @@ -368,7 +365,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im } /* MANAGERS */ - @Nonnull + @Override public TankManager getTankManager() { return tankManager; @@ -379,7 +376,6 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im return energyManager; } - @Nonnull @Override public IInventoryAdapter getInternalInventory() { if (isAssembled()) { @@ -395,40 +391,34 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im super.onMachineAssembled(); createLogics(); - if(region != null){ + if (region != null) { Map internalPositions = new HashMap<>(); - List wallPositions = new ArrayList<>(); - for(IMultiblockComponent comp : connectedParts){ - if(comp != null){ - wallPositions.add(comp.getCoordinates()); - } - } - for(IInternalBlock block : internalBlocks){ - if(block != null){ + for (IInternalBlock block : internalBlocks) { + if (block != null) { internalPositions.put(block.getPos(), new ClimatePosition(region, block.getPos())); } } ForestryAPI.climateManager.removeRegion(region); region = new ClimateRoom(region, internalPositions, getWallPositions()); ForestryAPI.climateManager.addRegion(region); - }else{ + } else { Map internalPositions = new HashMap<>(); region = new ClimateRoom(this, internalPositions, getWallPositions()); - for(IInternalBlock block : internalBlocks){ - if(block != null){ + for (IInternalBlock block : internalBlocks) { + if (block != null) { internalPositions.put(block.getPos(), new ClimatePosition(region, block.getPos())); } } ForestryAPI.climateManager.addRegion(region); } - - for(IClimateSourceProvider source : climatiserComponents){ + + for (IClimateSourceProvider source : climatiserComponents) { ForestryAPI.climateManager.addSource(source); } - + for (IMultiblockComponent comp : connectedParts) { if (comp instanceof ICamouflagedTile) { - worldObj.markBlockRangeForRenderUpdate(comp.getCoordinates(), comp.getCoordinates()); + world.markBlockRangeForRenderUpdate(comp.getCoordinates(), comp.getCoordinates()); } } } @@ -439,14 +429,14 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im internalBlocks.clear(); logics.clear(); - - for(IClimateSourceProvider source : climatiserComponents){ + + for (IClimateSourceProvider source : climatiserComponents) { ForestryAPI.climateManager.removeSource(source); } - + for (IMultiblockComponent comp : connectedParts) { if (comp instanceof ICamouflagedTile) { - worldObj.markBlockRangeForRenderUpdate(comp.getCoordinates(), comp.getCoordinates()); + world.markBlockRangeForRenderUpdate(comp.getCoordinates(), comp.getCoordinates()); } } } @@ -476,9 +466,9 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override protected void onAssimilate(IMultiblockControllerInternal assimilated) { - if(assimilated != null && ((IGreenhouseControllerInternal)assimilated).getRegion() != null){ - IGreenhouseControllerInternal internal = (IGreenhouseControllerInternal) assimilated; - if(region != null){ + IGreenhouseControllerInternal internal = (IGreenhouseControllerInternal) assimilated; + if (internal.getRegion() != null) { + if (region != null) { ForestryAPI.climateManager.removeRegion(region); region = new ClimateRoom(region, internal.getRegion().getPositions(), getWallPositions()); ForestryAPI.climateManager.addRegion(region); @@ -488,7 +478,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override public void onAssimilated(IMultiblockControllerInternal assimilator) { - if(region != null){ + if (region != null) { ForestryAPI.climateManager.removeRegion(region); } } @@ -563,7 +553,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im for (int z = minimumCoord.getZ(); z <= maximumCoord.getZ(); z++) { // Okay, figure out what sort of block this should be. BlockPos pos = new BlockPos(x, y, z); - te = this.worldObj.getTileEntity(pos); + te = this.world.getTileEntity(pos); if (te instanceof IMultiblockComponent) { part = (IMultiblockComponent) te; } else { @@ -608,23 +598,23 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im } isGoodForExteriorLevel(part, exteriorLevel); } else { - isBlockGoodForExteriorLevel(exteriorLevel, this.worldObj, pos); + isBlockGoodForExteriorLevel(exteriorLevel, this.world, pos); } } else { if (part != null) { - IBlockState state = worldObj.getBlockState(part.getCoordinates()); + IBlockState state = world.getBlockState(part.getCoordinates()); if (state.getBlock() instanceof BlockGreenhouse && ((BlockGreenhouse) state.getBlock()).getGreenhouseType() == BlockGreenhouseType.SPRINKLER || !myClass.equals(part.getMultiblockLogic().getController().getClass())) { isGoodForInterior(part); } else { throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.error.invalid.part", Translator.translateToLocal(getUnlocalizedType()))); } } else { - isBlockGoodForInterior(this.worldObj, pos); + isBlockGoodForInterior(this.world, pos); } } BlockPos posUp = pos.up(2); - TileEntity tileUp = worldObj.getTileEntity(posUp); + TileEntity tileUp = world.getTileEntity(posUp); if (sides >= 1 && !(tileUp instanceof IGreenhouseComponent)) { int delta = y - minimumCoord.getY(); if (delta + 2 >= minY) { @@ -649,7 +639,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im for (IMultiblockComponent comp : connectedParts) { if (comp instanceof ButterflyHatch) { hatches.add((ButterflyHatch) comp); - }else if(comp instanceof ClimateControl){ + } else if (comp instanceof ClimateControl) { controls.add((ClimateControl) comp); } } @@ -659,10 +649,10 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im if (controls.size() > 1) { throw new MultiblockValidationException(Translator.translateToLocal("for.multiblock.greenhouse.error.climatecontrol.toomany")); } - if(hatches.iterator().hasNext()){ + if (hatches.iterator().hasNext()) { butterflyHatch = hatches.iterator().next(); } - if(controls.iterator().hasNext()){ + if (controls.iterator().hasNext()) { climateControl = controls.iterator().next(); } } @@ -670,10 +660,9 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im @Override protected void updateClient(int tickCount) { } - + /** * Check all internal blocks. - * @throws MultiblockValidationException */ private void checkInternalBlocks() throws MultiblockValidationException{ Stack blocksToCheck = new Stack<>(); @@ -685,11 +674,9 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im blocksToCheck.addAll(newBlocksToCheck); } } - /** * Returns a list of more internal blocks to check. - * @throws MultiblockValidationException */ private List checkInternalBlock(IInternalBlock blockToCheck) throws MultiblockValidationException { List newBlocksToCheck = new ArrayList<>(); @@ -697,7 +684,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im internalBlocks.add(blockToCheck); BlockPos posRoot = blockToCheck.getPos(); - isBlockGoodForInterior(worldObj, posRoot); + isBlockGoodForInterior(world, posRoot); for (IInternalBlockFace faceToCheck : blockToCheck.getFaces()) { CheckInternalBlockFaceEvent checkEvent = new CheckInternalBlockFaceEvent(this, blockToCheck, faceToCheck); MinecraftForge.EVENT_BUS.post(checkEvent); @@ -713,7 +700,7 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im throw new MultiblockValidationException(Translator.translateToLocalFormatted("for.multiblock.greenhouse.error.space.closed")); } - TileEntity tileFace = worldObj.getTileEntity(posFacing); + TileEntity tileFace = world.getTileEntity(posFacing); if (tileFace instanceof IGreenhouseComponent) { if (((IGreenhouseComponent) tileFace).getMultiblockLogic().getController() != this) { @@ -749,16 +736,17 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im public Set getInternalBlocks() { return internalBlocks; } - + @Override public IClimateControl getClimateControl() { - if(climateControl == null){ + if (climateControl == null) { return DefaultClimateControl.instance; } return climateControl.getClimateControl(); } - + @Override + @Nullable public ButterflyHatch getButterflyHatch() { return butterflyHatch; } @@ -791,22 +779,20 @@ public class GreenhouseController extends RectangularMultiblockControllerBase im public Set getListenerComponents() { return listenerComponents; } - + @Override public boolean canWork() { boolean canWork = true; for (IGreenhouseComponent.Listener listenerComponent : listenerComponents) { - if(canWork){ - canWork = listenerComponent.getGreenhouseListener().canWork(this, canWork); - } + canWork = listenerComponent.getGreenhouseListener().canWork(this, canWork); } return canWork; } - - protected List getWallPositions(){ + + protected List getWallPositions() { List wallPositions = new ArrayList<>(); - for(IMultiblockComponent comp : connectedParts){ - if(comp != null){ + for (IMultiblockComponent comp : connectedParts) { + if (comp != null) { wallPositions.add(comp.getCoordinates()); } } diff --git a/src/main/java/forestry/greenhouse/multiblock/IGreenhouseControllerInternal.java b/src/main/java/forestry/greenhouse/multiblock/IGreenhouseControllerInternal.java index 28fd6fe66..c083a114e 100644 --- a/src/main/java/forestry/greenhouse/multiblock/IGreenhouseControllerInternal.java +++ b/src/main/java/forestry/greenhouse/multiblock/IGreenhouseControllerInternal.java @@ -10,18 +10,17 @@ ******************************************************************************/ package forestry.greenhouse.multiblock; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Set; import forestry.api.greenhouse.IInternalBlock; import forestry.api.multiblock.IGreenhouseComponent; import forestry.api.multiblock.IGreenhouseController; -import forestry.core.owner.IOwnedTile; import forestry.core.fluids.ITankManager; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.IMultiblockControllerInternal; import forestry.core.network.IStreamableGui; +import forestry.core.owner.IOwnedTile; import forestry.energy.EnergyManager; public interface IGreenhouseControllerInternal extends IGreenhouseController, IMultiblockControllerInternal, IOwnedTile, IStreamableGui { @@ -29,35 +28,33 @@ public interface IGreenhouseControllerInternal extends IGreenhouseController, IM /** * @return The inventory of the controller. */ - @Nonnull IInventoryAdapter getInternalInventory(); - + /** * @return The tank manager of the controller. */ - @Nonnull ITankManager getTankManager(); - - + + /** * @return The energy manager of the controller. */ - @Nullable EnergyManager getEnergyManager(); - + /** * @return All internal blocks of the greenhouse. */ Set getInternalBlocks(); - + /** * Set the region to null. */ void clearRegion(); - + boolean canWork(); - + Set getListenerComponents(); - + + @Nullable IGreenhouseComponent.ButterflyHatch getButterflyHatch(); } diff --git a/src/main/java/forestry/greenhouse/multiblock/InternalBlock.java b/src/main/java/forestry/greenhouse/multiblock/InternalBlock.java index 0302ca1d6..7419000f7 100644 --- a/src/main/java/forestry/greenhouse/multiblock/InternalBlock.java +++ b/src/main/java/forestry/greenhouse/multiblock/InternalBlock.java @@ -10,61 +10,56 @@ ******************************************************************************/ package forestry.greenhouse.multiblock; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.math.BlockPos; import forestry.api.greenhouse.IInternalBlock; import forestry.api.greenhouse.IInternalBlockFace; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; public class InternalBlock implements IInternalBlock { - @Nonnull private final BlockPos pos; - @Nonnull private final List faces = new ArrayList<>(6); @Nullable private final IInternalBlock root; - - public InternalBlock(@Nonnull BlockPos pos) { + + public InternalBlock(BlockPos pos) { this.pos = pos; this.root = null; - + for (EnumFacing facing : EnumFacing.VALUES) { this.faces.add(new InternalBlockFace(facing, getPos().offset(facing), false)); } } - - public InternalBlock(@Nonnull BlockPos pos, EnumFacing rootFace, @Nonnull IInternalBlock root) { + + public InternalBlock(BlockPos pos, EnumFacing rootFace, IInternalBlock root) { this.pos = pos; this.root = root; - + for (EnumFacing face : EnumFacing.VALUES) { this.faces.add(new InternalBlockFace(face, getPos().offset(face), face == rootFace)); } } - - @Nonnull + @Override public BlockPos getPos() { return pos; } - - @Nonnull + @Override public Collection getFaces() { return faces; } - + @Nullable @Override public IInternalBlock getRoot() { return root; } - + @Override public boolean equals(Object obj) { if (!(obj instanceof IInternalBlock)) { diff --git a/src/main/java/forestry/greenhouse/multiblock/InternalBlockCheck.java b/src/main/java/forestry/greenhouse/multiblock/InternalBlockCheck.java index b5ff3cce3..ea47c8109 100644 --- a/src/main/java/forestry/greenhouse/multiblock/InternalBlockCheck.java +++ b/src/main/java/forestry/greenhouse/multiblock/InternalBlockCheck.java @@ -1,14 +1,12 @@ package forestry.greenhouse.multiblock; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; -import net.minecraft.util.math.BlockPos; - import forestry.api.greenhouse.IInternalBlock; import forestry.api.greenhouse.IInternalBlockFace; +import net.minecraft.util.math.BlockPos; /** * Used to check if a blockPos is in a collection of IInternalBlock @@ -20,7 +18,6 @@ public class InternalBlockCheck implements IInternalBlock { this.pos = pos; } - @Nonnull @Override public BlockPos getPos() { return pos; @@ -32,7 +29,6 @@ public class InternalBlockCheck implements IInternalBlock { return null; } - @Nonnull @Override public Collection getFaces() { return Collections.emptyList(); diff --git a/src/main/java/forestry/greenhouse/multiblock/InternalBlockFace.java b/src/main/java/forestry/greenhouse/multiblock/InternalBlockFace.java index afc00feee..32fbe358f 100644 --- a/src/main/java/forestry/greenhouse/multiblock/InternalBlockFace.java +++ b/src/main/java/forestry/greenhouse/multiblock/InternalBlockFace.java @@ -10,42 +10,38 @@ ******************************************************************************/ package forestry.greenhouse.multiblock; -import javax.annotation.Nonnull; - -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.EnumFacing; - import forestry.api.greenhouse.IInternalBlockFace; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.math.BlockPos; public class InternalBlockFace implements IInternalBlockFace { private final EnumFacing face; private final BlockPos pos; private boolean isTested; - + public InternalBlockFace(EnumFacing face, BlockPos pos, boolean isTested) { this.face = face; this.pos = pos; this.isTested = isTested; } - + @Override public boolean isTested() { return isTested; } - + @Override public void setTested(boolean tested) { this.isTested = tested; } - @Nonnull + @Override public EnumFacing getFace() { return face; } - @Nonnull @Override public BlockPos getPos() { return pos; diff --git a/src/main/java/forestry/greenhouse/multiblock/MultiblockLogicGreenhouse.java b/src/main/java/forestry/greenhouse/multiblock/MultiblockLogicGreenhouse.java index 2630094e7..34379bff1 100644 --- a/src/main/java/forestry/greenhouse/multiblock/MultiblockLogicGreenhouse.java +++ b/src/main/java/forestry/greenhouse/multiblock/MultiblockLogicGreenhouse.java @@ -23,7 +23,7 @@ public class MultiblockLogicGreenhouse extends MultiblockLogic()); continue; - }else if(greenhouseType == BlockGreenhouseType.BUTTERFLY_HATCH){ - if(!ForestryAPI.enabledPlugins.contains(ForestryPluginUids.LEPIDOPTEROLOGY)){ + } else if (greenhouseType == BlockGreenhouseType.BUTTERFLY_HATCH) { + if (!ForestryAPI.enabledPlugins.contains(ForestryPluginUids.LEPIDOPTEROLOGY)) { continue; } - }else if(greenhouseType == BlockGreenhouseType.WINDOW || greenhouseType == BlockGreenhouseType.WINDOW_UP){ + } else if (greenhouseType == BlockGreenhouseType.WINDOW || greenhouseType == BlockGreenhouseType.WINDOW_UP) { continue; } - Block greenhouseBlock = PluginGreenhouse.blocks.getGreenhouseBlock(greenhouseType); if (greenhouseBlock != null) { ModelResourceLocation blockModelLocation = new ModelResourceLocation("forestry:greenhouse." + greenhouseType); ModelResourceLocation itemModelLocation = new ModelResourceLocation("forestry:greenhouse", "inventory"); diff --git a/src/main/java/forestry/greenhouse/proxy/package-info.java b/src/main/java/forestry/greenhouse/proxy/package-info.java new file mode 100644 index 000000000..a9f0528f1 --- /dev/null +++ b/src/main/java/forestry/greenhouse/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouse.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouse.java index 88e1173d2..1c7bcfdb0 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouse.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouse.java @@ -10,20 +10,9 @@ ******************************************************************************/ package forestry.greenhouse.tiles; -import javax.annotation.Nonnull; - import java.io.IOException; import java.util.List; -import net.minecraft.block.state.IBlockState; -import forestry.core.owner.IOwnedTile; -import forestry.core.owner.IOwnerHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraftforge.common.MinecraftForge; import forestry.api.core.CamouflageManager; import forestry.api.core.ICamouflageHandler; import forestry.api.core.ICamouflagedTile; @@ -36,11 +25,12 @@ import forestry.core.config.Config; import forestry.core.gui.IHintSource; import forestry.core.inventory.IInventoryAdapter; import forestry.core.multiblock.MultiblockTileEntityForestry; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.CamouflageSelectionType; import forestry.core.network.packets.PacketCamouflageSelectServer; +import forestry.core.owner.IOwnedTile; +import forestry.core.owner.IOwnerHandler; import forestry.core.proxy.Proxies; import forestry.core.tiles.ITitled; import forestry.core.utils.ItemStackUtil; @@ -50,33 +40,39 @@ import forestry.greenhouse.blocks.BlockGreenhouseType; import forestry.greenhouse.gui.ContainerGreenhouse; import forestry.greenhouse.gui.GuiGreenhouse; import forestry.greenhouse.multiblock.MultiblockLogicGreenhouse; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.common.MinecraftForge; public abstract class TileGreenhouse extends MultiblockTileEntityForestry implements IGreenhouseComponent, IHintSource, IStreamableGui, IErrorLogicSource, IOwnedTile, ITitled, ICamouflageHandler, ICamouflagedTile { - protected ItemStack camouflageBlock; protected TileGreenhouse() { super(new MultiblockLogicGreenhouse()); - camouflageBlock = null; + camouflageBlock = ItemStack.EMPTY; } - + @Override - public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate){ - if(newSate.getBlock() instanceof BlockGreenhouseDoor && oldState.getBlock() instanceof BlockGreenhouseDoor){ - return false; - } - return super.shouldRefresh(world, pos, oldState, newSate); - } + public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate) { + if (newSate.getBlock() instanceof BlockGreenhouseDoor && oldState.getBlock() instanceof BlockGreenhouseDoor) { + return false; + } + return super.shouldRefresh(world, pos, oldState, newSate); + } @Override public void onMachineAssembled(IMultiblockController multiblockController, BlockPos minCoord, BlockPos maxCoord) { - worldObj.notifyBlockOfStateChange(getPos(), worldObj.getBlockState(pos).getBlock()); + world.notifyNeighborsOfStateChange(getPos(), world.getBlockState(pos).getBlock(), false); markDirty(); } @Override public void onMachineBroken() { - worldObj.notifyBlockOfStateChange(getPos(), worldObj.getBlockState(pos).getBlock()); + world.notifyNeighborsOfStateChange(getPos(), world.getBlockState(pos).getBlock(), false); markDirty(); } @@ -84,17 +80,16 @@ public abstract class TileGreenhouse extends MultiblockTileEntityForestry loots = new ArrayList<>(); + public NonNullList addCocoonLoot(IButterflyCocoon cocoon) { + NonNullList loots = NonNullList.create(); for (ItemStack loot : cocoon.getCaterpillar().getCocoonDrop(cocoon)) { if (!InventoryUtil.tryAddStack(this, loot, 0, InventoryGreenhouseButterflyHatch.SLOTS, true)) { loots.add(loot); } } - if (!loots.isEmpty()) { - return loots.toArray(new ItemStack[loots.size()]); - } - return null; + return loots; } - + @Override public Object getGui(EntityPlayer player, int data) { return new GuiGreenhouseButterflyHatch(player, this); } - + @Override public Object getContainer(EntityPlayer player, int data) { return new ContainerGreenhouseButterflyHatch(player.inventory, this); diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimateControl.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimateControl.java index 299b2fae8..02e486093 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimateControl.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimateControl.java @@ -4,55 +4,55 @@ import java.io.IOException; import forestry.api.climate.IClimateControl; import forestry.api.multiblock.IGreenhouseComponent; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; import net.minecraft.nbt.NBTTagCompound; public class TileGreenhouseClimateControl extends TileGreenhouse implements IGreenhouseComponent.ClimateControl { private final forestry.core.climate.ClimateControl climateControl; - + public TileGreenhouseClimateControl() { super(); climateControl = new forestry.core.climate.ClimateControl(); } - + @Override protected void decodeDescriptionPacket(NBTTagCompound packetData) { super.decodeDescriptionPacket(packetData); climateControl.readFromNBT(packetData); } - + @Override protected void encodeDescriptionPacket(NBTTagCompound packetData) { super.encodeDescriptionPacket(packetData); climateControl.writeToNBT(packetData); } - + @Override public void readFromNBT(NBTTagCompound data) { climateControl.readFromNBT(data); super.readFromNBT(data); } - + + @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { climateControl.writeToNBT(data); return super.writeToNBT(data); } - + @Override - public void writeGuiData(DataOutputStreamForestry data) throws IOException { + public void writeGuiData(PacketBufferForestry data) { climateControl.writeData(data); super.writeGuiData(data); } - + @Override - public void readGuiData(DataInputStreamForestry data) throws IOException { + public void readGuiData(PacketBufferForestry data) throws IOException { climateControl.readData(data); super.readGuiData(data); } - + @Override public IClimateControl getClimateControl() { return climateControl; diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimatiser.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimatiser.java index 6cac98f2b..68b9a5c4c 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimatiser.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseClimatiser.java @@ -10,6 +10,10 @@ ******************************************************************************/ package forestry.greenhouse.tiles; +import javax.annotation.Nullable; + +import java.util.Collections; + import forestry.api.climate.IClimateSource; import forestry.api.climate.IClimatiserDefinition; import forestry.api.multiblock.IGreenhouseComponent; @@ -27,66 +31,64 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; public class TileGreenhouseClimatiser extends TileGreenhouse implements IActivatable, IGreenhouseComponent.Climatiser { - + protected static final int WORK_CYCLES = 1; protected static final int ENERGY_PER_OPERATION = 150; - + private final IClimatiserDefinition definition; private final ClimateSource source; - + + @Nullable protected EnumFacing inwards; + @Nullable protected EnumFacing leftwards; + @Nullable protected BlockPos maxPos; + @Nullable protected BlockPos minPos; - + private boolean active; - + protected TileGreenhouseClimatiser(IClimatiserDefinition definition, int ticksForChange) { this(definition, new GreenhouseClimateSource(ticksForChange)); } - + protected TileGreenhouseClimatiser(IClimatiserDefinition definition, ClimateSource source) { this.definition = definition; this.source = source; this.source.setProvider(this); } - + protected TileGreenhouseClimatiser(IClimatiserDefinition definition) { this(definition, 20 + ENERGY_PER_OPERATION / 25); } - + @Override public void onMachineBroken() { inwards = null; leftwards = null; - + minPos = null; maxPos = null; } - + @Override public void onMachineAssembled(IMultiblockController multiblockController, BlockPos minCoord, BlockPos maxCoord) { recalculateDirections(minCoord, maxCoord); - int range = Math.round((float)definition.getRange() / 2); - - if(leftwards != null){ - maxPos = getCoordinates().offset(inwards, range).offset(leftwards, range).offset(EnumFacing.UP, range); - minPos = getCoordinates().offset(inwards).offset(leftwards.getOpposite(), range).offset(EnumFacing.DOWN, range); - - }else{ - maxPos = getCoordinates().offset(inwards, range).offset(EnumFacing.EAST, range).offset(EnumFacing.NORTH, range); - minPos = getCoordinates().offset(inwards).offset(EnumFacing.WEST, range).offset(EnumFacing.SOUTH, range); + int range = Math.round((float) definition.getRange() / 2); + + if (inwards != null) { + if (leftwards != null) { + maxPos = getCoordinates().offset(inwards, range).offset(leftwards, range).offset(EnumFacing.UP, range); + minPos = getCoordinates().offset(inwards).offset(leftwards.getOpposite(), range).offset(EnumFacing.DOWN, range); + + } else { + maxPos = getCoordinates().offset(inwards, range).offset(EnumFacing.EAST, range).offset(EnumFacing.NORTH, range); + minPos = getCoordinates().offset(inwards).offset(EnumFacing.WEST, range).offset(EnumFacing.SOUTH, range); + } } } - - public BlockPos getMinPos() { - return minPos; - } - - public BlockPos getMaxPos() { - return maxPos; - } - + /* Network */ @Override protected void encodeDescriptionPacket(NBTTagCompound packetData) { @@ -105,7 +107,7 @@ public class TileGreenhouseClimatiser extends TileGreenhouse implements IActivat public boolean isActive() { return active; } - + public void recalculateDirections(BlockPos minCoord, BlockPos maxCoord) { inwards = null; leftwards = null; @@ -138,38 +140,35 @@ public class TileGreenhouseClimatiser extends TileGreenhouse implements IActivat } else { inwards = EnumFacing.UP; } - }else{ + } else { inwards = EnumFacing.DOWN; } } - + @Override public IClimatiserDefinition getDefinition() { return definition; } - + @Override public IClimateSource getClimateSource() { return source; } - - public boolean canWork(){ + + public boolean canWork() { MultiblockLogicGreenhouse logic = getMultiblockLogic(); - if (logic == null || !logic.isConnected()) { + if (!logic.isConnected()) { return false; } EnergyManager energyManager = logic.getController().getEnergyManager(); - if (energyManager == null) { - return false; - } return EnergyHelper.consumeEnergyToDoWork(energyManager, WORK_CYCLES, ENERGY_PER_OPERATION); } - - public Iterable getPositionsInRange(){ - if(maxPos == null || minPos == null){ - return null; + + public Iterable getPositionsInRange() { + if (maxPos == null || minPos == null) { + return Collections.emptyList(); } return BlockPos.getAllInBox(maxPos, minPos); } @@ -182,11 +181,11 @@ public class TileGreenhouseClimatiser extends TileGreenhouse implements IActivat this.active = active; - if (worldObj != null) { - if (worldObj.isRemote) { - worldObj.markBlockRangeForRenderUpdate(getCoordinates(), getCoordinates()); + if (world != null) { + if (world.isRemote) { + world.markBlockRangeForRenderUpdate(getCoordinates(), getCoordinates()); } else { - Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), worldObj); + Proxies.net.sendNetworkPacket(new PacketActiveUpdate(this), getCoordinates(), world); } } } diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseDoor.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseDoor.java index d05a0ed67..24f789663 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseDoor.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseDoor.java @@ -23,10 +23,10 @@ public class TileGreenhouseDoor extends TileGreenhouse { if(!ItemStackUtil.isIdenticalItem(camouflageBlock, this.camouflageBlock)){ super.setCamouflageBlock(type, camouflageBlock, sendClientUpdate); TileGreenhouseDoor otherDoorTile = null; - if(worldObj.getTileEntity(pos.up()) instanceof TileGreenhouseDoor){ - otherDoorTile = (TileGreenhouseDoor) worldObj.getTileEntity(pos.up()); - }else if(worldObj.getTileEntity(pos.down()) instanceof TileGreenhouseDoor){ - otherDoorTile = (TileGreenhouseDoor) worldObj.getTileEntity(pos.down()); + if(world.getTileEntity(pos.up()) instanceof TileGreenhouseDoor){ + otherDoorTile = (TileGreenhouseDoor) world.getTileEntity(pos.up()); + }else if(world.getTileEntity(pos.down()) instanceof TileGreenhouseDoor){ + otherDoorTile = (TileGreenhouseDoor) world.getTileEntity(pos.down()); } if(otherDoorTile != null){ return otherDoorTile.setCamouflageBlock(type, camouflageBlock, sendClientUpdate); diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseGearbox.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseGearbox.java index 590ce8659..fc7b56c6d 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseGearbox.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseGearbox.java @@ -10,21 +10,18 @@ ******************************************************************************/ package forestry.greenhouse.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import forestry.energy.EnergyManager; -import forestry.energy.compat.rf.IEnergyHandlerDelegated; -import forestry.energy.compat.rf.IEnergyReceiverDelegated; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; -public class TileGreenhouseGearbox extends TileGreenhouse implements IEnergyReceiverDelegated, IEnergyHandlerDelegated { +public class TileGreenhouseGearbox extends TileGreenhouse { public TileGreenhouseGearbox() { } - @Override + @Nullable public EnergyManager getEnergyManager() { if (!getMultiblockLogic().isConnected()) { return null; @@ -33,7 +30,7 @@ public class TileGreenhouseGearbox extends TileGreenhouse implements IEnergyRece } @Override - public boolean hasCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { EnergyManager energyManager = getEnergyManager(); if (energyManager != null && energyManager.hasCapability(capability)) { return true; @@ -41,9 +38,9 @@ public class TileGreenhouseGearbox extends TileGreenhouse implements IEnergyRece return super.hasCapability(capability, facing); } - @Nonnull + @Override - public T getCapability(@Nonnull Capability capability, @Nullable EnumFacing facing) { + public T getCapability(Capability capability, @Nullable EnumFacing facing) { EnergyManager energyManager = getEnergyManager(); if (energyManager != null) { T energyCapability = energyManager.getCapability(capability); diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseHatch.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseHatch.java index 66484345d..a64137867 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseHatch.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseHatch.java @@ -10,7 +10,6 @@ ******************************************************************************/ package forestry.greenhouse.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.util.List; @@ -27,15 +26,13 @@ import forestry.api.multiblock.IMultiblockController; import forestry.api.multiblock.MultiblockTileEntityBase; import forestry.core.config.Config; import forestry.core.gui.IHintSource; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamableGui; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.CamouflageSelectionType; import forestry.core.network.packets.PacketCamouflageSelectServer; import forestry.core.owner.IOwnedTile; import forestry.core.owner.IOwnerHandler; import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileUtil; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.PlayerUtil; import forestry.greenhouse.blocks.BlockGreenhouse; @@ -51,29 +48,29 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.items.CapabilityItemHandler; -import net.minecraftforge.items.IItemHandler; public class TileGreenhouseHatch extends MultiblockTileEntityBase implements IGreenhouseComponent, IStreamableGui, IHintSource, IErrorLogicSource, IOwnedTile, ICamouflageHandler, ICamouflagedTile { - EnumFacing outwards; + @Nullable + private EnumFacing outwards; private ItemStack camouflageBlock; - @Nullable private GameProfile owner; public TileGreenhouseHatch() { super(new MultiblockLogicGreenhouse()); outwards = null; - camouflageBlock = null; + camouflageBlock = ItemStack.EMPTY; } + @Nullable public EnumFacing getOutwardsDir() { return outwards; } @Override public void onMachineAssembled(IMultiblockController multiblockController, BlockPos minCoord, BlockPos maxCoord) { - worldObj.notifyBlockOfStateChange(getPos(), worldObj.getBlockState(pos).getBlock()); + world.notifyNeighborsOfStateChange(getPos(), world.getBlockState(pos).getBlock(), false); markDirty(); recalculateOutwardsDirection(minCoord, maxCoord); @@ -81,7 +78,7 @@ public class TileGreenhouseHatch extends MultiblockTileEntityBase T getCapability(@Nonnull Capability capability, @Nonnull EnumFacing facing) { - if(getOutwardsTile() != null){ + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { + if (getOutwardsTile() != null) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return getOutwardsTile().getCapability(capability, facing); } @@ -277,8 +268,8 @@ public class TileGreenhouseHatch extends MultiblockTileEntityBase capability, @Nonnull EnumFacing facing) { - if(getOutwardsTile() != null){ + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { + if (getOutwardsTile() != null) { if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || capability == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY) { return getOutwardsTile().hasCapability(capability, facing); } @@ -288,8 +279,6 @@ public class TileGreenhouseHatch extends MultiblockTileEntityBase 0; } - - @Override - public boolean hasCapability(Capability capability, EnumFacing side){ - if(capability == CapabilityAnimation.ANIMATION_CAPABILITY) - { - return true; - } - return super.hasCapability(capability, side); - } - @Override - public T getCapability(Capability capability, EnumFacing side){ - if(capability == CapabilityAnimation.ANIMATION_CAPABILITY) - { - return CapabilityAnimation.ANIMATION_CAPABILITY.cast(asm); - } - return super.getCapability(capability, side); - } + @Override + public boolean hasCapability(Capability capability, @Nullable EnumFacing side) { + if (capability == CapabilityAnimation.ANIMATION_CAPABILITY) { + return true; + } + return super.hasCapability(capability, side); + } + + @Override + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing side) { + if (capability == CapabilityAnimation.ANIMATION_CAPABILITY) { + return CapabilityAnimation.ANIMATION_CAPABILITY.cast(asm); + } + return super.getCapability(capability, side); + } } diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseValve.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseValve.java index 7455f4b11..f6d27218d 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseValve.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseValve.java @@ -10,7 +10,7 @@ ******************************************************************************/ package forestry.greenhouse.tiles; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.util.EnumFacing; @@ -21,14 +21,14 @@ import forestry.core.fluids.ITankManager; import forestry.core.tiles.ILiquidTankTile; public class TileGreenhouseValve extends TileGreenhouse implements ILiquidTankTile { - @Nonnull + @Override public ITankManager getTankManager() { return getMultiblockLogic().getController().getTankManager(); } @Override - public boolean hasCapability(Capability capability, EnumFacing facing) { + public boolean hasCapability(Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { return true; } @@ -36,7 +36,8 @@ public class TileGreenhouseValve extends TileGreenhouse implements ILiquidTankTi } @Override - public T getCapability(Capability capability, EnumFacing facing) { + @Nullable + public T getCapability(Capability capability, @Nullable EnumFacing facing) { if (super.hasCapability(capability, facing)) { return super.getCapability(capability, facing); } diff --git a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseWindow.java b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseWindow.java index 57984ef82..1cbb659b3 100644 --- a/src/main/java/forestry/greenhouse/tiles/TileGreenhouseWindow.java +++ b/src/main/java/forestry/greenhouse/tiles/TileGreenhouseWindow.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.greenhouse.tiles; +import javax.annotation.Nullable; + import forestry.api.climate.EnumClimatiserModes; import forestry.api.climate.EnumClimatiserTypes; import forestry.core.climate.ClimatiserDefinition; @@ -23,7 +25,7 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; public class TileGreenhouseWindow extends TileGreenhouseClimatiser{ - + @Nullable private WindowMode mode; public TileGreenhouseWindow() { @@ -38,22 +40,23 @@ public class TileGreenhouseWindow extends TileGreenhouseClimatiser{ } public WindowMode isBlocked(){ - if(worldObj == null){ + if(world == null){ return WindowMode.BLOCK; } - IBlockState state = worldObj.getBlockState(pos); - if(state == null){ + if (!world.isBlockLoaded(pos)) { return WindowMode.BLOCK; } + IBlockState state = world.getBlockState(pos); BlockPos blockedPos; if(state.getBlock() == PluginGreenhouse.blocks.getGreenhouseBlock(BlockGreenhouseType.WINDOW_UP)){ blockedPos = getCoordinates().offset(EnumFacing.UP); }else{ blockedPos = getCoordinates().offset(state.getValue(BlockGreenhouse.FACING)); } - return worldObj.isAirBlock(blockedPos) ? WindowMode.OPEN : WindowMode.BLOCK; + return world.isAirBlock(blockedPos) ? WindowMode.OPEN : WindowMode.BLOCK; } + @Override public NBTTagCompound writeToNBT(NBTTagCompound data) { if(mode != null){ @@ -95,7 +98,8 @@ public class TileGreenhouseWindow extends TileGreenhouseClimatiser{ this.mode = mode; setActive(mode == WindowMode.OPEN); } - + + @Nullable public WindowMode getMode(){ return mode; } diff --git a/src/main/java/forestry/greenhouse/tiles/package-info.java b/src/main/java/forestry/greenhouse/tiles/package-info.java new file mode 100644 index 000000000..fe9fd54ee --- /dev/null +++ b/src/main/java/forestry/greenhouse/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.greenhouse.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/ButterflySpawner.java b/src/main/java/forestry/lepidopterology/ButterflySpawner.java index 6124ded98..186c6f431 100755 --- a/src/main/java/forestry/lepidopterology/ButterflySpawner.java +++ b/src/main/java/forestry/lepidopterology/ButterflySpawner.java @@ -12,6 +12,7 @@ package forestry.lepidopterology; import java.util.Random; +import net.minecraft.entity.EntityLiving; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; @@ -65,9 +66,8 @@ public class ButterflySpawner implements ILeafTickHandler { } private static void attemptButterflySpawn(World world, IButterfly butterfly, BlockPos pos) { - if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), pos.getX(), pos.getY() + 0.1f, pos.getZ()) != null) { - Log.trace("Spawned a butterfly '%s' at %s/%s/%s.", butterfly.getDisplayName(), pos.getX(), pos.getY(), pos.getZ()); - } + EntityLiving entityLiving = ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), pos.getX(), pos.getY() + 0.1f, pos.getZ()); + Log.trace("Spawned a butterfly '%s' at %s/%s/%s.", butterfly.getDisplayName(), pos.getX(), pos.getY(), pos.getZ()); } } diff --git a/src/main/java/forestry/lepidopterology/PluginLepidopterology.java b/src/main/java/forestry/lepidopterology/PluginLepidopterology.java index 602b385f3..efb93cbde 100644 --- a/src/main/java/forestry/lepidopterology/PluginLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/PluginLepidopterology.java @@ -10,10 +10,7 @@ ******************************************************************************/ package forestry.lepidopterology; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Collections; @@ -24,21 +21,9 @@ import java.util.Map.Entry; import java.util.Random; import java.util.Set; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkGenerator; -import net.minecraftforge.client.event.ModelBakeEvent; -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fml.common.SidedProxy; -import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; -import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.RecipeSorter; - +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import forestry.Forestry; import forestry.api.arboriculture.TreeManager; import forestry.api.genetics.AlleleManager; @@ -64,8 +49,7 @@ import forestry.lepidopterology.genetics.ButterflyFactory; import forestry.lepidopterology.genetics.ButterflyMutationFactory; import forestry.lepidopterology.genetics.ButterflyRoot; import forestry.lepidopterology.genetics.MothDefinition; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyEffect; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; import forestry.lepidopterology.items.ItemRegistryLepidopterology; import forestry.lepidopterology.proxy.ProxyLepidopterology; import forestry.lepidopterology.recipes.MatingRecipe; @@ -75,10 +59,26 @@ import forestry.lepidopterology.worldgen.CocoonDecorator; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.CraftingManager; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkGenerator; +import net.minecraftforge.client.event.ModelBakeEvent; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.common.SidedProxy; +import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; +import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; +import net.minecraftforge.oredict.OreDictionary; +import net.minecraftforge.oredict.RecipeSorter; @ForestryPlugin(pluginID = ForestryPluginUids.LEPIDOPTEROLOGY, name = "Lepidopterology", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.lepidopterology.description") public class PluginLepidopterology extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.lepidopterology.proxy.ProxyLepidopterologyClient", serverSide = "forestry.lepidopterology.proxy.ProxyLepidopterology") public static ProxyLepidopterology proxy; private static final String CONFIG_CATEGORY = "lepidopterology"; @@ -93,7 +93,9 @@ public class PluginLepidopterology extends BlankForestryPlugin { private static float serumChance = 0.55f; private static float secondSerumChance = 0; + @Nullable public static ItemRegistryLepidopterology items; + @Nullable public static BlockRegistryLepidopterology blocks; @Override @@ -115,13 +117,13 @@ public class PluginLepidopterology extends BlankForestryPlugin { public void preInit() { MinecraftForge.EVENT_BUS.register(this); ButterflyBranchDefinition.createAlleles(); - AlleleButterflyEffect.createAlleles(); - + ButterflyAlleles.registerEffectAlleles(); + GameRegistry.registerTileEntity(TileCocoon.class, "forestry.Cocoon"); proxy.preInitializeRendering(); } - @Nonnull + @Override public Set getDependencyUids() { Set dependencyUids = super.getDependencyUids(); @@ -131,25 +133,28 @@ public class PluginLepidopterology extends BlankForestryPlugin { @Override public void doInit() { + Preconditions.checkState(blocks != null); + PluginCore.rootCommand.addChildCommand(new CommandButterfly()); - EntityUtil.registerEntity(EntityButterfly.class, "butterflyGE", 0, 0x000000, 0xffffff, 50, 1, true); + ResourceLocation butterflyResourceLocation = new ResourceLocation(Constants.MOD_ID, "butterflyGE"); + EntityUtil.registerEntity(butterflyResourceLocation, EntityButterfly.class, "butterflyGE", 0, 0x000000, 0xffffff, 50, 1, true); MothDefinition.initMoths(); ButterflyDefinition.initButterflies(); - AlleleButterflyCocoon.createLoot(); - + ButterflyAlleles.createLoot(); + MinecraftForge.EVENT_BUS.post(new AlleleSpeciesRegisterEvent(ButterflyManager.butterflyRoot)); blocks.butterflyChest.init(); - if(spawnButterflysFromLeaves){ + if (spawnButterflysFromLeaves) { TreeManager.treeRoot.registerLeafTickHandler(new ButterflySpawner()); } RecipeSorter.register("forestry:lepidopterologymating", MatingRecipe.class, RecipeSorter.Category.SHAPELESS, "before:minecraft:shapeless"); } - + @Override public void postInit() { File configFile = new File(Forestry.instance.getConfigFolder(), CONFIG_CATEGORY + ".cfg"); @@ -158,7 +163,7 @@ public class PluginLepidopterology extends BlankForestryPlugin { @Override public void populateChunk(IChunkGenerator chunkGenerator, World world, Random rand, int chunkX, int chunkZ, boolean hasVillageGenerated) { - if(generateCocoons){ + if (generateCocoons) { if (generateCocoonsAmount > 0.0) { CocoonDecorator.decorateCocoons(chunkGenerator, world, rand, chunkX, chunkZ, hasVillageGenerated); } @@ -167,7 +172,7 @@ public class PluginLepidopterology extends BlankForestryPlugin { @Override public void populateChunkRetroGen(World world, Random rand, int chunkX, int chunkZ) { - if(generateCocoons){ + if (generateCocoons) { if (generateCocoonsAmount > 0.0) { CocoonDecorator.decorateCocoons(world, rand, chunkX, chunkZ); } @@ -182,23 +187,23 @@ public class PluginLepidopterology extends BlankForestryPlugin { maxDistance = config.getIntLocalized("butterfly.entities", "maxDistance", maxDistance, 0, 1600); allowPollination = config.getBooleanLocalized("butterfly.entities", "pollination", allowPollination); spawnButterflysFromLeaves = config.getBooleanLocalized("butterfly.entities", "spawn.leaves", spawnButterflysFromLeaves); - + generateCocoons = config.getBooleanLocalized("butterfly.cocoons", "generate", generateCocoons); generateCocoonsAmount = config.getFloatLocalized("butterfly.cocoons", "generate.amount", generateCocoonsAmount, 0.0f, 10.0f); - + serumChance = config.getFloatLocalized("butterfly.cocoons", "serum", serumChance, 0.0f, 100.0f); secondSerumChance = config.getFloatLocalized("butterfly.cocoons", "second.serum", secondSerumChance, 0.0f, 100.0f); - + parseRarity(config); parseCooconLoots(config); - + config.save(); } - - private static void parseRarity(LocalizedConfiguration config){ + + private static void parseRarity(LocalizedConfiguration config) { List butterflyRarity = Lists.newArrayList(); - for(IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()){ - if(allele instanceof IAlleleButterflySpecies){ + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleButterflySpecies) { IAlleleButterflySpecies species = (IAlleleButterflySpecies) allele; butterflyRarity.add(species.getUID() + ":" + species.getRarity()); } @@ -208,32 +213,32 @@ public class PluginLepidopterology extends BlankForestryPlugin { Property rarityConf = config.get("butterfly.alleles", "rarity", defaultRaritys); rarityConf.setComment(Translator.translateToLocal("for.config.butterfly.alleles.rarity")); - + String[] configRaritys = rarityConf.getStringList(); - for(String rarity : configRaritys){ - if(rarity.contains(":") && rarity.length() > 3){ + for (String rarity : configRaritys) { + if (rarity.contains(":") && rarity.length() > 3) { String[] raritys = rarity.split(":"); - try{ + try { spawnRaritys.put(raritys[0], Float.parseFloat(raritys[1])); - }catch(Exception e){ + } catch (Exception e) { Log.error("Failed to parse spawn rarity for butterfly. {}", rarity, e); } } } } - - private static void parseCooconLoots(LocalizedConfiguration config){ - for(IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()){ - if(allele instanceof IAlleleButterflyCocoon){ + + private static void parseCooconLoots(LocalizedConfiguration config) { + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleButterflyCocoon) { parseCooconLoot(config, (IAlleleButterflyCocoon) allele); } } } - - private static void parseCooconLoot(LocalizedConfiguration config, IAlleleButterflyCocoon cocoon){ + + private static void parseCooconLoot(LocalizedConfiguration config, IAlleleButterflyCocoon cocoon) { Map cooconLoot = new HashMap<>(); List lootList = new ArrayList<>(); - for(Entry entry : cocoon.getCocoonLoot().entrySet()){ + for (Entry entry : cocoon.getCocoonLoot().entrySet()) { String itemStackString = ItemStackUtil.getItemNameFromRegistryAsString(entry.getKey().getItem()); int meta = entry.getKey().getItemDamage(); @@ -244,20 +249,20 @@ public class PluginLepidopterology extends BlankForestryPlugin { } Collections.sort(lootList); String[] defaultLoot = lootList.toArray(new String[lootList.size()]); - + Property lootConf = config.get("butterfly.cocoons.alleles.loot", cocoon.getUID(), defaultLoot); lootConf.setComment(Translator.translateToLocal("for.config.butterfly.alleles.loot")); - + String[] configLoot = lootConf.getStringList(); - for(String loot : configLoot){ - if(loot.contains(";") && loot.length() > 3){ + for (String loot : configLoot) { + if (loot.contains(";") && loot.length() > 3) { String[] loots = loot.split(";"); - try{ + try { ItemStack itemStack = ItemStackUtil.parseItemStackString(loots[0], OreDictionary.WILDCARD_VALUE); - if(itemStack != null){ + if (itemStack != null) { cooconLoot.put(itemStack, Float.parseFloat(loots[1])); } - }catch(Exception e){ + } catch (Exception e) { Log.error("Failed to parse cocoon loot. {}", loot, e); } } @@ -268,6 +273,9 @@ public class PluginLepidopterology extends BlankForestryPlugin { @Override public void registerRecipes() { + Preconditions.checkState(blocks != null); + Preconditions.checkState(items != null); + CraftingManager.getInstance().getRecipeList().add(new MatingRecipe()); RecipeUtil.addRecipe(blocks.butterflyChest, @@ -281,6 +289,8 @@ public class PluginLepidopterology extends BlankForestryPlugin { @Override public void getHiddenItems(List hiddenItems) { + Preconditions.checkState(blocks != null); + // cocoon itemBlock is different from the normal item hiddenItems.add(new ItemStack(blocks.cocoon)); hiddenItems.add(new ItemStack(blocks.solidCocoon)); @@ -289,27 +299,27 @@ public class PluginLepidopterology extends BlankForestryPlugin { public static boolean isPollinationAllowed() { return allowPollination; } - + public static boolean isSpawnButterflysFromLeaves() { return spawnButterflysFromLeaves; } - + public static boolean isGenerateCocoons() { return generateCocoons; } - + public static float getGenerateCocoonsAmount() { return generateCocoonsAmount; } - + public static float getSerumChance() { return serumChance; } - + public static float getSecondSerumChance() { return secondSerumChance; } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void onModelBake(ModelBakeEvent event) { diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java b/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java index 0c01a4005..68616eb5e 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockCocoon.java @@ -10,11 +10,23 @@ ******************************************************************************/ package forestry.lepidopterology.blocks; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; import java.util.Random; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IButterfly; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.TileUtil; +import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; +import forestry.lepidopterology.items.ItemButterflyGE; +import forestry.lepidopterology.tiles.TileCocoon; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; @@ -29,23 +41,9 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IButterfly; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileUtil; -import forestry.lepidopterology.blocks.property.PropertyCocoon; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; -import forestry.lepidopterology.items.ItemButterflyGE; -import forestry.lepidopterology.tiles.TileCocoon; - public class BlockCocoon extends Block implements ITileEntityProvider, IStateMapperRegister, IItemModelRegister { public static final AxisAlignedBB BOUNDING_BOX = new AxisAlignedBB(0.3125F, 0.3125F, 0.3125F, 0.6875F, 1F, 0.6875F); private static final PropertyCocoon COCOON = AlleleButterflyCocoon.COCOON; @@ -55,25 +53,24 @@ public class BlockCocoon extends Block implements ITileEntityProvider, IStateMap setTickRandomly(true); setSoundType(SoundType.GROUND); setCreativeTab(null); - setDefaultState(this.blockState.getBaseState().withProperty(COCOON, AlleleButterflyCocoon.cocoonDefault).withProperty(AlleleButterflyCocoon.AGE, 0)); + setDefaultState(this.blockState.getBaseState().withProperty(COCOON, ButterflyAlleles.cocoonDefault).withProperty(AlleleButterflyCocoon.AGE, 0)); } - - @Nonnull + @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, COCOON, AlleleButterflyCocoon.AGE); } - + @SideOnly(Side.CLIENT) @Override - public IBlockState getActualState(@Nonnull IBlockState state, IBlockAccess world, BlockPos pos) { + public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { TileCocoon cocoon = TileUtil.getTile(world, pos, TileCocoon.class); - if(cocoon != null){ + if (cocoon != null) { state = state.withProperty(COCOON, cocoon.getCaterpillar().getGenome().getCocoon()).withProperty(AlleleButterflyCocoon.AGE, cocoon.getAge()); } return super.getActualState(state, world, pos); } - + @SideOnly(Side.CLIENT) @Override public void registerStateMapper() { @@ -96,7 +93,7 @@ public class BlockCocoon extends Block implements ITileEntityProvider, IStateMap public boolean isOpaqueCube(IBlockState state) { return false; } - + @Override public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) { TileCocoon tileCocoon = TileUtil.getTile(world, pos, TileCocoon.class); @@ -119,61 +116,60 @@ public class BlockCocoon extends Block implements ITileEntityProvider, IStateMap return new TileCocoon(false); } - @Override - public int getMetaFromState(IBlockState state){ - return 0; - } + @Override + public int getMetaFromState(IBlockState state) { + return 0; + } @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { + @Deprecated + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { if (worldIn.isAirBlock(pos.up())) { worldIn.setBlockToAir(pos); } - } - - @Override - public List getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { - return Collections.emptyList(); - } + } + + @Override + public List getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { + return Collections.emptyList(); + } @Override public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { TileCocoon tile = TileUtil.getTile(world, pos, TileCocoon.class); if (tile == null) { - return null; + return ItemStack.EMPTY; } IButterfly caterpillar = tile.getCaterpillar(); int age = tile.getAge(); ItemStack stack = ButterflyManager.butterflyRoot.getMemberStack(caterpillar, EnumFlutterType.COCOON); - if (stack == null) { - return null; + if (!stack.isEmpty() && stack.getTagCompound() != null) { + stack.getTagCompound().setInteger(ItemButterflyGE.NBT_AGE, age); } - - stack.getTagCompound().setInteger(ItemButterflyGE.NBT_AGE, age); - return stack; } - + @Override - public boolean isFullCube(IBlockState state){ - return false; - } + public boolean isFullCube(IBlockState state) { + return false; + } @Override public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) { return BOUNDING_BOX.offset(pos); } + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return BOUNDING_BOX; } - + @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return BOUNDING_BOX; } - + } diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java b/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java index 4493fc023..ad63f4423 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockRegistryLepidopterology.java @@ -12,7 +12,7 @@ package forestry.lepidopterology.blocks; import forestry.core.blocks.BlockRegistry; import forestry.core.items.ItemBlockForestry; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; public class BlockRegistryLepidopterology extends BlockRegistry { public final BlockLepidopterology butterflyChest; @@ -23,7 +23,7 @@ public class BlockRegistryLepidopterology extends BlockRegistry { butterflyChest = new BlockLepidopterology(BlockTypeLepidopterologyTesr.LEPICHEST); registerBlock(butterflyChest, new ItemBlockForestry(butterflyChest), "butterfly_chest"); - AlleleButterflyCocoon.createAlleles(); + ButterflyAlleles.registerCocoonAlleles(); cocoon = new BlockCocoon(); registerBlock(cocoon, new ItemBlockForestry(cocoon), "cocoon"); diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockSolidCocoon.java b/src/main/java/forestry/lepidopterology/blocks/BlockSolidCocoon.java index 44a3762db..a22842ee9 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockSolidCocoon.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockSolidCocoon.java @@ -10,9 +10,19 @@ ******************************************************************************/ package forestry.lepidopterology.blocks; +import javax.annotation.Nullable; import java.util.Collections; import java.util.List; +import forestry.api.core.IItemModelRegister; +import forestry.api.core.IModelManager; +import forestry.api.core.IStateMapperRegister; +import forestry.core.proxy.Proxies; +import forestry.core.tiles.TileUtil; +import forestry.core.utils.ItemStackUtil; +import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; +import forestry.lepidopterology.tiles.TileCocoon; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; @@ -22,27 +32,17 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; - import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.core.IItemModelRegister; -import forestry.api.core.IModelManager; -import forestry.api.core.IStateMapperRegister; -import forestry.core.proxy.Proxies; -import forestry.core.tiles.TileUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.lepidopterology.blocks.property.PropertyCocoon; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; -import forestry.lepidopterology.tiles.TileCocoon; - public class BlockSolidCocoon extends Block implements ITileEntityProvider, IStateMapperRegister, IItemModelRegister { private static final PropertyCocoon COCOON = AlleleButterflyCocoon.COCOON; - + public BlockSolidCocoon() { super(new MaterialCocoon()); setHarvestLevel("scoop", 0); @@ -50,24 +50,24 @@ public class BlockSolidCocoon extends Block implements ITileEntityProvider, ISta setTickRandomly(true); setSoundType(SoundType.GROUND); setCreativeTab(null); - setDefaultState(this.blockState.getBaseState().withProperty(COCOON, AlleleButterflyCocoon.cocoonDefault).withProperty(AlleleButterflyCocoon.AGE, 0)); + setDefaultState(this.blockState.getBaseState().withProperty(COCOON, ButterflyAlleles.cocoonDefault).withProperty(AlleleButterflyCocoon.AGE, 0)); } - + @Override protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, COCOON, AlleleButterflyCocoon.AGE); } - + @SideOnly(Side.CLIENT) @Override public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) { TileCocoon cocoon = TileUtil.getTile(world, pos, TileCocoon.class); - if(cocoon != null){ + if (cocoon != null) { state = state.withProperty(COCOON, cocoon.getCaterpillar().getGenome().getCocoon()).withProperty(AlleleButterflyCocoon.AGE, cocoon.getAge()); } return super.getActualState(state, world, pos); } - + @SideOnly(Side.CLIENT) @Override public void registerStateMapper() { @@ -98,12 +98,10 @@ public class BlockSolidCocoon extends Block implements ITileEntityProvider, ISta if (tile instanceof TileCocoon) { TileCocoon cocoon = (TileCocoon) tile; - ItemStack[] drops = cocoon.getCocoonDrops(); - if (drops != null) { - for (ItemStack stack : drops) { - if (stack != null) { - ItemStackUtil.dropItemStackAsEntity(stack, world, pos); - } + NonNullList drops = cocoon.getCocoonDrops(); + for (ItemStack stack : drops) { + if (stack != null) { + ItemStackUtil.dropItemStackAsEntity(stack, world, pos); } } } @@ -117,31 +115,33 @@ public class BlockSolidCocoon extends Block implements ITileEntityProvider, ISta return new TileCocoon(true); } - @Override - public int getMetaFromState(IBlockState state){ - return 0; - } + @Override + public int getMetaFromState(IBlockState state) { + return 0; + } @Override - public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) { + @Deprecated + public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos) { if (worldIn.isAirBlock(pos.up())) { worldIn.setBlockToAir(pos); - } - } - - @Override - public List getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { - return Collections.emptyList(); - } + } + } + + @Override + public List getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { + return Collections.emptyList(); + } @Override public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) { return BlockCocoon.BOUNDING_BOX; } + @Nullable @Override - public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { + public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos) { return BlockCocoon.BOUNDING_BOX; } - + } diff --git a/src/main/java/forestry/lepidopterology/blocks/BlockTypeLepidopterologyTesr.java b/src/main/java/forestry/lepidopterology/blocks/BlockTypeLepidopterologyTesr.java index ac30b4751..8f0bad15d 100644 --- a/src/main/java/forestry/lepidopterology/blocks/BlockTypeLepidopterologyTesr.java +++ b/src/main/java/forestry/lepidopterology/blocks/BlockTypeLepidopterologyTesr.java @@ -10,12 +10,8 @@ ******************************************************************************/ package forestry.lepidopterology.blocks; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; -import net.minecraft.util.math.AxisAlignedBB; - import forestry.core.blocks.IBlockTypeTesr; import forestry.core.blocks.IMachinePropertiesTesr; import forestry.core.blocks.MachinePropertiesTesr; @@ -24,16 +20,17 @@ import forestry.core.proxy.Proxies; import forestry.core.tiles.TileForestry; import forestry.core.tiles.TileNaturalistChest; import forestry.lepidopterology.tiles.TileLepidopteristChest; +import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; +import net.minecraft.util.math.AxisAlignedBB; public enum BlockTypeLepidopterologyTesr implements IBlockTypeTesr { LEPICHEST(TileLepidopteristChest.class, "lepi_chest", Proxies.render.getRenderChest("lepichest"), TileNaturalistChest.chestBoundingBox); public static final BlockTypeLepidopterologyTesr[] VALUES = values(); - @Nonnull private final IMachinePropertiesTesr machineProperties; - BlockTypeLepidopterologyTesr(@Nonnull Class teClass, @Nonnull String name, @Nullable TileEntitySpecialRenderer renderer, @Nullable AxisAlignedBB boundingBox) { + BlockTypeLepidopterologyTesr(Class teClass, String name, @Nullable TileEntitySpecialRenderer renderer, @Nullable AxisAlignedBB boundingBox) { if (boundingBox != null) { this.machineProperties = new MachinePropertiesTesr<>(teClass, name, renderer, boundingBox, Constants.MOD_ID + ":blocks/" + name + ".0"); } else { @@ -41,7 +38,6 @@ public enum BlockTypeLepidopterologyTesr implements IBlockTypeTesr { } } - @Nonnull @Override public IMachinePropertiesTesr getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/lepidopterology/blocks/CocoonStateMapper.java b/src/main/java/forestry/lepidopterology/blocks/CocoonStateMapper.java index e66bc46f1..f7518de39 100644 --- a/src/main/java/forestry/lepidopterology/blocks/CocoonStateMapper.java +++ b/src/main/java/forestry/lepidopterology/blocks/CocoonStateMapper.java @@ -2,19 +2,17 @@ package forestry.lepidopterology.blocks; import java.util.Map; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.lepidopterology.IAlleleButterflyCocoon; import forestry.core.config.Constants; import forestry.core.render.ForestryStateMapper; import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class CocoonStateMapper extends ForestryStateMapper { @@ -22,9 +20,9 @@ public class CocoonStateMapper extends ForestryStateMapper { @Override public Map putStateModelLocations(Block block) { if (block instanceof BlockCocoon || block instanceof BlockSolidCocoon) { - for(IAllele allele :AlleleManager.alleleRegistry.getRegisteredAlleles().values()){ - if(allele instanceof IAlleleButterflyCocoon){ - for(int age = 0;age < 3;age++){ + for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { + if (allele instanceof IAlleleButterflyCocoon) { + for (int age = 0; age < 3; age++) { IAlleleButterflyCocoon cocoon = (IAlleleButterflyCocoon) allele; String resourcePath = Constants.MOD_ID + ":cocoons/cocoon_" + cocoon.getCocoonName(); IBlockState state = block.getDefaultState().withProperty(AlleleButterflyCocoon.COCOON, cocoon).withProperty(AlleleButterflyCocoon.AGE, age); @@ -36,5 +34,5 @@ public class CocoonStateMapper extends ForestryStateMapper { } return mapStateModelLocations; } - + } diff --git a/src/main/java/forestry/lepidopterology/blocks/property/PropertyCocoon.java b/src/main/java/forestry/lepidopterology/blocks/PropertyCocoon.java similarity index 94% rename from src/main/java/forestry/lepidopterology/blocks/property/PropertyCocoon.java rename to src/main/java/forestry/lepidopterology/blocks/PropertyCocoon.java index 49cb35845..3b3e40f5d 100644 --- a/src/main/java/forestry/lepidopterology/blocks/property/PropertyCocoon.java +++ b/src/main/java/forestry/lepidopterology/blocks/PropertyCocoon.java @@ -8,18 +8,17 @@ * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ -package forestry.lepidopterology.blocks.property; - -import com.google.common.base.Objects; +package forestry.lepidopterology.blocks; import java.util.ArrayList; import java.util.List; +import com.google.common.base.Objects; import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; import forestry.api.lepidopterology.IAlleleButterflyCocoon; -import forestry.core.blocks.propertys.PropertyAllele; +import forestry.core.blocks.properties.PropertyAllele; public class PropertyCocoon extends PropertyAllele { @@ -57,5 +56,5 @@ public class PropertyCocoon extends PropertyAllele { public String getName(IAlleleButterflyCocoon value) { return value.getCocoonName(); } - + } diff --git a/src/main/java/forestry/lepidopterology/blocks/package-info.java b/src/main/java/forestry/lepidopterology/blocks/package-info.java new file mode 100644 index 000000000..ea276259d --- /dev/null +++ b/src/main/java/forestry/lepidopterology/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/commands/package-info.java b/src/main/java/forestry/lepidopterology/commands/package-info.java new file mode 100644 index 000000000..a7ae25507 --- /dev/null +++ b/src/main/java/forestry/lepidopterology/commands/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.commands; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java index 026346481..f88d16643 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyBase.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import javax.annotation.Nullable; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.ai.EntityAIBase; @@ -25,25 +27,22 @@ public abstract class AIButterflyBase extends EntityAIBase { this.entity = entity; } + @Nullable protected Vec3d getRandomDestination() { if (entity.isInWater()) { return getRandomDestinationUpwards(); } - Vec3d randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom(entity, 16, 7, - new Vec3d(entity.posX, entity.posY, entity.posZ)); + Vec3d entityPos = new Vec3d(entity.posX, entity.posY, entity.posZ); + Vec3d randomTarget = RandomPositionGenerator.findRandomTargetBlockAwayFrom(entity, 16, 7, entityPos); - if (randomTarget == null) { - return null; - } - - if (validateDestination(randomTarget, false)) { + if (randomTarget != null && validateDestination(randomTarget, false)) { return randomTarget; - } else { - return null; } + return null; } + @Nullable protected Vec3d getRandomDestinationUpwards() { Vec3d destination = new Vec3d(entity.posX, entity.posY + entity.getRNG().nextInt(10) + 2, entity.posZ); if (validateDestination(destination, true)) { @@ -58,18 +57,18 @@ public abstract class AIButterflyBase extends EntityAIBase { return false; } BlockPos pos = new BlockPos(dest); - if (!entity.worldObj.isBlockLoaded(pos)) { + if (!entity.world.isBlockLoaded(pos)) { return false; } - IBlockState blockState = entity.worldObj.getBlockState(pos); + IBlockState blockState = entity.world.getBlockState(pos); Block block = blockState.getBlock(); if (!allowFluids && block.getMaterial(blockState).isLiquid()) { return false; } - if (!block.isPassable(entity.worldObj, pos)) { + if (!block.isPassable(entity.world, pos)) { return false; } - return entity.getButterfly().isAcceptedEnvironment(entity.worldObj, dest.xCoord, dest.yCoord, dest.zCoord); + return entity.getButterfly().isAcceptedEnvironment(entity.world, dest.xCoord, dest.yCoord, dest.zCoord); } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java index afca7746a..e754b2261 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyFlee.java @@ -22,7 +22,7 @@ public class AIButterflyFlee extends AIButterflyMovement { @Override public boolean shouldExecute() { - EntityPlayer player = entity.worldObj.getClosestPlayerToEntity(entity, entity.getButterfly().getGenome().getPrimary().getFlightDistance()); + EntityPlayer player = entity.world.getClosestPlayerToEntity(entity, entity.getButterfly().getGenome().getPrimary().getFlightDistance()); if (player == null || player.isSneaking()) { return false; diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyGoHome.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyGoHome.java index e25fc1e79..f5774e75c 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyGoHome.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyGoHome.java @@ -1,6 +1,5 @@ package forestry.lepidopterology.entities; -import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; public class AIButterflyGoHome extends AIButterflyMovement { @@ -17,7 +16,7 @@ public class AIButterflyGoHome extends AIButterflyMovement { } flightTarget = new Vec3d(entity.getHomePosition()); - if (flightTarget == null || flightTarget.equals(BlockPos.ORIGIN)) { + if (flightTarget.equals(Vec3d.ZERO)) { if (entity.getState().doesMovement) { entity.setState(EnumButterflyState.HOVER); } @@ -28,5 +27,5 @@ public class AIButterflyGoHome extends AIButterflyMovement { entity.setState(EnumButterflyState.FLYING); return true; } - + } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java index 43747e251..b92438002 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyInteract.java @@ -10,10 +10,12 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import javax.annotation.Nullable; + import net.minecraft.util.math.BlockPos; public abstract class AIButterflyInteract extends AIButterflyBase { - + @Nullable protected BlockPos rest; private boolean canInteract = false; @@ -31,7 +33,7 @@ public abstract class AIButterflyInteract extends AIButterflyBase { } rest = new BlockPos((int) entity.posX, (int) Math.floor(entity.posY) - 1, (int) entity.posZ); - if (entity.worldObj.isAirBlock(rest)) { + if (entity.world.isAirBlock(rest)) { return false; } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java index a74ca9b97..dd5977e06 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyMate.java @@ -10,25 +10,25 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import javax.annotation.Nullable; import java.util.List; + import forestry.api.genetics.IPollinatable; import forestry.api.lepidopterology.IButterflyNursery; import forestry.core.utils.GeneticsUtil; import forestry.lepidopterology.PluginLepidopterology; public class AIButterflyMate extends AIButterflyInteract { + @Nullable + private EntityButterfly targetMate; - private EntityButterfly targetMate; - private double moveSpeed; - - public AIButterflyMate(EntityButterfly entity) { super(entity); } @Override protected boolean canInteract() { - if(entity.getButterfly().getMate() == null && entity.canMate()){ + if (entity.getButterfly().getMate() == null && entity.canMate()) { return true; } if (entity.cooldownEgg > 0) { @@ -39,28 +39,28 @@ public class AIButterflyMate extends AIButterflyInteract { return false; } - if (entity.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { + if (entity.world.countEntities(EntityButterfly.class) > PluginLepidopterology.spawnConstraint) { return false; } - return GeneticsUtil.canNurse(entity.getButterfly(), entity.worldObj, rest); + return rest != null && GeneticsUtil.canNurse(entity.getButterfly(), entity.world, rest); } @Override public void updateTask() { if (continueExecuting()) { - if(entity.getButterfly().getMate() == null){ - if (entity.cooldownMate <= 0 && entity.getDistanceSqToEntity(targetMate) < 9.0D){ - entity.getButterfly().mate(targetMate.getButterfly()); - targetMate.getButterfly().mate(entity.getButterfly()); - entity.cooldownMate = EntityButterfly.COOLDOWNS; - } - }else{ - IPollinatable tile = GeneticsUtil.getOrCreatePollinatable(null, entity.worldObj, rest); + if (entity.getButterfly().getMate() == null && targetMate != null) { + if (entity.cooldownMate <= 0 && entity.getDistanceSqToEntity(targetMate) < 9.0D) { + entity.getButterfly().mate(targetMate.getButterfly()); + targetMate.getButterfly().mate(entity.getButterfly()); + entity.cooldownMate = EntityButterfly.COOLDOWNS; + } + } else if (rest != null) { + IPollinatable tile = GeneticsUtil.getOrCreatePollinatable(null, entity.world, rest); if (tile instanceof IButterflyNursery) { IButterflyNursery nursery = (IButterflyNursery) tile; if (nursery.canNurse(entity.getButterfly())) { - nursery.setCaterpillar(entity.getButterfly().spawnCaterpillar(entity.worldObj, nursery)); + nursery.setCaterpillar(entity.getButterfly().spawnCaterpillar(entity.world, nursery)); //Log.finest("A butterfly '%s' laid an egg at %s/%s/%s.", entity.getButterfly().getIdent(), rest.posX, rest.posY, rest.posZ); if (entity.getRNG().nextFloat() < 1.0f / entity.getButterfly().getGenome().getFertility()) { entity.setHealth(0); @@ -72,54 +72,55 @@ public class AIButterflyMate extends AIButterflyInteract { } } } - - @Override - public boolean shouldExecute(){ - if(!super.shouldExecute()){ - return false; - } - if(entity.getButterfly().getMate() == null){ - if (!entity.canMate()){ - return false; - }else{ - targetMate = getNearbyMate(); - return targetMate != null; - } - } - return true; - } - @Override - public boolean continueExecuting(){ - if(!super.continueExecuting()){ - return false; - } - if(entity.getButterfly().getMate() == null){ - return targetMate.isEntityAlive() && targetMate.canMate(); - } - return true; - } + @Override + public boolean shouldExecute() { + if (!super.shouldExecute()) { + return false; + } + if (entity.getButterfly().getMate() == null) { + if (!entity.canMate()) { + return false; + } else { + targetMate = getNearbyMate(); + return targetMate != null; + } + } + return true; + } - @Override - public void resetTask(){ - super.resetTask(); - - targetMate = null; - } + @Override + public boolean continueExecuting() { + if (!super.continueExecuting()) { + return false; + } + if (entity.getButterfly().getMate() == null) { + return targetMate != null && targetMate.isEntityAlive() && targetMate.canMate(); + } + return true; + } - private EntityButterfly getNearbyMate(){ - float f = 8.0F; - List nextButterflys = entity.worldObj.getEntitiesWithinAABB(EntityButterfly.class, this.entity.getEntityBoundingBox().expand(f, f, f)); - double d0 = Double.MAX_VALUE; - EntityButterfly nextButterfly = null; + @Override + public void resetTask() { + super.resetTask(); - for (EntityButterfly butterfly : nextButterflys){ - if (this.entity.canMateWith(butterfly) && this.entity.getDistanceSqToEntity(butterfly) < d0){ - nextButterfly = butterfly; - d0 = this.entity.getDistanceSqToEntity(butterfly); - } - } + targetMate = null; + } - return nextButterfly; - } + @Nullable + private EntityButterfly getNearbyMate() { + float f = 8.0F; + List nextButterflys = entity.world.getEntitiesWithinAABB(EntityButterfly.class, this.entity.getEntityBoundingBox().expand(f, f, f)); + double d0 = Double.MAX_VALUE; + EntityButterfly nextButterfly = null; + + for (EntityButterfly butterfly : nextButterflys) { + if (this.entity.canMateWith(butterfly) && this.entity.getDistanceSqToEntity(butterfly) < d0) { + nextButterfly = butterfly; + d0 = this.entity.getDistanceSqToEntity(butterfly); + } + } + + return nextButterfly; + } } diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java index 86ea2c1cc..97d759ea7 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyMovement.java @@ -10,13 +10,15 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import javax.annotation.Nullable; + import net.minecraft.util.math.Vec3d; /** * @author CovertJaguar */ public abstract class AIButterflyMovement extends AIButterflyBase { - + @Nullable protected Vec3d flightTarget; protected AIButterflyMovement(EntityButterfly entity) { @@ -52,7 +54,7 @@ public abstract class AIButterflyMovement extends AIButterflyBase { flightTarget = getRandomDestinationUpwards(); } else if (entity.isCollided) { flightTarget = entity.getRNG().nextBoolean() ? getRandomDestination() : null; - } else if (entity.worldObj.rand.nextInt(300) == 0) { + } else if (entity.world.rand.nextInt(300) == 0) { flightTarget = getRandomDestination(); } entity.setDestination(flightTarget); diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java index d5a309a62..bb5f9f098 100644 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyPollinate.java @@ -30,12 +30,16 @@ public class AIButterflyPollinate extends AIButterflyInteract { return false; } - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.worldObj, rest); + if (rest == null) { + return false; + } + + ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.world, rest); if (checkPollinatable == null) { return false; } - if (!entity.getButterfly().getGenome().getFlowerProvider().isAcceptedPollinatable(entity.worldObj, checkPollinatable)) { + if (!entity.getButterfly().getGenome().getFlowerProvider().isAcceptedPollinatable(entity.world, checkPollinatable)) { return false; } @@ -44,14 +48,14 @@ public class AIButterflyPollinate extends AIButterflyInteract { @Override public void updateTask() { - if (continueExecuting()) { - ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.worldObj, rest); + if (continueExecuting() && rest != null) { + ICheckPollinatable checkPollinatable = GeneticsUtil.getCheckPollinatable(entity.world, rest); if (checkPollinatable != null) { if (entity.getPollen() == null) { entity.setPollen(checkPollinatable.getPollen()); // Log.finest("A butterfly '%s' grabbed a pollen '%s' at %s/%s/%s.", entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, rest.posZ); } else if (checkPollinatable.canMateWith(entity.getPollen())) { - IPollinatable realPollinatable = GeneticsUtil.getOrCreatePollinatable(null, entity.worldObj, rest); + IPollinatable realPollinatable = GeneticsUtil.getOrCreatePollinatable(null, entity.world, rest); if (realPollinatable != null) { realPollinatable.mateWith(entity.getPollen()); // Log.finest("A butterfly '%s' unloaded pollen '%s' at %s/%s/%s.", entity.getButterfly().getIdent(), entity.getPollen().getIdent(), rest.posX, rest.posY, rest.posZ); diff --git a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java index 042571eef..98c0bef96 100755 --- a/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java +++ b/src/main/java/forestry/lepidopterology/entities/AIButterflyRest.java @@ -46,14 +46,14 @@ public class AIButterflyRest extends AIButterflyBase { } pos = pos.add(x, -1, z); - if (entity.worldObj.isAirBlock(pos)) { + if (entity.world.isAirBlock(pos)) { return false; } - IBlockState blockState = entity.worldObj.getBlockState(pos); + IBlockState blockState = entity.world.getBlockState(pos); if (blockState.getBlock().getMaterial(blockState).isLiquid()) { return false; } - if (!entity.getButterfly().isAcceptedEnvironment(entity.worldObj, x, pos.getY(), z)) { + if (!entity.getButterfly().isAcceptedEnvironment(entity.world, x, pos.getY(), z)) { return false; } @@ -84,21 +84,21 @@ public class AIButterflyRest extends AIButterflyBase { } private boolean canLand(BlockPos pos) { - if (!entity.worldObj.isBlockLoaded(pos)) { + if (!entity.world.isBlockLoaded(pos)) { return false; } - IBlockState blockState = entity.worldObj.getBlockState(pos); + IBlockState blockState = entity.world.getBlockState(pos); Block block = blockState.getBlock(); - if (!block.isPassable(entity.worldObj, pos)) { + if (!block.isPassable(entity.world, pos)) { return false; } if (isPlant(blockState)) { return true; } - IBlockState blockStateBelow = entity.worldObj.getBlockState(pos.down()); + IBlockState blockStateBelow = entity.world.getBlockState(pos.down()); Block blockBelow = blockStateBelow.getBlock(); - return isRest(blockBelow) || blockBelow.isLeaves(blockStateBelow, entity.worldObj, pos.down()); + return isRest(blockBelow) || blockBelow.isLeaves(blockStateBelow, entity.world, pos.down()); } private static boolean isRest(Block block) { diff --git a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java index 5902e64de..35fe7b90e 100755 --- a/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java +++ b/src/main/java/forestry/lepidopterology/entities/EntityButterfly.java @@ -10,6 +10,26 @@ ******************************************************************************/ package forestry.lepidopterology.entities; +import javax.annotation.Nullable; + +import forestry.api.arboriculture.EnumGermlingType; +import forestry.api.arboriculture.TreeManager; +import forestry.api.core.IToolScoop; +import forestry.api.genetics.AlleleManager; +import forestry.api.genetics.IAllele; +import forestry.api.genetics.IIndividual; +import forestry.api.genetics.ISpeciesRoot; +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.EnumFlutterType; +import forestry.api.lepidopterology.IAlleleButterflySpecies; +import forestry.api.lepidopterology.IButterfly; +import forestry.api.lepidopterology.IButterflyGenome; +import forestry.api.lepidopterology.IButterflyRoot; +import forestry.api.lepidopterology.IEntityButterfly; +import forestry.api.lepidopterology.ILepidopteristTracker; +import forestry.core.utils.ItemStackUtil; +import forestry.lepidopterology.PluginLepidopterology; +import forestry.lepidopterology.genetics.Butterfly; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFlower; @@ -37,30 +57,10 @@ import net.minecraft.util.math.Vec3d; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; - import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.arboriculture.EnumGermlingType; -import forestry.api.arboriculture.TreeManager; -import forestry.api.core.IToolScoop; -import forestry.api.genetics.AlleleManager; -import forestry.api.genetics.IAllele; -import forestry.api.genetics.IIndividual; -import forestry.api.genetics.ISpeciesRoot; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.EnumFlutterType; -import forestry.api.lepidopterology.IAlleleButterflySpecies; -import forestry.api.lepidopterology.IButterfly; -import forestry.api.lepidopterology.IButterflyGenome; -import forestry.api.lepidopterology.IButterflyRoot; -import forestry.api.lepidopterology.IEntityButterfly; -import forestry.api.lepidopterology.ILepidopteristTracker; -import forestry.core.utils.ItemStackUtil; -import forestry.lepidopterology.PluginLepidopterology; -import forestry.lepidopterology.genetics.Butterfly; - public class EntityButterfly extends EntityCreature implements IEntityButterfly { /* CONSTANTS */ @@ -77,9 +77,11 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly public static final int EXHAUSTION_CONSUMPTION = 100 * EXHAUSTION_REST; public static final int MAX_LIFESPAN = 24000 * 7; // one minecraft week in ticks + @Nullable private Vec3d flightTarget; private int exhaustion; - private IButterfly contained; + private IButterfly contained = ButterflyManager.butterflyRoot.templateAsIndividual(ButterflyManager.butterflyRoot.getDefaultTemplate()); + @Nullable private IIndividual pollen; public int cooldownPollination = 0; @@ -87,9 +89,12 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly public int cooldownMate = 0; // Client Rendering + @Nullable private IAlleleButterflySpecies species; private float size = DEFAULT_BUTTERFLY_SIZE; private EnumButterflyState state = DEFAULT_STATE; + @SideOnly(Side.CLIENT) + private ResourceLocation textureResource; /* CONSTRUCTOR */ public EntityButterfly(World world) { @@ -133,11 +138,9 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); - if (contained != null) { - NBTTagCompound bio = new NBTTagCompound(); - contained.writeToNBT(bio); - nbttagcompound.setTag("BTFLY", bio); - } + NBTTagCompound bio = new NBTTagCompound(); + contained.writeToNBT(bio); + nbttagcompound.setTag("BTFLY", bio); if (pollen != null) { NBTTagCompound pln = new NBTTagCompound(); @@ -147,7 +150,7 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly nbttagcompound.setByte("STATE", (byte) getState().ordinal()); nbttagcompound.setInteger("EXH", exhaustion); - + nbttagcompound.setInteger("homeX", getHomePosition().getX()); nbttagcompound.setInteger("homeY", getHomePosition().getY()); nbttagcompound.setInteger("homeZ", getHomePosition().getZ()); @@ -175,14 +178,15 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly } public float getWingFlap(float partialTicktime) { - return getState().getWingFlap(this, species.getUID().hashCode(), partialTicktime); + int offset = species != null ? species.getUID().hashCode() : world.rand.nextInt(); + return getState().getWingFlap(this, offset, partialTicktime); } /* STATE - Used for AI and rendering */ public void setState(EnumButterflyState state) { if (this.state != state) { this.state = state; - if (!worldObj.isRemote) { + if (!world.isRemote) { dataManager.set(DATAWATCHER_ID_STATE, (byte) state.ordinal()); } } @@ -201,27 +205,28 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly } /* DESTINATION */ + @Nullable public Vec3d getDestination() { return flightTarget; } - public void setDestination(Vec3d destination) { + public void setDestination(@Nullable Vec3d destination) { flightTarget = destination; } @Override public float getBlockPathWeight(BlockPos pos) { - if (!worldObj.isBlockLoaded(pos)) { + if (!world.isBlockLoaded(pos)) { return -100f; } float weight = 0.0f; - if (!getButterfly().isAcceptedEnvironment(worldObj, pos.getX(), pos.getY(), pos.getZ())) { + if (!getButterfly().isAcceptedEnvironment(world, pos.getX(), pos.getY(), pos.getZ())) { weight -= 15.0f; } - if (!worldObj.getEntitiesWithinAABB(EntityButterfly.class, new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1)).isEmpty()) { + if (!world.getEntitiesWithinAABB(EntityButterfly.class, new AxisAlignedBB(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1)).isEmpty()) { weight -= 1.0f; } @@ -229,7 +234,7 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly if (depth > 0) { weight -= 0.1f * depth; } else { - IBlockState blockState = worldObj.getBlockState(pos); + IBlockState blockState = world.getBlockState(pos); Block block = blockState.getBlock(); if (block instanceof BlockFlower) { weight += 2.0f; @@ -237,14 +242,14 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly weight += 1.5f; } else if (block instanceof IGrowable) { weight += 1.0f; - } else if (block.getMaterial(blockState) == Material.PLANTS) { + } else if (blockState.getMaterial() == Material.PLANTS) { weight += 1.0f; } BlockPos posBelow = pos.down(); - IBlockState blockStateBelow = worldObj.getBlockState(posBelow); + IBlockState blockStateBelow = world.getBlockState(posBelow); Block blockBelow = blockStateBelow.getBlock(); - if (blockBelow.isLeaves(blockStateBelow, worldObj, posBelow)) { + if (blockBelow.isLeaves(blockStateBelow, world, posBelow)) { weight += 2.5f; } else if (blockBelow instanceof BlockFence) { weight += 1.0f; @@ -253,21 +258,21 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly } } - weight += worldObj.getLightBrightness(pos); + weight += world.getLightBrightness(pos); return weight; } private int getFluidDepth(BlockPos pos) { - Chunk chunk = worldObj.getChunkFromBlockCoords(pos); + Chunk chunk = world.getChunkFromBlockCoords(pos); int xx = pos.getX() & 15; int zz = pos.getZ() & 15; int depth = 0; for (int y = chunk.getTopFilledSegment() + 15; y > 0; --y) { IBlockState blockState = chunk.getBlockState(xx, y, zz); Block block = blockState.getBlock(); - if (block.getMaterial(blockState).isLiquid()) { + if (blockState.getMaterial().isLiquid()) { depth++; - } else if (!block.isAir(blockState, worldObj, pos)) { + } else if (!block.isAir(blockState, world, pos)) { break; } } @@ -277,19 +282,16 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly /* POLLEN */ @Override + @Nullable public IIndividual getPollen() { return pollen; } @Override - public void setPollen(IIndividual pollen) { + public void setPollen(@Nullable IIndividual pollen) { this.pollen = pollen; } - public boolean isRenderable() { - return species != null; - } - /* EXHAUSTION */ @Override public void changeExhaustion(int change) { @@ -303,10 +305,10 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly /* FLYING ABILITY */ public boolean canFly() { - return contained.canTakeFlight(worldObj, posX, posY, posZ); + return contained.canTakeFlight(world, posX, posY, posZ); } - public void setIndividual(IButterfly butterfly) { + public void setIndividual(@Nullable IButterfly butterfly) { if (butterfly == null) { butterfly = ButterflyManager.butterflyRoot.templateAsIndividual(ButterflyManager.butterflyRoot.getDefaultTemplate()); } @@ -319,7 +321,7 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly setSize(size, 0.4f); species = genome.getPrimary(); - if (!worldObj.isRemote) { + if (!world.isRemote) { dataManager.set(DATAWATCHER_ID_SIZE, (int) (size * 100)); dataManager.set(DATAWATCHER_ID_SPECIES, species.getUID()); } else { @@ -331,10 +333,10 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly public IButterfly getButterfly() { return contained; } - + @Override - public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData data) { - if (!worldObj.isRemote) { + public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, @Nullable IEntityLivingData data) { + if (!world.isRemote) { setIndividual(contained); } return data; @@ -358,8 +360,9 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly return 1000; } - @SideOnly(Side.CLIENT) - private ResourceLocation textureResource; + public boolean isRenderable() { + return species != null; + } @SideOnly(Side.CLIENT) public ResourceLocation getTexture() { @@ -388,46 +391,43 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly /* INTERACTION */ @Override - protected boolean processInteract(EntityPlayer player, EnumHand hand, ItemStack stack) { + protected boolean processInteract(EntityPlayer player, EnumHand hand) { if (isDead) { return false; } - if (stack == null) { - return false; + ItemStack stack = player.getHeldItem(hand); + if ((stack.getItem() instanceof IToolScoop)) { + if (!world.isRemote) { + IButterflyRoot root = contained.getGenome().getPrimary().getRoot(); + ILepidopteristTracker tracker = root.getBreedingTracker(world, player.getGameProfile()); + ItemStack itemStack = root.getMemberStack(contained.copy(), EnumFlutterType.BUTTERFLY); + + tracker.registerCatch(contained); + ItemStackUtil.dropItemStackAsEntity(itemStack, world, posX, posY, posZ); + setDead(); + } else { + player.swingArm(hand); + } + return true; } - if (!(stack.getItem() instanceof IToolScoop)) { - return false; - } - - if (!worldObj.isRemote) { - IButterflyRoot root = contained.getGenome().getPrimary().getRoot(); - ILepidopteristTracker tracker = root.getBreedingTracker(worldObj, player.getGameProfile()); - ItemStack itemStack = root.getMemberStack(contained.copy(), EnumFlutterType.BUTTERFLY); - - tracker.registerCatch(contained); - ItemStackUtil.dropItemStackAsEntity(itemStack, worldObj, posX, posY, posZ); - setDead(); - } else { - player.swingArm(hand); - } - return true; + return false; } /* LOOT */ @Override protected void dropFewItems(boolean playerKill, int lootLevel) { for (ItemStack stack : contained.getLootDrop(this, playerKill, lootLevel)) { - ItemStackUtil.dropItemStackAsEntity(stack, worldObj, posX, posY, posZ); + ItemStackUtil.dropItemStackAsEntity(stack, world, posX, posY, posZ); } // Drop pollen if any IIndividual pollen = getPollen(); if (pollen != null) { - ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(pollen.getClass()); + ISpeciesRoot root = AlleleManager.alleleRegistry.getSpeciesRoot(pollen); ItemStack pollenStack = root.getMemberStack(pollen, EnumGermlingType.POLLEN); - ItemStackUtil.dropItemStackAsEntity(pollenStack, worldObj, posX, posY, posZ); + ItemStackUtil.dropItemStackAsEntity(pollenStack, world, posX, posY, posZ); } } @@ -437,7 +437,7 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly super.onUpdate(); // Update stuff client side - if (worldObj.isRemote) { + if (world.isRemote) { if (species == null) { String speciesUid = dataManager.get(DATAWATCHER_ID_SPECIES); IAllele allele = AlleleManager.alleleRegistry.getAllele(speciesUid); @@ -449,7 +449,7 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly } byte stateOrdinal = dataManager.get(DATAWATCHER_ID_STATE); - if (state == null || state.ordinal() != stateOrdinal) { + if (state.ordinal() != stateOrdinal) { setState(EnumButterflyState.VALUES[stateOrdinal]); } } @@ -458,11 +458,11 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly // Make sure we die if the butterfly hasn't rested in a long, long time. if (exhaustion > EXHAUSTION_CONSUMPTION && getRNG().nextInt(20) == 0) { - attackEntityFrom(DamageSource.generic, 1); + attackEntityFrom(DamageSource.GENERIC, 1); } if (ticksExisted > MAX_LIFESPAN) { - attackEntityFrom(DamageSource.generic, 1); + attackEntityFrom(DamageSource.GENERIC, 1); } // Reduce cooldowns @@ -534,20 +534,23 @@ public class EntityButterfly extends EntityCreature implements IEntityButterfly @Override public ItemStack getPickedResult(RayTraceResult target) { if (species == null) { - return null; + return ItemStack.EMPTY; } IButterflyRoot root = species.getRoot(); IAllele[] template = root.getTemplate(species.getUID()); + if (template == null) { + return ItemStack.EMPTY; + } IButterfly butterfly = root.templateAsIndividual(template); return root.getMemberStack(butterfly, EnumFlutterType.BUTTERFLY); } @Override public boolean canMateWith(IEntityButterfly butterfly) { - if(butterfly == null || butterfly.getButterfly() == null || butterfly.getButterfly().getMate() != null){ + if (butterfly.getButterfly().getMate() != null) { return false; } - if (getButterfly() == null || getButterfly().getMate() != null) { + if (getButterfly().getMate() != null) { return false; } return !getButterfly().isGeneticEqual(butterfly.getButterfly()); diff --git a/src/main/java/forestry/lepidopterology/entities/package-info.java b/src/main/java/forestry/lepidopterology/entities/package-info.java new file mode 100644 index 000000000..d353b1974 --- /dev/null +++ b/src/main/java/forestry/lepidopterology/entities/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.entities; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java index 796265935..e6900a094 100755 --- a/src/main/java/forestry/lepidopterology/genetics/Butterfly.java +++ b/src/main/java/forestry/lepidopterology/genetics/Butterfly.java @@ -10,23 +10,12 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; - -import net.minecraft.entity.EntityCreature; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.text.TextFormatting; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; - -import net.minecraftforge.common.BiomeDictionary; +import java.util.Set; import forestry.api.core.EnumHumidity; import forestry.api.core.EnumTemperature; @@ -52,18 +41,25 @@ import forestry.core.genetics.GenericRatings; import forestry.core.genetics.IndividualLiving; import forestry.core.utils.Translator; import forestry.lepidopterology.PluginLepidopterology; +import net.minecraft.entity.EntityCreature; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.TextFormatting; +import net.minecraft.world.World; +import net.minecraft.world.biome.Biome; +import net.minecraftforge.common.BiomeDictionary; public class Butterfly extends IndividualLiving implements IButterfly { - private static final Random rand = new Random(); - @Nonnull private final IButterflyGenome genome; @Nullable private IButterflyGenome mate; /* CONSTRUCTOR */ - public Butterfly(@Nonnull NBTTagCompound nbt) { + public Butterfly(NBTTagCompound nbt) { super(nbt); if (nbt.hasKey("Genome")) { @@ -77,7 +73,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { } } - public Butterfly(@Nonnull IButterflyGenome genome) { + public Butterfly(IButterflyGenome genome) { super(genome.getLifespan()); this.genome = genome; } @@ -117,7 +113,6 @@ public class Butterfly extends IndividualLiving implements IButterfly { return new Butterfly(nbttagcompound); } - @Nonnull @Override public IButterflyGenome getGenome() { return genome; @@ -140,13 +135,13 @@ public class Butterfly extends IndividualLiving implements IButterfly { boolean noneMatched = true; if (getGenome().getPrimary().strictSpawnMatch()) { - BiomeDictionary.Type[] types = BiomeDictionary.getTypesForBiome(biome); - if (types.length == 1 && getGenome().getPrimary().getSpawnBiomes().contains(types[0])) { + Set types = BiomeDictionary.getTypes(biome); + if (types.size() == 1 && getGenome().getPrimary().getSpawnBiomes().containsAll(types)) { noneMatched = false; } } else { for (BiomeDictionary.Type type : getGenome().getPrimary().getSpawnBiomes()) { - if (BiomeDictionary.isBiomeOfType(biome, type)) { + if (BiomeDictionary.hasType(biome, type)) { noneMatched = false; break; } @@ -163,17 +158,13 @@ public class Butterfly extends IndividualLiving implements IButterfly { @Override public boolean canTakeFlight(World world, double x, double y, double z) { - if (!canFly(world)) { - return false; - } - return isAcceptedEnvironment(world, x, y, z); + return canFly(world) && + isAcceptedEnvironment(world, x, y, z); } private boolean canFly(World world) { - if (world.isRaining() && !getGenome().getTolerantFlyer()) { - return false; - } - return isActiveThisTime(world.isDaytime()); + return (!world.isRaining() || getGenome().getTolerantFlyer()) && + isActiveThisTime(world.isDaytime()); } @Override @@ -191,6 +182,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { } @Override + @Nullable public IButterfly spawnCaterpillar(World world, IButterflyNursery nursery) { // We need a mated queen to produce offspring. if (mate == null) { @@ -221,6 +213,7 @@ public class Butterfly extends IndividualLiving implements IButterfly { return new Butterfly(new ButterflyGenome(chromosomes)); } + @Nullable private static IChromosome[] mutateSpecies(World world, IButterflyNursery nursery, IGenome genomeOne, IGenome genomeTwo) { IChromosome[] parent1 = genomeOne.getChromosomes(); @@ -278,24 +271,24 @@ public class Butterfly extends IndividualLiving implements IButterfly { } @Override - public ItemStack[] getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel) { - ArrayList drop = new ArrayList<>(); + public NonNullList getLootDrop(IEntityButterfly entity, boolean playerKill, int lootLevel) { + NonNullList drop = NonNullList.create(); EntityCreature creature = entity.getEntity(); float metabolism = (float) getGenome().getMetabolism() / 10; for (Map.Entry entry : getGenome().getPrimary().getButterflyLoot().entrySet()) { - if (creature.worldObj.rand.nextFloat() < entry.getValue() * metabolism) { + if (creature.world.rand.nextFloat() < entry.getValue() * metabolism) { drop.add(entry.getKey().copy()); } } - return drop.toArray(new ItemStack[drop.size()]); + return drop; } @Override - public ItemStack[] getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel) { - ArrayList drop = new ArrayList<>(); + public NonNullList getCaterpillarDrop(IButterflyNursery nursery, boolean playerKill, int lootLevel) { + NonNullList drop = NonNullList.create(); float metabolism = (float) getGenome().getMetabolism() / 10; for (Map.Entry entry : getGenome().getPrimary().getCaterpillarLoot().entrySet()) { @@ -304,12 +297,12 @@ public class Butterfly extends IndividualLiving implements IButterfly { } } - return drop.toArray(new ItemStack[drop.size()]); + return drop; } - + @Override - public ItemStack[] getCocoonDrop(IButterflyCocoon cocoon) { - ArrayList drop = new ArrayList<>(); + public NonNullList getCocoonDrop(IButterflyCocoon cocoon) { + NonNullList drop = NonNullList.create(); float metabolism = (float) getGenome().getMetabolism() / 10; for (Map.Entry entry : getGenome().getCocoon().getCocoonLoot().entrySet()) { @@ -317,24 +310,24 @@ public class Butterfly extends IndividualLiving implements IButterfly { drop.add(entry.getKey().copy()); } } - - if(PluginLepidopterology.getSerumChance() > 0){ - if(rand.nextFloat() < PluginLepidopterology.getSerumChance() * metabolism){ + + if (PluginLepidopterology.getSerumChance() > 0) { + if (rand.nextFloat() < PluginLepidopterology.getSerumChance() * metabolism) { ItemStack stack = ButterflyManager.butterflyRoot.getMemberStack(this, EnumFlutterType.SERUM); - if(PluginLepidopterology.getSecondSerumChance() > 0){ - if(rand.nextFloat() < PluginLepidopterology.getSecondSerumChance() * metabolism){ - stack.stackSize = 2; + if (PluginLepidopterology.getSecondSerumChance() > 0) { + if (rand.nextFloat() < PluginLepidopterology.getSecondSerumChance() * metabolism) { + stack.setCount(2); } } drop.add(ButterflyManager.butterflyRoot.getMemberStack(this, EnumFlutterType.SERUM)); } } - - if(cocoon.isSolid()){ + + if (cocoon.isSolid()) { drop.add(ButterflyManager.butterflyRoot.getMemberStack(this, EnumFlutterType.BUTTERFLY)); } - return drop.toArray(new ItemStack[drop.size()]); + return drop; } } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java index bb42335ed..b8eb52161 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyBranchDefinition.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; +import javax.annotation.Nullable; import java.util.Arrays; import forestry.api.genetics.AlleleManager; @@ -20,8 +21,7 @@ import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.core.genetics.IBranchDefinition; import forestry.core.genetics.alleles.AlleleHelper; import forestry.core.genetics.alleles.EnumAllele; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyEffect; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; public enum ButterflyBranchDefinition implements IBranchDefinition { Anthocharis, @@ -50,6 +50,7 @@ public enum ButterflyBranchDefinition implements IBranchDefinition { Siproeta, Speyeria; + @Nullable private static IAllele[] defaultTemplate; private final IClassification branch; @@ -62,20 +63,20 @@ public enum ButterflyBranchDefinition implements IBranchDefinition { public IAllele[] getTemplate() { if (defaultTemplate == null) { defaultTemplate = new IAllele[EnumButterflyChromosome.values().length]; - - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALL); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWEST); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.METABOLISM, 3); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FERTILITY, 3); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.NOCTURNAL, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.TOLERANT_FLYER, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FIRE_RESIST, false); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.EFFECT, AlleleButterflyEffect.butterflyNone); - AlleleHelper.instance.set(defaultTemplate, EnumButterflyChromosome.COCOON, AlleleButterflyCocoon.cocoonDefault); + AlleleHelper alleleHelper = AlleleHelper.getInstance(); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALL); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWEST); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.METABOLISM, 3); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.FERTILITY, 3); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.NONE); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.NONE); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.NOCTURNAL, false); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.TOLERANT_FLYER, false); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.FIRE_RESIST, false); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.FLOWER_PROVIDER, EnumAllele.Flowers.VANILLA); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.EFFECT, ButterflyAlleles.butterflyNone); + alleleHelper.set(defaultTemplate, EnumButterflyChromosome.COCOON, ButterflyAlleles.cocoonDefault); } return Arrays.copyOf(defaultTemplate, defaultTemplate.length); } diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java index 5f4ebb6d5..2ba6682eb 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyDefinition.java @@ -35,46 +35,46 @@ public enum ButterflyDefinition implements IButterflyDefinition { CabbageWhite(ButterflyBranchDefinition.Pieris, "cabbageWhite", "rapae", new Color(0xccffee), true, 1.0f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); } }, Brimstone(ButterflyBranchDefinition.Gonepteryx, "brimstone", "rhamni", new Color(0xf0ee38), true, 1.0f), Aurora(ButterflyBranchDefinition.Anthocharis, "orangeTip", "cardamines", new Color(0xe34f05), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); } }, Postillion(ButterflyBranchDefinition.Colias, "postillion", "croceus", new Color(0xd77e04), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); } }, PalaenoSulphur(ButterflyBranchDefinition.Colias, "palaenoSulphur", "palaeno", new Color(0xf8fba3), true, 0.4f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); } }, Reseda(ButterflyBranchDefinition.Pontia, "reseda", "edusa", new Color(0x747d48), true, 0.3f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); } }, SpringAzure(ButterflyBranchDefinition.Celastrina, "springAzure", "argiolus", new Color(0xb8cae2), true, 0.3f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } }, GozoraAzure(ButterflyBranchDefinition.Celastrina, "gozoraAzure", "gozora", new Color(0x6870e7), true, 0.2f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); } }, CitrusSwallow(ButterflyBranchDefinition.Papilio, "swallowtailC", "demodocus", new Color(0xeae389), false, 1.0f) { @@ -86,13 +86,13 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 10); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 8); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 10); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.METABOLISM, 8); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); } }, EmeraldPeacock(ButterflyBranchDefinition.Papilio, "emeraldPeacock", "palinurus", new Color(0x7cfe80), true, 0.1f) { @@ -104,11 +104,11 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.NORMAL); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 5); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); } }, ThoasSwallow(ButterflyBranchDefinition.Papilio, "swallowtailT", "thoas", new Color(0xeac783), false, 0.2f) { @@ -120,32 +120,32 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); } }, Spicebush(ButterflyBranchDefinition.Papilio, "swallowtailS", "troilus", new Color(0xeefeff), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); } }, BlackSwallow(ButterflyBranchDefinition.Papilio, "swallowtailB", "polyxenes", new Color(0xeac783), true, 1.0f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOW); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); } }, ZebraSwallow(ButterflyBranchDefinition.Protographium, "swallowtailZ", "marcellus", new Color(0xeafeff), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); } }, Glasswing(ButterflyBranchDefinition.Greta, "glasswing", "oto", new Color(0x583732), true, 0.1f) { @@ -156,28 +156,28 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 5); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORT); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 5); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); } }, SpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWood", "aegeria", new Color(0x947245), true, 1.0f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, MSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodM", "xiphia", new Color(0x402919), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, CSpeckledWood(ButterflyBranchDefinition.Pararge, "speckledWoodC", "xiphioides", new Color(0x51372a), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, MBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoM", "menelaus", new Color(0x72e1fd), true, 0.5f) { @@ -189,9 +189,9 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, PBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoP", "peleides", new Color(0x6ecce8), true, 0.25f) { @@ -203,9 +203,9 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, RBlueMorpho(ButterflyBranchDefinition.Morpho, "blueMorphoR", "rhetenor", new Color(0x00bef8), true, 0.1f) { @@ -217,15 +217,15 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.FERTILITY, 2); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.LIFESPAN, EnumAllele.Lifespan.SHORTEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.FERTILITY, 2); } }, Comma(ButterflyBranchDefinition.Polygonia, "comma", "c-album", new Color(0xf89505), true, 0.3f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); } }, Batesia(ButterflyBranchDefinition.Batesia, "paintedBeauty", "hypochlora", new Color(0xfe7763), true, 0.3f) { @@ -237,20 +237,20 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGE); } }, BlueWing(ButterflyBranchDefinition.Myscelia, "blueWing", "ethusa", new Color(0x3a93cc), true, 0.3f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 5); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.METABOLISM, 5); } }, Monarch(ButterflyBranchDefinition.Danaus, "monarch", "plexippus", new Color(0xffa722), true, 0.2f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); } }, BlueDuke(ButterflyBranchDefinition.Bassarona, "blueDuke", "durga", new Color(0x304240), true, 0.5f) { @@ -261,13 +261,13 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.BOTH_1); } }, GlassyTiger(ButterflyBranchDefinition.Parantica, "glassyTiger", "aglea", new Color(0x5b3935), true, 0.3f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); } }, Postman(ButterflyBranchDefinition.Heliconius, "postman", "melpomene", new Color(0xf7302d), true, 0.3f), @@ -280,23 +280,23 @@ public enum ButterflyDefinition implements IButterflyDefinition { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.AVERAGE); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.DOWN_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.DOWN_1); } }, LLacewing(ButterflyBranchDefinition.Cethosia, "leopardLacewing", "cyane", new Color(0xfb8a06), true, 0.7f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.TEMPERATURE_TOLERANCE, EnumAllele.Tolerance.UP_1); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.HUMIDITY_TOLERANCE, EnumAllele.Tolerance.UP_1); } }, DianaFrit(ButterflyBranchDefinition.Speyeria, "dianaFritillary", "diana", new Color(0xffac05), true, 0.6f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLER); } }; @@ -332,7 +332,7 @@ public enum ButterflyDefinition implements IButterflyDefinition { private void init() { template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); + AlleleHelper.getInstance().set(template, EnumButterflyChromosome.SPECIES, species); setAlleles(template); genome = ButterflyManager.butterflyRoot.templateAsGenome(template); diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java index e19b3583d..fec9feeb7 100755 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyGenome.java @@ -12,6 +12,7 @@ package forestry.lepidopterology.genetics; import javax.annotation.Nonnull; +import com.google.common.base.Preconditions; import forestry.api.genetics.EnumTolerance; import forestry.api.genetics.IAlleleFloat; import forestry.api.genetics.IAlleleFlowers; @@ -45,9 +46,7 @@ public class ButterflyGenome extends Genome implements IButterflyGenome { // NBT RETRIEVAL public static IAlleleButterflySpecies getSpecies(ItemStack itemStack) { - if (!ButterflyManager.butterflyRoot.isMember(itemStack)) { - return null; - } + Preconditions.checkArgument(ButterflyManager.butterflyRoot.isMember(itemStack), "Must be a butterfly"); IAlleleSpecies species = getSpeciesDirectly(ButterflyManager.butterflyRoot, itemStack); if (species instanceof IAlleleButterflySpecies) { diff --git a/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java b/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java index 2b0733e16..5ce2a3966 100644 --- a/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java +++ b/src/main/java/forestry/lepidopterology/genetics/ButterflyRoot.java @@ -16,6 +16,7 @@ import java.util.Collections; import java.util.List; import java.util.Map.Entry; +import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAllele; @@ -53,12 +54,15 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { private static int butterflySpeciesCount = -1; public static final String UID = "rootButterflies"; + private static final List butterflyTemplates = new ArrayList<>(); + @Override public String getUID() { return UID; } + @Override public Class getMemberClass() { return IButterfly.class; @@ -88,7 +92,7 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { @Nullable @Override public EnumFlutterType getType(ItemStack stack) { - if (stack == null) { + if (stack.isEmpty()) { return null; } @@ -101,11 +105,11 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { return EnumFlutterType.CATERPILLAR; } else if (PluginLepidopterology.items.cocoonGE == item) { return EnumFlutterType.COCOON; - }else { + } else { return null; } } - + @Override public EnumFlutterType getIconType() { return EnumFlutterType.BUTTERFLY; @@ -123,12 +127,8 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { @Override public IButterfly getMember(ItemStack stack) { - if (!stack.hasTagCompound()) { - return null; - } - if (!isMember(stack)) { - return null; - } + Preconditions.checkArgument(isMember(stack)); + Preconditions.checkArgument(stack.getTagCompound() != null); return new Butterfly(stack.getTagCompound()); } @@ -140,9 +140,7 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { @Override public ItemStack getMemberStack(IIndividual butterfly, ISpeciesType type) { - if (!(type instanceof EnumFlutterType)) { - return null; - } + Preconditions.checkArgument(type instanceof EnumFlutterType); Item butterflyItem; switch ((EnumFlutterType) type) { @@ -173,9 +171,13 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { public EntityButterfly spawnButterflyInWorld(World world, IButterfly butterfly, double x, double y, double z) { return EntityUtil.spawnEntity(world, new EntityButterfly(world, butterfly, new BlockPos(x, y, z)), x, y, z); } - + @Override public boolean plantCocoon(World world, IButterflyNursery nursery, GameProfile owner, int age) { + if (nursery.getCaterpillar() == null) { + return false; + } + BlockPos pos = getNextPos(world, nursery.getCoordinates()); IBlockState state = PluginLepidopterology.blocks.cocoon.getDefaultState(); boolean placed = world.setBlockState(pos, state); @@ -202,8 +204,8 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { return true; } - - private BlockPos getNextPos(World world, BlockPos pos){ + + private BlockPos getNextPos(World world, BlockPos pos) { IBlockState blockState; do { pos = pos.down(); @@ -216,10 +218,6 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { @Override public boolean isMated(ItemStack stack) { IButterfly butterfly = getMember(stack); - if (butterfly == null) { - return false; - } - return butterfly.getMate() != null; } @@ -245,13 +243,13 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { } /* TEMPLATES */ - private static final ArrayList butterflyTemplates = new ArrayList<>(); @Override - public ArrayList getIndividualTemplates() { + public List getIndividualTemplates() { return butterflyTemplates; } + @Override public IAllele[] getDefaultTemplate() { return MothDefinition.Brimstone.getTemplate(); @@ -291,14 +289,14 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { /* BREEDING TRACKER */ @Override - public ILepidopteristTracker getBreedingTracker(World world, GameProfile player) { + public ILepidopteristTracker getBreedingTracker(World world, @Nullable GameProfile player) { String filename = "LepidopteristTracker." + (player == null ? "common" : player.getId()); - LepidopteristTracker tracker = (LepidopteristTracker) world.loadItemData(LepidopteristTracker.class, filename); + LepidopteristTracker tracker = (LepidopteristTracker) world.loadData(LepidopteristTracker.class, filename); // Create a tracker if there is none yet. if (tracker == null) { tracker = new LepidopteristTracker(filename); - world.setItemData(filename, tracker); + world.setData(filename, tracker); } tracker.setUsername(player); @@ -321,5 +319,4 @@ public class ButterflyRoot extends SpeciesRoot implements IButterflyRoot { public IAlyzerPlugin getAlyzerPlugin() { return FlutterlyzerPlugin.INSTANCE; } - } diff --git a/src/main/java/forestry/lepidopterology/genetics/FlutterlyzerPlugin.java b/src/main/java/forestry/lepidopterology/genetics/FlutterlyzerPlugin.java index 957edddde..dceebc17f 100644 --- a/src/main/java/forestry/lepidopterology/genetics/FlutterlyzerPlugin.java +++ b/src/main/java/forestry/lepidopterology/genetics/FlutterlyzerPlugin.java @@ -10,17 +10,10 @@ ******************************************************************************/ package forestry.lepidopterology.genetics; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleFlowers; import forestry.api.genetics.IAlleleInteger; @@ -39,6 +32,11 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.StringUtil; import forestry.core.utils.Translator; import forestry.lepidopterology.PluginLepidopterology; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class FlutterlyzerPlugin implements IAlyzerPlugin { public static final FlutterlyzerPlugin INSTANCE = new FlutterlyzerPlugin(); @@ -46,127 +44,119 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { protected final Map iconStacks = new HashMap<>(); private FlutterlyzerPlugin() { - List butterflyList = new ArrayList<>(); + NonNullList butterflyList = NonNullList.create(); PluginLepidopterology.items.butterflyGE.addCreativeItems(butterflyList, false); for (ItemStack butterflyStack : butterflyList) { IAlleleButterflySpecies species = ButterflyGenome.getSpecies(butterflyStack); - if (species != null) { - iconStacks.put(species.getUID(), butterflyStack); - } + iconStacks.put(species.getUID(), butterflyStack); } } @SideOnly(Side.CLIENT) @Override public void drawAnalyticsPage1(GuiScreen gui, ItemStack itemStack) { - if(gui instanceof GuiAlyzer){ + if (gui instanceof GuiAlyzer) { GuiAlyzer guiAlyzer = (GuiAlyzer) gui; IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(itemStack); - if (butterfly == null) { - return; - } - + TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - + textLayout.startPage(GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); - + textLayout.drawLine(Translator.translateToLocal("for.gui.active"), GuiAlyzer.COLUMN_1); textLayout.drawLine(Translator.translateToLocal("for.gui.inactive"), GuiAlyzer.COLUMN_2); - + textLayout.newLine(); textLayout.newLine(); - + guiAlyzer.drawSpeciesRow(Translator.translateToLocal("for.gui.species"), butterfly, EnumButterflyChromosome.SPECIES, null, null); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.size"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.SIZE).getName(), butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.SIZE).getName(), butterfly, EnumButterflyChromosome.SPEED); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.lifespan"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.LIFESPAN).getName(), butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.LIFESPAN).getName(), butterfly, EnumButterflyChromosome.LIFESPAN); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.speed"), butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.SPEED).getName(), butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.SPEED).getName(), butterfly, EnumButterflyChromosome.SPEED); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.metabolism"), GenericRatings.rateMetabolism(butterfly.getGenome().getMetabolism()), GenericRatings.rateMetabolism(((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.METABOLISM)).getValue()), butterfly, EnumButterflyChromosome.METABOLISM); textLayout.newLine(); - + textLayout.drawLine(Translator.translateToLocal("for.gui.fertility"), GuiAlyzer.COLUMN_0); guiAlyzer.drawFertilityInfo(butterfly.getGenome().getFertility(), GuiAlyzer.COLUMN_1, guiAlyzer.getColorCoding(butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.FERTILITY) .isDominant()), 8); guiAlyzer.drawFertilityInfo(((IAlleleInteger) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY)).getValue(), GuiAlyzer.COLUMN_2, guiAlyzer.getColorCoding(butterfly .getGenome().getInactiveAllele(EnumButterflyChromosome.FERTILITY).isDominant()), 8); - + textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.flowers"), butterfly.getGenome().getFlowerProvider().getDescription(), ((IAlleleFlowers) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FLOWER_PROVIDER)).getProvider() .getDescription(), butterfly, EnumButterflyChromosome.FLOWER_PROVIDER); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.effect"), butterfly.getGenome().getEffect().getName(), butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.EFFECT).getName(), butterfly, EnumButterflyChromosome.EFFECT); - + textLayout.newLine(); - + textLayout.endPage(); } } - + @SideOnly(Side.CLIENT) @Override public void drawAnalyticsPage2(GuiScreen gui, ItemStack itemStack) { - if(gui instanceof GuiAlyzer){ + if (gui instanceof GuiAlyzer) { GuiAlyzer guiAlyzer = (GuiAlyzer) gui; IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(itemStack); - if (butterfly == null) { - return; - } - + TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - + textLayout.startPage(GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); - + textLayout.drawLine(Translator.translateToLocal("for.gui.active"), GuiAlyzer.COLUMN_1); textLayout.drawLine(Translator.translateToLocal("for.gui.inactive"), GuiAlyzer.COLUMN_2); - + textLayout.newLine(); textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.climate"), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getTemperature()), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getTemperature()), butterfly, EnumButterflyChromosome.SPECIES); textLayout.newLine(); - + IAlleleTolerance tempToleranceActive = (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); IAlleleTolerance tempToleranceInactive = (IAlleleTolerance) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TEMPERATURE_TOLERANCE); textLayout.drawLine(" " + Translator.translateToLocal("for.gui.tolerance"), GuiAlyzer.COLUMN_0); guiAlyzer.drawToleranceInfo(tempToleranceActive, GuiAlyzer.COLUMN_1); guiAlyzer.drawToleranceInfo(tempToleranceInactive, GuiAlyzer.COLUMN_2); - + textLayout.newLine(); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.humidity"), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getHumidity()), AlleleManager.climateHelper.toDisplay(butterfly.getGenome().getPrimary().getHumidity()), butterfly, EnumButterflyChromosome.SPECIES); textLayout.newLine(); - + IAlleleTolerance humidToleranceActive = (IAlleleTolerance) butterfly.getGenome().getActiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); IAlleleTolerance humidToleranceInactive = (IAlleleTolerance) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.HUMIDITY_TOLERANCE); textLayout.drawLine(" " + Translator.translateToLocal("for.gui.tolerance"), GuiAlyzer.COLUMN_0); guiAlyzer.drawToleranceInfo(humidToleranceActive, GuiAlyzer.COLUMN_1); guiAlyzer.drawToleranceInfo(humidToleranceInactive, GuiAlyzer.COLUMN_2); - + textLayout.newLine(); textLayout.newLine(); - + String yes = Translator.translateToLocal("for.yes"); String no = Translator.translateToLocal("for.no"); - + String diurnal0, diurnal1, nocturnal0, nocturnal1; if (butterfly.getGenome().getNocturnal()) { nocturnal0 = diurnal0 = yes; @@ -180,30 +170,30 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { nocturnal1 = butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; diurnal1 = !butterfly.getGenome().getSecondary().isNocturnal() ? yes : no; } - + textLayout.drawLine(Translator.translateToLocal("for.gui.diurnal"), GuiAlyzer.COLUMN_0); textLayout.drawLine(diurnal0, GuiAlyzer.COLUMN_1, guiAlyzer.getColorCoding(false)); textLayout.drawLine(diurnal1, GuiAlyzer.COLUMN_2, guiAlyzer.getColorCoding(false)); textLayout.newLine(); - + textLayout.drawLine(Translator.translateToLocal("for.gui.nocturnal"), GuiAlyzer.COLUMN_0); textLayout.drawLine(nocturnal0, GuiAlyzer.COLUMN_1, guiAlyzer.getColorCoding(false)); textLayout.drawLine(nocturnal1, GuiAlyzer.COLUMN_2, guiAlyzer.getColorCoding(false)); textLayout.newLine(); - + String primary = StringUtil.readableBoolean(butterfly.getGenome().getTolerantFlyer(), yes, no); String secondary = StringUtil.readableBoolean(((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.TOLERANT_FLYER)).getValue(), yes, no); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.flyer"), primary, secondary, butterfly, EnumButterflyChromosome.TOLERANT_FLYER); textLayout.newLine(); - + primary = StringUtil.readableBoolean(butterfly.getGenome().getFireResist(), yes, no); secondary = StringUtil.readableBoolean(((AlleleBoolean) butterfly.getGenome().getInactiveAllele(EnumButterflyChromosome.FIRE_RESIST)).getValue(), yes, no); - + guiAlyzer.drawRow(Translator.translateToLocal("for.gui.fireresist"), primary, secondary, butterfly, EnumButterflyChromosome.FIRE_RESIST); - + textLayout.endPage(); } } @@ -211,20 +201,17 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { @SideOnly(Side.CLIENT) @Override public void drawAnalyticsPage3(GuiScreen gui, ItemStack itemStack) { - if(gui instanceof GuiAlyzer){ + if (gui instanceof GuiAlyzer) { GuiAlyzer guiAlyzer = (GuiAlyzer) gui; IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(itemStack); - if (butterfly == null) { - return; - } - + TextLayoutHelper textLayout = guiAlyzer.getTextLayout(); - + textLayout.startPage(GuiAlyzer.COLUMN_0, GuiAlyzer.COLUMN_1, GuiAlyzer.COLUMN_2); - + textLayout.drawLine(Translator.translateToLocal("for.gui.loot.butterfly") + ":", GuiAlyzer.COLUMN_0); textLayout.newLine(); - + int x = GuiAlyzer.COLUMN_0; for (ItemStack stack : butterfly.getGenome().getPrimary().getButterflyLoot().keySet()) { Proxies.common.getClientInstance().getRenderItem().renderItemIntoGUI(stack, guiAlyzer.getGuiLeft() + x, guiAlyzer.getGuiTop() + textLayout.getLineY()); @@ -234,13 +221,13 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { textLayout.newLine(); } } - + textLayout.newLine(); textLayout.newLine(); - + textLayout.drawLine(Translator.translateToLocal("for.gui.loot.caterpillar") + ":", GuiAlyzer.COLUMN_0); textLayout.newLine(); - + x = GuiAlyzer.COLUMN_0; for (ItemStack stack : butterfly.getGenome().getPrimary().getCaterpillarLoot().keySet()) { Proxies.common.getClientInstance().getRenderItem().renderItemIntoGUI(stack, guiAlyzer.getGuiLeft() + x, guiAlyzer.getGuiTop() + textLayout.getLineY()); @@ -250,7 +237,7 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { textLayout.newLine(); } } - + textLayout.endPage(); } } @@ -259,7 +246,7 @@ public class FlutterlyzerPlugin implements IAlyzerPlugin { public Map getIconStacks() { return iconStacks; } - + @Override public List getHints() { return Config.hints.get("flutterlyzer"); diff --git a/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java b/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java index d3c27f79d..c4591494b 100755 --- a/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java +++ b/src/main/java/forestry/lepidopterology/genetics/LepidopteristTracker.java @@ -28,7 +28,7 @@ public class LepidopteristTracker extends BreedingTracker implements ILepidopter @Override protected IBreedingTracker getBreedingTracker(EntityPlayer player) { - return ButterflyManager.butterflyRoot.getBreedingTracker(player.worldObj, player.getGameProfile()); + return ButterflyManager.butterflyRoot.getBreedingTracker(player.world, player.getGameProfile()); } @Override diff --git a/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java b/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java index df08ee297..d16030027 100644 --- a/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java +++ b/src/main/java/forestry/lepidopterology/genetics/MothDefinition.java @@ -14,8 +14,6 @@ import java.awt.Color; import java.util.Arrays; import java.util.Locale; -import net.minecraft.item.ItemStack; - import forestry.api.genetics.IAllele; import forestry.api.genetics.IClassification; import forestry.api.lepidopterology.ButterflyManager; @@ -29,31 +27,32 @@ import forestry.api.lepidopterology.IButterflyMutationBuilder; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleHelper; import forestry.core.genetics.alleles.EnumAllele; -import forestry.lepidopterology.genetics.alleles.AlleleButterflyCocoon; +import forestry.lepidopterology.genetics.alleles.ButterflyAlleles; +import net.minecraft.item.ItemStack; public enum MothDefinition implements IButterflyDefinition { Brimstone(ButterflyBranchDefinition.Opisthograptis, "brimstone", "luteolata", new Color(0xffea40), true, 1.0f), LatticedHeath(ButterflyBranchDefinition.Chiasmia, "latticedHeath", "clathrata", new Color(0xf2f0be), true, 0.5f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); } }, Atlas(ButterflyBranchDefinition.Attacus, "atlas", "atlas", new Color(0xd96e3d), false, 0.1f) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.LARGEST); } }, - BombyxMori(ButterflyBranchDefinition.Bombyx, "bombyxMori", "bombyxMori", new Color(0xDADADA), false, 0){ + BombyxMori(ButterflyBranchDefinition.Bombyx, "bombyxMori", "bombyxMori", new Color(0xDADADA), false, 0) { @Override protected void setAlleles(IAllele[] alleles) { - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.METABOLISM, 4); - AlleleHelper.instance.set(alleles, EnumButterflyChromosome.COCOON, AlleleButterflyCocoon.cocoonSilk); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SIZE, EnumAllele.Size.SMALLEST); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.SPEED, EnumAllele.Speed.SLOWER); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.METABOLISM, 4); + AlleleHelper.getInstance().set(alleles, EnumButterflyChromosome.COCOON, ButterflyAlleles.cocoonSilk); } - + @Override protected void registerMutations() { registerMutation(MothDefinition.LatticedHeath, ButterflyDefinition.Brimstone, 7); @@ -93,7 +92,7 @@ public enum MothDefinition implements IButterflyDefinition { private void init() { template = branch.getTemplate(); - AlleleHelper.instance.set(template, EnumButterflyChromosome.SPECIES, species); + AlleleHelper.getInstance().set(template, EnumButterflyChromosome.SPECIES, species); setAlleles(template); genome = ButterflyManager.butterflyRoot.templateAsGenome(template); @@ -108,24 +107,31 @@ public enum MothDefinition implements IButterflyDefinition { protected void setAlleles(IAllele[] alleles) { } - - protected void registerMutations(){ - + + protected void registerMutations() { + } - + protected final IButterflyMutationBuilder registerMutation(IButterflyDefinition parent1, IButterflyDefinition parent2, int chance) { - IAlleleButterflySpecies species1 = null; - IAlleleButterflySpecies species2 = null; - if(parent1 instanceof MothDefinition){ + IAlleleButterflySpecies species1; + IAlleleButterflySpecies species2; + + if (parent1 instanceof MothDefinition) { species1 = ((MothDefinition) parent1).species; - }else if(parent1 instanceof ButterflyDefinition){ + } else if (parent1 instanceof ButterflyDefinition) { species1 = ((ButterflyDefinition) parent1).getSpecies(); + } else { + throw new IllegalArgumentException("Unknown parent1: " + parent1); } - if(parent2 instanceof MothDefinition){ + + if (parent2 instanceof MothDefinition) { species2 = ((MothDefinition) parent2).species; - }else if(parent2 instanceof ButterflyDefinition){ + } else if (parent2 instanceof ButterflyDefinition) { species2 = ((ButterflyDefinition) parent2).getSpecies(); + } else { + throw new IllegalArgumentException("Unknown parent2: " + parent2); } + return ButterflyManager.butterflyMutationFactory.createMutation(species1, species2, getTemplate(), chance); } @@ -149,7 +155,7 @@ public enum MothDefinition implements IButterflyDefinition { IButterfly butterfly = getIndividual(); return ButterflyManager.butterflyRoot.getMemberStack(butterfly, flutterType); } - + public IAlleleButterflySpecies getSpecies() { return species; } diff --git a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyCocoon.java b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyCocoon.java index ce360313e..7685b6611 100644 --- a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyCocoon.java +++ b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyCocoon.java @@ -10,77 +10,44 @@ ******************************************************************************/ package forestry.lepidopterology.genetics.alleles; -import javax.annotation.Nonnull; -import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; -import net.minecraft.block.properties.PropertyInteger; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import forestry.api.genetics.AlleleManager; -import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.api.lepidopterology.IAlleleButterflyCocoon; -import forestry.core.PluginCore; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleCategorized; -import forestry.lepidopterology.blocks.property.PropertyCocoon; +import forestry.lepidopterology.blocks.PropertyCocoon; +import net.minecraft.block.properties.PropertyInteger; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.item.ItemStack; public class AlleleButterflyCocoon extends AlleleCategorized implements IAlleleButterflyCocoon { - public static final PropertyCocoon COCOON = new PropertyCocoon("cocoon"); public static final PropertyInteger AGE = PropertyInteger.create("age", 0, 2); - - public static IAlleleButterflyCocoon cocoonDefault; - public static IAlleleButterflyCocoon cocoonSilk; - private static List cocoonAlleles; - public static void createAlleles() { - List cocoonAlleles = Arrays.asList( - cocoonDefault = new AlleleButterflyCocoon("default", false), - cocoonSilk = new AlleleButterflyCocoon("silk", false) - ); - - for (IAlleleButterflyCocoon cocoonAllele : cocoonAlleles) { - AlleleManager.alleleRegistry.registerAllele(cocoonAllele, EnumButterflyChromosome.COCOON); - } - } - - public static void createLoot(){ - cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING, 2), 1F); - cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING), 0.75F); - cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING, 3), 0.25F); - - cocoonSilk.getCocoonLoot().put(new ItemStack(PluginCore.items.craftingMaterial, 3, 2), 0.75F); - cocoonSilk.getCocoonLoot().put(new ItemStack(PluginCore.items.craftingMaterial, 2, 2), 0.25F); - } - private final Map loot = new HashMap<>(); private final String name; - + public AlleleButterflyCocoon(String name, boolean isDominant) { super(Constants.MOD_ID, "cocoon", name, isDominant); this.name = name; } - - private static String getAgeKey(int age){ - if(age == 0){ + + private static String getAgeKey(int age) { + if (age == 0) { return "early"; - }else if(age == 1){ + } else if (age == 1) { return "middle"; - }else{ + } else { return "late"; } } - + @Override public String getCocoonName() { return name; } - + @Override public ModelResourceLocation getCocoonItemModel(int age) { return new ModelResourceLocation(Constants.MOD_ID + ":lepidopterology/cocoons/cocoon_" + name + "_" + getAgeKey(age), "inventory"); @@ -90,10 +57,10 @@ public class AlleleButterflyCocoon extends AlleleCategorized implements IAlleleB public Map getCocoonLoot() { return loot; } - + @Override - public int compareTo(@Nonnull IAlleleButterflyCocoon o) { + public int compareTo(IAlleleButterflyCocoon o) { return 0; } - + } diff --git a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyEffect.java b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyEffect.java index f13a4d663..bf3789f8d 100644 --- a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyEffect.java +++ b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflyEffect.java @@ -10,9 +10,9 @@ ******************************************************************************/ package forestry.lepidopterology.genetics.alleles; -import forestry.api.genetics.AlleleManager; +import javax.annotation.Nullable; + import forestry.api.genetics.IEffectData; -import forestry.api.lepidopterology.EnumButterflyChromosome; import forestry.api.lepidopterology.IAlleleButterflyEffect; import forestry.api.lepidopterology.IEntityButterfly; import forestry.core.config.Constants; @@ -20,13 +20,6 @@ import forestry.core.genetics.alleles.AlleleCategorized; public class AlleleButterflyEffect extends AlleleCategorized implements IAlleleButterflyEffect { - public static IAlleleButterflyEffect butterflyNone; - - public static void createAlleles() { - butterflyNone = new AlleleButterflyEffectNone(); - AlleleManager.alleleRegistry.registerAllele(butterflyNone, EnumButterflyChromosome.EFFECT); - } - protected AlleleButterflyEffect(String valueName, boolean isDominant) { super(Constants.MOD_ID, "bf", valueName, isDominant); } @@ -38,7 +31,7 @@ public class AlleleButterflyEffect extends AlleleCategorized implements IAlleleB @Override public IEffectData validateStorage(IEffectData storedData) { - return null; + return storedData; } @Override diff --git a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflySpecies.java b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflySpecies.java index 39a24df86..bbf6d02f8 100644 --- a/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflySpecies.java +++ b/src/main/java/forestry/lepidopterology/genetics/alleles/AlleleButterflySpecies.java @@ -11,23 +11,12 @@ package forestry.lepidopterology.genetics.alleles; import java.awt.Color; -import java.util.EnumSet; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; +import java.util.Set; import com.mojang.authlib.GameProfile; - -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IClassification; import forestry.api.genetics.IIndividual; @@ -39,6 +28,15 @@ import forestry.api.lepidopterology.IAlleleButterflySpeciesBuilder; import forestry.api.lepidopterology.IButterflyRoot; import forestry.core.config.Constants; import forestry.core.genetics.alleles.AlleleSpecies; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButterflySpecies, IAlleleButterflySpeciesBuilder { private final String texture; @@ -48,7 +46,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt private float flightDistance = 5.0f; private boolean isActualNocturnal = false; - private final EnumSet spawnBiomes = EnumSet.noneOf(BiomeDictionary.Type.class); + private final Set spawnBiomes = new HashSet<>(); private final Map butterflyLoot = new HashMap<>(); private final Map caterpillarLoot = new HashMap<>(); @@ -56,7 +54,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt public AlleleButterflySpecies(String uid, String unlocalizedName, String authority, String unlocalizedDescription, String modID, String texturePath, boolean isDominant, IClassification branch, String binomial, Color serumColour) { super(uid, unlocalizedName, authority, unlocalizedDescription, isDominant, branch, binomial); this.serumColour = serumColour; - + this.modID = modID; this.texture = texturePath; } @@ -90,7 +88,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt return this; } - public AlleleButterflySpecies addSpawnBiomes(EnumSet biomeTags) { + public AlleleButterflySpecies addSpawnBiomes(Set biomeTags) { spawnBiomes.addAll(biomeTags); return this; } @@ -104,14 +102,14 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt public String getEntityTexture() { return getModID() + ":" + Constants.TEXTURE_PATH_ENTITIES + "/" + texture + ".png"; } - + @Override public String getItemTexture() { return getModID() + ":items/" + texture; } - + @Override - public EnumSet getSpawnBiomes() { + public Set getSpawnBiomes() { return spawnBiomes; } @@ -128,7 +126,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt @Override public float getResearchSuitability(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return 0f; } @@ -193,7 +191,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt } return 0xffffff; } - + @Override @SideOnly(Side.CLIENT) public void registerSprites() { @@ -201,7 +199,7 @@ public class AlleleButterflySpecies extends AlleleSpecies implements IAlleleButt TextureMap textureMap = Minecraft.getMinecraft().getTextureMapBlocks(); textureMap.registerSprite(new ResourceLocation(spriteName)); } - + @Override public String getModID() { return modID; diff --git a/src/main/java/forestry/lepidopterology/genetics/alleles/ButterflyAlleles.java b/src/main/java/forestry/lepidopterology/genetics/alleles/ButterflyAlleles.java new file mode 100644 index 000000000..88cfe44fe --- /dev/null +++ b/src/main/java/forestry/lepidopterology/genetics/alleles/ButterflyAlleles.java @@ -0,0 +1,48 @@ +package forestry.lepidopterology.genetics.alleles; + +import java.util.Arrays; +import java.util.List; + +import forestry.api.genetics.AlleleManager; +import forestry.api.lepidopterology.EnumButterflyChromosome; +import forestry.api.lepidopterology.IAlleleButterflyCocoon; +import forestry.api.lepidopterology.IAlleleButterflyEffect; +import forestry.core.PluginCore; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; + +public class ButterflyAlleles { + public static final IAlleleButterflyCocoon cocoonDefault; + public static final IAlleleButterflyCocoon cocoonSilk; + public static final List cocoonAlleles; + + public static final IAlleleButterflyEffect butterflyNone = new AlleleButterflyEffectNone(); + + static { + cocoonAlleles = Arrays.asList( + cocoonDefault = new AlleleButterflyCocoon("default", false), + cocoonSilk = new AlleleButterflyCocoon("silk", false) + ); + } + + public static void registerCocoonAlleles() { + for (IAlleleButterflyCocoon cocoonAllele : cocoonAlleles) { + AlleleManager.alleleRegistry.registerAllele(cocoonAllele, EnumButterflyChromosome.COCOON); + } + } + + public static void registerEffectAlleles() { + AlleleManager.alleleRegistry.registerAllele(butterflyNone, EnumButterflyChromosome.EFFECT); + } + + public static void createLoot() { + cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING, 2), 1F); + cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING), 0.75F); + cocoonDefault.getCocoonLoot().put(new ItemStack(Items.STRING, 3), 0.25F); + + cocoonSilk.getCocoonLoot().put(new ItemStack(PluginCore.items.craftingMaterial, 3, 2), 0.75F); + cocoonSilk.getCocoonLoot().put(new ItemStack(PluginCore.items.craftingMaterial, 2, 2), 0.25F); + } + + +} diff --git a/src/main/java/forestry/lepidopterology/genetics/alleles/package-info.java b/src/main/java/forestry/lepidopterology/genetics/alleles/package-info.java new file mode 100644 index 000000000..6efc3311e --- /dev/null +++ b/src/main/java/forestry/lepidopterology/genetics/alleles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.genetics.alleles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/genetics/package-info.java b/src/main/java/forestry/lepidopterology/genetics/package-info.java new file mode 100644 index 000000000..6a497da69 --- /dev/null +++ b/src/main/java/forestry/lepidopterology/genetics/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.genetics; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java b/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java index e5f2a3b66..43937ea59 100755 --- a/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java +++ b/src/main/java/forestry/lepidopterology/items/ItemButterflyGE.java @@ -10,28 +10,8 @@ ******************************************************************************/ package forestry.lepidopterology.items; -import java.util.List; import java.util.Random; -import net.minecraft.block.state.IBlockState; -import net.minecraft.client.renderer.ItemMeshDefinition; -import net.minecraft.client.renderer.block.model.ModelBakery; -import net.minecraft.client.renderer.block.model.ModelResourceLocation; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.EnumActionResult; -import net.minecraft.util.EnumFacing; -import net.minecraft.util.EnumHand; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - -import net.minecraftforge.fml.relauncher.Side; -import net.minecraftforge.fml.relauncher.SideOnly; - import forestry.api.arboriculture.ITree; import forestry.api.core.IModelManager; import forestry.api.core.ISpriteRegister; @@ -60,6 +40,24 @@ import forestry.core.utils.Translator; import forestry.lepidopterology.PluginLepidopterology; import forestry.lepidopterology.entities.EntityButterfly; import forestry.lepidopterology.genetics.ButterflyGenome; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.renderer.ItemMeshDefinition; +import net.minecraft.client.renderer.block.model.ModelBakery; +import net.minecraft.client.renderer.block.model.ModelResourceLocation; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.EnumActionResult; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColoredItem { @@ -84,36 +82,36 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored } @Override - public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList) { - addCreativeItems(itemList, true); + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { + addCreativeItems(subItems, true); } - public void addCreativeItems(List itemList, boolean hideSecrets) { - if(type == EnumFlutterType.COCOON){ - for(int age = 0;age < 3;age++){ + public void addCreativeItems(NonNullList subItems, boolean hideSecrets) { + if (type == EnumFlutterType.COCOON) { + for (int age = 0; age < 3; age++) { for (IIndividual individual : ButterflyManager.butterflyRoot.getIndividualTemplates()) { // Don't show secret butterflies unless ordered to. if (hideSecrets && individual.isSecret() && !Config.isDebug) { continue; } - + ItemStack butterfly = ButterflyManager.butterflyRoot.getMemberStack(individual, type); - - if(type == EnumFlutterType.COCOON){ + + if (butterfly.getTagCompound() != null) { butterfly.getTagCompound().setInteger(NBT_AGE, age); } - - itemList.add(butterfly); + + subItems.add(butterfly); } } - }else{ + } else { for (IIndividual individual : ButterflyManager.butterflyRoot.getIndividualTemplates()) { // Don't show secret butterflies unless ordered to. if (hideSecrets && individual.isSecret() && !Config.isDebug) { continue; } - - itemList.add(ButterflyManager.butterflyRoot.getMemberStack(individual, type)); + + subItems.add(ButterflyManager.butterflyRoot.getMemberStack(individual, type)); } } } @@ -123,7 +121,7 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored if (type != EnumFlutterType.BUTTERFLY) { return false; } - if (entityItem.worldObj.isRemote || entityItem.ticksExisted < 80) { + if (entityItem.world.isRemote || entityItem.ticksExisted < 80) { return false; } if (rand.nextInt(24) != 0) { @@ -131,42 +129,25 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored } IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(entityItem.getEntityItem()); - if (butterfly == null) { + + if (!butterfly.canTakeFlight(entityItem.world, entityItem.posX, entityItem.posY, entityItem.posZ)) { return false; } - if (!butterfly.canTakeFlight(entityItem.worldObj, entityItem.posX, entityItem.posY, entityItem.posZ)) { + if (entityItem.world.countEntities(EntityButterfly.class) > PluginLepidopterology.entityConstraint) { return false; } - if (entityItem.worldObj.countEntities(EntityButterfly.class) > PluginLepidopterology.entityConstraint) { - return false; + EntityUtil.spawnEntity(entityItem.world, new EntityButterfly(entityItem.world, butterfly, entityItem.getPosition()), entityItem.posX, entityItem.posY, entityItem.posZ); + if (!entityItem.getEntityItem().isEmpty()) { + entityItem.getEntityItem().shrink(1); + } else { + entityItem.setDead(); } - - if (EntityUtil.spawnEntity(entityItem.worldObj, new EntityButterfly(entityItem.worldObj, butterfly, entityItem.getPosition()), entityItem.posX, entityItem.posY, entityItem.posZ) != null) { - if (entityItem.getEntityItem().stackSize > 1) { - entityItem.getEntityItem().stackSize--; - } else { - entityItem.setDead(); - } - return true; - } - - return false; + return true; } /* MODELS */ - @SideOnly(Side.CLIENT) - @Override - public int getColourFromSpecies(IAlleleSpecies species, int renderPass) { - if (species != null) { - return species.getSpriteColour(renderPass); - } else { - return 0xffffff; - } - - } - @SideOnly(Side.CLIENT) @Override public void registerModel(Item item, IModelManager manager) { @@ -181,7 +162,7 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored manager.registerItemModel(item, new CocoonMeshDefinition()); for (IAllele allele : AlleleManager.alleleRegistry.getRegisteredAlleles().values()) { if (allele instanceof IAlleleButterflyCocoon) { - for(int age = 0;age < 3;age++){ + for (int age = 0; age < 3; age++) { ModelBakery.registerItemVariants(this, ((IAlleleButterflyCocoon) allele).getCocoonItemModel(age)); } } @@ -191,38 +172,37 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored manager.registerItemModel(item, 0, "liquids/jar"); } } - - private static class CocoonMeshDefinition implements ItemMeshDefinition { + private static class CocoonMeshDefinition implements ItemMeshDefinition { @Override public ModelResourceLocation getModelLocation(ItemStack itemstack) { int age = itemstack.getTagCompound().getInteger(NBT_AGE); IButterflyGenome genome = (IButterflyGenome) AlleleManager.alleleRegistry.getIndividual(itemstack).getGenome(); return genome.getCocoon().getCocoonItemModel(age); } - + } + @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, final BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (worldIn.isRemote) { return EnumActionResult.PASS; } + ItemStack stack = player.getHeldItem(hand); + IButterfly flutter = ButterflyManager.butterflyRoot.getMember(stack); - if (flutter == null) { - return EnumActionResult.PASS; - } TileEntity tileEntity = worldIn.getTileEntity(pos); IBlockState blockState = worldIn.getBlockState(pos); if (type == EnumFlutterType.COCOON) { int age = stack.getTagCompound().getInteger(NBT_AGE); - + // x, y, z are the coordinates of the block "hit", can thus either be the soil or tall grass, etc. int yShift; if (!BlockUtil.isReplaceableBlock(blockState, worldIn, pos)) { - if(!worldIn.isAirBlock(pos.down())){ + if (!worldIn.isAirBlock(pos.down())) { return EnumActionResult.PASS; } yShift = 1; @@ -230,40 +210,40 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored yShift = 0; } BlockPos posS = pos.add(0, -yShift, 0); - + IButterflyNursery nursery = null; - - if(tileEntity instanceof IButterflyNursery){ + + if (tileEntity instanceof IButterflyNursery) { nursery = (IButterflyNursery) tileEntity; - }else{ + } else { IIndividual treeLeave = GeneticsUtil.getPollen(worldIn, pos); - - if(treeLeave != null && treeLeave instanceof ITree){ - if(((ITree)treeLeave).setLeaves(worldIn, playerIn.getGameProfile(), pos)){ + + if (treeLeave != null && treeLeave instanceof ITree) { + if (((ITree) treeLeave).setLeaves(worldIn, player.getGameProfile(), pos)) { nursery = (IButterflyNursery) worldIn.getTileEntity(pos); } } } - if(nursery != null){ - if(nursery.canNurse(flutter)){ + if (nursery != null) { + if (nursery.canNurse(flutter)) { nursery.setCaterpillar(flutter); - if(ButterflyManager.butterflyRoot.plantCocoon(worldIn, nursery, playerIn.getGameProfile(), age)){ + if (ButterflyManager.butterflyRoot.plantCocoon(worldIn, nursery, player.getGameProfile(), age)) { PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.SoundFXType.BLOCK_PLACE, pos, worldIn.getBlockState(posS)); - Proxies.net.sendNetworkPacket(packet, worldIn); + Proxies.net.sendNetworkPacket(packet, pos, worldIn); - if (!playerIn.capabilities.isCreativeMode) { - stack.stackSize--; + if (!player.capabilities.isCreativeMode) { + stack.shrink(1); } nursery.setCaterpillar(null); return EnumActionResult.SUCCESS; - }else{ + } else { nursery.setCaterpillar(null); return EnumActionResult.PASS; } } } return EnumActionResult.PASS; - }else if (type == EnumFlutterType.CATERPILLAR) { + } else if (type == EnumFlutterType.CATERPILLAR) { if (!(tileEntity instanceof IButterflyNursery)) { return EnumActionResult.PASS; @@ -277,10 +257,10 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored pollinatable.setCaterpillar(flutter); PacketFXSignal packet = new PacketFXSignal(PacketFXSignal.VisualFXType.BLOCK_BREAK, PacketFXSignal.SoundFXType.BLOCK_BREAK, pos, blockState); - Proxies.net.sendNetworkPacket(packet, worldIn); + Proxies.net.sendNetworkPacket(packet, pos, worldIn); - if (!playerIn.capabilities.isCreativeMode) { - stack.stackSize--; + if (!player.capabilities.isCreativeMode) { + stack.shrink(1); } return EnumActionResult.SUCCESS; @@ -302,6 +282,7 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored } } + @Override public String getItemStackDisplayName(ItemStack itemstack) { if (itemstack.getTagCompound() == null) { @@ -321,9 +302,10 @@ public class ItemButterflyGE extends ItemGE implements ISpriteRegister, IColored @Override public int getColorFromItemstack(ItemStack stack, int tintIndex) { - if (stack.hasTagCompound()) { - IAlleleSpecies species = AlleleManager.alleleRegistry.getIndividual(stack).getGenome().getPrimary(); - if (species != null) { + if (stack.getTagCompound() != null) { + IIndividual individual = AlleleManager.alleleRegistry.getIndividual(stack); + if (individual != null) { + IAlleleSpecies species = individual.getGenome().getPrimary(); return species.getSpriteColour(tintIndex); } } diff --git a/src/main/java/forestry/lepidopterology/items/package-info.java b/src/main/java/forestry/lepidopterology/items/package-info.java new file mode 100644 index 000000000..438a240d7 --- /dev/null +++ b/src/main/java/forestry/lepidopterology/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/package-info.java b/src/main/java/forestry/lepidopterology/package-info.java new file mode 100644 index 000000000..4fe80619d --- /dev/null +++ b/src/main/java/forestry/lepidopterology/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java index 075a6a142..8e71bd60c 100644 --- a/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java +++ b/src/main/java/forestry/lepidopterology/proxy/ProxyLepidopterologyClient.java @@ -19,6 +19,7 @@ import forestry.lepidopterology.entities.EntityButterfly; import forestry.lepidopterology.render.ModelButterflyItem; import forestry.lepidopterology.render.RenderButterflyEntity; +@SuppressWarnings("unused") public class ProxyLepidopterologyClient extends ProxyLepidopterology { @Override diff --git a/src/main/java/forestry/lepidopterology/proxy/package-info.java b/src/main/java/forestry/lepidopterology/proxy/package-info.java new file mode 100644 index 000000000..fdb1ed0e6 --- /dev/null +++ b/src/main/java/forestry/lepidopterology/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java b/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java index 4d17e2e4b..500d4094e 100644 --- a/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java +++ b/src/main/java/forestry/lepidopterology/recipes/MatingRecipe.java @@ -10,31 +10,35 @@ ******************************************************************************/ package forestry.lepidopterology.recipes; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.world.World; +import javax.annotation.Nullable; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IButterfly; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.IRecipe; +import net.minecraft.util.NonNullList; +import net.minecraft.world.World; +import net.minecraftforge.common.ForgeHooks; public class MatingRecipe implements IRecipe { private final ItemStack unknown; + @Nullable private ItemStack cached; - + public MatingRecipe() { unknown = ButterflyManager.butterflyRoot.getMemberStack(ButterflyManager.butterflyRoot.getIndividualTemplates().get(0), EnumFlutterType.BUTTERFLY); } - + @Override public boolean matches(InventoryCrafting crafting, World world) { - + boolean mated = true; int butterflies = 0; int sera = 0; - + for (int i = 0; i < crafting.getSizeInventory(); i++) { if (ButterflyManager.butterflyRoot.isMember(crafting.getStackInSlot(i), EnumFlutterType.BUTTERFLY)) { butterflies++; @@ -44,7 +48,7 @@ public class MatingRecipe implements IRecipe { sera++; } } - + return !mated && butterflies == 1 && sera == 1; } @@ -69,9 +73,9 @@ public class MatingRecipe implements IRecipe { } } if (butterfly == null || serum == null) { - return null; + return ItemStack.EMPTY; } - + IButterfly mated = butterfly.copy(); mated.mate(serum); return ButterflyManager.butterflyRoot.getMemberStack(mated, EnumFlutterType.BUTTERFLY); @@ -81,14 +85,14 @@ public class MatingRecipe implements IRecipe { public int getRecipeSize() { return 2; } - - @Override - public ItemStack[] getRemainingItems(InventoryCrafting inv) { - ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()]; - for (int i = 0; i < aitemstack.length; ++i) { + @Override + public NonNullList getRemainingItems(InventoryCrafting inv) { + NonNullList aitemstack = NonNullList.withSize(inv.getSizeInventory(), ItemStack.EMPTY); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { ItemStack itemstack = inv.getStackInSlot(i); - aitemstack[i] = net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack); + aitemstack.set(i, ForgeHooks.getContainerItem(itemstack)); } return aitemstack; } diff --git a/src/main/java/forestry/lepidopterology/recipes/package-info.java b/src/main/java/forestry/lepidopterology/recipes/package-info.java new file mode 100644 index 000000000..c1c3c11ff --- /dev/null +++ b/src/main/java/forestry/lepidopterology/recipes/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.recipes; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/render/ModelButterflyItem.java b/src/main/java/forestry/lepidopterology/render/ModelButterflyItem.java index 331d10f82..0adb90cde 100644 --- a/src/main/java/forestry/lepidopterology/render/ModelButterflyItem.java +++ b/src/main/java/forestry/lepidopterology/render/ModelButterflyItem.java @@ -10,14 +10,20 @@ ******************************************************************************/ package forestry.lepidopterology.render; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + import com.google.common.base.Function; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableMap; - -import java.util.Collections; -import java.util.concurrent.TimeUnit; - +import forestry.api.lepidopterology.ButterflyManager; +import forestry.api.lepidopterology.IAlleleButterflySpecies; +import forestry.api.lepidopterology.IButterfly; +import forestry.core.models.BlankModel; +import forestry.core.models.DefaultTextureGetter; +import forestry.core.models.TRSRBakedModel; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemOverrideList; import net.minecraft.client.renderer.block.model.ModelRotation; @@ -33,26 +39,21 @@ import net.minecraftforge.client.model.ModelLoaderRegistry; import net.minecraftforge.client.model.ModelProcessingHelper; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; -import forestry.api.lepidopterology.ButterflyManager; -import forestry.api.lepidopterology.IAlleleButterflySpecies; -import forestry.api.lepidopterology.IButterfly; -import forestry.core.models.BlankModel; -import forestry.core.models.DefaultTextureGetter; -import forestry.core.models.TRSRBakedModel; @SideOnly(Side.CLIENT) public class ModelButterflyItem extends BlankModel { private final Function textureGetter = new DefaultTextureGetter(); @SideOnly(Side.CLIENT) + @Nullable private static IModel modelButterfly; - + private static final Cache cache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(); - public static void onModelBake(ModelBakeEvent event){ + public static void onModelBake(ModelBakeEvent event) { modelButterfly = null; cache.invalidateAll(); } - + @Override protected ItemOverrideList createOverrides() { return new ButterflyItemOverrideList(); @@ -61,18 +62,18 @@ public class ModelButterflyItem extends BlankModel { private IBakedModel bakeModel(IButterfly butterfly) { ImmutableMap.Builder textures = ImmutableMap.builder(); textures.put("butterfly", butterfly.getGenome().getPrimary().getItemTexture()); - + if (modelButterfly == null) { try { modelButterfly = ModelLoaderRegistry.getModel(new ResourceLocation("forestry:item/butterflyGE")); } catch (Exception e) { - return null; + throw new IllegalArgumentException(e); } if (modelButterfly == null) { - return null; + throw new IllegalArgumentException("Could not bake butterfly model"); } } - IModel retexturedModel = ModelProcessingHelper.retexture(modelButterfly, textures.build()); + IModel retexturedModel = ModelProcessingHelper.retexture(modelButterfly, textures.build()); return new TRSRBakedModel(retexturedModel.bake(ModelRotation.X0_Y0, DefaultVertexFormats.ITEM, textureGetter), -0.03125F, 0.25F - butterfly.getSize() * 0.37F, -0.03125F, butterfly.getSize() * 1.5F); } @@ -82,14 +83,11 @@ public class ModelButterflyItem extends BlankModel { } @Override - public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity) { + public IBakedModel handleItemState(IBakedModel originalModel, ItemStack stack, @Nullable World world, @Nullable EntityLivingBase entity) { IButterfly butterfly = ButterflyManager.butterflyRoot.getMember(stack); - if (butterfly == null) { - butterfly = ButterflyManager.butterflyRoot.templateAsIndividual(ButterflyManager.butterflyRoot.getDefaultTemplate()); - } IAlleleButterflySpecies primary = butterfly.getGenome().getPrimary(); IBakedModel bakedModel = cache.getIfPresent(primary); - if(bakedModel == null){ + if (bakedModel == null) { bakedModel = bakeModel(butterfly); cache.put(primary, bakedModel); } diff --git a/src/main/java/forestry/lepidopterology/render/package-info.java b/src/main/java/forestry/lepidopterology/render/package-info.java new file mode 100644 index 000000000..d5f339a5f --- /dev/null +++ b/src/main/java/forestry/lepidopterology/render/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.render; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/tiles/TileCocoon.java b/src/main/java/forestry/lepidopterology/tiles/TileCocoon.java index fb2d92945..1875cbb13 100644 --- a/src/main/java/forestry/lepidopterology/tiles/TileCocoon.java +++ b/src/main/java/forestry/lepidopterology/tiles/TileCocoon.java @@ -10,23 +10,10 @@ ******************************************************************************/ package forestry.lepidopterology.tiles; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; -import forestry.core.owner.IOwnedTile; -import forestry.core.owner.IOwnerHandler; -import forestry.core.owner.OwnerHandler; -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.play.server.SPacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; - +import com.google.common.base.Preconditions; import forestry.api.genetics.IAllele; import forestry.api.greenhouse.GreenhouseManager; import forestry.api.lepidopterology.ButterflyManager; @@ -35,13 +22,15 @@ import forestry.api.lepidopterology.IButterflyCocoon; import forestry.api.lepidopterology.IButterflyGenome; import forestry.api.lepidopterology.IButterflyNursery; import forestry.api.multiblock.IGreenhouseComponent; +import forestry.api.multiblock.IGreenhouseComponent.ButterflyHatch; import forestry.api.multiblock.IGreenhouseController; import forestry.api.multiblock.IMultiblockComponent; -import forestry.api.multiblock.IGreenhouseComponent.ButterflyHatch; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.IStreamable; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.packets.PacketTileStream; +import forestry.core.owner.IOwnedTile; +import forestry.core.owner.IOwnerHandler; +import forestry.core.owner.OwnerHandler; import forestry.core.proxy.Proxies; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.Log; @@ -49,18 +38,30 @@ import forestry.core.utils.NBTUtilForestry; import forestry.greenhouse.multiblock.IGreenhouseControllerInternal; import forestry.lepidopterology.genetics.Butterfly; import forestry.lepidopterology.genetics.ButterflyDefinition; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.EntityLiving; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.play.server.SPacketUpdateTileEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.NonNullList; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, IButterflyCocoon { private final OwnerHandler ownerHandler = new OwnerHandler(); private int age; private int maturationTime; private IButterfly caterpillar = ButterflyDefinition.CabbageWhite.getIndividual(); + @Nullable private BlockPos nursery; private boolean isSolid; public TileCocoon() { } - + public TileCocoon(boolean isSolid) { this.isSolid = isSolid; if (isSolid) { @@ -89,17 +90,17 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I isSolid = nbttagcompound.getBoolean("isSolid"); } - @Nonnull + @Override public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); - if (caterpillar != null) { - NBTTagCompound subcompound = new NBTTagCompound(); - caterpillar.writeToNBT(subcompound); - nbttagcompound.setTag("Caterpillar", subcompound); - } + NBTTagCompound subcompound = new NBTTagCompound(); + caterpillar.writeToNBT(subcompound); + nbttagcompound.setTag("Caterpillar", subcompound); + ownerHandler.writeToNBT(nbttagcompound); + if (nursery != null) { BlockPos pos = nursery; NBTTagCompound nbt = new NBTTagCompound(); @@ -108,6 +109,7 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I nbt.setInteger("z", pos.getZ()); nbttagcompound.setTag("nursery", nbt); } + nbttagcompound.setInteger("Age", age); nbttagcompound.setInteger("CATMAT", maturationTime); nbttagcompound.setBoolean("isSolid", isSolid); @@ -115,19 +117,16 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - String speciesUID = ""; + public void writeData(PacketBufferForestry data) { IButterfly caterpillar = getCaterpillar(); - if (caterpillar != null) { - speciesUID = caterpillar.getIdent(); - } - data.writeUTF(speciesUID); + String speciesUID = caterpillar.getIdent(); + data.writeString(speciesUID); data.writeInt(age); } @Override - public void readData(DataInputStreamForestry data) throws IOException { - String speciesUID = data.readUTF(); + public void readData(PacketBufferForestry data) throws IOException { + String speciesUID = data.readString(); IButterfly caterpillar = getButterfly(speciesUID); setCaterpillar(caterpillar); age = data.readInt(); @@ -135,9 +134,7 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I private static IButterfly getButterfly(String speciesUID) { IAllele[] butterflyTemplate = ButterflyManager.butterflyRoot.getTemplate(speciesUID); - if (butterflyTemplate == null) { - return null; - } + Preconditions.checkNotNull(butterflyTemplate, "Could not find butterfly template for species: %s", speciesUID); return ButterflyManager.butterflyRoot.templateAsIndividual(butterflyTemplate); } @@ -158,7 +155,6 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I return new SPacketUpdateTileEntity(this.getPos(), 0, getUpdateTag()); } - @Nonnull @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = super.getUpdateTag(); @@ -166,11 +162,11 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I } @Override - public void handleUpdateTag(@Nonnull NBTTagCompound tag) { + public void handleUpdateTag(NBTTagCompound tag) { super.handleUpdateTag(tag); NBTUtilForestry.readStreamableFromNbt(this, tag); } - + @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { super.onDataPacket(net, pkt); @@ -179,11 +175,6 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I } public void onBlockTick() { - if (caterpillar == null) { - worldObj.setBlockToAir(getPos()); - return; - } - maturationTime++; IButterflyGenome caterpillarGenome = caterpillar.getGenome(); @@ -193,43 +184,46 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I if (age < 2) { age++; maturationTime = 0; - } else if (caterpillar.canTakeFlight(worldObj, getPos().getX(), getPos().getY(), getPos().getZ())) { - IGreenhouseComponent.ButterflyHatch hatch = getButterflyHatch(worldObj, pos); - ItemStack[] cocoonDrops; + } else if (caterpillar.canTakeFlight(world, getPos().getX(), getPos().getY(), getPos().getZ())) { + IGreenhouseComponent.ButterflyHatch hatch = getButterflyHatch(world, pos); + NonNullList cocoonDrops; if (hatch != null) { cocoonDrops = hatch.addCocoonLoot(this); } else { cocoonDrops = caterpillar.getCocoonDrop(this); } for (ItemStack drop : cocoonDrops) { - ItemStackUtil.dropItemStackAsEntity(drop, worldObj, pos); + ItemStackUtil.dropItemStackAsEntity(drop, world, pos); } - worldObj.setBlockToAir(getPos()); - attemptButterflySpawn(worldObj, caterpillar, getPos()); + world.setBlockToAir(getPos()); + attemptButterflySpawn(world, caterpillar, getPos()); } } } - + + @Nullable public ButterflyHatch getButterflyHatch(World world, BlockPos pos) { if (GreenhouseManager.greenhouseHelper == null || GreenhouseManager.greenhouseHelper.getGreenhouseController(world, pos) == null) { return null; } IGreenhouseController controller = GreenhouseManager.greenhouseHelper.getGreenhouseController(world, pos); - if(controller instanceof IGreenhouseControllerInternal){ - return ((IGreenhouseControllerInternal) controller).getButterflyHatch(); - } - for (IMultiblockComponent greenhouse : controller.getComponents()) { - if (greenhouse instanceof ButterflyHatch) { - return (ButterflyHatch) greenhouse; + if (controller != null) { + if (controller instanceof IGreenhouseControllerInternal) { + return ((IGreenhouseControllerInternal) controller).getButterflyHatch(); + } + + for (IMultiblockComponent greenhouse : controller.getComponents()) { + if (greenhouse instanceof ButterflyHatch) { + return (ButterflyHatch) greenhouse; + } } } return null; } - + private static void attemptButterflySpawn(World world, IButterfly butterfly, BlockPos pos) { - if (ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), pos.getX(), pos.getY() + 0.1f, pos.getZ()) != null) { - Log.trace("A caterpillar '%s' hatched at %s/%s/%s.", butterfly.getDisplayName(), pos.getX(), pos.getY(), pos.getZ()); - } + EntityLiving entityLiving = ButterflyManager.butterflyRoot.spawnButterflyInWorld(world, butterfly.copy(), pos.getX(), pos.getY() + 0.1f, pos.getZ()); + Log.trace("A caterpillar '%s' hatched at %s/%s/%s.", butterfly.getDisplayName(), pos.getX(), pos.getY(), pos.getZ()); } @Override @@ -243,14 +237,18 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I } @Override + @Nullable public IButterflyNursery getNursery() { - TileEntity nursery = worldObj.getTileEntity(this.nursery); + if (this.nursery == null) { + return null; + } + TileEntity nursery = world.getTileEntity(this.nursery); if (nursery instanceof IButterflyNursery) { return (IButterflyNursery) nursery; } return null; } - + @Override public void setNursery(IButterflyNursery nursery) { this.nursery = nursery.getCoordinates(); @@ -263,18 +261,18 @@ public class TileCocoon extends TileEntity implements IStreamable, IOwnedTile, I } private void sendNetworkUpdate() { - Proxies.net.sendNetworkPacket(new PacketTileStream(this), worldObj); + Proxies.net.sendNetworkPacket(new PacketTileStream(this), pos, world); } - + public int getAge() { return age; } - + public void setAge(int age) { this.age = age; } - - public ItemStack[] getCocoonDrops() { + + public NonNullList getCocoonDrops() { return caterpillar.getCocoonDrop(this); } diff --git a/src/main/java/forestry/lepidopterology/tiles/package-info.java b/src/main/java/forestry/lepidopterology/tiles/package-info.java new file mode 100644 index 000000000..39c110c4d --- /dev/null +++ b/src/main/java/forestry/lepidopterology/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/lepidopterology/worldgen/CocoonDecorator.java b/src/main/java/forestry/lepidopterology/worldgen/CocoonDecorator.java index 401ddceb0..473c77356 100644 --- a/src/main/java/forestry/lepidopterology/worldgen/CocoonDecorator.java +++ b/src/main/java/forestry/lepidopterology/worldgen/CocoonDecorator.java @@ -11,23 +11,9 @@ package forestry.lepidopterology.worldgen; import java.util.Collections; -import java.util.EnumSet; import java.util.List; import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.block.state.IBlockState; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.World; -import net.minecraft.world.biome.Biome; -import net.minecraft.world.chunk.IChunkGenerator; - -import net.minecraftforge.common.BiomeDictionary; -import net.minecraftforge.common.BiomeDictionary.Type; -import net.minecraftforge.common.util.EnumHelper; -import net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType; -import net.minecraftforge.event.terraingen.TerrainGen; +import java.util.Set; import forestry.api.lepidopterology.ButterflyManager; import forestry.api.lepidopterology.IButterfly; @@ -35,6 +21,18 @@ import forestry.core.config.Constants; import forestry.core.utils.BlockUtil; import forestry.lepidopterology.PluginLepidopterology; import forestry.lepidopterology.tiles.TileCocoon; +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import net.minecraft.world.biome.Biome; +import net.minecraft.world.chunk.IChunkGenerator; +import net.minecraftforge.common.BiomeDictionary; +import net.minecraftforge.common.BiomeDictionary.Type; +import net.minecraftforge.common.util.EnumHelper; +import net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType; +import net.minecraftforge.event.terraingen.TerrainGen; public abstract class CocoonDecorator { @@ -68,13 +66,13 @@ public abstract class CocoonDecorator { int worldZ = chunkZ * 16; Biome biome = world.getBiome(new BlockPos(worldX, 0, worldZ)); - - Type[] types = BiomeDictionary.getTypesForBiome(biome); - EnumSet speciesTypes = butterfly.getGenome().getPrimary().getSpawnBiomes(); + + Set types = BiomeDictionary.getTypes(biome); + Set speciesTypes = butterfly.getGenome().getPrimary().getSpawnBiomes(); boolean biomeTypesGood = false; for (Type type : types) { - if (speciesTypes == null || speciesTypes.size() <= 0 || speciesTypes.contains(type)) { + if (speciesTypes.isEmpty() || speciesTypes.contains(type)) { biomeTypesGood = true; } } @@ -120,7 +118,7 @@ public abstract class CocoonDecorator { if (!Block.isEqualTo(cocoonBlock, state.getBlock())) { return false; } - + TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileCocoon) { TileCocoon cocoon = (TileCocoon) tile; @@ -134,7 +132,7 @@ public abstract class CocoonDecorator { return true; } - + private static int getYForCocoon(World world, int x, int z) { int y = world.getHeight(new BlockPos(x, 0, z)).getY() - 1; BlockPos pos = new BlockPos(x, y, z); @@ -150,7 +148,7 @@ public abstract class CocoonDecorator { return y; } - + public static boolean isValidLocation(World world, BlockPos pos) { BlockPos posAbove = pos.up(); IBlockState blockStateAbove = world.getBlockState(posAbove); diff --git a/src/main/java/forestry/lepidopterology/worldgen/package-info.java b/src/main/java/forestry/lepidopterology/worldgen/package-info.java new file mode 100644 index 000000000..c3b8eeb5c --- /dev/null +++ b/src/main/java/forestry/lepidopterology/worldgen/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.lepidopterology.worldgen; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/EnumDeliveryState.java b/src/main/java/forestry/mail/EnumDeliveryState.java index 667afa60e..d84e870a2 100755 --- a/src/main/java/forestry/mail/EnumDeliveryState.java +++ b/src/main/java/forestry/mail/EnumDeliveryState.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.mail; -import javax.annotation.Nonnull; - import forestry.api.mail.IPostalState; import forestry.core.utils.Translator; @@ -25,7 +23,7 @@ public enum EnumDeliveryState implements IPostalState { private final String unlocalizedDescription; - EnumDeliveryState(@Nonnull String unlocalizedDescription) { + EnumDeliveryState(String unlocalizedDescription) { this.unlocalizedDescription = unlocalizedDescription; } diff --git a/src/main/java/forestry/mail/EventHandlerMailAlert.java b/src/main/java/forestry/mail/EventHandlerMailAlert.java index 1144284fb..439e55329 100644 --- a/src/main/java/forestry/mail/EventHandlerMailAlert.java +++ b/src/main/java/forestry/mail/EventHandlerMailAlert.java @@ -20,7 +20,7 @@ import net.minecraftforge.fml.common.gameevent.TickEvent.Phase; import forestry.core.proxy.Proxies; import forestry.mail.gui.GuiMailboxInfo; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; public class EventHandlerMailAlert { @SubscribeEvent @@ -29,7 +29,7 @@ public class EventHandlerMailAlert { return; } - if (Minecraft.getMinecraft().theWorld != null && GuiMailboxInfo.instance.hasPOBoxInfo()) { + if (Minecraft.getMinecraft().world != null && GuiMailboxInfo.instance.hasPOBoxInfo()) { GuiMailboxInfo.instance.render(); } } @@ -39,10 +39,8 @@ public class EventHandlerMailAlert { EntityPlayer player = event.player; if (player != null) { MailAddress address = new MailAddress(player.getGameProfile()); - POBox pobox = PostRegistry.getOrCreatePOBox(player.worldObj, address); - if (pobox != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); - } + POBox pobox = PostRegistry.getOrCreatePOBox(player.world, address); + Proxies.net.sendToPlayer(new PacketPOBoxInfoResponse(pobox.getPOBoxInfo()), player); } } } diff --git a/src/main/java/forestry/mail/Letter.java b/src/main/java/forestry/mail/Letter.java index 0fe91141b..fd2e20065 100755 --- a/src/main/java/forestry/mail/Letter.java +++ b/src/main/java/forestry/mail/Letter.java @@ -10,23 +10,22 @@ ******************************************************************************/ package forestry.mail; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.List; import java.util.Random; -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.text.ITextComponent; - import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; import forestry.api.mail.IStamps; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.InventoryUtil; import forestry.core.utils.Translator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; +import net.minecraft.util.text.ITextComponent; +import org.apache.commons.lang3.StringUtils; public class Letter implements ILetter { private static final Random rand = new Random(); @@ -38,27 +37,23 @@ public class Letter implements ILetter { private boolean isProcessed = false; private IMailAddress sender; - private IMailAddress[] recipient; + @Nullable + private IMailAddress recipient; - private String text; + private String text = ""; private final InventoryAdapter inventory = new InventoryAdapter(22, "INV"); private final String uid; public Letter(IMailAddress sender, IMailAddress recipient) { this.sender = sender; - this.recipient = new IMailAddress[]{recipient}; + this.recipient = recipient; this.uid = String.valueOf(rand.nextInt()); } - public Letter(@Nonnull NBTTagCompound nbttagcompound) { + public Letter(NBTTagCompound nbttagcompound) { this.isProcessed = nbttagcompound.getBoolean("PRC"); this.sender = new MailAddress(nbttagcompound.getCompoundTag("SDR")); - - int recipientCount = nbttagcompound.getShort("CRC"); - this.recipient = new MailAddress[recipientCount]; - for (int i = 0; i < recipientCount; i++) { - this.recipient[i] = new MailAddress(nbttagcompound.getCompoundTag("RC" + i)); - } + this.recipient = new MailAddress(nbttagcompound.getCompoundTag("RC")); this.text = nbttagcompound.getString("TXT"); this.uid = nbttagcompound.getString("UID"); @@ -74,11 +69,10 @@ public class Letter implements ILetter { this.sender.writeToNBT(subcompound); nbttagcompound.setTag("SDR", subcompound); - nbttagcompound.setShort("CRC", (short) recipient.length); - for (int i = 0; i < recipient.length; i++) { + if (this.recipient != null) { subcompound = new NBTTagCompound(); - this.recipient[i].writeToNBT(subcompound); - nbttagcompound.setTag("RC" + i, subcompound); + this.recipient.writeToNBT(subcompound); + nbttagcompound.setTag("RC", subcompound); } nbttagcompound.setString("TXT", this.text); @@ -88,12 +82,12 @@ public class Letter implements ILetter { } @Override - public ItemStack[] getPostage() { + public NonNullList getPostage() { return InventoryUtil.getStacks(inventory, SLOT_POSTAGE_1, SLOT_POSTAGE_COUNT); } @Override - public ItemStack[] getAttachments() { + public NonNullList getAttachments() { return InventoryUtil.getStacks(inventory, SLOT_ATTACHMENT_1, SLOT_ATTACHMENT_COUNT); } @@ -115,7 +109,7 @@ public class Letter implements ILetter { } @Override - public void addAttachments(ItemStack[] itemstacks) { + public void addAttachments(NonNullList itemstacks) { for (ItemStack stack : itemstacks) { addAttachment(stack); } @@ -124,7 +118,7 @@ public class Letter implements ILetter { @Override public void invalidatePostage() { for (int i = SLOT_POSTAGE_1; i < SLOT_POSTAGE_1 + SLOT_POSTAGE_COUNT; i++) { - inventory.setInventorySlotContents(i, null); + inventory.setInventorySlotContents(i, ItemStack.EMPTY); } } @@ -142,7 +136,7 @@ public class Letter implements ILetter { public boolean isMailable() { // Can't resend an already sent letter // Requires at least one recipient - return !isProcessed && recipient != null && recipient.length > 0; + return !isProcessed && recipient != null; } @Override @@ -158,7 +152,7 @@ public class Letter implements ILetter { continue; } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); } return posted >= requiredPostage(); @@ -184,16 +178,7 @@ public class Letter implements ILetter { @Override public boolean hasRecipient() { - if (getRecipients().length <= 0) { - return false; - } - - IMailAddress recipient = getRecipients()[0]; - if (recipient == null) { - return false; - } - - return !StringUtils.isBlank(recipient.getName()); + return recipient != null && !StringUtils.isBlank(recipient.getName()); } @Override @@ -207,30 +192,22 @@ public class Letter implements ILetter { } @Override - public void setRecipient(IMailAddress address) { - if (address == null) { - this.recipient = new IMailAddress[]{}; - } else { - this.recipient = new IMailAddress[]{address}; - } + public void setRecipient(@Nullable IMailAddress address) { + this.recipient = address; } @Override - public IMailAddress[] getRecipients() { + @Nullable + public IMailAddress getRecipient() { return recipient; } @Override public String getRecipientString() { - StringBuilder recipientString = new StringBuilder(); - for (IMailAddress address : recipient) { - if (recipientString.length() > 0) { - recipientString.append(", "); - } - recipientString.append(address.getName()); + if (recipient == null) { + return ""; } - - return recipientString.toString(); + return recipient.getName(); } @Override @@ -245,15 +222,20 @@ public class Letter implements ILetter { @Override public void addTooltip(List list) { - if (this.sender != null && StringUtils.isNotBlank(this.sender.getName())) { + if (StringUtils.isNotBlank(this.sender.getName())) { list.add(Translator.translateToLocal("for.gui.mail.from") + ": " + this.sender.getName()); } - if (this.recipient != null && this.recipient.length > 0) { + if (this.recipient != null) { list.add(Translator.translateToLocal("for.gui.mail.to") + ": " + this.getRecipientString()); } } // / IINVENTORY + @Override + public boolean isEmpty() { + return inventory.isEmpty(); + } + @Override public int getSizeInventory() { return inventory.getSizeInventory(); @@ -268,7 +250,7 @@ public class Letter implements ILetter { public ItemStack decrStackSize(int var1, int var2) { return inventory.decrStackSize(var1, var2); } - + @Override public ItemStack removeStackFromSlot(int index) { return inventory.removeStackFromSlot(index); @@ -295,7 +277,7 @@ public class Letter implements ILetter { } @Override - public boolean isUseableByPlayer(EntityPlayer var1) { + public boolean isUsableByPlayer(EntityPlayer var1) { return true; } diff --git a/src/main/java/forestry/mail/MailAddress.java b/src/main/java/forestry/mail/MailAddress.java index 11d878d15..7d6e541ad 100644 --- a/src/main/java/forestry/mail/MailAddress.java +++ b/src/main/java/forestry/mail/MailAddress.java @@ -10,26 +10,23 @@ ******************************************************************************/ package forestry.mail; -import javax.annotation.Nonnull; import java.util.Locale; import java.util.UUID; -import net.minecraft.nbt.NBTTagCompound; - +import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; - import forestry.api.core.INbtWritable; import forestry.api.mail.EnumAddressee; import forestry.api.mail.IMailAddress; import forestry.core.utils.PlayerUtil; +import net.minecraft.nbt.NBTTagCompound; +import org.apache.commons.lang3.StringUtils; public class MailAddress implements INbtWritable, IMailAddress { private static final GameProfile invalidGameProfile = new GameProfile(new UUID(0, 0), ""); - @Nonnull private final EnumAddressee type; - @Nonnull private final GameProfile gameProfile; // gameProfile is a fake GameProfile for traders, and real for players public MailAddress() { @@ -37,27 +34,24 @@ public class MailAddress implements INbtWritable, IMailAddress { this.gameProfile = invalidGameProfile; } - public MailAddress(@Nonnull GameProfile gameProfile) { - if (gameProfile == null) { - throw new IllegalArgumentException("gameProfile must not be null"); - } + public MailAddress(GameProfile gameProfile) { + Preconditions.checkNotNull(gameProfile, "gameProfile must not be null"); this.type = EnumAddressee.PLAYER; this.gameProfile = gameProfile; } - public MailAddress(@Nonnull String name) { - if (name == null) { - throw new IllegalArgumentException("name must not be null"); - } + public MailAddress(String name) { + Preconditions.checkNotNull(name, "name must not be null"); + Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not be blank"); this.type = EnumAddressee.TRADER; this.gameProfile = new GameProfile(null, name); } - public MailAddress(@Nonnull NBTTagCompound nbt) { + public MailAddress(NBTTagCompound nbt) { EnumAddressee type = null; - GameProfile gameProfile = null; + GameProfile gameProfile = invalidGameProfile; if (nbt.hasKey("TP")) { String typeName = nbt.getString("TP"); type = EnumAddressee.fromString(typeName); @@ -75,7 +69,6 @@ public class MailAddress implements INbtWritable, IMailAddress { this.gameProfile = gameProfile; } - @Nonnull @Override public EnumAddressee getType() { return type; @@ -90,7 +83,7 @@ public class MailAddress implements INbtWritable, IMailAddress { public boolean isValid() { return gameProfile.getName() != null && !PlayerUtil.isSameGameProfile(gameProfile, invalidGameProfile); } - + @Override public GameProfile getPlayerProfile() { if (this.type != EnumAddressee.PLAYER) { diff --git a/src/main/java/forestry/mail/POBox.java b/src/main/java/forestry/mail/POBox.java index 4edd957d2..be1c8e7df 100755 --- a/src/main/java/forestry/mail/POBox.java +++ b/src/main/java/forestry/mail/POBox.java @@ -10,6 +10,9 @@ ******************************************************************************/ package forestry.mail; +import javax.annotation.Nullable; + +import com.google.common.base.Preconditions; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; @@ -29,6 +32,7 @@ public class POBox extends WorldSavedData implements IInventory { public static final String SAVE_NAME = "POBox_"; public static final short SLOT_SIZE = 84; + @Nullable private IMailAddress address; private final InventoryAdapter letters = new InventoryAdapter(SLOT_SIZE, "Letters").disableAutomation(); @@ -40,6 +44,7 @@ public class POBox extends WorldSavedData implements IInventory { this.address = address; } + @SuppressWarnings("unused") public POBox(String savename) { super(savename); } @@ -65,6 +70,7 @@ public class POBox extends WorldSavedData implements IInventory { public boolean storeLetter(ItemStack letterstack) { ILetter letter = PostManager.postRegistry.getLetter(letterstack); + Preconditions.checkNotNull(letter, "Letter stack must be a valid letter"); // Mark letter as processed letter.setProcessed(true); @@ -82,14 +88,17 @@ public class POBox extends WorldSavedData implements IInventory { int playerLetters = 0; int tradeLetters = 0; for (int i = 0; i < letters.getSizeInventory(); i++) { - if (letters.getStackInSlot(i) == null) { + if (letters.getStackInSlot(i).isEmpty()) { continue; } - ILetter letter = new Letter(letters.getStackInSlot(i).getTagCompound()); - if (letter.getSender().getType() == EnumAddressee.PLAYER) { - playerLetters++; - } else { - tradeLetters++; + NBTTagCompound tagCompound = letters.getStackInSlot(i).getTagCompound(); + if (tagCompound != null) { + ILetter letter = new Letter(tagCompound); + if (letter.getSender().getType() == EnumAddressee.PLAYER) { + playerLetters++; + } else { + tradeLetters++; + } } } @@ -97,6 +106,12 @@ public class POBox extends WorldSavedData implements IInventory { } /* IINVENTORY */ + + @Override + public boolean isEmpty() { + return letters.isEmpty(); + } + @Override public void markDirty() { super.markDirty(); @@ -140,8 +155,8 @@ public class POBox extends WorldSavedData implements IInventory { } @Override - public boolean isUseableByPlayer(EntityPlayer var1) { - return letters.isUseableByPlayer(var1); + public boolean isUsableByPlayer(EntityPlayer var1) { + return letters.isUsableByPlayer(var1); } @Override diff --git a/src/main/java/forestry/mail/PluginMail.java b/src/main/java/forestry/mail/PluginMail.java index a8c48350d..9a130e991 100644 --- a/src/main/java/forestry/mail/PluginMail.java +++ b/src/main/java/forestry/mail/PluginMail.java @@ -10,13 +10,9 @@ ******************************************************************************/ package forestry.mail; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; +import javax.annotation.Nullable; +import com.google.common.base.Preconditions; import forestry.api.circuits.ICircuit; import forestry.api.mail.EnumAddressee; import forestry.api.mail.PostManager; @@ -31,6 +27,7 @@ import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.fluids.Fluids; import forestry.core.items.EnumElectronTube; +import forestry.core.items.ItemRegistryCore; import forestry.core.network.IPacketRegistry; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.OreDictUtil; @@ -42,10 +39,17 @@ import forestry.mail.network.PacketRegistryMail; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; @ForestryPlugin(pluginID = ForestryPluginUids.MAIL, name = "Mail", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.mail.description") public class PluginMail extends BlankForestryPlugin { + @Nullable public static ItemRegistryMail items; + @Nullable public static BlockRegistryMail blocks; @Override @@ -64,7 +68,7 @@ public class PluginMail extends BlankForestryPlugin { @Override public void preInit() { super.preInit(); - + PluginCore.rootCommand.addChildCommand(new CommandMail()); if (Config.mailAlertEnabled) { @@ -81,6 +85,7 @@ public class PluginMail extends BlankForestryPlugin { @Override public void doInit() { super.doInit(); + Preconditions.checkState(blocks != null); blocks.mailbox.init(); blocks.tradeStation.init(); @@ -94,6 +99,11 @@ public class PluginMail extends BlankForestryPlugin { @Override public void registerRecipes() { + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); + Preconditions.checkState(blocks != null); + Preconditions.checkState(items != null); + Object stampGlue; Object letterGlue; @@ -123,7 +133,7 @@ public class PluginMail extends BlankForestryPlugin { 'X', stampDefinition.getCraftingIngredient(), '#', Items.PAPER, 'Z', stampGlue); - RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEED_OIL.getFluid(300), null, stamps, + RecipeManagers.carpenterManager.addRecipe(10, Fluids.SEED_OIL.getFluid(300), ItemStack.EMPTY, stamps, "XXX", "###", 'X', stampDefinition.getCraftingIngredient(), @@ -135,7 +145,7 @@ public class PluginMail extends BlankForestryPlugin { RecipeUtil.addRecipe(new ItemStack(Items.PAPER), "###", '#', OreDictUtil.EMPTIED_LETTER_ORE_DICT); // Carpenter - RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 250), null, items.letters.getItemStack(), "###", "###", '#', PluginCore.items.woodPulp); + RecipeManagers.carpenterManager.addRecipe(10, new FluidStack(FluidRegistry.WATER, 250), ItemStack.EMPTY, items.letters.getItemStack(), "###", "###", '#', coreItems.woodPulp); RecipeUtil.addShapelessRecipe(items.catalogue.getItemStack(), items.stamps.getWildcard(), new ItemStack(Items.BOOK)); @@ -145,16 +155,16 @@ public class PluginMail extends BlankForestryPlugin { "XXX", '#', "ingotTin", 'X', "chestWood", - 'Y', PluginCore.items.sturdyCasing); + 'Y', coreItems.sturdyCasing); RecipeUtil.addRecipe(new ItemStack(blocks.tradeStation), "Z#Z", "#Y#", "XWX", - '#', PluginCore.items.tubes.get(EnumElectronTube.BRONZE, 1), + '#', coreItems.tubes.get(EnumElectronTube.BRONZE, 1), 'X', "chestWood", - 'Y', PluginCore.items.sturdyCasing, - 'Z', PluginCore.items.tubes.get(EnumElectronTube.IRON, 1), + 'Y', coreItems.sturdyCasing, + 'Z', coreItems.tubes.get(EnumElectronTube.IRON, 1), 'W', ItemCircuitBoard.createCircuitboard(EnumCircuitBoardType.REFINED, null, new ICircuit[]{})); } diff --git a/src/main/java/forestry/mail/PostOffice.java b/src/main/java/forestry/mail/PostOffice.java index 20471c1af..ddd27a483 100755 --- a/src/main/java/forestry/mail/PostOffice.java +++ b/src/main/java/forestry/mail/PostOffice.java @@ -15,6 +15,7 @@ import java.util.LinkedHashMap; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.NonNullList; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; @@ -34,12 +35,14 @@ public class PostOffice extends WorldSavedData implements IPostOffice { // / CONSTANTS public static final String SAVE_NAME = "ForestryMail"; private final int[] collectedPostage = new int[EnumPostage.values().length]; + private LinkedHashMap activeTradeStations = new LinkedHashMap<>(); // CONSTRUCTORS public PostOffice() { super(SAVE_NAME); } + @SuppressWarnings("unused") public PostOffice(String s) { super(s); } @@ -66,7 +69,6 @@ public class PostOffice extends WorldSavedData implements IPostOffice { } /* TRADE STATION MANAGMENT */ - private LinkedHashMap activeTradeStations; @Override public LinkedHashMap getActiveTradeStations(World world) { @@ -75,19 +77,18 @@ public class PostOffice extends WorldSavedData implements IPostOffice { private void refreshActiveTradeStations(World world) { activeTradeStations = new LinkedHashMap<>(); - if (world == null || world.getSaveHandler() == null) { - return; - } File worldSave = world.getSaveHandler().getMapFileFromName("dummy"); - if (worldSave == null) { - return; - } File file = worldSave.getParentFile(); if (!file.exists() || !file.isDirectory()) { return; } - for (String str : file.list()) { + String[] list = file.list(); + if (list == null) { + return; + } + + for (String str : list) { if (!str.startsWith(TradeStation.SAVE_NAME)) { continue; } @@ -140,13 +141,16 @@ public class PostOffice extends WorldSavedData implements IPostOffice { } } - return null; + return ItemStack.EMPTY; } // / DELIVERY @Override public IPostalState lodgeLetter(World world, ItemStack itemstack, boolean doLodge) { ILetter letter = PostManager.postRegistry.getLetter(itemstack); + if (letter == null) { + return EnumDeliveryState.NOT_MAILABLE; + } if (letter.isProcessed()) { return EnumDeliveryState.ALREADY_MAILED; @@ -161,14 +165,11 @@ public class PostOffice extends WorldSavedData implements IPostOffice { } IPostalState state = EnumDeliveryState.NOT_MAILABLE; - for (IMailAddress address : letter.getRecipients()) { + IMailAddress address = letter.getRecipient(); + if (address != null) { IPostalCarrier carrier = PostManager.postRegistry.getCarrier(address.getType()); - if (carrier == null) { - continue; - } - state = carrier.deliverLetter(world, this, address, itemstack, doLodge); - if (!state.isOk()) { - break; + if (carrier != null) { + state = carrier.deliverLetter(world, this, address, itemstack, doLodge); } } @@ -184,7 +185,7 @@ public class PostOffice extends WorldSavedData implements IPostOffice { } @Override - public void collectPostage(ItemStack[] stamps) { + public void collectPostage(NonNullList stamps) { for (ItemStack stamp : stamps) { if (stamp == null) { continue; @@ -192,7 +193,7 @@ public class PostOffice extends WorldSavedData implements IPostOffice { if (stamp.getItem() instanceof IStamps) { EnumPostage postage = ((IStamps) stamp.getItem()).getPostage(stamp); - collectedPostage[postage.ordinal()] += stamp.stackSize; + collectedPostage[postage.ordinal()] += stamp.getCount(); } } } diff --git a/src/main/java/forestry/mail/PostRegistry.java b/src/main/java/forestry/mail/PostRegistry.java index 917c7f8bb..15b17eed7 100755 --- a/src/main/java/forestry/mail/PostRegistry.java +++ b/src/main/java/forestry/mail/PostRegistry.java @@ -10,19 +10,13 @@ ******************************************************************************/ package forestry.mail; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; @@ -32,15 +26,22 @@ import forestry.api.mail.IPostalCarrier; import forestry.api.mail.ITradeStation; import forestry.api.mail.PostManager; import forestry.core.proxy.Proxies; +import forestry.core.utils.Log; import forestry.core.utils.PlayerUtil; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; public class PostRegistry implements IPostRegistry { - + @Nullable public static PostOffice cachedPostOffice; public static final Map cachedPOBoxes = new HashMap<>(); public static final Map cachedTradeStations = new HashMap<>(); + private final Map carriers = new EnumMap<>(EnumAddressee.class); + /** * @param world the Minecraft world the PO box will be in * @param address the potential address of the PO box @@ -51,13 +52,14 @@ public class PostRegistry implements IPostRegistry { return address.getType() == EnumAddressee.PLAYER && address.getName().matches("^[a-zA-Z0-9]+$"); } + @Nullable public static POBox getPOBox(World world, IMailAddress address) { if (cachedPOBoxes.containsKey(address)) { return cachedPOBoxes.get(address); } - POBox pobox = (POBox) world.loadItemData(POBox.class, POBox.SAVE_NAME + address); + POBox pobox = (POBox) world.loadData(POBox.class, POBox.SAVE_NAME + address); if (pobox != null) { cachedPOBoxes.put(address, pobox); } @@ -69,13 +71,13 @@ public class PostRegistry implements IPostRegistry { if (pobox == null) { pobox = new POBox(address); - world.setItemData(POBox.SAVE_NAME + address, pobox); + world.setData(POBox.SAVE_NAME + address, pobox); pobox.markDirty(); cachedPOBoxes.put(address, pobox); EntityPlayer player = PlayerUtil.getPlayer(world, address.getPlayerProfile()); if (player != null) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfoResponse(pobox.getPOBoxInfo()), player); } } @@ -89,7 +91,7 @@ public class PostRegistry implements IPostRegistry { */ @Override public boolean isValidTradeAddress(World world, IMailAddress address) { - return address != null && address.getType() == EnumAddressee.TRADER && address.getName().matches("^[a-zA-Z0-9]+$"); + return address.getType() == EnumAddressee.TRADER && address.getName().matches("^[a-zA-Z0-9]+$"); } /** @@ -99,20 +101,16 @@ public class PostRegistry implements IPostRegistry { */ @Override public boolean isAvailableTradeAddress(World world, IMailAddress address) { - return address != null && getTradeStation(world, address) == null; + return getTradeStation(world, address) == null; } @Override public TradeStation getTradeStation(World world, IMailAddress address) { - if (address == null || address.getName() == null) { - return null; - } - if (cachedTradeStations.containsKey(address)) { return (TradeStation) cachedTradeStations.get(address); } - TradeStation trade = (TradeStation) world.loadItemData(TradeStation.class, TradeStation.SAVE_NAME + address); + TradeStation trade = (TradeStation) world.loadData(TradeStation.class, TradeStation.SAVE_NAME + address); // Only existing and valid mail orders are returned if (trade != null && trade.isValid()) { @@ -130,7 +128,7 @@ public class PostRegistry implements IPostRegistry { if (trade == null) { trade = new TradeStation(owner, address); - world.setItemData(TradeStation.SAVE_NAME + address, trade); + world.setData(TradeStation.SAVE_NAME + address, trade); trade.markDirty(); cachedTradeStations.put(address, trade); getPostOffice(world).registerTradeStation(trade); @@ -151,7 +149,10 @@ public class PostRegistry implements IPostRegistry { cachedTradeStations.remove(address); getPostOffice(world).deregisterTradeStation(trade); File file = world.getSaveHandler().getMapFileFromName(trade.mapName); - file.delete(); + boolean delete = file.delete(); + if (!delete) { + Log.error("Failed to delete trade station file. {}", file); + } } @Override @@ -160,12 +161,12 @@ public class PostRegistry implements IPostRegistry { return cachedPostOffice; } - PostOffice office = (PostOffice) world.loadItemData(PostOffice.class, PostOffice.SAVE_NAME); + PostOffice office = (PostOffice) world.loadData(PostOffice.class, PostOffice.SAVE_NAME); // Create office if there is none yet if (office == null) { office = new PostOffice(); - world.setItemData(PostOffice.SAVE_NAME, office); + world.setData(PostOffice.SAVE_NAME, office); } office.setWorld(world); @@ -174,20 +175,18 @@ public class PostRegistry implements IPostRegistry { return office; } - @Nonnull + @Override - public IMailAddress getMailAddress(@Nonnull GameProfile gameProfile) { + public IMailAddress getMailAddress(GameProfile gameProfile) { return new MailAddress(gameProfile); } @Override - public IMailAddress getMailAddress(@Nonnull String traderName) { + public IMailAddress getMailAddress(String traderName) { return new MailAddress(traderName); } /* CARRIER */ - private final Map carriers = new EnumMap<>(EnumAddressee.class); - @Override public Map getRegisteredCarriers() { return carriers; @@ -221,8 +220,9 @@ public class PostRegistry implements IPostRegistry { } @Override + @Nullable public ILetter getLetter(ItemStack itemstack) { - if (itemstack == null) { + if (itemstack.isEmpty()) { return null; } @@ -239,6 +239,6 @@ public class PostRegistry implements IPostRegistry { @Override public boolean isLetter(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == PluginMail.items.letters; + return itemstack.getItem() == PluginMail.items.letters; } } diff --git a/src/main/java/forestry/mail/PostalCarrier.java b/src/main/java/forestry/mail/PostalCarrier.java index 08b330458..77e7734cf 100755 --- a/src/main/java/forestry/mail/PostalCarrier.java +++ b/src/main/java/forestry/mail/PostalCarrier.java @@ -30,7 +30,7 @@ import forestry.core.proxy.Proxies; import forestry.core.render.TextureManager; import forestry.core.utils.PlayerUtil; import forestry.core.utils.Translator; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; public class PostalCarrier implements IPostalCarrier { @@ -88,7 +88,7 @@ public class PostalCarrier implements IPostalCarrier { } else { EntityPlayer player = PlayerUtil.getPlayer(world, recipient.getPlayerProfile()); if (player instanceof EntityPlayerMP) { - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(pobox.getPOBoxInfo()), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfoResponse(pobox.getPOBoxInfo()), player); } } diff --git a/src/main/java/forestry/mail/ResponseNotMailable.java b/src/main/java/forestry/mail/ResponseNotMailable.java index 6139266df..e4ef67f95 100644 --- a/src/main/java/forestry/mail/ResponseNotMailable.java +++ b/src/main/java/forestry/mail/ResponseNotMailable.java @@ -1,15 +1,12 @@ package forestry.mail; -import javax.annotation.Nonnull; - import forestry.api.mail.IPostalState; import forestry.core.utils.Translator; public class ResponseNotMailable implements IPostalState { - @Nonnull private final IPostalState state; - public ResponseNotMailable(@Nonnull IPostalState state) { + public ResponseNotMailable(IPostalState state) { this.state = state; } diff --git a/src/main/java/forestry/mail/TradeStation.java b/src/main/java/forestry/mail/TradeStation.java index 6101235af..1c0d8960c 100755 --- a/src/main/java/forestry/mail/TradeStation.java +++ b/src/main/java/forestry/mail/TradeStation.java @@ -10,13 +10,12 @@ ******************************************************************************/ package forestry.mail; -import java.util.ArrayList; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; @@ -143,7 +142,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve @Override public TradeStationInfo getTradeInfo() { - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); + NonNullList condensedRequired = ItemStackUtil.condenseStacks(InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT)); // Set current state EnumTradeStationState state = EnumTradeStationState.OK; @@ -172,7 +171,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve public IPostalState handleLetter(World world, IMailAddress recipient, ItemStack letterstack, boolean doLodge) { boolean sendOwnerNotice = doLodge && owner != null; - + ILetter letter = PostManager.postRegistry.getLetter(letterstack); if (!isVirtual() && !hasPaper(sendOwnerNotice ? 2 : 1)) { @@ -303,7 +302,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve /* TRADE LOGIC */ private int countFillableOrders(int max, ItemStack tradegood) { - if (tradegood == null) { + if (tradegood.isEmpty()) { return 0; } @@ -312,7 +311,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_SEND_BUFFER, SLOT_SEND_BUFFER_COUNT)) { if (stack != null && stack.isItemEqual(tradegood) && ItemStack.areItemStackTagsEqual(stack, tradegood)) { - orderCount += stack.stackSize / (float) tradegood.stackSize; + orderCount += stack.getCount() / (float) tradegood.getCount(); if (orderCount >= max) { return max; } @@ -324,12 +323,12 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve public boolean canReceivePayment() { InventoryAdapter test = inventory.copy(); - ItemStack[] payment = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); + NonNullList payment = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); return InventoryUtil.tryAddStacksCopy(test, payment, SLOT_RECEIVE_BUFFER, SLOT_RECEIVE_BUFFER_COUNT, true); } - private int countStorablePayment(int max, ItemStack[] exchange) { + private int countStorablePayment(int max, NonNullList exchange) { InventoryAdapter test = inventory.copy(); int count = 0; @@ -348,26 +347,20 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve private void removeTradegood(int filled) { for (int j = 0; j < filled; j++) { - int toRemove = inventory.getStackInSlot(SLOT_TRADEGOOD).stackSize; + int toRemove = inventory.getStackInSlot(SLOT_TRADEGOOD).getCount(); for (int i = SLOT_SEND_BUFFER; i < SLOT_SEND_BUFFER + SLOT_SEND_BUFFER_COUNT; i++) { ItemStack buffer = inventory.getStackInSlot(i); - if (buffer == null) { - continue; - } - if (!buffer.isItemEqual(inventory.getStackInSlot(SLOT_TRADEGOOD))) { - continue; - } + if (!buffer.isEmpty() && + buffer.isItemEqual(inventory.getStackInSlot(SLOT_TRADEGOOD)) && + ItemStack.areItemStackTagsEqual(buffer, inventory.getStackInSlot(SLOT_TRADEGOOD))) { - if (!ItemStack.areItemStackTagsEqual(buffer, inventory.getStackInSlot(SLOT_TRADEGOOD))) { - continue; - } + ItemStack decrease = inventory.decrStackSize(i, toRemove); + toRemove -= decrease.getCount(); - ItemStack decrease = inventory.decrStackSize(i, toRemove); - toRemove -= decrease.stackSize; - - if (toRemove <= 0) { - break; + if (toRemove <= 0) { + break; + } } } } @@ -380,7 +373,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve for (ItemStack stack : InventoryUtil.getStacks(inventory, SLOT_LETTERS_1, SLOT_LETTERS_COUNT)) { if (stack != null) { - amountFound += stack.stackSize; + amountFound += stack.getCount(); } if (amountFound >= amountRequired) { @@ -395,7 +388,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve private void removePaper() { for (int i = SLOT_LETTERS_1; i < SLOT_LETTERS_1 + SLOT_LETTERS_COUNT; i++) { ItemStack stack = inventory.getStackInSlot(i); - if (stack != null && stack.getItem() == Items.PAPER && stack.stackSize > 0) { + if (stack.getItem() == Items.PAPER) { inventory.decrStackSize(i, 1); break; } @@ -414,7 +407,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve continue; } - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); if (posted >= postage) { return true; @@ -480,7 +473,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve } if (((IStamps) stamp.getItem()).getPostage(stamp) == postage) { - count += stamp.stackSize; + count += stamp.getCount(); } } @@ -501,7 +494,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve } ItemStack stamp = inventory.getStackInSlot(j); - if (stamp == null) { + if (stamp.isEmpty()) { continue; } @@ -511,43 +504,44 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve if (((IStamps) stamp.getItem()).getPostage(stamp) == EnumPostage.values()[i]) { ItemStack decrease = inventory.decrStackSize(j, stampCount[i]); - stampCount[i] -= decrease.stackSize; + stampCount[i] -= decrease.getCount(); } } } } - private ItemStack[] getSurplusAttachments(int filled, ItemStack[] attachments) { - ArrayList surplus = new ArrayList<>(); + private NonNullList getSurplusAttachments(int filled, NonNullList attachments) { + NonNullList surplus = NonNullList.create(); // Get a copy of the attachments to play with - ItemStack[] pool = new ItemStack[attachments.length]; - for (int i = 0; i < attachments.length; i++) { - if (attachments[i] != null) { - pool[i] = attachments[i].copy(); + NonNullList pool = NonNullList.withSize(attachments.size(), ItemStack.EMPTY); + for (int i = 0; i < attachments.size(); i++) { + ItemStack attachment = attachments.get(i); + if (!attachment.isEmpty()) { + pool.set(i, attachment.copy()); } } // Remove stuff until we are only left with the remnants for (int i = 0; i < filled; i++) { - ItemStack[] required = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); - ItemStack[] condensedRequired = ItemStackUtil.condenseStacks(required); + NonNullList required = InventoryUtil.getStacks(inventory, SLOT_EXCHANGE_1, SLOT_EXCHANGE_COUNT); + NonNullList condensedRequired = ItemStackUtil.condenseStacks(required); for (ItemStack req : condensedRequired) { - for (int j = 0; j < pool.length; j++) { - ItemStack pol = pool[j]; - if (pol == null) { + for (int j = 0; j < pool.size(); j++) { + ItemStack pol = pool.get(j); + if (pol.isEmpty()) { continue; } if (!pol.isItemEqual(req)) { continue; } - if (req.stackSize >= pol.stackSize) { - req.stackSize -= pol.stackSize; - pool[j] = null; + if (req.getCount() >= pol.getCount()) { + req.shrink(pol.getCount()); + pool.set(j, ItemStack.EMPTY); } else { - pol.stackSize -= req.stackSize; - req.stackSize = 0; + pol.shrink(req.getCount()); + req.setCount(0); } } } @@ -559,10 +553,16 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve } } - return surplus.toArray(new ItemStack[surplus.size()]); + return surplus; } /* IINVENTORY */ + + @Override + public boolean isEmpty() { + return inventory.isEmpty(); + } + @Override public void markDirty() { super.markDirty(); @@ -606,7 +606,7 @@ public class TradeStation extends WorldSavedData implements ITradeStation, IInve } @Override - public boolean isUseableByPlayer(EntityPlayer player) { + public boolean isUsableByPlayer(EntityPlayer player) { return true; } diff --git a/src/main/java/forestry/mail/TradeStationInfo.java b/src/main/java/forestry/mail/TradeStationInfo.java index 25573fdf3..030bcb618 100644 --- a/src/main/java/forestry/mail/TradeStationInfo.java +++ b/src/main/java/forestry/mail/TradeStationInfo.java @@ -18,15 +18,16 @@ import forestry.api.mail.EnumAddressee; import forestry.api.mail.EnumTradeStationState; import forestry.api.mail.IMailAddress; import forestry.api.mail.ITradeStationInfo; +import net.minecraft.util.NonNullList; public class TradeStationInfo implements ITradeStationInfo { private final IMailAddress address; private final GameProfile owner; private final ItemStack tradegood; - private final ItemStack[] required; + private final NonNullList required; private final EnumTradeStationState state; - public TradeStationInfo(IMailAddress address, GameProfile owner, ItemStack tradegood, ItemStack[] required, EnumTradeStationState state) { + public TradeStationInfo(IMailAddress address, GameProfile owner, ItemStack tradegood, NonNullList required, EnumTradeStationState state) { if (address.getType() != EnumAddressee.TRADER) { throw new IllegalArgumentException("TradeStation address must be a trader"); } @@ -53,7 +54,7 @@ public class TradeStationInfo implements ITradeStationInfo { } @Override - public ItemStack[] getRequired() { + public NonNullList getRequired() { return required; } diff --git a/src/main/java/forestry/mail/blocks/BlockTypeMail.java b/src/main/java/forestry/mail/blocks/BlockTypeMail.java index 8576170ea..4d5c55e8c 100644 --- a/src/main/java/forestry/mail/blocks/BlockTypeMail.java +++ b/src/main/java/forestry/mail/blocks/BlockTypeMail.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.mail.blocks; -import javax.annotation.Nonnull; - import forestry.core.blocks.IBlockType; import forestry.core.blocks.IMachineProperties; import forestry.core.blocks.MachineProperties; @@ -27,14 +25,12 @@ public enum BlockTypeMail implements IBlockType { public static final BlockTypeMail[] VALUES = values(); - @Nonnull private final IMachineProperties machineProperties; - BlockTypeMail(@Nonnull Class teClass, @Nonnull String name) { + BlockTypeMail(Class teClass, String name) { this.machineProperties = new MachineProperties<>(teClass, name); } - @Nonnull @Override public IMachineProperties getMachineProperties() { return machineProperties; diff --git a/src/main/java/forestry/mail/blocks/package-info.java b/src/main/java/forestry/mail/blocks/package-info.java new file mode 100644 index 000000000..fd55c940a --- /dev/null +++ b/src/main/java/forestry/mail/blocks/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.blocks; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/commands/CommandMail.java b/src/main/java/forestry/mail/commands/CommandMail.java index 9670e75ed..b4859282a 100644 --- a/src/main/java/forestry/mail/commands/CommandMail.java +++ b/src/main/java/forestry/mail/commands/CommandMail.java @@ -53,7 +53,7 @@ public class CommandMail extends SubCommand { if (!(sender instanceof EntityPlayer)) { return; } - for (ITradeStation trade : PostManager.postRegistry.getPostOffice(((EntityPlayer) sender).worldObj).getActiveTradeStations(((EntityPlayer) sender).worldObj).values()) { + for (ITradeStation trade : PostManager.postRegistry.getPostOffice(((EntityPlayer) sender).world).getActiveTradeStations(((EntityPlayer) sender).world).values()) { CommandHelpers.sendChatMessage(sender, makeTradeListEntry(trade.getTradeInfo())); } } @@ -62,14 +62,14 @@ public class CommandMail extends SubCommand { TextFormatting formatting = info.getState().isOk() ? TextFormatting.GREEN : TextFormatting.RED; String tradegood = "[ ? ]"; - if (info.getTradegood() != null) { - tradegood = info.getTradegood().stackSize + "x" + info.getTradegood().getDisplayName(); + if (!info.getTradegood().isEmpty()) { + tradegood = info.getTradegood().getCount() + "x" + info.getTradegood().getDisplayName(); } String demand = "[ ? ]"; - if (info.getRequired().length > 0) { + if (!info.getRequired().isEmpty()) { demand = ""; for (ItemStack dmd : info.getRequired()) { - demand = StringUtil.append(", ", demand, dmd.stackSize + "x" + dmd.getDisplayName()); + demand = StringUtil.append(", ", demand, dmd.getCount() + "x" + dmd.getDisplayName()); } } diff --git a/src/main/java/forestry/mail/commands/package-info.java b/src/main/java/forestry/mail/commands/package-info.java new file mode 100644 index 000000000..d0f2e1baf --- /dev/null +++ b/src/main/java/forestry/mail/commands/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.commands; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/compat/MailJeiPlugin.java b/src/main/java/forestry/mail/compat/MailJeiPlugin.java index 938d97620..cd0f408e7 100644 --- a/src/main/java/forestry/mail/compat/MailJeiPlugin.java +++ b/src/main/java/forestry/mail/compat/MailJeiPlugin.java @@ -1,7 +1,5 @@ package forestry.mail.compat; -import javax.annotation.Nonnull; - import forestry.core.utils.JeiUtil; import forestry.mail.PluginMail; import forestry.mail.blocks.BlockRegistryMail; @@ -12,7 +10,7 @@ import mezz.jei.api.JEIPlugin; @JEIPlugin public class MailJeiPlugin extends BlankModPlugin { @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { BlockRegistryMail blocks = PluginMail.blocks; JeiUtil.addDescription(registry, blocks.mailbox, diff --git a/src/main/java/forestry/mail/compat/package-info.java b/src/main/java/forestry/mail/compat/package-info.java new file mode 100644 index 000000000..c0ffcc476 --- /dev/null +++ b/src/main/java/forestry/mail/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java b/src/main/java/forestry/mail/gui/AddresseeSlot.java similarity index 94% rename from src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java rename to src/main/java/forestry/mail/gui/AddresseeSlot.java index f7219ec34..6e46f4a05 100644 --- a/src/main/java/forestry/mail/gui/widgets/AddresseeSlot.java +++ b/src/main/java/forestry/mail/gui/AddresseeSlot.java @@ -1,60 +1,59 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.mail.gui.widgets; - -import forestry.api.mail.IPostalCarrier; -import forestry.api.mail.PostManager; -import forestry.core.gui.tooltips.ToolTip; -import forestry.core.gui.widgets.Widget; -import forestry.core.gui.widgets.WidgetManager; -import forestry.core.proxy.Proxies; -import forestry.core.render.TextureManager; -import forestry.core.utils.Translator; -import forestry.mail.gui.ContainerLetter; -import net.minecraft.client.renderer.GlStateManager; - -public class AddresseeSlot extends Widget { - - private final ContainerLetter containerLetter; - - public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, ContainerLetter containerLetter) { - super(widgetManager, xPos, yPos); - this.containerLetter = containerLetter; - this.width = 26; - this.height = 15; - } - - @Override - public void draw(int startX, int startY) { - IPostalCarrier carrier = PostManager.postRegistry.getCarrier(containerLetter.getCarrierType()); - if (carrier != null) { - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0F); - Proxies.render.bindTexture(TextureManager.getInstance().getGuiTextureMap()); - manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, carrier.getSprite(), 32, 32); - } - } - - @Override - public ToolTip getToolTip(int mouseX, int mouseY) { - String tooltipString = Translator.translateToLocal("for.gui.addressee." + containerLetter.getCarrierType()); - ToolTip tooltip = new ToolTip(); - tooltip.add(tooltipString); - return tooltip; - } - - @Override - public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { - if (!containerLetter.getLetter().isProcessed()) { - containerLetter.advanceCarrierType(); - Proxies.common.playButtonClick(); - } - } -} +/******************************************************************************* + * Copyright (c) 2011-2014 SirSengir. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser Public License v3 + * which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl-3.0.txt + * + * Various Contributors including, but not limited to: + * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges + ******************************************************************************/ +package forestry.mail.gui; + +import forestry.api.mail.IPostalCarrier; +import forestry.api.mail.PostManager; +import forestry.core.gui.tooltips.ToolTip; +import forestry.core.gui.widgets.Widget; +import forestry.core.gui.widgets.WidgetManager; +import forestry.core.proxy.Proxies; +import forestry.core.render.TextureManager; +import forestry.core.utils.Translator; +import net.minecraft.client.renderer.GlStateManager; + +public class AddresseeSlot extends Widget { + + private final ContainerLetter containerLetter; + + public AddresseeSlot(WidgetManager widgetManager, int xPos, int yPos, ContainerLetter containerLetter) { + super(widgetManager, xPos, yPos); + this.containerLetter = containerLetter; + this.width = 26; + this.height = 15; + } + + @Override + public void draw(int startX, int startY) { + IPostalCarrier carrier = PostManager.postRegistry.getCarrier(containerLetter.getCarrierType()); + if (carrier != null) { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0F); + Proxies.render.bindTexture(TextureManager.getInstance().getGuiTextureMap()); + manager.gui.drawTexturedModalRect(startX + xPos, startY + yPos, carrier.getSprite(), 32, 32); + } + } + + @Override + public ToolTip getToolTip(int mouseX, int mouseY) { + String tooltipString = Translator.translateToLocal("for.gui.addressee." + containerLetter.getCarrierType()); + ToolTip tooltip = new ToolTip(); + tooltip.add(tooltipString); + return tooltip; + } + + @Override + public void handleMouseClick(int mouseX, int mouseY, int mouseButton) { + if (!containerLetter.getLetter().isProcessed()) { + containerLetter.advanceCarrierType(); + Proxies.common.playButtonClick(); + } + } +} diff --git a/src/main/java/forestry/mail/gui/ContainerCatalogue.java b/src/main/java/forestry/mail/gui/ContainerCatalogue.java index 6b112a37d..ceaacb835 100755 --- a/src/main/java/forestry/mail/gui/ContainerCatalogue.java +++ b/src/main/java/forestry/mail/gui/ContainerCatalogue.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; @@ -40,6 +41,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe private final EntityPlayer player; private final List stations = new ArrayList<>(); + @Nullable private ITradeStationInfo currentTrade = null; private int stationIndex = 0; @@ -67,7 +69,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe public ContainerCatalogue(EntityPlayer player) { this.player = player; - if (!player.worldObj.isRemote) { + if (!player.world.isRemote) { rebuildStationsList(); } } @@ -87,14 +89,14 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe private void rebuildStationsList() { stations.clear(); - IPostOffice postOffice = PostManager.postRegistry.getPostOffice(player.worldObj); - Map tradeStations = postOffice.getActiveTradeStations(player.worldObj); + IPostOffice postOffice = PostManager.postRegistry.getPostOffice(player.world); + Map tradeStations = postOffice.getActiveTradeStations(player.world); for (ITradeStation station : tradeStations.values()) { ITradeStationInfo info = station.getTradeInfo(); // Filter out any trade stations which do not actually offer anything. - if (info.getTradegood() != null && FILTERS.get(currentFilter).contains(info.getState())) { + if (FILTERS.get(currentFilter).contains(info.getState())) { stations.add(station); } } @@ -104,7 +106,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe } public void nextPage() { - if (player.worldObj.isRemote) { + if (player.world.isRemote) { sendSelection(true); return; } @@ -117,7 +119,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe } public void previousPage() { - if (player.worldObj.isRemote) { + if (player.world.isRemote) { sendSelection(false); return; } @@ -130,7 +132,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe } public void cycleFilter() { - if (player.worldObj.isRemote) { + if (player.world.isRemote) { Proxies.net.sendToServer(new PacketGuiSelectRequest(2, 0)); return; } @@ -148,7 +150,7 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe /* Managing Trade info */ private void updateTradeInfo() { // Updating is done by the server. - if (player.worldObj.isRemote) { + if (player.world.isRemote) { return; } @@ -162,15 +164,16 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe } @Override - public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { - setTradeInfo(packet.tradeInfo); + public void handleLetterInfoUpdate(EnumAddressee type, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo) { + setTradeInfo(tradeInfo); } + @Nullable public ITradeStationInfo getTradeInfo() { return currentTrade; } - private void setTradeInfo(ITradeStationInfo info) { + private void setTradeInfo(@Nullable ITradeStationInfo info) { currentTrade = info; } @@ -211,9 +214,9 @@ public class ContainerCatalogue extends Container implements IGuiSelectable, ILe } @Override - public void handleSelectionRequest(EntityPlayerMP player, PacketGuiSelectRequest packet) { + public void handleSelectionRequest(EntityPlayerMP player, int primary, int secondary) { - switch (packet.getPrimaryIndex()) { + switch (primary) { case 0: nextPage(); break; diff --git a/src/main/java/forestry/mail/gui/ContainerLetter.java b/src/main/java/forestry/mail/gui/ContainerLetter.java index 4cc7be3ed..578825c98 100755 --- a/src/main/java/forestry/mail/gui/ContainerLetter.java +++ b/src/main/java/forestry/mail/gui/ContainerLetter.java @@ -13,6 +13,7 @@ package forestry.mail.gui; import javax.annotation.Nullable; import java.util.Iterator; +import forestry.core.utils.Log; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; @@ -28,7 +29,6 @@ import forestry.api.mail.ITradeStationInfo; import forestry.api.mail.PostManager; import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.slots.SlotFiltered; -import forestry.core.network.packets.PacketString; import forestry.core.proxy.Proxies; import forestry.mail.Letter; import forestry.mail.inventory.ItemInventoryLetter; @@ -38,6 +38,7 @@ import forestry.mail.network.packets.PacketLetterTextSet; public class ContainerLetter extends ContainerItemInventory implements ILetterInfoReceiver { private EnumAddressee carrierType = EnumAddressee.PLAYER; + @Nullable private ITradeStationInfo tradeInfo = null; public ContainerLetter(EntityPlayer player, ItemInventoryLetter inventory) { @@ -58,7 +59,7 @@ public class ContainerLetter extends ContainerItemInventory } // Rip open delivered mails - if (!player.worldObj.isRemote) { + if (!player.world.isRemote) { if (inventory.getLetter().isProcessed()) { inventory.onLetterOpened(); } @@ -67,9 +68,9 @@ public class ContainerLetter extends ContainerItemInventory // Set recipient type ILetter letter = inventory.getLetter(); if (letter != null) { - IMailAddress[] recipients = letter.getRecipients(); - if (recipients != null && recipients.length > 0) { - this.carrierType = recipients[0].getType(); + IMailAddress recipient = letter.getRecipient(); + if (recipient != null) { + this.carrierType = recipient.getType(); } } } @@ -77,7 +78,7 @@ public class ContainerLetter extends ContainerItemInventory @Override public void onContainerClosed(EntityPlayer entityplayer) { - if (!entityplayer.worldObj.isRemote) { + if (!entityplayer.world.isRemote) { ILetter letter = inventory.getLetter(); if (!letter.isProcessed()) { IMailAddress sender = PostManager.postRegistry.getMailAddress(entityplayer.getGameProfile()); @@ -121,13 +122,18 @@ public class ContainerLetter extends ContainerItemInventory } public void handleRequestLetterInfo(EntityPlayer player, String recipientName, EnumAddressee type) { - IMailAddress recipient = getRecipient(player.getServer(), recipientName, type); + MinecraftServer server = player.getServer(); + if (server == null) { + Log.error("Could not get server"); + return; + } + IMailAddress recipient = getRecipient(server, recipientName, type); getLetter().setRecipient(recipient); // Update the trading info if (recipient == null || recipient.getType() == EnumAddressee.TRADER) { - updateTradeInfo(player.worldObj, recipient); + updateTradeInfo(player.world, recipient); } // Update info on client @@ -152,12 +158,9 @@ public class ContainerLetter extends ContainerItemInventory } } + @Nullable public IMailAddress getRecipient() { - if (getLetter().getRecipients().length > 0) { - return getLetter().getRecipients()[0]; - } else { - return null; - } + return getLetter().getRecipient(); } public String getText() { @@ -170,13 +173,12 @@ public class ContainerLetter extends ContainerItemInventory Proxies.net.sendToServer(new PacketLetterTextSet(text)); } - public void handleSetText(PacketString packet) { - String text = packet.getString(); + public void handleSetText(String text) { getLetter().setText(text); } /* Managing Trade info */ - private void updateTradeInfo(World world, IMailAddress address) { + private void updateTradeInfo(World world, @Nullable IMailAddress address) { // Updating is done by the server. if (world.isRemote) { return; @@ -197,20 +199,21 @@ public class ContainerLetter extends ContainerItemInventory } @Override - public void handleLetterInfoUpdate(PacketLetterInfoResponse packet) { - carrierType = packet.type; - if (packet.type == EnumAddressee.PLAYER) { - getLetter().setRecipient(packet.address); - } else if (packet.type == EnumAddressee.TRADER) { - this.setTradeInfo(packet.tradeInfo); + public void handleLetterInfoUpdate(EnumAddressee type, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo) { + carrierType = type; + if (type == EnumAddressee.PLAYER) { + getLetter().setRecipient(address); + } else if (type == EnumAddressee.TRADER) { + this.setTradeInfo(tradeInfo); } } + @Nullable public ITradeStationInfo getTradeInfo() { return this.tradeInfo; } - private void setTradeInfo(ITradeStationInfo info) { + private void setTradeInfo(@Nullable ITradeStationInfo info) { this.tradeInfo = info; if (tradeInfo == null) { getLetter().setRecipient(null); diff --git a/src/main/java/forestry/mail/gui/ContainerMailbox.java b/src/main/java/forestry/mail/gui/ContainerMailbox.java index cc3ec7de3..2b1b75b86 100755 --- a/src/main/java/forestry/mail/gui/ContainerMailbox.java +++ b/src/main/java/forestry/mail/gui/ContainerMailbox.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.mail.gui; +import javax.annotation.Nullable; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ClickType; @@ -22,19 +24,19 @@ import forestry.core.proxy.Proxies; import forestry.core.utils.SlotUtil; import forestry.mail.POBox; import forestry.mail.POBoxInfo; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; import forestry.mail.tiles.TileMailbox; public class ContainerMailbox extends ContainerTile { public static final short SLOT_LETTERS = 0; public static final short SLOT_LETTERS_COUNT = 7 * 12; - + @Nullable private final POBox mailInventory; public ContainerMailbox(InventoryPlayer playerInventory, TileMailbox tile) { super(tile, playerInventory, 35, 145); - IInventory inventory = tile.getOrCreateMailInventory(playerInventory.player.worldObj, playerInventory.player.getGameProfile()); + IInventory inventory = tile.getOrCreateMailInventory(playerInventory.player.world, playerInventory.player.getGameProfile()); if (inventory instanceof POBox) { this.mailInventory = (POBox) inventory; @@ -54,9 +56,9 @@ public class ContainerMailbox extends ContainerTile { ItemStack stack = super.slotClick(slotId, dragType_or_button, clickTypeIn, player); if (SlotUtil.isSlotInRange(slotId, SLOT_LETTERS, SLOT_LETTERS_COUNT)) { - if (!player.worldObj.isRemote && mailInventory != null) { + if (!player.world.isRemote && mailInventory != null) { POBoxInfo info = mailInventory.getPOBoxInfo(); - Proxies.net.sendToPlayer(new PacketPOBoxInfoUpdate(info), player); + Proxies.net.sendToPlayer(new PacketPOBoxInfoResponse(info), player); } } diff --git a/src/main/java/forestry/mail/gui/GuiCatalogue.java b/src/main/java/forestry/mail/gui/GuiCatalogue.java index 2eca3985c..3d4c8a54d 100755 --- a/src/main/java/forestry/mail/gui/GuiCatalogue.java +++ b/src/main/java/forestry/mail/gui/GuiCatalogue.java @@ -44,6 +44,9 @@ public class GuiCatalogue extends GuiForestry { super(new ResourceLocation("textures/gui/book.png"), new ContainerCatalogue(player), null); this.xSize = 192; this.ySize = 192; + + buttonFilter = new GuiButton(4, width / 2 - 44, guiTop + 150, 42, 20, Translator.translateToLocal("for.gui.mail.filter.all")); + buttonUse = new GuiButton(5, width / 2, guiTop + 150, 42, 20, Translator.translateToLocal("for.gui.mail.address.copy")); } @Override @@ -104,8 +107,8 @@ public class GuiCatalogue extends GuiForestry { fontRendererObj.drawString(Translator.translateToLocal("for.gui.mail.tradefor"), x, y + 46, ColourProperties.INSTANCE.get("gui.book")); - for (int i = 0; i < tradeInfo.getRequired().length; i++) { - ItemStack itemStack = tradeInfo.getRequired()[i]; + for (int i = 0; i < tradeInfo.getRequired().size(); i++) { + ItemStack itemStack = tradeInfo.getRequired().get(i); addTradeInfoWidget(new ItemStackWidget(widgetManager, x - guiLeft + i * 18, y - guiTop + 56, itemStack)); } @@ -132,7 +135,7 @@ public class GuiCatalogue extends GuiForestry { protected void actionPerformed(GuiButton button) { switch (button.id) { case 0: - mc.thePlayer.closeScreen(); + mc.player.closeScreen(); break; case 2: container.nextPage(); @@ -149,7 +152,7 @@ public class GuiCatalogue extends GuiForestry { SessionVars.setStringVar("mail.letter.recipient", info.getAddress().getName()); SessionVars.setStringVar("mail.letter.addressee", EnumAddressee.TRADER.toString()); } - mc.thePlayer.closeScreen(); + mc.player.closeScreen(); break; } } diff --git a/src/main/java/forestry/mail/gui/GuiLetter.java b/src/main/java/forestry/mail/gui/GuiLetter.java index 9c1a5c8aa..a6c6c5879 100755 --- a/src/main/java/forestry/mail/gui/GuiLetter.java +++ b/src/main/java/forestry/mail/gui/GuiLetter.java @@ -31,7 +31,6 @@ import forestry.core.gui.widgets.Widget; import forestry.core.proxy.Proxies; import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; -import forestry.mail.gui.widgets.AddresseeSlot; import forestry.mail.inventory.ItemInventoryLetter; import forestry.mail.network.packets.PacketLetterInfoRequest; @@ -56,6 +55,9 @@ public class GuiLetter extends GuiForestry this.isProcessedLetter = container.getLetter().isProcessed(); this.widgetManager.add(new AddresseeSlot(widgetManager, 16, 12, container)); this.tradeInfoWidgets = new ArrayList<>(); + + address = new GuiTextField(0, this.fontRendererObj, guiLeft + 46, guiTop + 13, 93, 13); + text = new GuiTextBox(1, this.fontRendererObj, guiLeft + 17, guiTop + 31, 122, 57); } @Override @@ -165,7 +167,7 @@ public class GuiLetter extends GuiForestry String infoString = null; if (container.getTradeInfo() == null) { infoString = Translator.translateToLocal("for.gui.mail.no.trader"); - } else if (container.getTradeInfo().getTradegood() == null) { + } else if (container.getTradeInfo().getTradegood().isEmpty()) { infoString = Translator.translateToLocal("for.gui.mail.nothing.to.trade"); } else if (!container.getTradeInfo().getState().isOk()) { infoString = container.getTradeInfo().getState().getDescription(); @@ -182,8 +184,8 @@ public class GuiLetter extends GuiForestry fontRendererObj.drawString(Translator.translateToLocal("for.gui.mail.foreveryattached"), guiLeft + x, guiTop + y + 28, ColourProperties.INSTANCE.get("gui.mail.lettertext")); - for (int i = 0; i < container.getTradeInfo().getRequired().length; i++) { - addTradeInfoWidget(new ItemStackWidget(widgetManager, x + i * 18, y + 38, container.getTradeInfo().getRequired()[i])); + for (int i = 0; i < container.getTradeInfo().getRequired().size(); i++) { + addTradeInfoWidget(new ItemStackWidget(widgetManager, x + i * 18, y + 38, container.getTradeInfo().getRequired().get(i))); } } @@ -229,7 +231,7 @@ public class GuiLetter extends GuiForestry } private void setRecipient(String recipientName, EnumAddressee type) { - if (this.isProcessedLetter || StringUtils.isBlank(recipientName) || type == null) { + if (this.isProcessedLetter || StringUtils.isBlank(recipientName)) { return; } diff --git a/src/main/java/forestry/mail/gui/GuiMailboxInfo.java b/src/main/java/forestry/mail/gui/GuiMailboxInfo.java index 1d4156c5b..7e71259a2 100755 --- a/src/main/java/forestry/mail/gui/GuiMailboxInfo.java +++ b/src/main/java/forestry/mail/gui/GuiMailboxInfo.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.mail.gui; +import javax.annotation.Nullable; + import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.proxy.Proxies; @@ -41,6 +43,7 @@ public class GuiMailboxInfo extends Gui { private static final int HEIGHT = 17; private final FontRenderer fontRendererObj; + @Nullable private POBoxInfo poInfo; // TODO: this texture is a terrible waste of space in graphics memory, find a better way to do it. private final ResourceLocation textureAlert = new ForestryResource(Constants.TEXTURE_PATH_GUI + "/mailalert.png"); @@ -96,7 +99,7 @@ public class GuiMailboxInfo extends Gui { } if (playJingle) { - EntityPlayerSP thePlayer = Proxies.common.getClientInstance().thePlayer; + EntityPlayerSP thePlayer = Proxies.common.getClientInstance().player; World world = Proxies.common.getRenderWorld(); world.playSound(null, thePlayer.posX, thePlayer.posY, thePlayer.posZ, SoundEvents.ENTITY_PLAYER_LEVELUP, SoundCategory.PLAYERS, 1.0f, 1.0F); } diff --git a/src/main/java/forestry/mail/gui/GuiTradeName.java b/src/main/java/forestry/mail/gui/GuiTradeName.java index 09617d2f0..e340fea6b 100755 --- a/src/main/java/forestry/mail/gui/GuiTradeName.java +++ b/src/main/java/forestry/mail/gui/GuiTradeName.java @@ -12,12 +12,6 @@ package forestry.mail.gui; import java.io.IOException; -import org.apache.commons.lang3.StringUtils; - -import net.minecraft.client.gui.GuiTextField; - -import org.lwjgl.input.Keyboard; - import forestry.core.config.Constants; import forestry.core.gui.GuiForestry; import forestry.core.proxy.Proxies; @@ -25,15 +19,19 @@ import forestry.core.render.ColourProperties; import forestry.core.utils.Translator; import forestry.mail.network.packets.PacketTraderAddressRequest; import forestry.mail.tiles.TileTrader; +import net.minecraft.client.gui.GuiTextField; +import org.apache.commons.lang3.StringUtils; +import org.lwjgl.input.Keyboard; public class GuiTradeName extends GuiForestry { - private GuiTextField addressNameField; public GuiTradeName(TileTrader tile) { super(Constants.TEXTURE_PATH_GUI + "/tradername.png", new ContainerTradeName(tile), tile); this.xSize = 176; this.ySize = 90; + + addressNameField = new GuiTextField(0, this.fontRendererObj, guiLeft + 44, guiTop + 39, 90, 14); } @Override @@ -41,9 +39,7 @@ public class GuiTradeName extends GuiForestry { super.initGui(); addressNameField = new GuiTextField(0, this.fontRendererObj, guiLeft + 44, guiTop + 39, 90, 14); - if (container.getAddress() != null) { - addressNameField.setText(container.getAddress().getName()); - } + addressNameField.setText(container.getAddress().getName()); addressNameField.setFocused(true); } diff --git a/src/main/java/forestry/mail/gui/GuiTrader.java b/src/main/java/forestry/mail/gui/GuiTrader.java index c7bb67bc9..8ecc31724 100755 --- a/src/main/java/forestry/mail/gui/GuiTrader.java +++ b/src/main/java/forestry/mail/gui/GuiTrader.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.mail.gui; +import com.google.common.base.Preconditions; import net.minecraft.entity.player.InventoryPlayer; import forestry.core.config.Constants; @@ -28,6 +29,7 @@ public class GuiTrader extends GuiForestry { @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + Preconditions.checkState(inventory != null); String name = Translator.translateToLocal(inventory.getUnlocalizedTitle()); this.fontRendererObj.drawString(name, textLayout.getCenteredOffset(name), 6, ColourProperties.INSTANCE.get("gui.mail.text")); diff --git a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java index b9eb41ef2..f2ad9f989 100644 --- a/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java +++ b/src/main/java/forestry/mail/gui/ILetterInfoReceiver.java @@ -10,8 +10,12 @@ ******************************************************************************/ package forestry.mail.gui; -import forestry.mail.network.packets.PacketLetterInfoResponse; +import javax.annotation.Nullable; + +import forestry.api.mail.EnumAddressee; +import forestry.api.mail.IMailAddress; +import forestry.api.mail.ITradeStationInfo; public interface ILetterInfoReceiver { - void handleLetterInfoUpdate(PacketLetterInfoResponse packet); + void handleLetterInfoUpdate(EnumAddressee type, @Nullable IMailAddress address, @Nullable ITradeStationInfo tradeInfo); } diff --git a/src/main/java/forestry/mail/gui/package-info.java b/src/main/java/forestry/mail/gui/package-info.java new file mode 100644 index 000000000..9d30b58bc --- /dev/null +++ b/src/main/java/forestry/mail/gui/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.gui; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java index c6f262441..2f2844366 100644 --- a/src/main/java/forestry/mail/inventory/InventoryTradeStation.java +++ b/src/main/java/forestry/mail/inventory/InventoryTradeStation.java @@ -11,27 +11,27 @@ package forestry.mail.inventory; import java.util.ArrayList; - -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumFacing; +import java.util.List; import forestry.api.mail.IStamps; import forestry.core.inventory.InventoryAdapter; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.SlotUtil; import forestry.mail.TradeStation; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumFacing; public class InventoryTradeStation extends InventoryAdapter { public InventoryTradeStation() { super(TradeStation.SLOT_SIZE, "INV"); } - + @Override public int[] getSlotsForFace(EnumFacing side) { - ArrayList slots = new ArrayList<>(); + List slots = new ArrayList<>(); for (int i = TradeStation.SLOT_LETTERS_1; i < TradeStation.SLOT_LETTERS_1 + TradeStation.SLOT_LETTERS_COUNT; i++) { slots.add(i); diff --git a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java index db93a9eec..c6641ce59 100644 --- a/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java +++ b/src/main/java/forestry/mail/inventory/ItemInventoryLetter.java @@ -10,15 +10,10 @@ ******************************************************************************/ package forestry.mail.inventory; -import com.google.common.collect.ImmutableSet; - import java.util.List; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; import forestry.api.core.IErrorSource; import forestry.api.core.IErrorState; import forestry.api.mail.ILetter; @@ -31,12 +26,19 @@ import forestry.core.utils.SlotUtil; import forestry.mail.Letter; import forestry.mail.LetterProperties; import forestry.mail.items.ItemStamps; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class ItemInventoryLetter extends ItemInventory implements IErrorSource, IHintSource { - private ILetter letter; + private final ILetter letter; - public ItemInventoryLetter(EntityPlayer player,ItemStack itemstack) { + public ItemInventoryLetter(EntityPlayer player, ItemStack itemstack) { super(player, 0, itemstack); + NBTTagCompound tagCompound = itemstack.getTagCompound(); + Preconditions.checkNotNull(tagCompound); + letter = new Letter(tagCompound); } public ILetter getLetter() { @@ -45,42 +47,29 @@ public class ItemInventoryLetter extends ItemInventory implements IErrorSource, public void onLetterClosed() { ItemStack parent = getParent(); - if (parent == null) { - return; - } - LetterProperties.closeLetter(parent, letter); } public void onLetterOpened() { ItemStack parent = getParent(); - if (parent == null) { - return; - } - LetterProperties.openLetter(parent); } @Override - public void readFromNBT(NBTTagCompound nbttagcompound) { - if (nbttagcompound == null) { - return; - } - - letter = new Letter(nbttagcompound); - } - - @Override - public ItemStack decrStackSize(int i, int j) { - ItemStack result = letter.decrStackSize(i, j); - letter.writeToNBT(getParent().getTagCompound()); + public ItemStack decrStackSize(int index, int count) { + ItemStack result = letter.decrStackSize(index, count); + NBTTagCompound tagCompound = getParent().getTagCompound(); + Preconditions.checkNotNull(tagCompound); + letter.writeToNBT(tagCompound); return result; } @Override - public void setInventorySlotContents(int i, ItemStack itemstack) { - letter.setInventorySlotContents(i, itemstack); - letter.writeToNBT(getParent().getTagCompound()); + public void setInventorySlotContents(int index, ItemStack itemstack) { + letter.setInventorySlotContents(index, itemstack); + NBTTagCompound tagCompound = getParent().getTagCompound(); + Preconditions.checkNotNull(tagCompound); + letter.writeToNBT(tagCompound); } @Override @@ -104,10 +93,10 @@ public class ItemInventoryLetter extends ItemInventory implements IErrorSource, } @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return letter.isUseableByPlayer(entityplayer); + public boolean isUsableByPlayer(EntityPlayer entityplayer) { + return letter.isUsableByPlayer(entityplayer); } - + @Override public ItemStack removeStackFromSlot(int slot) { return letter.removeStackFromSlot(slot); diff --git a/src/main/java/forestry/mail/inventory/package-info.java b/src/main/java/forestry/mail/inventory/package-info.java new file mode 100644 index 000000000..9034032ea --- /dev/null +++ b/src/main/java/forestry/mail/inventory/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.inventory; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/items/ItemLetter.java b/src/main/java/forestry/mail/items/ItemLetter.java index d669bc103..06437493e 100755 --- a/src/main/java/forestry/mail/items/ItemLetter.java +++ b/src/main/java/forestry/mail/items/ItemLetter.java @@ -29,6 +29,7 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; +import net.minecraft.util.NonNullList; import net.minecraft.util.text.TextComponentTranslation; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; @@ -40,12 +41,13 @@ public class ItemLetter extends ItemWithGui { } @Override - public ActionResult onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { - if (itemStackIn.stackSize == 1) { - return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand); + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { + ItemStack heldItem = playerIn.getHeldItem(handIn); + if (heldItem.getCount() == 1) { + return super.onItemRightClick(worldIn, playerIn, handIn); } else { - playerIn.addChatMessage(new TextComponentTranslation("for.chat.mail.wrongstacksize")); - return ActionResult.newResult(EnumActionResult.FAIL, itemStackIn); + playerIn.sendMessage(new TextComponentTranslation("for.chat.mail.wrongstacksize")); + return ActionResult.newResult(EnumActionResult.FAIL, heldItem); } } @@ -74,10 +76,10 @@ public class ItemLetter extends ItemWithGui { ILetter letter = new Letter(nbttagcompound); letter.addTooltip(list); } - + @Override - public void getSubItems(Item item, CreativeTabs tab, List list) { - LetterProperties.getSubItems(item, tab, list); + public void getSubItems(Item item, CreativeTabs tab, NonNullList subItems) { + LetterProperties.getSubItems(item, tab, subItems); } public List getEmptiedLetters() { diff --git a/src/main/java/forestry/mail/items/package-info.java b/src/main/java/forestry/mail/items/package-info.java new file mode 100644 index 000000000..56fd926b5 --- /dev/null +++ b/src/main/java/forestry/mail/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/network/PacketRegistryMail.java b/src/main/java/forestry/mail/network/PacketRegistryMail.java index 4dd7138e2..eaab4d585 100644 --- a/src/main/java/forestry/mail/network/PacketRegistryMail.java +++ b/src/main/java/forestry/mail/network/PacketRegistryMail.java @@ -10,23 +10,25 @@ ******************************************************************************/ package forestry.mail.network; -import forestry.core.network.PacketRegistry; +import forestry.core.network.IPacketRegistry; +import forestry.core.network.PacketIdClient; +import forestry.core.network.PacketIdServer; import forestry.mail.network.packets.PacketLetterInfoRequest; import forestry.mail.network.packets.PacketLetterInfoResponse; import forestry.mail.network.packets.PacketLetterTextSet; -import forestry.mail.network.packets.PacketPOBoxInfoUpdate; +import forestry.mail.network.packets.PacketPOBoxInfoResponse; import forestry.mail.network.packets.PacketTraderAddressRequest; import forestry.mail.network.packets.PacketTraderAddressResponse; -public class PacketRegistryMail extends PacketRegistry { +public class PacketRegistryMail implements IPacketRegistry { @Override public void registerPackets() { - registerServerPacket(new PacketLetterInfoRequest()); - registerServerPacket(new PacketTraderAddressRequest()); - registerServerPacket(new PacketLetterTextSet()); - - registerClientPacket(new PacketLetterInfoResponse()); - registerClientPacket(new PacketTraderAddressResponse()); - registerClientPacket(new PacketPOBoxInfoUpdate()); + PacketIdClient.LETTER_INFO_RESPONSE.setPacketHandler(new PacketLetterInfoResponse.Handler()); + PacketIdClient.TRADING_ADDRESS_RESPONSE.setPacketHandler(new PacketTraderAddressResponse.Handler()); + PacketIdClient.POBOX_INFO_RESPONSE.setPacketHandler(new PacketPOBoxInfoResponse.Handler()); + + PacketIdServer.LETTER_INFO_REQUEST.setPacketHandler(new PacketLetterInfoRequest.Handler()); + PacketIdServer.TRADING_ADDRESS_REQUEST.setPacketHandler(new PacketTraderAddressRequest.Handler()); + PacketIdServer.LETTER_TEXT_SET.setPacketHandler(new PacketLetterTextSet.Handler()); } } diff --git a/src/main/java/forestry/mail/network/package-info.java b/src/main/java/forestry/mail/network/package-info.java new file mode 100644 index 000000000..fc9afd777 --- /dev/null +++ b/src/main/java/forestry/mail/network/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.network; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java index 59c616b04..b9deb5919 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoRequest.java @@ -12,54 +12,46 @@ package forestry.mail.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.api.mail.EnumAddressee; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdServer; import forestry.mail.gui.ContainerLetter; +import net.minecraft.entity.player.EntityPlayerMP; public class PacketLetterInfoRequest extends ForestryPacket implements IForestryPacketServer { - - private String recipientName; - private EnumAddressee addressType; - - public PacketLetterInfoRequest() { - } + private final String recipientName; + private final EnumAddressee addressType; public PacketLetterInfoRequest(String recipientName, EnumAddressee addressType) { this.recipientName = recipientName; this.addressType = addressType; } - @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(recipientName); - data.writeByte(addressType.ordinal()); - } - - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - recipientName = data.readUTF(); - addressType = EnumAddressee.values()[data.readByte()]; - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof ContainerLetter)) { - return; - } - - ((ContainerLetter) player.openContainer).handleRequestLetterInfo(player, recipientName, addressType); - } - @Override public PacketIdServer getPacketId() { return PacketIdServer.LETTER_INFO_REQUEST; } + + @Override + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeString(recipientName); + data.writeEnum(addressType, EnumAddressee.values()); + } + + public static class Handler implements IForestryPacketHandlerServer { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + String recipientName = data.readString(); + EnumAddressee addressType = data.readEnum(EnumAddressee.values()); + + if (player.openContainer instanceof ContainerLetter) { + ContainerLetter containerLetter = (ContainerLetter) player.openContainer; + containerLetter.handleRequestLetterInfo(player, recipientName, addressType); + } + } + } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java index 9b906cf0d..a16652013 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterInfoResponse.java @@ -10,43 +10,46 @@ ******************************************************************************/ package forestry.mail.network.packets; +import javax.annotation.Nullable; import java.io.IOException; import java.util.UUID; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.item.ItemStack; - +import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; - import forestry.api.mail.EnumAddressee; import forestry.api.mail.EnumTradeStationState; import forestry.api.mail.IMailAddress; import forestry.api.mail.ITradeStationInfo; import forestry.api.mail.PostManager; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; import forestry.mail.TradeStationInfo; import forestry.mail.gui.ILetterInfoReceiver; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.item.ItemStack; +import net.minecraft.util.NonNullList; +// TODO: split this into two different packets public class PacketLetterInfoResponse extends ForestryPacket implements IForestryPacketClient { + public final EnumAddressee type; + public final ITradeStationInfo tradeInfo; + @Nullable + public final IMailAddress address; - public EnumAddressee type; - public ITradeStationInfo tradeInfo; - public IMailAddress address; - - public PacketLetterInfoResponse() { - } - - public PacketLetterInfoResponse(EnumAddressee type, ITradeStationInfo info, IMailAddress address) { + public PacketLetterInfoResponse(EnumAddressee type, ITradeStationInfo info, @Nullable IMailAddress address) { this.type = type; if (type == EnumAddressee.TRADER) { this.tradeInfo = info; + this.address = null; } else if (type == EnumAddressee.PLAYER) { + this.tradeInfo = info; this.address = address; + } else { + throw new IllegalArgumentException("Unknown addressee type: " + type); } } @@ -56,91 +59,55 @@ public class PacketLetterInfoResponse extends ForestryPacket implements IForestr } @Override - public void writeData(DataOutputStreamForestry data) throws IOException { - - if (type == null) { - data.writeShort(-1); - return; - } - data.writeShort(0); - - data.writeUTF(type.toString()); + public void writeData(PacketBufferForestry data) { + data.writeEnum(type, EnumAddressee.values()); if (type == EnumAddressee.PLAYER) { - - if (address == null) { - data.writeShort(-1); - return; - } - data.writeShort(0); - + Preconditions.checkNotNull(address); GameProfile profile = address.getPlayerProfile(); data.writeLong(profile.getId().getMostSignificantBits()); data.writeLong(profile.getId().getLeastSignificantBits()); - data.writeUTF(profile.getName()); + data.writeString(profile.getName()); } else if (type == EnumAddressee.TRADER) { - - if (tradeInfo == null) { - data.writeShort(-1); - return; - } - - data.writeShort(0); - - data.writeUTF(tradeInfo.getAddress().getName()); + data.writeString(tradeInfo.getAddress().getName()); data.writeLong(tradeInfo.getOwner().getId().getMostSignificantBits()); data.writeLong(tradeInfo.getOwner().getId().getLeastSignificantBits()); - data.writeUTF(tradeInfo.getOwner().getName()); + data.writeString(tradeInfo.getOwner().getName()); data.writeItemStack(tradeInfo.getTradegood()); data.writeItemStacks(tradeInfo.getRequired()); - data.writeShort(tradeInfo.getState().ordinal()); + data.writeEnum(tradeInfo.getState(), EnumTradeStationState.values()); } } - @Override - public void readData(DataInputStreamForestry data) throws IOException { + public static class Handler implements IForestryPacketHandlerClient { + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + Container container = player.openContainer; + if (container instanceof ILetterInfoReceiver) { + EnumAddressee type = data.readEnum(EnumAddressee.values()); + ITradeStationInfo tradeInfo = null; + IMailAddress address = null; - if (data.readShort() < 0) { - return; - } + if (type == EnumAddressee.PLAYER) { + GameProfile profile = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readString()); + address = PostManager.postRegistry.getMailAddress(profile); + } else if (type == EnumAddressee.TRADER) { + address = PostManager.postRegistry.getMailAddress(data.readString()); + GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readString()); - type = EnumAddressee.fromString(data.readUTF()); - tradeInfo = null; - address = null; + ItemStack tradegood = data.readItemStack(); + NonNullList required = data.readItemStacks(); - if (type == EnumAddressee.PLAYER) { - if (data.readShort() < 0) { - return; + EnumTradeStationState state = data.readEnum(EnumTradeStationState.values()); + tradeInfo = new TradeStationInfo(address, owner, tradegood, required, state); + } + ((ILetterInfoReceiver) container).handleLetterInfoUpdate(type, address, tradeInfo); } - GameProfile player = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - this.address = PostManager.postRegistry.getMailAddress(player); - - } else if (type == EnumAddressee.TRADER) { - if (data.readShort() < 0) { - return; - } - IMailAddress address = PostManager.postRegistry.getMailAddress(data.readUTF()); - GameProfile owner = new GameProfile(new UUID(data.readLong(), data.readLong()), data.readUTF()); - ItemStack tradegood; - ItemStack[] required; - - tradegood = data.readItemStack(); - required = data.readItemStacks(); - - this.tradeInfo = new TradeStationInfo(address, owner, tradegood, required, EnumTradeStationState.values()[data.readShort()]); - } - } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - Container container = player.openContainer; - if (container instanceof ILetterInfoReceiver) { - ((ILetterInfoReceiver) container).handleLetterInfoUpdate(this); } } } diff --git a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java index ee6804259..3ebb505c9 100644 --- a/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java +++ b/src/main/java/forestry/mail/network/packets/PacketLetterTextSet.java @@ -12,21 +12,19 @@ package forestry.mail.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdServer; +import forestry.mail.gui.ContainerLetter; import net.minecraft.entity.player.EntityPlayerMP; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketString; -import forestry.mail.gui.ContainerLetter; - -public class PacketLetterTextSet extends PacketString implements IForestryPacketServer { - - public PacketLetterTextSet() { - } +public class PacketLetterTextSet extends ForestryPacket implements IForestryPacketServer { + private final String string; public PacketLetterTextSet(String string) { - super(string); + this.string = string; } @Override @@ -35,11 +33,18 @@ public class PacketLetterTextSet extends PacketString implements IForestryPacket } @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - if (!(player.openContainer instanceof ContainerLetter)) { - return; - } + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeString(string); + } - ((ContainerLetter) player.openContainer).handleSetText(this); + public static class Handler implements IForestryPacketHandlerServer { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + if (player.openContainer instanceof ContainerLetter) { + String string = data.readString(); + ((ContainerLetter) player.openContainer).handleSetText(string); + } + } } } diff --git a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java similarity index 56% rename from src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java rename to src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java index fd6224c5d..8c0d7fdbc 100644 --- a/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoUpdate.java +++ b/src/main/java/forestry/mail/network/packets/PacketPOBoxInfoResponse.java @@ -12,24 +12,19 @@ package forestry.mail.network.packets; import java.io.IOException; -import net.minecraft.entity.player.EntityPlayer; - -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; import forestry.core.network.ForestryPacket; import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; import forestry.core.network.PacketIdClient; import forestry.mail.POBoxInfo; import forestry.mail.gui.GuiMailboxInfo; +import net.minecraft.entity.player.EntityPlayer; -public class PacketPOBoxInfoUpdate extends ForestryPacket implements IForestryPacketClient { +public class PacketPOBoxInfoResponse extends ForestryPacket implements IForestryPacketClient { + public final POBoxInfo poboxInfo; - public POBoxInfo poboxInfo; - - public PacketPOBoxInfoUpdate() { - } - - public PacketPOBoxInfoUpdate(POBoxInfo info) { + public PacketPOBoxInfoResponse(POBoxInfo info) { this.poboxInfo = info; } @@ -39,30 +34,17 @@ public class PacketPOBoxInfoUpdate extends ForestryPacket implements IForestryPa } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - if (poboxInfo == null) { - data.writeShort(-1); - return; - } - - data.writeShort(0); + protected void writeData(PacketBufferForestry data) throws IOException { data.writeInt(poboxInfo.playerLetters); data.writeInt(poboxInfo.tradeLetters); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - short isNotNull = data.readShort(); - if (isNotNull < 0) { - return; + public static class Handler implements IForestryPacketHandlerClient { + + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + POBoxInfo poboxInfo = new POBoxInfo(data.readInt(), data.readInt()); + GuiMailboxInfo.instance.setPOBoxInfo(poboxInfo); } - - this.poboxInfo = new POBoxInfo(data.readInt(), data.readInt()); } - - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - GuiMailboxInfo.instance.setPOBoxInfo(poboxInfo); - } - } diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java index b3f564a36..6a0842530 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressRequest.java @@ -12,25 +12,22 @@ package forestry.mail.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketHandlerServer; +import forestry.core.network.IForestryPacketServer; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdServer; +import forestry.mail.tiles.TileTrader; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketServer; -import forestry.core.network.PacketIdServer; -import forestry.core.network.packets.PacketCoordinates; -import forestry.mail.tiles.TileTrader; - -public class PacketTraderAddressRequest extends PacketCoordinates implements IForestryPacketServer { - - private String addressName; - - public PacketTraderAddressRequest() { - } +public class PacketTraderAddressRequest extends ForestryPacket implements IForestryPacketServer { + private final BlockPos pos; + private final String addressName; public PacketTraderAddressRequest(TileTrader tile, String addressName) { - super(tile); + this.pos = tile.getPos(); this.addressName = addressName; } @@ -40,22 +37,22 @@ public class PacketTraderAddressRequest extends PacketCoordinates implements IFo } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(addressName); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeString(addressName); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - addressName = data.readUTF(); - } + public static class Handler implements IForestryPacketHandlerServer { - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayerMP player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if (tile instanceof TileTrader) { - ((TileTrader) tile).handleSetAddressRequest(addressName); + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayerMP player) throws IOException { + BlockPos pos = data.readBlockPos(); + String addressName = data.readString(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileTrader) { + ((TileTrader) tile).handleSetAddressRequest(addressName); + } } } } diff --git a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java index 20b6e38c8..509e34d3a 100644 --- a/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java +++ b/src/main/java/forestry/mail/network/packets/PacketTraderAddressResponse.java @@ -12,25 +12,22 @@ package forestry.mail.network.packets; import java.io.IOException; +import forestry.core.network.ForestryPacket; +import forestry.core.network.IForestryPacketClient; +import forestry.core.network.IForestryPacketHandlerClient; +import forestry.core.network.PacketBufferForestry; +import forestry.core.network.PacketIdClient; +import forestry.mail.tiles.TileTrader; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.math.BlockPos; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; -import forestry.core.network.IForestryPacketClient; -import forestry.core.network.PacketIdClient; -import forestry.core.network.packets.PacketCoordinates; -import forestry.mail.tiles.TileTrader; - -public class PacketTraderAddressResponse extends PacketCoordinates implements IForestryPacketClient { - - private String addressName; - - public PacketTraderAddressResponse() { - } +public class PacketTraderAddressResponse extends ForestryPacket implements IForestryPacketClient { + private final BlockPos pos; + private final String addressName; public PacketTraderAddressResponse(TileTrader tile, String addressName) { - super(tile); + this.pos = tile.getPos(); this.addressName = addressName; } @@ -40,23 +37,22 @@ public class PacketTraderAddressResponse extends PacketCoordinates implements IF } @Override - protected void writeData(DataOutputStreamForestry data) throws IOException { - super.writeData(data); - data.writeUTF(addressName); + protected void writeData(PacketBufferForestry data) throws IOException { + data.writeBlockPos(pos); + data.writeString(addressName); } - @Override - public void readData(DataInputStreamForestry data) throws IOException { - super.readData(data); - addressName = data.readUTF(); - } + public static class Handler implements IForestryPacketHandlerClient { - @Override - public void onPacketData(DataInputStreamForestry data, EntityPlayer player) throws IOException { - TileEntity tile = getTarget(player.worldObj); - if (tile instanceof TileTrader) { - ((TileTrader) tile).handleSetAddressResponse(addressName); + @Override + public void onPacketData(PacketBufferForestry data, EntityPlayer player) throws IOException { + BlockPos pos = data.readBlockPos(); + String addressName = data.readString(); + + TileEntity tile = player.world.getTileEntity(pos); + if (tile instanceof TileTrader) { + ((TileTrader) tile).handleSetAddressResponse(addressName); + } } } - } diff --git a/src/main/java/forestry/mail/network/packets/package-info.java b/src/main/java/forestry/mail/network/packets/package-info.java new file mode 100644 index 000000000..2cd148ae8 --- /dev/null +++ b/src/main/java/forestry/mail/network/packets/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.network.packets; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/package-info.java b/src/main/java/forestry/mail/package-info.java new file mode 100644 index 000000000..2fd142fd3 --- /dev/null +++ b/src/main/java/forestry/mail/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/tiles/TileMailbox.java b/src/main/java/forestry/mail/tiles/TileMailbox.java index 60add380b..f463af666 100644 --- a/src/main/java/forestry/mail/tiles/TileMailbox.java +++ b/src/main/java/forestry/mail/tiles/TileMailbox.java @@ -10,16 +10,7 @@ ******************************************************************************/ package forestry.mail.tiles; -import javax.annotation.Nonnull; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.util.text.TextComponentString; -import net.minecraft.world.World; - import com.mojang.authlib.GameProfile; - import forestry.api.mail.ILetter; import forestry.api.mail.IMailAddress; import forestry.api.mail.IPostalState; @@ -31,6 +22,11 @@ import forestry.mail.POBox; import forestry.mail.PostRegistry; import forestry.mail.gui.ContainerMailbox; import forestry.mail.gui.GuiMailbox; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.text.TextComponentString; +import net.minecraft.world.World; public class TileMailbox extends TileBase { @@ -42,7 +38,7 @@ public class TileMailbox extends TileBase { /* GUI */ @Override public void openGui(EntityPlayer player, ItemStack heldItem) { - if (worldObj.isRemote) { + if (world.isRemote) { return; } @@ -50,9 +46,9 @@ public class TileMailbox extends TileBase { if (PostManager.postRegistry.isLetter(heldItem)) { IPostalState result = this.tryDispatchLetter(heldItem); if (!result.isOk()) { - player.addChatMessage(new TextComponentString(result.getDescription())); + player.sendMessage(new TextComponentString(result.getDescription())); } else { - heldItem.stackSize--; + heldItem.shrink(1); } } else { super.openGui(player, heldItem); @@ -60,13 +56,13 @@ public class TileMailbox extends TileBase { } /* MAIL HANDLING */ - public IInventory getOrCreateMailInventory(World world, @Nonnull GameProfile playerProfile) { + public IInventory getOrCreateMailInventory(World world, GameProfile playerProfile) { if (world.isRemote) { return getInternalInventory(); } IMailAddress address = PostManager.postRegistry.getMailAddress(playerProfile); - return PostRegistry.getOrCreatePOBox(worldObj, address); + return PostRegistry.getOrCreatePOBox(world, address); } private IPostalState tryDispatchLetter(ItemStack letterStack) { @@ -74,7 +70,7 @@ public class TileMailbox extends TileBase { IPostalState result; if (letter != null) { - result = PostManager.postRegistry.getPostOffice(worldObj).lodgeLetter(worldObj, letterStack, true); + result = PostManager.postRegistry.getPostOffice(world).lodgeLetter(world, letterStack, true); } else { result = EnumDeliveryState.NOT_MAILABLE; } diff --git a/src/main/java/forestry/mail/tiles/TileStampCollector.java b/src/main/java/forestry/mail/tiles/TileStampCollector.java index ae73864ef..b466e1915 100644 --- a/src/main/java/forestry/mail/tiles/TileStampCollector.java +++ b/src/main/java/forestry/mail/tiles/TileStampCollector.java @@ -10,10 +10,6 @@ ******************************************************************************/ package forestry.mail.tiles; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; - import forestry.api.mail.IStamps; import forestry.api.mail.PostManager; import forestry.core.inventory.IInventoryAdapter; @@ -22,6 +18,9 @@ import forestry.core.utils.InventoryUtil; import forestry.mail.gui.ContainerStampCollector; import forestry.mail.gui.GuiStampCollector; import forestry.mail.inventory.InventoryStampCollector; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; public class TileStampCollector extends TileBase implements IInventory { public TileStampCollector() { @@ -38,12 +37,12 @@ public class TileStampCollector extends TileBase implements IInventory { ItemStack stamp = null; IInventoryAdapter inventory = getInternalInventory(); - if (inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER) == null) { - stamp = PostManager.postRegistry.getPostOffice(worldObj).getAnyStamp(1); + if (inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER).isEmpty()) { + stamp = PostManager.postRegistry.getPostOffice(world).getAnyStamp(1); } else { ItemStack filter = inventory.getStackInSlot(InventoryStampCollector.SLOT_FILTER); if (filter.getItem() instanceof IStamps) { - stamp = PostManager.postRegistry.getPostOffice(worldObj).getAnyStamp(((IStamps) filter.getItem()).getPostage(filter), 1); + stamp = PostManager.postRegistry.getPostOffice(world).getAnyStamp(((IStamps) filter.getItem()).getPostage(filter), 1); } } diff --git a/src/main/java/forestry/mail/tiles/TileTrader.java b/src/main/java/forestry/mail/tiles/TileTrader.java index 730209add..874bea66c 100644 --- a/src/main/java/forestry/mail/tiles/TileTrader.java +++ b/src/main/java/forestry/mail/tiles/TileTrader.java @@ -13,15 +13,7 @@ package forestry.mail.tiles; import javax.annotation.Nonnull; import java.io.IOException; -import forestry.core.owner.IOwnedTile; -import forestry.core.owner.IOwnerHandler; -import forestry.core.owner.OwnerHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; - +import com.google.common.base.Preconditions; import forestry.api.core.IErrorLogic; import forestry.api.mail.IMailAddress; import forestry.api.mail.IStamps; @@ -29,8 +21,10 @@ import forestry.api.mail.PostManager; import forestry.core.errors.EnumErrorCode; import forestry.core.gui.GuiHandler; import forestry.core.inventory.IInventoryAdapter; -import forestry.core.network.DataInputStreamForestry; -import forestry.core.network.DataOutputStreamForestry; +import forestry.core.network.PacketBufferForestry; +import forestry.core.owner.IOwnedTile; +import forestry.core.owner.IOwnerHandler; +import forestry.core.owner.OwnerHandler; import forestry.core.proxy.Proxies; import forestry.core.tiles.TileBase; import forestry.core.utils.ItemStackUtil; @@ -42,6 +36,11 @@ import forestry.mail.gui.GuiTradeName; import forestry.mail.gui.GuiTrader; import forestry.mail.inventory.InventoryTradeStation; import forestry.mail.network.packets.PacketTraderAddressResponse; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; public class TileTrader extends TileBase implements IOwnedTile { private final OwnerHandler ownerHandler = new OwnerHandler(); @@ -67,7 +66,7 @@ public class TileTrader extends TileBase implements IOwnedTile { @Override public void onRemoval() { if (isLinked()) { - PostManager.postRegistry.deleteTradeStation(worldObj, address); + PostManager.postRegistry.deleteTradeStation(world, address); } } @@ -77,11 +76,10 @@ public class TileTrader extends TileBase implements IOwnedTile { public NBTTagCompound writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound = super.writeToNBT(nbttagcompound); - if (address != null) { - NBTTagCompound nbt = new NBTTagCompound(); - address.writeToNBT(nbt); - nbttagcompound.setTag("address", nbt); - } + NBTTagCompound nbt = new NBTTagCompound(); + address.writeToNBT(nbt); + nbttagcompound.setTag("address", nbt); + ownerHandler.writeToNBT(nbttagcompound); return nbttagcompound; } @@ -99,24 +97,18 @@ public class TileTrader extends TileBase implements IOwnedTile { /* NETWORK */ @Override - public void writeData(DataOutputStreamForestry data) throws IOException { + public void writeData(PacketBufferForestry data) { super.writeData(data); ownerHandler.writeData(data); - String addressName = null; - if (address != null) { - addressName = address.getName(); - } - if (addressName == null) { - addressName = ""; - } - data.writeUTF(addressName); + String addressName = address.getName(); + data.writeString(addressName); } @Override - public void readData(DataInputStreamForestry data) throws IOException { + public void readData(PacketBufferForestry data) throws IOException { super.readData(data); ownerHandler.readData(data); - String addressName = data.readUTF(); + String addressName = data.readString(); if (!addressName.isEmpty()) { address = PostManager.postRegistry.getMailAddress(addressName); } @@ -142,13 +134,13 @@ public class TileTrader extends TileBase implements IOwnedTile { IInventory inventory = getInternalInventory(); ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); - errorLogic.setCondition(tradeGood == null, EnumErrorCode.NO_TRADE); + errorLogic.setCondition(tradeGood.isEmpty(), EnumErrorCode.NO_TRADE); - boolean hasRequest = hasItemCount(TradeStation.SLOT_EXCHANGE_1, TradeStation.SLOT_EXCHANGE_COUNT, null, 1); + boolean hasRequest = hasItemCount(TradeStation.SLOT_EXCHANGE_1, TradeStation.SLOT_EXCHANGE_COUNT, ItemStack.EMPTY, 1); errorLogic.setCondition(!hasRequest, EnumErrorCode.NO_TRADE); - if (tradeGood != null) { - boolean hasSupplies = hasItemCount(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood, tradeGood.stackSize); + if (!tradeGood.isEmpty()) { + boolean hasSupplies = hasItemCount(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood, tradeGood.getCount()); errorLogic.setCondition(!hasSupplies, EnumErrorCode.NO_SUPPLIES); } @@ -160,7 +152,7 @@ public class TileTrader extends TileBase implements IOwnedTile { /* STATE INFORMATION */ public boolean isLinked() { - if (address == null || !address.isValid()) { + if (!address.isValid()) { return false; } @@ -179,11 +171,11 @@ public class TileTrader extends TileBase implements IOwnedTile { IInventory tradeInventory = this.getInternalInventory(); for (int i = startSlot; i < startSlot + countSlots; i++) { ItemStack itemInSlot = tradeInventory.getStackInSlot(i); - if (itemInSlot == null) { + if (itemInSlot.isEmpty()) { continue; } - if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { - count += itemInSlot.stackSize; + if (item.isEmpty() || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { + count += itemInSlot.getCount(); } if (count >= itemCount) { return true; @@ -204,12 +196,12 @@ public class TileTrader extends TileBase implements IOwnedTile { IInventory tradeInventory = this.getInternalInventory(); for (int i = startSlot; i < startSlot + countSlots; i++) { ItemStack itemInSlot = tradeInventory.getStackInSlot(i); - if (itemInSlot == null) { - total += 64; + if (itemInSlot.isEmpty()) { + total += tradeInventory.getInventoryStackLimit(); } else { total += itemInSlot.getMaxStackSize(); - if (item == null || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { - count += itemInSlot.stackSize; + if (item.isEmpty() || ItemStackUtil.isIdenticalItem(itemInSlot, item)) { + count += itemInSlot.getCount(); } } } @@ -224,14 +216,14 @@ public class TileTrader extends TileBase implements IOwnedTile { public boolean hasInputBufMin(float percentage) { IInventory inventory = getInternalInventory(); ItemStack tradeGood = inventory.getStackInSlot(TradeStation.SLOT_TRADEGOOD); - if (tradeGood == null) { + if (tradeGood.isEmpty()) { return true; } return percentOccupied(TradeStation.SLOT_SEND_BUFFER, TradeStation.SLOT_SEND_BUFFER_COUNT, tradeGood) > percentage; } public boolean hasOutputBufMin(float percentage) { - return percentOccupied(TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT, null) > percentage; + return percentOccupied(TradeStation.SLOT_RECEIVE_BUFFER, TradeStation.SLOT_RECEIVE_BUFFER_COUNT, ItemStack.EMPTY) > percentage; } public boolean hasPostageMin(int postage) { @@ -241,16 +233,13 @@ public class TileTrader extends TileBase implements IOwnedTile { IInventory tradeInventory = this.getInternalInventory(); for (int i = TradeStation.SLOT_STAMPS_1; i < TradeStation.SLOT_STAMPS_1 + TradeStation.SLOT_STAMPS_COUNT; i++) { ItemStack stamp = tradeInventory.getStackInSlot(i); - if (stamp == null) { - continue; - } - if (!(stamp.getItem() instanceof IStamps)) { - continue; - } - - posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.stackSize; - if (posted >= postage) { - return true; + if (!stamp.isEmpty()) { + if (stamp.getItem() instanceof IStamps) { + posted += ((IStamps) stamp.getItem()).getPostage(stamp).getValue() * stamp.getCount(); + if (posted >= postage) { + return true; + } + } } } @@ -267,12 +256,10 @@ public class TileTrader extends TileBase implements IOwnedTile { setAddress(address); IMailAddress newAddress = getAddress(); - if (newAddress != null) { - String newAddressName = newAddress.getName(); - if (newAddressName != null && newAddressName.equals(addressName)) { - PacketTraderAddressResponse packetResponse = new PacketTraderAddressResponse(this, addressName); - Proxies.net.sendNetworkPacket(packetResponse, worldObj); - } + String newAddressName = newAddress.getName(); + if (newAddressName.equals(addressName)) { + PacketTraderAddressResponse packetResponse = new PacketTraderAddressResponse(this, addressName); + Proxies.net.sendNetworkPacket(packetResponse, pos, world); } } @@ -282,26 +269,24 @@ public class TileTrader extends TileBase implements IOwnedTile { } private void setAddress(IMailAddress address) { - if (address == null) { - throw new NullPointerException("address must not be null"); - } + Preconditions.checkNotNull(address, "address must not be null"); - if (this.address != null && this.address.isValid() && this.address.equals(address)) { + if (this.address.isValid() && this.address.equals(address)) { return; } - if (!worldObj.isRemote) { + if (!world.isRemote) { IErrorLogic errorLogic = getErrorLogic(); - boolean hasValidTradeAddress = PostManager.postRegistry.isValidTradeAddress(worldObj, address); + boolean hasValidTradeAddress = PostManager.postRegistry.isValidTradeAddress(world, address); errorLogic.setCondition(!hasValidTradeAddress, EnumErrorCode.NOT_ALPHANUMERIC); - boolean hasUniqueTradeAddress = PostManager.postRegistry.isAvailableTradeAddress(worldObj, address); + boolean hasUniqueTradeAddress = PostManager.postRegistry.isAvailableTradeAddress(world, address); errorLogic.setCondition(!hasUniqueTradeAddress, EnumErrorCode.NOT_UNIQUE); if (hasValidTradeAddress & hasUniqueTradeAddress) { this.address = address; - PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwnerHandler().getOwner(), address); + PostManager.postRegistry.getOrCreateTradeStation(world, getOwnerHandler().getOwner(), address); } } else { this.address = address; @@ -311,11 +296,11 @@ public class TileTrader extends TileBase implements IOwnedTile { @Override public IInventoryAdapter getInternalInventory() { // Handle client side - if (worldObj.isRemote || !address.isValid()) { + if (world.isRemote || !address.isValid()) { return super.getInternalInventory(); } - return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation(worldObj, getOwnerHandler().getOwner(), address); + return (TradeStation) PostManager.postRegistry.getOrCreateTradeStation(world, getOwnerHandler().getOwner(), address); } // TODO: Buildcraft for 1.9 diff --git a/src/main/java/forestry/mail/tiles/package-info.java b/src/main/java/forestry/mail/tiles/package-info.java new file mode 100644 index 000000000..b2fb37b5c --- /dev/null +++ b/src/main/java/forestry/mail/tiles/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.tiles; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/mail/triggers/package-info.java b/src/main/java/forestry/mail/triggers/package-info.java new file mode 100644 index 000000000..683a58b09 --- /dev/null +++ b/src/main/java/forestry/mail/triggers/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.mail.triggers; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/package-info.java b/src/main/java/forestry/package-info.java new file mode 100644 index 000000000..5ca70d5e9 --- /dev/null +++ b/src/main/java/forestry/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/plugins/ForestryPluginUtil.java b/src/main/java/forestry/plugins/ForestryPluginUtil.java index 75adb6e1e..6671391ec 100644 --- a/src/main/java/forestry/plugins/ForestryPluginUtil.java +++ b/src/main/java/forestry/plugins/ForestryPluginUtil.java @@ -1,24 +1,22 @@ package forestry.plugins; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Set; -import net.minecraftforge.fml.common.discovery.ASMDataTable; - import forestry.core.utils.Log; +import net.minecraftforge.fml.common.discovery.ASMDataTable; public class ForestryPluginUtil { private ForestryPluginUtil() { } - public static List getForestryPlugins(@Nonnull ASMDataTable asmDataTable) { + public static List getForestryPlugins(ASMDataTable asmDataTable) { return getInstances(asmDataTable, ForestryPlugin.class, IForestryPlugin.class); } - private static List getInstances(@Nonnull ASMDataTable asmDataTable, Class annotationClass, Class instanceClass) { + private static List getInstances(ASMDataTable asmDataTable, Class annotationClass, Class instanceClass) { String annotationClassName = annotationClass.getCanonicalName(); Set asmDatas = asmDataTable.getAll(annotationClassName); List instances = new ArrayList<>(); diff --git a/src/main/java/forestry/plugins/IForestryPlugin.java b/src/main/java/forestry/plugins/IForestryPlugin.java index 089092410..ba97de822 100644 --- a/src/main/java/forestry/plugins/IForestryPlugin.java +++ b/src/main/java/forestry/plugins/IForestryPlugin.java @@ -1,23 +1,20 @@ package forestry.plugins; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import java.util.Random; import java.util.Set; -import net.minecraft.command.ICommand; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkGenerator; - -import net.minecraftforge.fml.common.IFuelHandler; -import net.minecraftforge.fml.common.event.FMLInterModComms; - import forestry.core.IPickupHandler; import forestry.core.IResupplyHandler; import forestry.core.ISaveEventHandler; import forestry.core.network.IPacketRegistry; +import net.minecraft.command.ICommand; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkGenerator; +import net.minecraftforge.fml.common.IFuelHandler; +import net.minecraftforge.fml.common.event.FMLInterModComms; public interface IForestryPlugin { boolean isAvailable(); @@ -29,7 +26,6 @@ public interface IForestryPlugin { /** * See ForestryPlugin.pluginID() */ - @Nonnull Set getDependencyUids(); void setupAPI(); diff --git a/src/main/java/forestry/plugins/PluginManager.java b/src/main/java/forestry/plugins/PluginManager.java index 34367d565..3764ba254 100644 --- a/src/main/java/forestry/plugins/PluginManager.java +++ b/src/main/java/forestry/plugins/PluginManager.java @@ -10,11 +10,6 @@ ******************************************************************************/ package forestry.plugins; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; - -import javax.annotation.Nonnull; import java.io.File; import java.util.ArrayList; import java.util.HashSet; @@ -25,21 +20,9 @@ import java.util.Locale; import java.util.Random; import java.util.Set; -import net.minecraft.command.CommandHandler; -import net.minecraft.command.ICommand; -import net.minecraft.item.ItemStack; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.World; -import net.minecraft.world.chunk.IChunkGenerator; - -import net.minecraftforge.common.config.Configuration; -import net.minecraftforge.common.config.Property; -import net.minecraftforge.fml.common.IFuelHandler; -import net.minecraftforge.fml.common.discovery.ASMDataTable; -import net.minecraftforge.fml.common.event.FMLInterModComms; -import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; -import net.minecraftforge.fml.common.registry.GameRegistry; - +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; import forestry.Forestry; import forestry.api.core.ForestryAPI; import forestry.core.IPickupHandler; @@ -49,6 +32,19 @@ import forestry.core.PluginCore; import forestry.core.network.IPacketRegistry; import forestry.core.utils.Log; import forestry.core.utils.Translator; +import net.minecraft.command.CommandHandler; +import net.minecraft.command.ICommand; +import net.minecraft.item.ItemStack; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.World; +import net.minecraft.world.chunk.IChunkGenerator; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.common.IFuelHandler; +import net.minecraftforge.fml.common.discovery.ASMDataTable; +import net.minecraftforge.fml.common.event.FMLInterModComms; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; +import net.minecraftforge.fml.common.registry.GameRegistry; public class PluginManager { @@ -73,7 +69,6 @@ public class PluginManager { FINISHED } - @Nonnull public static final Set configDisabledPlugins = new HashSet<>(); public static Stage getStage() { @@ -113,16 +108,16 @@ public class PluginManager { } } - private static IForestryPlugin getPluginCore(@Nonnull List forestryPlugins) { + private static IForestryPlugin getPluginCore(List forestryPlugins) { for (IForestryPlugin plugin : forestryPlugins) { if (plugin instanceof PluginCore) { return plugin; } } - return null; + throw new IllegalStateException("Could not find core plugin"); } - private static void configurePlugins(@Nonnull List forestryPlugins) { + private static void configurePlugins(List forestryPlugins) { Locale locale = Locale.getDefault(); Locale.setDefault(Locale.ENGLISH); @@ -297,7 +292,7 @@ public class PluginManager { } } - @Nonnull + public static List getHiddenItems() { List hiddenItems = new ArrayList<>(); for (IForestryPlugin plugin : loadedPlugins) { @@ -306,7 +301,7 @@ public class PluginManager { return hiddenItems; } - @Nonnull + public static Set getLootPoolNames() { Set lootPoolNames = new HashSet<>(); for (IForestryPlugin plugin : loadedPlugins) { diff --git a/src/main/java/forestry/plugins/compat/BlockRegistryIC2.java b/src/main/java/forestry/plugins/compat/BlockRegistryIC2.java index 95a073881..e626c8b00 100644 --- a/src/main/java/forestry/plugins/compat/BlockRegistryIC2.java +++ b/src/main/java/forestry/plugins/compat/BlockRegistryIC2.java @@ -1,20 +1,20 @@ -package forestry.plugins.compat; - -import forestry.core.blocks.BlockBase; -import forestry.core.blocks.BlockRegistry; -import forestry.core.items.ItemBlockForestry; -import forestry.energy.blocks.BlockEngine; -import forestry.energy.blocks.BlockTypeEngine; - -public class BlockRegistryIC2 extends BlockRegistry { - public final BlockBase electricalEngine; - public final BlockEngine generator; - - public BlockRegistryIC2() { - electricalEngine = new BlockEngine(BlockTypeEngine.ELECTRICAL); - registerBlock(electricalEngine, new ItemBlockForestry<>(electricalEngine), "engine_electrical"); - - generator = new BlockEngine(BlockTypeEngine.GENERATOR); - registerBlock(generator, new ItemBlockForestry<>(generator), "engine_generator"); - } -} +//package forestry.plugins.compat; +// +//import forestry.core.blocks.BlockBase; +//import forestry.core.blocks.BlockRegistry; +//import forestry.core.items.ItemBlockForestry; +//import forestry.energy.blocks.BlockEngine; +//import forestry.energy.blocks.BlockTypeEngine; +// +//public class BlockRegistryIC2 extends BlockRegistry { +// public final BlockBase electricalEngine; +// public final BlockEngine generator; +// +// public BlockRegistryIC2() { +// electricalEngine = new BlockEngine(BlockTypeEngine.ELECTRICAL); +// registerBlock(electricalEngine, new ItemBlockForestry<>(electricalEngine), "engine_electrical"); +// +// generator = new BlockEngine(BlockTypeEngine.GENERATOR); +// registerBlock(generator, new ItemBlockForestry<>(generator), "engine_generator"); +// } +//} diff --git a/src/main/java/forestry/plugins/compat/ForestryJeiPlugin.java b/src/main/java/forestry/plugins/compat/ForestryJeiPlugin.java index ad47fafd0..27a406b36 100644 --- a/src/main/java/forestry/plugins/compat/ForestryJeiPlugin.java +++ b/src/main/java/forestry/plugins/compat/ForestryJeiPlugin.java @@ -1,8 +1,8 @@ package forestry.plugins.compat; -import javax.annotation.Nonnull; import java.util.List; +import com.google.common.base.Preconditions; import forestry.core.PluginCore; import forestry.core.blocks.BlockRegistryCore; import forestry.core.items.ItemRegistryCore; @@ -18,7 +18,7 @@ import net.minecraft.item.ItemStack; @JEIPlugin public class ForestryJeiPlugin extends BlankModPlugin { @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { IJeiHelpers jeiHelpers = registry.getJeiHelpers(); IItemBlacklist itemBlacklist = jeiHelpers.getItemBlacklist(); List hiddenItems = PluginManager.getHiddenItems(); @@ -27,6 +27,7 @@ public class ForestryJeiPlugin extends BlankModPlugin { } ItemRegistryCore items = PluginCore.items; + Preconditions.checkState(items != null); JeiUtil.addDescription(registry, items.solderingIron, @@ -39,6 +40,8 @@ public class ForestryJeiPlugin extends BlankModPlugin { ); BlockRegistryCore blocks = PluginCore.blocks; + Preconditions.checkState(blocks != null); + JeiUtil.addDescription(registry, blocks.analyzer, blocks.bogEarth, diff --git a/src/main/java/forestry/plugins/compat/PluginActuallyAdditions.java b/src/main/java/forestry/plugins/compat/PluginActuallyAdditions.java index a4e13480d..fd7c3773e 100644 --- a/src/main/java/forestry/plugins/compat/PluginActuallyAdditions.java +++ b/src/main/java/forestry/plugins/compat/PluginActuallyAdditions.java @@ -1,6 +1,5 @@ package forestry.plugins.compat; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; @@ -59,8 +58,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { FluidStack seedFluid = Fluids.SEED_OIL.getFluid(amount); for (Item seed : Arrays.asList(canolaSeed, flaxSeed, riceSeed, coffeeSeed)) { if (seed != null) { - ItemStack[] resources = {new ItemStack(seed)}; - RecipeManagers.squeezerManager.addRecipe(10, resources, seedFluid); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(seed), seedFluid); } } @@ -70,7 +68,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { Item misc = getItem("itemMisc"); if (misc != null) { ItemStack canola = new ItemStack(misc, 1, 13); - RecipeManagers.squeezerManager.addRecipe(15, new ItemStack[]{canola}, new FluidStack(canolaOil, 80)); + RecipeManagers.squeezerManager.addRecipe(15, canola, new FluidStack(canolaOil, 80)); } //add canola oil fermenting in still @@ -81,7 +79,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { } } - private static void registerSeedPlant(@Nullable Item seedItem, @Nonnull String blockName) { + private static void registerSeedPlant(@Nullable Item seedItem, String blockName) { if (seedItem != null) { Block plantBlock = getBlock(blockName); if (plantBlock != null) { @@ -94,7 +92,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { } @Nullable - private static Fluid getFluid(@Nonnull String fluidName) { + private static Fluid getFluid(String fluidName) { Fluid fluid = FluidRegistry.getFluid(fluidName); if (fluid == null) { Log.error("Could not find fluid {}", fluidName); @@ -103,7 +101,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { } @Nullable - private static Block getBlock(@Nonnull String blockName) { + private static Block getBlock(String blockName) { ResourceLocation key = new ResourceLocation(ACT_ADD, blockName); if (ForgeRegistries.BLOCKS.containsKey(key)) { return ForgeRegistries.BLOCKS.getValue(key); @@ -114,7 +112,7 @@ public class PluginActuallyAdditions extends BlankForestryPlugin { } @Nullable - private static Item getItem(@Nonnull String itemName) { + private static Item getItem(String itemName) { ResourceLocation key = new ResourceLocation(ACT_ADD, itemName); if (ForgeRegistries.ITEMS.containsKey(key)) { return ForgeRegistries.ITEMS.getValue(key); diff --git a/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java b/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java index 935639fb5..f5ba88713 100644 --- a/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java +++ b/src/main/java/forestry/plugins/compat/PluginBiomesOPlenty.java @@ -10,6 +10,7 @@ ******************************************************************************/ package forestry.plugins.compat; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -42,8 +43,11 @@ public class PluginBiomesOPlenty extends BlankForestryPlugin { private static final String BoP = "BiomesOPlenty"; + @Nullable private static Block saplings; + @Nullable private static Block colorizedSaplings; + @Nullable private static Item food; private static int amount; @@ -111,11 +115,11 @@ public class PluginBiomesOPlenty extends BlankForestryPlugin { if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && boPTurnip != null) { Item boPTurnipSeeds = ForgeRegistries.ITEMS.getValue(new ResourceLocation(BoP, "turnipSeeds")); ItemStack boPTurnipSeedStack = new ItemStack(boPTurnipSeeds, 1, 0); - if (boPTurnipSeeds != null) { + if (!boPTurnipSeedStack.isEmpty()) { //TODO BoP for 1.9: Add farmable saplings // Farmables.farmables.get("farmVegetables").add(new FarmableHandPlanted(boPTurnipSeedStack, boPTurnip, 7)); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FACTORY)) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{boPTurnipSeedStack}, Fluids.SEED_OIL.getFluid(amount)); + RecipeManagers.squeezerManager.addRecipe(10, boPTurnipSeedStack, Fluids.SEED_OIL.getFluid(amount)); } } @@ -127,11 +131,11 @@ public class PluginBiomesOPlenty extends BlankForestryPlugin { private static void addFermenterRecipes() { int saplingYield = ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"); - if (saplings != Blocks.AIR) { + if (saplings != null && saplings != Blocks.AIR) { RecipeUtil.addFermenterRecipes(new ItemStack(saplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); } - if (colorizedSaplings != Blocks.AIR) { + if (colorizedSaplings != null && colorizedSaplings != Blocks.AIR) { RecipeUtil.addFermenterRecipes(new ItemStack(colorizedSaplings, 1, OreDictionary.WILDCARD_VALUE), saplingYield, Fluids.BIOMASS); } } @@ -141,16 +145,16 @@ public class PluginBiomesOPlenty extends BlankForestryPlugin { Item pinecone = ForgeRegistries.ITEMS.getValue(new ResourceLocation(BoP, "pinecone")); if (pinecone != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(pinecone)}, Fluids.SEED_OIL.getFluid(3 * amount)); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(pinecone), Fluids.SEED_OIL.getFluid(3 * amount)); } if (food != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(food)}, Fluids.JUICE.getFluid(50), mulch, 5); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(food), Fluids.JUICE.getFluid(50), mulch, 5); } Item persimmon = ForgeRegistries.ITEMS.getValue(new ResourceLocation(BoP, "persimmon")); if (persimmon != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{new ItemStack(persimmon)}, Fluids.JUICE.getFluid(200), mulch, 20); + RecipeManagers.squeezerManager.addRecipe(10, new ItemStack(persimmon), Fluids.JUICE.getFluid(200), mulch, 20); } } @@ -232,8 +236,8 @@ public class PluginBiomesOPlenty extends BlankForestryPlugin { Block block = ForgeRegistries.BLOCKS.getValue(new ResourceLocation(BoP, blockName)); if (block != null) { Item item = Item.getItemFromBlock(block); - if (item != null) { - ItemStack blockStack = new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE); + ItemStack blockStack = new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE); + if (!blockStack.isEmpty()) { BackpackManager.backpackInterface.addItemToForestryBackpack(backpackUid, blockStack); } else { Log.warning("Could not find an item for block: {}", blockName); diff --git a/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java b/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java index 1c4a31443..68fdb3c2b 100644 --- a/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java +++ b/src/main/java/forestry/plugins/compat/PluginBuildCraftTransport.java @@ -13,7 +13,8 @@ package forestry.plugins.compat; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.ForgeRegistries; import forestry.core.PluginCore; import forestry.core.config.Constants; @@ -42,7 +43,7 @@ public class PluginBuildCraftTransport extends BlankForestryPlugin { @Override public void registerRecipes() { Item beeswax = PluginCore.items.beeswax; - Item pipeWaterproof = GameRegistry.findItem(BCT, "pipeWaterproof"); + Item pipeWaterproof = ForgeRegistries.ITEMS.getValue(new ResourceLocation(BCT, "pipeWaterproof")); if (pipeWaterproof != null) { RecipeUtil.addShapelessRecipe(new ItemStack(pipeWaterproof), beeswax); } else { diff --git a/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java b/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java index 5dbb9d220..039d417ce 100644 --- a/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java +++ b/src/main/java/forestry/plugins/compat/PluginExtraUtilities.java @@ -17,7 +17,7 @@ import forestry.api.circuits.ICircuitLayout; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.core.PluginCore; -import forestry.core.circuits.Circuit; +import forestry.core.circuits.Circuits; import forestry.core.config.Config; import forestry.core.config.Constants; import forestry.core.items.EnumElectronTube; @@ -33,6 +33,7 @@ import forestry.plugins.ForestryPluginUids; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.init.Blocks; +import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; @@ -62,7 +63,7 @@ public class PluginExtraUtilities extends BlankForestryPlugin { Item enderLillyItem = Item.getItemFromBlock(enderLillyBlock); if (enderLillyBlock == Blocks.AIR) { Log.error("Could not find ender lilly block."); - } else if (enderLillyItem == null) { + } else if (enderLillyItem == Items.AIR) { Log.error("Could not find ender lilly item."); } else { IProperty growthProperty = BlockUtil.getProperty(enderLillyBlock, "growth", Integer.class); @@ -72,7 +73,7 @@ public class PluginExtraUtilities extends BlankForestryPlugin { int harvestAge = Collections.max(growthProperty.getAllowedValues()); int replantAge = enderLillyBlock.getDefaultState().getValue(growthProperty); Farmables.farmables.put("farmEnder", new FarmableAgingCrop(new ItemStack(enderLillyItem), enderLillyBlock, growthProperty, harvestAge, replantAge)); - Circuit.farmEnderManaged = new CircuitFarmLogic("managedEnder", new FarmLogicEnder()); + Circuits.farmEnderManaged = new CircuitFarmLogic("managedEnder", new FarmLogicEnder()); } } } @@ -81,9 +82,9 @@ public class PluginExtraUtilities extends BlankForestryPlugin { @Override public void registerRecipes() { super.registerRecipes(); - if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && Circuit.farmEnderManaged != null) { + if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && Circuits.farmEnderManaged != null) { ICircuitLayout layoutManaged = ChipsetManager.circuitRegistry.getLayout("forestry.farms.managed"); - ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.ENDER, 1), Circuit.farmEnderManaged); + ChipsetManager.solderManager.addRecipe(layoutManaged, PluginCore.items.tubes.get(EnumElectronTube.ENDER, 1), Circuits.farmEnderManaged); } } } diff --git a/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java b/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java index 2d05ff0d4..993549bdf 100644 --- a/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java +++ b/src/main/java/forestry/plugins/compat/PluginHarvestCraft.java @@ -10,20 +10,11 @@ ******************************************************************************/ package forestry.plugins.compat; -import com.google.common.collect.ImmutableList; - -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.block.Block; -import net.minecraft.block.properties.PropertyInteger; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import net.minecraftforge.fml.common.registry.ForgeRegistries; - +import static forestry.core.PluginCore.items; +import com.google.common.collect.ImmutableList; import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.fuels.FuelManager; @@ -38,8 +29,12 @@ import forestry.farming.logic.FarmableAgingCrop; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; - -import static forestry.core.PluginCore.items; +import net.minecraft.block.Block; +import net.minecraft.block.properties.PropertyInteger; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.registry.ForgeRegistries; @ForestryPlugin(pluginID = ForestryPluginUids.HARVESTCRAFT, name = "HarvestCraft", author = "Nirek", url = Constants.URL, unlocalizedDescription = "for.plugin.harvestcraft.description") public class PluginHarvestCraft extends BlankForestryPlugin { @@ -55,17 +50,19 @@ public class PluginHarvestCraft extends BlankForestryPlugin { public String getFailMessage() { return "HarvestCraft not found"; } - + @Nullable - private static ItemStack getItemStack(@Nonnull String itemName) { + private static ItemStack getItemStack(String itemName) { ResourceLocation key = new ResourceLocation(HC, itemName); if (ForgeRegistries.ITEMS.containsKey(key)) { - return new ItemStack(ForgeRegistries.ITEMS.getValue(key),1); + return new ItemStack(ForgeRegistries.ITEMS.getValue(key), 1); } else { return null; } } - private static Block getBlock(@Nonnull String blockName) { + + @Nullable + private static Block getBlock(String blockName) { ResourceLocation key = new ResourceLocation(HC, blockName); if (ForgeRegistries.BLOCKS.containsKey(key)) { return ForgeRegistries.BLOCKS.getValue(key); @@ -73,7 +70,8 @@ public class PluginHarvestCraft extends BlankForestryPlugin { return null; } } - @Override + + @Override public void registerRecipes() { ImmutableList berries = ImmutableList.of( @@ -216,17 +214,17 @@ public class PluginHarvestCraft extends BlankForestryPlugin { int wheatamount = ForestryAPI.activeMode.getIntegerSetting("recipe.output.compost.wheat"); PropertyInteger plantAGE = PropertyInteger.create("age", 0, 3); PropertyInteger fruitAGE = PropertyInteger.create("age", 0, 2); - + juiceAmount = Math.max(juiceAmount, 1); // Produce at least 1 mb of juice. for (String berryName : berries) { ItemStack berry = getItemStack(berryName + "Item"); - ItemStack berrySeed = getItemStack( berryName + "seedItem"); + ItemStack berrySeed = getItemStack(berryName + "seedItem"); Block berryBlock = getBlock("pam" + berryName + "Crop"); if (berry != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{berry}, Fluids.JUICE.getFluid(juiceAmount)); + RecipeManagers.squeezerManager.addRecipe(10, berry, Fluids.JUICE.getFluid(juiceAmount)); } if (berrySeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{berrySeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, berrySeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && berrySeed != null && berryBlock != null) { Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(berrySeed, berryBlock, plantAGE, 3)); @@ -241,14 +239,14 @@ public class PluginHarvestCraft extends BlankForestryPlugin { ItemStack fruitSeed = getItemStack(fruitName + "seedItem"); Block fruitBlock = getBlock("pam" + fruitName + "Crop"); if (fruit != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{fruit}, Fluids.JUICE.getFluid(juiceAmount)); + RecipeManagers.squeezerManager.addRecipe(10, fruit, Fluids.JUICE.getFluid(juiceAmount)); } if (fruitSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{fruitSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, fruitSeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && fruitSeed != null && fruitBlock != null) { - Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(fruitSeed, fruitBlock,plantAGE, 3)); - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(fruitSeed,fruitBlock,plantAGE, 3, 0)); + Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(fruitSeed, fruitBlock, plantAGE, 3)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(fruitSeed, fruitBlock, plantAGE, 3, 0)); } plants.add(fruitName); } @@ -260,14 +258,14 @@ public class PluginHarvestCraft extends BlankForestryPlugin { ItemStack vegetableSeed = getItemStack(vegetableName + "seedItem"); Block vegetableBlock = getBlock("pam" + vegetableName + "Crop"); if (vegetable != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{vegetable}, Fluids.JUICE.getFluid(juiceAmount)); + RecipeManagers.squeezerManager.addRecipe(10, vegetable, Fluids.JUICE.getFluid(juiceAmount)); } if (vegetableSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{vegetableSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, vegetableSeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && vegetableSeed != null && vegetableBlock != null) { - Farmables.farmables.get("farmVegetables").add(new FarmableAgingCrop(vegetableSeed, vegetableBlock,plantAGE, 3)); - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(vegetableSeed, vegetableBlock,plantAGE, 3, 0)); + Farmables.farmables.get("farmVegetables").add(new FarmableAgingCrop(vegetableSeed, vegetableBlock, plantAGE, 3)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(vegetableSeed, vegetableBlock, plantAGE, 3, 0)); } plants.add(vegetableName); } @@ -281,12 +279,12 @@ public class PluginHarvestCraft extends BlankForestryPlugin { FuelManager.moistenerResource.put(grain, new MoistenerFuel(grain, items.mouldyWheat.getItemStack(), 0, 300)); } if (grainSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{grainSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, grainSeed, Fluids.SEED_OIL.getFluid(seedamount)); RecipeManagers.moistenerManager.addRecipe(grainSeed, new ItemStack(Blocks.MYCELIUM), 5000); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && grainSeed != null && grainBlock != null) { - Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(grainSeed, grainBlock,plantAGE, 3)); - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(grainSeed,grainBlock,plantAGE, 3, 0)); + Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(grainSeed, grainBlock, plantAGE, 3)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(grainSeed, grainBlock, plantAGE, 3, 0)); } plants.add(grainName); } @@ -295,10 +293,10 @@ public class PluginHarvestCraft extends BlankForestryPlugin { ItemStack treeFruit = getItemStack(treeFruitName + "Item"); Block treeFruitBlock = getBlock("pam" + (Character.toUpperCase(treeFruitName.charAt(0)) + treeFruitName.substring(1))); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && treeFruitBlock != null) { - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(null, treeFruitBlock, fruitAGE, 2, 0)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(ItemStack.EMPTY, treeFruitBlock, fruitAGE, 2, 0)); } if (treeFruit != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{treeFruit}, Fluids.JUICE.getFluid(juiceAmount)); + RecipeManagers.squeezerManager.addRecipe(10, treeFruit, Fluids.JUICE.getFluid(juiceAmount)); } plants.add(treeFruitName); } @@ -306,7 +304,7 @@ public class PluginHarvestCraft extends BlankForestryPlugin { for (String treeName : trees) { Block fruitBlock = getBlock("pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && fruitBlock != null) { - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(null, fruitBlock, fruitAGE, 2, 0)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(ItemStack.EMPTY, fruitBlock, fruitAGE, 2, 0)); } plants.add(treeName); } @@ -314,7 +312,7 @@ public class PluginHarvestCraft extends BlankForestryPlugin { for (String treeName : treesSpecial) { Block fruitBlock = getBlock("pam" + (Character.toUpperCase(treeName.charAt(0)) + treeName.substring(1))); if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && fruitBlock != null) { - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(null, fruitBlock, fruitAGE, 2, 0)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(ItemStack.EMPTY, fruitBlock, fruitAGE, 2, 0)); } } @@ -322,7 +320,7 @@ public class PluginHarvestCraft extends BlankForestryPlugin { ItemStack genericCropSeed = getItemStack(cropName + "seedItem"); Block genericCropBlock = getBlock("pam" + cropName + "Crop"); if (genericCropSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{genericCropSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, genericCropSeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && genericCropSeed != null && genericCropBlock != null) { Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(genericCropSeed, genericCropBlock, plantAGE, 3)); @@ -334,11 +332,11 @@ public class PluginHarvestCraft extends BlankForestryPlugin { Block mustardCropBlock = getBlock("pam" + "mustardseeds" + "Crop"); ItemStack mustardFruit = getItemStack("mustard" + "seedsItem"); if (mustardCropSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{mustardCropSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, mustardCropSeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && mustardCropSeed != null && mustardCropBlock != null) { Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(mustardCropSeed, mustardCropBlock, plantAGE, 3)); - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(mustardCropSeed,mustardCropBlock, plantAGE, 3, 0)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(mustardCropSeed, mustardCropBlock, plantAGE, 3, 0)); } if (mustardFruit != null) { RecipeUtil.addFermenterRecipes(mustardFruit, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); @@ -356,31 +354,31 @@ public class PluginHarvestCraft extends BlankForestryPlugin { ItemStack cropnutSeed = getItemStack(cropnutName + "seedItem"); Block cropnutBlock = getBlock("pam" + cropnutName + "Crop"); if (cropnutSeed != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{cropnutSeed}, Fluids.SEED_OIL.getFluid(seedamount)); + RecipeManagers.squeezerManager.addRecipe(10, cropnutSeed, Fluids.SEED_OIL.getFluid(seedamount)); } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && cropnutSeed != null && cropnutBlock != null) { Farmables.farmables.get("farmWheat").add(new FarmableAgingCrop(cropnutSeed, cropnutBlock, plantAGE, 3)); - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(cropnutSeed,cropnutBlock, plantAGE, 3, 0)); + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(cropnutSeed, cropnutBlock, plantAGE, 3, 0)); } if (cropnut != null) { - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{cropnut}, Fluids.SEED_OIL.getFluid(12 * seedamount)); + RecipeManagers.squeezerManager.addRecipe(20, cropnut, Fluids.SEED_OIL.getFluid(12 * seedamount)); } } for (String nutName : nuts) { ItemStack nut = getItemStack(nutName + "Item"); Block nutBlock = getBlock("pam" + (Character.toUpperCase(nutName.charAt(0)) + nutName.substring(1))); - if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)&& nutBlock != null) { - Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(null, nutBlock, fruitAGE, 2, 0)); + if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING) && nutBlock != null) { + Farmables.farmables.get("farmOrchard").add(new FarmableAgingCrop(ItemStack.EMPTY, nutBlock, fruitAGE, 2, 0)); } if (nut != null) { - RecipeManagers.squeezerManager.addRecipe(20, new ItemStack[]{nut}, Fluids.SEED_OIL.getFluid(15 * seedamount)); + RecipeManagers.squeezerManager.addRecipe(20, nut, Fluids.SEED_OIL.getFluid(15 * seedamount)); } } ItemStack hcHoneyItem = getItemStack("honeyItem"); if (hcHoneyItem != null) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{hcHoneyItem}, Fluids.FOR_HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP)); + RecipeManagers.squeezerManager.addRecipe(10, hcHoneyItem, Fluids.FOR_HONEY.getFluid(Constants.FLUID_PER_HONEY_DROP)); } ItemStack hcBeeswaxItem = getItemStack("beeswaxItem"); diff --git a/src/main/java/forestry/plugins/compat/PluginIC2.java b/src/main/java/forestry/plugins/compat/PluginIC2.java index 2f98b453b..a79442199 100644 --- a/src/main/java/forestry/plugins/compat/PluginIC2.java +++ b/src/main/java/forestry/plugins/compat/PluginIC2.java @@ -1,314 +1,314 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 SirSengir. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser Public License v3 - * which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl-3.0.txt - * - * Various Contributors including, but not limited to: - * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges - ******************************************************************************/ -package forestry.plugins.compat; - -import javax.annotation.Nonnull; -import java.util.Set; - -import com.google.common.collect.ImmutableMap; -import forestry.api.circuits.ChipsetManager; -import forestry.api.circuits.CircuitSocketType; -import forestry.api.circuits.ICircuitLayout; -import forestry.api.core.ForestryAPI; -import forestry.api.farming.Farmables; -import forestry.api.fuels.EngineBronzeFuel; -import forestry.api.fuels.FuelManager; -import forestry.api.recipes.RecipeManagers; -import forestry.api.storage.BackpackManager; -import forestry.api.storage.ICrateRegistry; -import forestry.api.storage.StorageManager; -import forestry.apiculture.PluginApiculture; -import forestry.apiculture.items.EnumPropolis; -import forestry.apiculture.items.ItemRegistryApiculture; -import forestry.core.PluginCore; -import forestry.core.blocks.BlockBogEarth; -import forestry.core.circuits.Circuit; -import forestry.core.circuits.CircuitLayout; -import forestry.core.config.Constants; -import forestry.core.fluids.Fluids; -import forestry.core.items.EnumElectronTube; -import forestry.core.items.ItemRegistryCore; -import forestry.core.recipes.RecipeUtil; -import forestry.core.utils.ItemStackUtil; -import forestry.core.utils.Log; -import forestry.core.utils.ModUtil; -import forestry.energy.PluginEnergy; -import forestry.energy.blocks.BlockRegistryEnergy; -import forestry.energy.circuits.CircuitElectricBoost; -import forestry.energy.circuits.CircuitElectricChoke; -import forestry.energy.circuits.CircuitElectricEfficiency; -import forestry.farming.circuits.CircuitFarmLogic; -import forestry.farming.logic.FarmLogicRubber; -import forestry.farming.logic.FarmableBasicIC2Crop; -import forestry.plugins.BlankForestryPlugin; -import forestry.plugins.ForestryPlugin; -import forestry.plugins.ForestryPluginUids; -import ic2.api.item.IC2Items; -import ic2.api.recipe.RecipeInputItemStack; -import ic2.api.recipe.Recipes; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fml.common.Optional; -import net.minecraftforge.fml.common.event.FMLInterModComms; - -@ForestryPlugin(pluginID = ForestryPluginUids.INDUSTRIALCRAFT2, name = "IndustrialCraft2", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.ic2.description") -public class PluginIC2 extends BlankForestryPlugin { - public static final String modId = "IC2"; - public static PluginIC2 instance; - - private static ItemStack rubberSapling; - private static ItemStack rubber; - public static ItemStack rubberWood; - public static ItemStack resin; - - public BlockRegistryIC2 blocks; - - public PluginIC2() { - if (PluginIC2.instance == null) { - PluginIC2.instance = this; - } - } - - @Override - public boolean isAvailable() { - return ModUtil.isModLoaded(PluginIC2.modId); - } - - @Override - public String getFailMessage() { - return "IndustrialCraft2 not found"; - } - - @Nonnull - @Override - public Set getDependencyUids() { - Set dependencyUids = super.getDependencyUids(); - dependencyUids.add(ForestryPluginUids.FARMING); - dependencyUids.add(ForestryPluginUids.FACTORY); - return dependencyUids; - } - - @Override - @Optional.Method(modid = PluginIC2.modId) - public void preInit() { - super.preInit(); - - // rubber chain - rubberWood = IC2Items.getItem("rubber_wood"); - resin = IC2Items.getItem("misc_resource", "resin"); - rubberSapling = IC2Items.getItem("sapling"); - rubber = IC2Items.getItem("crafting", "rubber"); - - Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", new FarmLogicRubber()); - - ICircuitLayout layoutEngineTin = new CircuitLayout("engine.tin", CircuitSocketType.ELECTRIC_ENGINE); - ChipsetManager.circuitRegistry.registerLayout(layoutEngineTin); - - Farmables.fertilizers.put(IC2Items.getItem("crop_res", "fertilizer"), 250); - } - - @Override - @Optional.Method(modid = PluginIC2.modId) - public void doInit() { - super.doInit(); - - // Remove some items from the recycler - if (Recipes.recyclerBlacklist != null) { - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beeQueenGE))); - Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beePrincessGE))); - } - } else { - Log.error("IC2 Recipes.recyclerBlacklist not found."); - } - - Circuit.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); - Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); - Circuit.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 7, 20); - Circuit.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 15, 40); - - blocks.electricalEngine.init(); - blocks.generator.init(); - } - - @Override - public void postInit() { - super.postInit(); - - if (BackpackManager.backpackInterface == null) { - return; - } - - if (resin != null) { - BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, resin); - } - if (rubber != null) { - BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubber); - } - if (rubberSapling != null) { - BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubberSapling); - } - ItemStack rubberLeaves = IC2Items.getItem("leaves"); - if (rubberLeaves != null) { - BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubberLeaves); - } - } - - @Override - public void registerCrates() { - ICrateRegistry crateRegistry = StorageManager.crateRegistry; - if (crateRegistry == null) { - return; - } - - if (resin != null) { - crateRegistry.registerCrate(resin); - } - - if (rubber != null) { - crateRegistry.registerCrate(rubber); - } - - ItemStack scrap = IC2Items.getItem("crafting", "scrap"); - if (scrap != null) { - crateRegistry.registerCrate(scrap); - } - - ItemStack uuMatter = IC2Items.getItem("misc_resource", "matter"); - if (uuMatter != null) { - crateRegistry.registerCrate(uuMatter); - } - - ItemStack silver = IC2Items.getItem("ingot", "silver"); - if (silver != null) { - crateRegistry.registerCrate(silver); - } - - ItemStack brass = IC2Items.getItem("ingot", "bronze"); - if (brass != null) { - crateRegistry.registerCrate(brass); - } - } - - @Override - @Optional.Method(modid = PluginIC2.modId) - public void registerRecipes() { - ItemRegistryCore coreItems = PluginCore.items; - - if (rubber != null) { - for (Object rubberOreDict : RecipeUtil.getOreDictRecipeEquivalents(rubber)) { - RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), coreItems.tubes.get(EnumElectronTube.RUBBER, 4), - new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', rubberOreDict}); - } - } - - ItemStack plantBall = IC2Items.getItem("crafting", "plant_ball"); - if (plantBall != null) { - RecipeUtil.addFermenterRecipes(plantBall, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); - } - - ItemStack bioChaff = IC2Items.getItem("crafting", "bio_chaff"); - if (bioChaff != null) { - RecipeUtil.addFermenterRecipes(bioChaff, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); - } - - ItemRegistryApiculture beeItems = PluginApiculture.items; - if (beeItems != null) { - if (resin != null) { - RecipeManagers.centrifugeManager.addRecipe(20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(resin, 1.0f)); - } else { - Log.info("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); - } - } - - if (rubberSapling != null) { - RecipeUtil.addFermenterRecipes(rubberSapling, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - } else { - Log.info("Missing IC2 rubber sapling, skipping fermenter recipe for converting rubber sapling to biomass."); - } - - if (rubberSapling != null && resin != null) { - String saplingName = ItemStackUtil.getBlockNameFromRegistryAsSting(ItemStackUtil.getBlock(rubberSapling)); - String resinName = ItemStackUtil.getItemNameFromRegistryAsString(resin.getItem()); - String imc = String.format("farmArboreal@%s.%s.%s.%s", - saplingName, rubberSapling.getItemDamage(), - resinName, resin.getItemDamage()); - Log.trace("Sending IMC '%s'.", imc); - FMLInterModComms.sendMessage(Constants.MOD_ID, "add-farmable-sapling", imc); - } - - - if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ENERGY)) { - Fluid biogas = FluidRegistry.getFluid("ic2biogas"); - if (biogas != null) { - int burnDuration = Math.round(Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")); - EngineBronzeFuel bronzeFuel = new EngineBronzeFuel(Fluids.BIOMASS.getFluid(), Constants.ENGINE_FUEL_VALUE_BIOMASS, burnDuration, 1); - FuelManager.bronzeEngineFuel.put(biogas, bronzeFuel); - } - } - - ItemStack waterCell = IC2Items.getItem("fluid_cell", "water"); - if (waterCell != null) { - int bogEarthOutputCan = ForestryAPI.activeMode.getIntegerSetting("recipe.output.bogearth.can"); - if (bogEarthOutputCan > 0) { - ItemStack bogEarthCan = PluginCore.blocks.bogEarth.get(BlockBogEarth.SoilType.BOG_EARTH, bogEarthOutputCan); - RecipeUtil.addRecipe(bogEarthCan, "#Y#", "YXY", "#Y#", '#', Blocks.DIRT, 'X', waterCell, 'Y', "sand"); - } - } - - ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.engine.tin"); - - // / Solder Manager - ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.COPPER, 1), Circuit.energyElectricChoke1); - ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.TIN, 1), Circuit.energyElectricBoost1); - ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.energyElectricBoost2); - ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.IRON, 1), Circuit.energyElectricEfficiency1); - - if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)) { - if (resin != null && rubberWood != null) { - ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); - ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.RUBBER, 1), Circuit.farmRubberManual); - } - - Farmables.farmables.get("farmOrchard").add(new FarmableBasicIC2Crop()); - } - - - BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; - if (energyBlocks != null) { - RecipeUtil.addRecipe(blocks.generator, - "X#X", - "XYX", - "X#X", - '#', "blockGlass", - 'X', "ingotGold", - 'Y', coreItems.sturdyCasing); - - RecipeUtil.addRecipe(blocks.electricalEngine, - "###", - " X ", - "YVY", - '#', "ingotTin", - 'X', "blockGlass", - 'Y', "gearTin", - 'V', Blocks.PISTON); - } - } - - @Override - public void registerItemsAndBlocks() { - super.registerItemsAndBlocks(); - blocks = new BlockRegistryIC2(); - } -} +///******************************************************************************* +// * Copyright (c) 2011-2014 SirSengir. +// * All rights reserved. This program and the accompanying materials +// * are made available under the terms of the GNU Lesser Public License v3 +// * which accompanies this distribution, and is available at +// * http://www.gnu.org/licenses/lgpl-3.0.txt +// * +// * Various Contributors including, but not limited to: +// * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges +// ******************************************************************************/ +//package forestry.plugins.compat; +// +//import javax.annotation.Nonnull; +//import java.util.Set; +// +//import com.google.common.collect.ImmutableMap; +//import forestry.api.circuits.ChipsetManager; +//import forestry.api.circuits.CircuitSocketType; +//import forestry.api.circuits.ICircuitLayout; +//import forestry.api.core.ForestryAPI; +//import forestry.api.farming.Farmables; +//import forestry.api.fuels.EngineBronzeFuel; +//import forestry.api.fuels.FuelManager; +//import forestry.api.recipes.RecipeManagers; +//import forestry.api.storage.BackpackManager; +//import forestry.api.storage.ICrateRegistry; +//import forestry.api.storage.StorageManager; +//import forestry.apiculture.PluginApiculture; +//import forestry.apiculture.items.EnumPropolis; +//import forestry.apiculture.items.ItemRegistryApiculture; +//import forestry.core.PluginCore; +//import forestry.core.blocks.BlockBogEarth; +//import forestry.core.circuits.Circuit; +//import forestry.core.circuits.CircuitLayout; +//import forestry.core.config.Constants; +//import forestry.core.fluids.Fluids; +//import forestry.core.items.EnumElectronTube; +//import forestry.core.items.ItemRegistryCore; +//import forestry.core.recipes.RecipeUtil; +//import forestry.core.utils.ItemStackUtil; +//import forestry.core.utils.Log; +//import forestry.core.utils.ModUtil; +//import forestry.energy.PluginEnergy; +//import forestry.energy.blocks.BlockRegistryEnergy; +//import forestry.energy.circuits.CircuitElectricBoost; +//import forestry.energy.circuits.CircuitElectricChoke; +//import forestry.energy.circuits.CircuitElectricEfficiency; +//import forestry.farming.circuits.CircuitFarmLogic; +//import forestry.farming.logic.FarmLogicRubber; +//import forestry.farming.logic.FarmableBasicIC2Crop; +//import forestry.plugins.BlankForestryPlugin; +//import forestry.plugins.ForestryPlugin; +//import forestry.plugins.ForestryPluginUids; +//import ic2.api.item.IC2Items; +//import ic2.api.recipe.RecipeInputItemStack; +//import ic2.api.recipe.Recipes; +//import net.minecraft.init.Blocks; +//import net.minecraft.item.ItemStack; +//import net.minecraftforge.fluids.Fluid; +//import net.minecraftforge.fluids.FluidRegistry; +//import net.minecraftforge.fml.common.Optional; +//import net.minecraftforge.fml.common.event.FMLInterModComms; +// +//@ForestryPlugin(pluginID = ForestryPluginUids.INDUSTRIALCRAFT2, name = "IndustrialCraft2", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.ic2.description") +//public class PluginIC2 extends BlankForestryPlugin { +// public static final String modId = "IC2"; +// public static PluginIC2 instance; +// +// private static ItemStack rubberSapling; +// private static ItemStack rubber; +// public static ItemStack rubberWood; +// public static ItemStack resin; +// +// public BlockRegistryIC2 blocks; +// +// public PluginIC2() { +// if (PluginIC2.instance == null) { +// PluginIC2.instance = this; +// } +// } +// +// @Override +// public boolean isAvailable() { +// return ModUtil.isModLoaded(PluginIC2.modId); +// } +// +// @Override +// public String getFailMessage() { +// return "IndustrialCraft2 not found"; +// } +// +// @Nonnull +// @Override +// public Set getDependencyUids() { +// Set dependencyUids = super.getDependencyUids(); +// dependencyUids.add(ForestryPluginUids.FARMING); +// dependencyUids.add(ForestryPluginUids.FACTORY); +// return dependencyUids; +// } +// +// @Override +// @Optional.Method(modid = PluginIC2.modId) +// public void preInit() { +// super.preInit(); +// +// // rubber chain +// rubberWood = IC2Items.getItem("rubber_wood"); +// resin = IC2Items.getItem("misc_resource", "resin"); +// rubberSapling = IC2Items.getItem("sapling"); +// rubber = IC2Items.getItem("crafting", "rubber"); +// +// Circuit.farmRubberManual = new CircuitFarmLogic("manualRubber", new FarmLogicRubber()); +// +// ICircuitLayout layoutEngineTin = new CircuitLayout("engine.tin", CircuitSocketType.ELECTRIC_ENGINE); +// ChipsetManager.circuitRegistry.registerLayout(layoutEngineTin); +// +// Farmables.fertilizers.put(IC2Items.getItem("crop_res", "fertilizer"), 250); +// } +// +// @Override +// @Optional.Method(modid = PluginIC2.modId) +// public void doInit() { +// super.doInit(); +// +// // Remove some items from the recycler +// if (Recipes.recyclerBlacklist != null) { +// ItemRegistryApiculture beeItems = PluginApiculture.items; +// if (beeItems != null) { +// Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beeQueenGE))); +// Recipes.recyclerBlacklist.add(new RecipeInputItemStack(new ItemStack(beeItems.beePrincessGE))); +// } +// } else { +// Log.error("IC2 Recipes.recyclerBlacklist not found."); +// } +// +// Circuit.energyElectricChoke1 = new CircuitElectricChoke("electric.choke.1"); +// Circuit.energyElectricEfficiency1 = new CircuitElectricEfficiency("electric.efficiency.1"); +// Circuit.energyElectricBoost1 = new CircuitElectricBoost("electric.boost.1", 7, 20); +// Circuit.energyElectricBoost2 = new CircuitElectricBoost("electric.boost.2", 15, 40); +// +// blocks.electricalEngine.init(); +// blocks.generator.init(); +// } +// +// @Override +// public void postInit() { +// super.postInit(); +// +// if (BackpackManager.backpackInterface == null) { +// return; +// } +// +// if (resin != null) { +// BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, resin); +// } +// if (rubber != null) { +// BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubber); +// } +// if (rubberSapling != null) { +// BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubberSapling); +// } +// ItemStack rubberLeaves = IC2Items.getItem("leaves"); +// if (rubberLeaves != null) { +// BackpackManager.backpackInterface.addItemToForestryBackpack(BackpackManager.FORESTER_UID, rubberLeaves); +// } +// } +// +// @Override +// public void registerCrates() { +// ICrateRegistry crateRegistry = StorageManager.crateRegistry; +// if (crateRegistry == null) { +// return; +// } +// +// if (resin != null) { +// crateRegistry.registerCrate(resin); +// } +// +// if (rubber != null) { +// crateRegistry.registerCrate(rubber); +// } +// +// ItemStack scrap = IC2Items.getItem("crafting", "scrap"); +// if (scrap != null) { +// crateRegistry.registerCrate(scrap); +// } +// +// ItemStack uuMatter = IC2Items.getItem("misc_resource", "matter"); +// if (uuMatter != null) { +// crateRegistry.registerCrate(uuMatter); +// } +// +// ItemStack silver = IC2Items.getItem("ingot", "silver"); +// if (silver != null) { +// crateRegistry.registerCrate(silver); +// } +// +// ItemStack brass = IC2Items.getItem("ingot", "bronze"); +// if (brass != null) { +// crateRegistry.registerCrate(brass); +// } +// } +// +// @Override +// @Optional.Method(modid = PluginIC2.modId) +// public void registerRecipes() { +// ItemRegistryCore coreItems = PluginCore.items; +// +// if (rubber != null) { +// for (Object rubberOreDict : RecipeUtil.getOreDictRecipeEquivalents(rubber)) { +// RecipeManagers.fabricatorManager.addRecipe(null, Fluids.GLASS.getFluid(500), coreItems.tubes.get(EnumElectronTube.RUBBER, 4), +// new Object[]{" X ", "#X#", "XXX", '#', "dustRedstone", 'X', rubberOreDict}); +// } +// } +// +// ItemStack plantBall = IC2Items.getItem("crafting", "plant_ball"); +// if (plantBall != null) { +// RecipeUtil.addFermenterRecipes(plantBall, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); +// } +// +// ItemStack bioChaff = IC2Items.getItem("crafting", "bio_chaff"); +// if (bioChaff != null) { +// RecipeUtil.addFermenterRecipes(bioChaff, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat") * 9, Fluids.BIOMASS); +// } +// +// ItemRegistryApiculture beeItems = PluginApiculture.items; +// if (beeItems != null) { +// if (resin != null) { +// RecipeManagers.centrifugeManager.addRecipe(20, beeItems.propolis.get(EnumPropolis.NORMAL, 1), ImmutableMap.of(resin, 1.0f)); +// } else { +// Log.info("Missing IC2 resin, skipping centrifuge recipe for propolis to resin."); +// } +// } +// +// if (rubberSapling != null) { +// RecipeUtil.addFermenterRecipes(rubberSapling, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); +// } else { +// Log.info("Missing IC2 rubber sapling, skipping fermenter recipe for converting rubber sapling to biomass."); +// } +// +// if (rubberSapling != null && resin != null) { +// String saplingName = ItemStackUtil.getBlockNameFromRegistryAsSting(ItemStackUtil.getBlock(rubberSapling)); +// String resinName = ItemStackUtil.getItemNameFromRegistryAsString(resin.getItem()); +// String imc = String.format("farmArboreal@%s.%s.%s.%s", +// saplingName, rubberSapling.getItemDamage(), +// resinName, resin.getItemDamage()); +// Log.trace("Sending IMC '%s'.", imc); +// FMLInterModComms.sendMessage(Constants.MOD_ID, "add-farmable-sapling", imc); +// } +// +// +// if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.ENERGY)) { +// Fluid biogas = FluidRegistry.getFluid("ic2biogas"); +// if (biogas != null) { +// int burnDuration = Math.round(Constants.ENGINE_CYCLE_DURATION_BIOMASS * ForestryAPI.activeMode.getFloatSetting("fuel.biomass.biogas")); +// EngineBronzeFuel bronzeFuel = new EngineBronzeFuel(Fluids.BIOMASS.getFluid(), Constants.ENGINE_FUEL_VALUE_BIOMASS, burnDuration, 1); +// FuelManager.bronzeEngineFuel.put(biogas, bronzeFuel); +// } +// } +// +// ItemStack waterCell = IC2Items.getItem("fluid_cell", "water"); +// if (waterCell != null) { +// int bogEarthOutputCan = ForestryAPI.activeMode.getIntegerSetting("recipe.output.bogearth.can"); +// if (bogEarthOutputCan > 0) { +// ItemStack bogEarthCan = PluginCore.blocks.bogEarth.get(BlockBogEarth.SoilType.BOG_EARTH, bogEarthOutputCan); +// RecipeUtil.addRecipe(bogEarthCan, "#Y#", "YXY", "#Y#", '#', Blocks.DIRT, 'X', waterCell, 'Y', "sand"); +// } +// } +// +// ICircuitLayout layout = ChipsetManager.circuitRegistry.getLayout("forestry.engine.tin"); +// +// // / Solder Manager +// ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.COPPER, 1), Circuit.energyElectricChoke1); +// ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.TIN, 1), Circuit.energyElectricBoost1); +// ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.BRONZE, 1), Circuit.energyElectricBoost2); +// ChipsetManager.solderManager.addRecipe(layout, coreItems.tubes.get(EnumElectronTube.IRON, 1), Circuit.energyElectricEfficiency1); +// +// if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)) { +// if (resin != null && rubberWood != null) { +// ICircuitLayout layoutManual = ChipsetManager.circuitRegistry.getLayout("forestry.farms.manual"); +// ChipsetManager.solderManager.addRecipe(layoutManual, coreItems.tubes.get(EnumElectronTube.RUBBER, 1), Circuit.farmRubberManual); +// } +// +// Farmables.farmables.get("farmOrchard").add(new FarmableBasicIC2Crop()); +// } +// +// +// BlockRegistryEnergy energyBlocks = PluginEnergy.blocks; +// if (energyBlocks != null) { +// RecipeUtil.addRecipe(blocks.generator, +// "X#X", +// "XYX", +// "X#X", +// '#', "blockGlass", +// 'X', "ingotGold", +// 'Y', coreItems.sturdyCasing); +// +// RecipeUtil.addRecipe(blocks.electricalEngine, +// "###", +// " X ", +// "YVY", +// '#', "ingotTin", +// 'X', "blockGlass", +// 'Y', "gearTin", +// 'V', Blocks.PISTON); +// } +// } +// +// @Override +// public void registerItemsAndBlocks() { +// super.registerItemsAndBlocks(); +// blocks = new BlockRegistryIC2(); +// } +//} diff --git a/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java b/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java index e63e73efb..1c993a4b0 100644 --- a/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java +++ b/src/main/java/forestry/plugins/compat/PluginImmersiveEngineering.java @@ -1,5 +1,7 @@ package forestry.plugins.compat; +import javax.annotation.Nullable; + import forestry.api.core.ForestryAPI; import forestry.api.farming.Farmables; import forestry.api.farming.ICrop; @@ -15,15 +17,13 @@ import forestry.plugins.ForestryPluginUids; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.ForgeRegistries; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - @ForestryPlugin(pluginID = ForestryPluginUids.IMMERSIVE_ENGINEERING, name = "ImmersiveEngineering", author = "marcin212", url = Constants.URL, unlocalizedDescription = "for.plugin.immersiveengineering.description") public class PluginImmersiveEngineering extends BlankForestryPlugin { private static final String IE = "immersiveengineering"; @@ -43,9 +43,9 @@ public class PluginImmersiveEngineering extends BlankForestryPlugin { ItemStack hempSeed = getItemStack("seed"); Block hempCrop = getBlock("hemp"); int seedAmount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - IProperty age = hempCrop.getBlockState().getProperties().stream().filter(p -> p.getName().equals("type")).findAny().get(); + IProperty age = hempCrop.getBlockState().getProperties().stream().filter(p -> p.getName().equals("type")).findAny().orElseGet(null); - if (hempSeed != null && hempCrop != null && age != null) { + if (hempSeed != null && hempCrop != Blocks.AIR && age != null) { IBlockState planted = hempCrop.getDefaultState().withProperty(age, (Comparable) age.parseValue("bottom0").get()); IBlockState mature = hempCrop.getDefaultState().withProperty(age, (Comparable) age.parseValue("top0").get()); Farmables.farmables.get("farmWheat").add(new FarmableBase(hempSeed, planted, mature, false) { @@ -59,11 +59,12 @@ public class PluginImmersiveEngineering extends BlankForestryPlugin { } }); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{hempSeed}, Fluids.SEED_OIL.getFluid(seedAmount)); + RecipeManagers.squeezerManager.addRecipe(10, hempSeed, Fluids.SEED_OIL.getFluid(seedAmount)); } } - private static Block getBlock(@Nonnull String blockName) { + @Nullable + private static Block getBlock(String blockName) { ResourceLocation key = new ResourceLocation(IE, blockName); if (ForgeRegistries.BLOCKS.containsKey(key)) { return ForgeRegistries.BLOCKS.getValue(key); @@ -73,7 +74,7 @@ public class PluginImmersiveEngineering extends BlankForestryPlugin { } @Nullable - private static ItemStack getItemStack(@Nonnull String itemName, int meta) { + private static ItemStack getItemStack(String itemName, int meta) { ResourceLocation key = new ResourceLocation(IE, itemName); if (ForgeRegistries.ITEMS.containsKey(key)) { return new ItemStack(ForgeRegistries.ITEMS.getValue(key), 1, meta); @@ -83,7 +84,7 @@ public class PluginImmersiveEngineering extends BlankForestryPlugin { } @Nullable - private static ItemStack getItemStack(@Nonnull String itemName) { + private static ItemStack getItemStack(String itemName) { return getItemStack(itemName, 0); } } diff --git a/src/main/java/forestry/plugins/compat/PluginNatura.java b/src/main/java/forestry/plugins/compat/PluginNatura.java index 610537367..0b39a1c4c 100644 --- a/src/main/java/forestry/plugins/compat/PluginNatura.java +++ b/src/main/java/forestry/plugins/compat/PluginNatura.java @@ -10,18 +10,10 @@ ******************************************************************************/ package forestry.plugins.compat; +import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; -import net.minecraft.block.Block; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.common.event.FMLInterModComms; -import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.oredict.OreDictionary; - import forestry.api.core.ForestryAPI; import forestry.api.fuels.FuelManager; import forestry.api.fuels.MoistenerFuel; @@ -37,18 +29,31 @@ import forestry.core.utils.ModUtil; import forestry.plugins.BlankForestryPlugin; import forestry.plugins.ForestryPlugin; import forestry.plugins.ForestryPluginUids; +import net.minecraft.block.Block; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.event.FMLInterModComms; +import net.minecraftforge.fml.common.registry.ForgeRegistries; +import net.minecraftforge.oredict.OreDictionary; @ForestryPlugin(pluginID = ForestryPluginUids.NATURA, name = "Natura", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.natura.description") public class PluginNatura extends BlankForestryPlugin { private static final String NATURA = "Natura"; + @Nullable private static Block logNatura; + @Nullable private static Block logWillow; - + @Nullable private static Block leavesNatura; + @Nullable private static Block saplingNatura; + @Nullable private static Block saplingNaturaRare; + private static ItemStack berryBlight; private static ItemStack berryDusk; private static ItemStack berrySky; @@ -73,11 +78,11 @@ public class PluginNatura extends BlankForestryPlugin { public void preInit() { super.preInit(); - logNatura = GameRegistry.findBlock(NATURA, "tree"); - logWillow = GameRegistry.findBlock(NATURA, "willow"); - leavesNatura = GameRegistry.findBlock(NATURA, "floraleaves"); - saplingNatura = GameRegistry.findBlock(NATURA, "florasapling"); - saplingNaturaRare = GameRegistry.findBlock(NATURA, "Rare Sapling"); + logNatura = getBlock("tree"); + logWillow = getBlock("willow"); + leavesNatura = getBlock("floraleaves"); + saplingNatura = getBlock("florasapling"); + saplingNaturaRare = getBlock("Rare Sapling"); ArrayList saplingItemKeys = new ArrayList<>(); @@ -89,28 +94,24 @@ public class PluginNatura extends BlankForestryPlugin { } for (String key : saplingItemKeys) { - Item saplingItem = GameRegistry.findItem(NATURA, key); + ItemStack saplingWild = getItemStack(key, OreDictionary.WILDCARD_VALUE); + if (!saplingWild.isEmpty()) { + RecipeUtil.addFermenterRecipes(saplingWild, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - ItemStack saplingWild = new ItemStack(saplingItem, 1, OreDictionary.WILDCARD_VALUE); - RecipeUtil.addFermenterRecipes(saplingWild, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.sapling"), Fluids.BIOMASS); - - String saplingName = ItemStackUtil.getItemNameFromRegistryAsString(saplingItem); - FMLInterModComms.sendMessage(Constants.MOD_ID, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + String saplingName = ItemStackUtil.getItemNameFromRegistryAsString(saplingWild.getItem()); + FMLInterModComms.sendMessage(Constants.MOD_ID, "add-farmable-sapling", String.format("farmArboreal@%s.-1", saplingName)); + } } - Item netherBerry = GameRegistry.findItem(NATURA, "berry.nether"); - Item berry = GameRegistry.findItem(NATURA, "berry"); - Item barley = GameRegistry.findItem(NATURA, "barleyFood"); - - berryBlight = new ItemStack(netherBerry, 1, 0); - berryDusk = new ItemStack(netherBerry, 1, 1); - berrySky = new ItemStack(netherBerry, 1, 2); - berrySting = new ItemStack(netherBerry, 1, 3); - berryRasp = new ItemStack(berry, 1, 0); - berryBlue = new ItemStack(berry, 1, 1); - berryBlack = new ItemStack(berry, 1, 2); - berryMalo = new ItemStack(berry, 1, 3); - itemBarley = new ItemStack(barley); + berryBlight = getItemStack("berry.nether", 0); + berryDusk = getItemStack("berry.nether", 1); + berrySky = getItemStack("berry.nether", 2); + berrySting = getItemStack("berry.nether", 3); + berryRasp = getItemStack("berry", 0); + berryBlue = getItemStack("berry", 1); + berryBlack = getItemStack("berry", 2); + berryMalo = getItemStack("berry", 3); + itemBarley = getItemStack("barleyFood", 0); } @Override @@ -119,31 +120,31 @@ public class PluginNatura extends BlankForestryPlugin { ICrateRegistry crateRegistry = StorageManager.crateRegistry; - if (berryBlight != null) { + if (!berryBlight.isEmpty()) { crateRegistry.registerCrate(berryBlight); } - if (berryDusk != null) { + if (!berryDusk.isEmpty()) { crateRegistry.registerCrate(berryDusk); } - if (berrySky != null) { + if (!berrySky.isEmpty()) { crateRegistry.registerCrate(berrySky); } - if (berrySting != null) { + if (!berrySting.isEmpty()) { crateRegistry.registerCrate(berrySting); } - if (berryRasp != null) { + if (!berryRasp.isEmpty()) { crateRegistry.registerCrate(berryRasp); } - if (berryBlue != null) { + if (!berryBlue.isEmpty()) { crateRegistry.registerCrate(berryBlue); } - if (berryBlack != null) { + if (!berryBlack.isEmpty()) { crateRegistry.registerCrate(berryBlack); } - if (berryMalo != null) { + if (!berryMalo.isEmpty()) { crateRegistry.registerCrate(berryMalo); } - if (itemBarley != null) { + if (!itemBarley.isEmpty()) { crateRegistry.registerCrate(itemBarley); } if (saplingNatura != null) { @@ -164,11 +165,11 @@ public class PluginNatura extends BlankForestryPlugin { crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 3)); crateRegistry.registerCrate(new ItemStack(saplingNaturaRare, 1, 4)); } - Item potashApple = GameRegistry.findItem(NATURA, "Natura.netherfood"); - if (potashApple != null) { - crateRegistry.registerCrate(new ItemStack(potashApple, 1, 0)); + ItemStack potashApple = getItemStack("Natura.netherfood", 0); + if (!potashApple.isEmpty()) { + crateRegistry.registerCrate(potashApple); } - Item glowShroom = GameRegistry.findItem(NATURA, "Glowshroom"); + Item glowShroom = getItem("Glowshroom"); if (glowShroom != null) { crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 0)); crateRegistry.registerCrate(new ItemStack(glowShroom, 1, 1)); @@ -179,22 +180,25 @@ public class PluginNatura extends BlankForestryPlugin { crateRegistry.registerCrate(new ItemStack(logNatura, 1, 1)); crateRegistry.registerCrate(new ItemStack(logNatura, 1, 2)); crateRegistry.registerCrate(new ItemStack(logNatura, 1, 3)); + } + if (logWillow != null) { crateRegistry.registerCrate(new ItemStack(logWillow, 1, 0)); } - Item bloodWood = GameRegistry.findItem(NATURA, "bloodwood"); + + Item bloodWood = getItem("bloodwood"); if (bloodWood != null) { crateRegistry.registerCrate(new ItemStack(bloodWood, 1, 0)); } - Item darkTree = GameRegistry.findItem(NATURA, "Dark Tree"); + Item darkTree = getItem("Dark Tree"); if (darkTree != null) { crateRegistry.registerCrate(new ItemStack(darkTree, 1, 0)); crateRegistry.registerCrate(new ItemStack(darkTree, 1, 1)); } - Item heatSand = GameRegistry.findItem(NATURA, "heatsand"); + Item heatSand = getItem("heatsand"); if (heatSand != null) { crateRegistry.registerCrate(new ItemStack(heatSand, 1, 0)); } - Item taintedSoil = GameRegistry.findItem(NATURA, "soil.tainted"); + Item taintedSoil = getItem("soil.tainted"); if (taintedSoil != null) { crateRegistry.registerCrate(new ItemStack(taintedSoil, 1, 0)); } @@ -202,71 +206,74 @@ public class PluginNatura extends BlankForestryPlugin { @Override public void registerRecipes() { - Item seed = GameRegistry.findItem(NATURA, "barley.seed"); - ItemStack seedBarley = new ItemStack(seed, 1, 0); - ItemStack seedCotton = new ItemStack(seed, 1, 1); - - ArrayList seedList = new ArrayList<>(); - if (seedBarley != null) { - seedList.add(seedBarley); - RecipeManagers.moistenerManager.addRecipe(seedBarley, new ItemStack(Blocks.MYCELIUM), 5000); - } - if (seedCotton != null) { - seedList.add(seedCotton); - } - int amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.seed"); - for (ItemStack aSeedList : seedList) { - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{aSeedList}, Fluids.SEED_OIL.getFluid(amount)); + + Item seed = getItem("barley.seed"); + if (seed != null) { + ItemStack seedBarley = new ItemStack(seed, 1, 0); + ItemStack seedCotton = new ItemStack(seed, 1, 1); + + ArrayList seedList = new ArrayList<>(); + if (!seedBarley.isEmpty()) { + seedList.add(seedBarley); + RecipeManagers.moistenerManager.addRecipe(seedBarley, new ItemStack(Blocks.MYCELIUM), 5000); + } + if (!seedCotton.isEmpty()) { + seedList.add(seedCotton); + } + + for (ItemStack aSeedList : seedList) { + RecipeManagers.squeezerManager.addRecipe(10, aSeedList, Fluids.SEED_OIL.getFluid(amount)); + } } if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FARMING)) { - Block cropBlock = GameRegistry.findBlock(NATURA, "N Crops"); + Block cropBlock = getBlock("N Crops"); //TODO: Natura for 1.9 // Farmables.farmables.get("farmWheat").add(new FarmableHandPlanted(seedBarley, cropBlock, 3)); // Farmables.farmables.get("farmWheat").add(new FarmableHandPlanted(seedCotton, cropBlock, 8)); } - + List berries = new ArrayList<>(); - if (berryBlight != null) { + if (!berryBlight.isEmpty()) { berries.add(berryBlight); } - if (berryDusk != null) { + if (!berryDusk.isEmpty()) { berries.add(berryDusk); } - if (berrySky != null) { + if (!berrySky.isEmpty()) { berries.add(berrySky); } - if (berrySting != null) { + if (!berrySting.isEmpty()) { berries.add(berrySting); } - if (berryRasp != null) { + if (!berryRasp.isEmpty()) { berries.add(berryRasp); } - if (berryBlue != null) { + if (!berryBlue.isEmpty()) { berries.add(berryBlue); } - if (berryBlack != null) { + if (!berryBlack.isEmpty()) { berries.add(berryBlack); } - if (berryMalo != null) { + if (!berryMalo.isEmpty()) { berries.add(berryMalo); } amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 2; amount = Math.max(amount, 1); // Produce at least 1 mb of juice. - ItemStack netherFood = new ItemStack(GameRegistry.findItem(NATURA, "Natura.netherfood"), 1, 0); + ItemStack netherFood = getItemStack("Natura.netherfood", 0); ItemStack mulch = PluginCore.items.mulch.getItemStack(); - RecipeManagers.squeezerManager.addRecipe(10, new ItemStack[]{netherFood}, Fluids.JUICE.getFluid(amount), mulch, ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple")); + RecipeManagers.squeezerManager.addRecipe(10, netherFood, Fluids.JUICE.getFluid(amount), mulch, ForestryAPI.activeMode.getIntegerSetting("squeezer.mulch.apple")); amount = ForestryAPI.activeMode.getIntegerSetting("squeezer.liquid.apple") / 25; amount = Math.max(amount, 1); // Produce at least 1 mb of juice. for (ItemStack berry : berries) { - RecipeManagers.squeezerManager.addRecipe(3, new ItemStack[]{berry}, Fluids.JUICE.getFluid(amount)); + RecipeManagers.squeezerManager.addRecipe(3, berry, Fluids.JUICE.getFluid(amount)); } - if (itemBarley != null) { + if (!itemBarley.isEmpty()) { RecipeUtil.addFermenterRecipes(itemBarley, ForestryAPI.activeMode.getIntegerSetting("fermenter.yield.wheat"), Fluids.BIOMASS); int compostWheatAmount = ForestryAPI.activeMode.getIntegerSetting("recipe.output.compost.wheat"); if (compostWheatAmount > 0) { @@ -277,4 +284,32 @@ public class PluginNatura extends BlankForestryPlugin { } } + @Nullable + private static Block getBlock(String blockName) { + ResourceLocation key = new ResourceLocation(NATURA, blockName); + if (ForgeRegistries.BLOCKS.containsKey(key)) { + return ForgeRegistries.BLOCKS.getValue(key); + } else { + return null; + } + } + + @Nullable + private static Item getItem(String itemName) { + ResourceLocation key = new ResourceLocation(NATURA, itemName); + if (ForgeRegistries.ITEMS.containsKey(key)) { + return ForgeRegistries.ITEMS.getValue(key); + } else { + return null; + } + } + + private static ItemStack getItemStack(String itemName, int meta) { + ResourceLocation key = new ResourceLocation(NATURA, itemName); + if (ForgeRegistries.ITEMS.containsKey(key)) { + return new ItemStack(ForgeRegistries.ITEMS.getValue(key), 1, meta); + } else { + return ItemStack.EMPTY; + } + } } diff --git a/src/main/java/forestry/plugins/compat/package-info.java b/src/main/java/forestry/plugins/compat/package-info.java new file mode 100644 index 000000000..d0626a303 --- /dev/null +++ b/src/main/java/forestry/plugins/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.plugins.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/plugins/package-info.java b/src/main/java/forestry/plugins/package-info.java new file mode 100644 index 000000000..3b51069df --- /dev/null +++ b/src/main/java/forestry/plugins/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.plugins; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/storage/BackpackDefinition.java b/src/main/java/forestry/storage/BackpackDefinition.java index fd49bdd7a..cbd1f49c2 100755 --- a/src/main/java/forestry/storage/BackpackDefinition.java +++ b/src/main/java/forestry/storage/BackpackDefinition.java @@ -10,8 +10,7 @@ ******************************************************************************/ package forestry.storage; -import javax.annotation.Nonnull; -import java.awt.*; +import java.awt.Color; import java.util.function.Predicate; import forestry.api.storage.BackpackManager; @@ -24,26 +23,23 @@ import net.minecraft.nbt.NBTTagCompound; public class BackpackDefinition implements IBackpackDefinition { private final int primaryColor; private final int secondaryColor; - @Nonnull private final Predicate filter; - public BackpackDefinition(@Nonnull Color primaryColor, @Nonnull Color secondaryColor) { + public BackpackDefinition(Color primaryColor, Color secondaryColor) { this(primaryColor, secondaryColor, BackpackManager.backpackInterface.createBackpackFilter()); } - public BackpackDefinition(@Nonnull Color primaryColor, @Nonnull Color secondaryColor, @Nonnull Predicate filter) { + public BackpackDefinition(Color primaryColor, Color secondaryColor, Predicate filter) { this.primaryColor = primaryColor.getRGB(); this.secondaryColor = secondaryColor.getRGB(); this.filter = filter; } @Override - @Nonnull public Predicate getFilter() { return filter; } - @Nonnull @Override public String getName(ItemStack backpack) { Item item = backpack.getItem(); diff --git a/src/main/java/forestry/storage/BackpackFilter.java b/src/main/java/forestry/storage/BackpackFilter.java index a0d0660c5..b3f281ead 100644 --- a/src/main/java/forestry/storage/BackpackFilter.java +++ b/src/main/java/forestry/storage/BackpackFilter.java @@ -55,15 +55,11 @@ public class BackpackFilter implements IBackpackFilterConfigurable { @Override public boolean test(ItemStack itemStack) { - if (itemStack == null) { + if (itemStack.isEmpty()) { return false; } Item item = itemStack.getItem(); - if (item == null) { - return false; - } - String itemStackStringWild = ItemStackUtil.getItemNameFromRegistryAsString(item); if (rejectedItemStacks.contains(itemStackStringWild)) { return false; diff --git a/src/main/java/forestry/storage/BackpackFilterNaturalist.java b/src/main/java/forestry/storage/BackpackFilterNaturalist.java index 05ede58ea..875b45fe0 100644 --- a/src/main/java/forestry/storage/BackpackFilterNaturalist.java +++ b/src/main/java/forestry/storage/BackpackFilterNaturalist.java @@ -1,6 +1,5 @@ package forestry.storage; -import javax.annotation.Nonnull; import java.util.function.Predicate; import forestry.api.genetics.AlleleManager; @@ -8,16 +7,15 @@ import forestry.api.genetics.ISpeciesRoot; import net.minecraft.item.ItemStack; public class BackpackFilterNaturalist implements Predicate { - @Nonnull private final String speciesRootUid; - public BackpackFilterNaturalist(@Nonnull String speciesRootUid) { + public BackpackFilterNaturalist(String speciesRootUid) { this.speciesRootUid = speciesRootUid; } @Override public boolean test(ItemStack itemStack) { ISpeciesRoot speciesRoot = AlleleManager.alleleRegistry.getSpeciesRoot(speciesRootUid); - return speciesRoot.isMember(itemStack); + return speciesRoot != null && speciesRoot.isMember(itemStack); } } diff --git a/src/main/java/forestry/storage/BackpackInterface.java b/src/main/java/forestry/storage/BackpackInterface.java index c3d52f1bf..f702b3c4e 100644 --- a/src/main/java/forestry/storage/BackpackInterface.java +++ b/src/main/java/forestry/storage/BackpackInterface.java @@ -10,12 +10,12 @@ ******************************************************************************/ package forestry.storage; -import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; +import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import forestry.api.genetics.ISpeciesRoot; @@ -39,53 +39,36 @@ public class BackpackInterface implements IBackpackInterface { } @Override - public void addItemToForestryBackpack(@Nullable String backpackUid, @Nullable ItemStack itemStack) { - if (backpackUid == null) { - throw new NullPointerException("backpackUid must not be null"); - } - if (itemStack == null) { - throw new NullPointerException("itemStack must not be null"); - } - if (itemStack.getItem() == null) { - throw new NullPointerException("itemStack.getItem() must not be null"); - } + public void addItemToForestryBackpack(String backpackUid, ItemStack itemStack) { + Preconditions.checkNotNull(backpackUid, "backpackUid must not be null"); + Preconditions.checkNotNull(itemStack, "itemStack must not be null"); + Preconditions.checkArgument(!itemStack.isEmpty(), "itemStack must not be empty"); String stringForItemStack = ItemStackUtil.getStringForItemStack(itemStack); backpackAcceptedItems.put(backpackUid, stringForItemStack); } @Override - public void registerBackpackDefinition(@Nullable String backpackUid, @Nullable IBackpackDefinition definition) { - if (backpackUid == null) { - throw new NullPointerException("backpackUid must not be null"); - } - if (definition == null) { - throw new NullPointerException("definition must not be null"); - } + public void registerBackpackDefinition(String backpackUid, IBackpackDefinition definition) { + Preconditions.checkNotNull(backpackUid, "backpackUid must not be null"); + Preconditions.checkNotNull(definition, "definition must not be null"); + definitions.put(backpackUid, definition); } @Nullable @Override - public IBackpackDefinition getBackpackDefinition(@Nullable String backpackUid) { - if (backpackUid == null) { - throw new NullPointerException("backpackUid must not be null"); - } + public IBackpackDefinition getBackpackDefinition(String backpackUid) { + Preconditions.checkNotNull(backpackUid, "backpackUid must not be null"); + return definitions.get(backpackUid); } - @Nonnull @Override - public Item createBackpack(@Nullable String backpackUid, @Nullable EnumBackpackType type) { - if (backpackUid == null) { - throw new NullPointerException("backpackUid must not be null"); - } - if (type == null) { - throw new NullPointerException("type must not be null"); - } - if (type == EnumBackpackType.NATURALIST) { - throw new IllegalArgumentException("type must not be NATURALIST. Use createNaturalistBackpack instead."); - } + public Item createBackpack(String backpackUid, EnumBackpackType type) { + Preconditions.checkNotNull(backpackUid, "backpackUid must not be null"); + Preconditions.checkNotNull(type, "type must not be null"); + Preconditions.checkArgument(type != EnumBackpackType.NATURALIST, "type must not be NATURALIST. Use createNaturalistBackpack instead."); IBackpackDefinition definition = definitions.get(backpackUid); if (definition == null) { @@ -95,13 +78,9 @@ public class BackpackInterface implements IBackpackInterface { } @Override - public Item createNaturalistBackpack(@Nullable String backpackUid, @Nullable ISpeciesRoot speciesRoot) { - if (backpackUid == null) { - throw new NullPointerException("backpackUid must not be null"); - } - if (speciesRoot == null) { - throw new NullPointerException("speciesRoot must not be null"); - } + public Item createNaturalistBackpack(String backpackUid, ISpeciesRoot speciesRoot) { + Preconditions.checkNotNull(backpackUid, "backpackUid must not be null"); + Preconditions.checkNotNull(speciesRoot, "speciesRoot must not be null"); IBackpackDefinition definition = definitions.get(backpackUid); if (definition == null) { diff --git a/src/main/java/forestry/storage/CrateRegistry.java b/src/main/java/forestry/storage/CrateRegistry.java index b68a506cc..85f8dcbfa 100644 --- a/src/main/java/forestry/storage/CrateRegistry.java +++ b/src/main/java/forestry/storage/CrateRegistry.java @@ -10,26 +10,23 @@ ******************************************************************************/ package forestry.storage; -import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -import net.minecraftforge.fml.common.registry.GameRegistry; -import net.minecraftforge.oredict.OreDictionary; - import forestry.api.storage.ICrateRegistry; import forestry.core.items.ItemCrated; import forestry.core.proxy.Proxies; import forestry.core.utils.ItemStackUtil; import forestry.core.utils.Log; +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.common.registry.GameRegistry; +import net.minecraftforge.oredict.OreDictionary; public class CrateRegistry implements ICrateRegistry { - private static void registerCrate(@Nonnull ItemStack stack, @Nullable String oreDictName) { - if (stack == null || stack.getItem() == null) { + private static void registerCrate(ItemStack stack, @Nullable String oreDictName) { + if (stack.isEmpty()) { Log.warning("Tried to make a crate without an item"); return; } @@ -52,7 +49,7 @@ public class CrateRegistry implements ICrateRegistry { } @Override - public void registerCrate(@Nonnull String oreDictName) { + public void registerCrate(String oreDictName) { if (OreDictionary.doesOreNameExist(oreDictName)) { for (ItemStack stack : OreDictionary.getOres(oreDictName)) { if (stack != null) { @@ -64,17 +61,17 @@ public class CrateRegistry implements ICrateRegistry { } @Override - public void registerCrate(@Nonnull Block block) { + public void registerCrate(Block block) { registerCrate(new ItemStack(block), null); } @Override - public void registerCrate(@Nonnull Item item) { + public void registerCrate(Item item) { registerCrate(new ItemStack(item), null); } @Override - public void registerCrate(@Nonnull ItemStack stack) { + public void registerCrate(ItemStack stack) { registerCrate(stack, null); } } diff --git a/src/main/java/forestry/storage/PickupHandlerStorage.java b/src/main/java/forestry/storage/PickupHandlerStorage.java index 503ce6a77..7302eb148 100755 --- a/src/main/java/forestry/storage/PickupHandlerStorage.java +++ b/src/main/java/forestry/storage/PickupHandlerStorage.java @@ -25,7 +25,7 @@ public class PickupHandlerStorage implements IPickupHandler { public boolean onItemPickup(EntityPlayer player, EntityItem entityitem) { ItemStack itemstack = entityitem.getEntityItem(); - if (itemstack == null || itemstack.stackSize <= 0) { + if (itemstack.isEmpty()) { return false; } @@ -38,12 +38,7 @@ public class PickupHandlerStorage implements IPickupHandler { topOffPlayerInventory(player, itemstack); for (ItemStack pack : player.inventory.mainInventory) { - - if (pack == null || pack.stackSize <= 0) { - continue; - } - - if (itemstack.stackSize <= 0) { + if (pack.isEmpty() || itemstack.isEmpty()) { break; } @@ -58,7 +53,7 @@ public class PickupHandlerStorage implements IPickupHandler { } } - return itemstack.stackSize == 0; + return itemstack.isEmpty(); } /** @@ -72,27 +67,26 @@ public class PickupHandlerStorage implements IPickupHandler { for (int i = 0; i < player.inventory.getSizeInventory(); i++) { ItemStack inventoryStack = player.inventory.getStackInSlot(i); // We only add to existing stacks. - if (inventoryStack == null) { + if (inventoryStack.isEmpty()) { continue; } // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + if (inventoryStack.getCount() >= inventoryStack.getMaxStackSize()) { continue; } if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { - int space = inventoryStack.getMaxStackSize() - inventoryStack.stackSize; + int space = inventoryStack.getMaxStackSize() - inventoryStack.getCount(); - // Enough space to add all - if (space > itemstack.stackSize) { - inventoryStack.stackSize += itemstack.stackSize; - itemstack.stackSize = 0; - break; - // Only part can be added + if (space > itemstack.getCount()) { + // Enough space to add all + inventoryStack.grow(itemstack.getCount()); + itemstack.setCount(0); } else { - inventoryStack.stackSize = inventoryStack.getMaxStackSize(); - itemstack.stackSize -= space; + // Only part can be added + inventoryStack.setCount(inventoryStack.getMaxStackSize()); + itemstack.shrink(space); } } } diff --git a/src/main/java/forestry/storage/PluginStorage.java b/src/main/java/forestry/storage/PluginStorage.java index e0ccf3843..314ca0a5a 100644 --- a/src/main/java/forestry/storage/PluginStorage.java +++ b/src/main/java/forestry/storage/PluginStorage.java @@ -10,8 +10,8 @@ ******************************************************************************/ package forestry.storage; -import javax.annotation.Nonnull; -import java.awt.*; +import javax.annotation.Nullable; +import java.awt.Color; import java.io.File; import java.util.ArrayList; import java.util.Arrays; @@ -21,6 +21,7 @@ import java.util.List; import java.util.Set; import java.util.function.Predicate; +import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import forestry.Forestry; @@ -38,6 +39,7 @@ import forestry.core.PluginCore; import forestry.core.config.Constants; import forestry.core.config.LocalizedConfiguration; import forestry.core.items.ItemCrated; +import forestry.core.items.ItemRegistryCore; import forestry.core.models.ModelCrate; import forestry.core.recipes.RecipeUtil; import forestry.core.utils.IMCUtil; @@ -72,12 +74,14 @@ import net.minecraftforge.oredict.OreDictionary; @ForestryPlugin(pluginID = ForestryPluginUids.STORAGE, name = "Storage", author = "SirSengir", url = Constants.URL, unlocalizedDescription = "for.plugin.storage.description") public class PluginStorage extends BlankForestryPlugin { + @SuppressWarnings("NullableProblems") @SidedProxy(clientSide = "forestry.storage.proxy.ProxyStorageClient", serverSide = "forestry.storage.proxy.ProxyStorage") public static ProxyStorage proxy; - + private static final List crates = new ArrayList<>(); private static final String CONFIG_CATEGORY = "backpacks"; + @Nullable public static ItemRegistryStorage items; private final Multimap backpackAcceptedOreDictRegexpDefaults = HashMultimap.create(); @@ -133,7 +137,7 @@ public class PluginStorage extends BlankForestryPlugin { definition = new BackpackDefinition(new Color(0xdd3a3a), Color.WHITE); BackpackManager.backpackInterface.registerBackpackDefinition(BackpackManager.BUILDER_UID, definition); - + proxy.registerCrateModel(); } @@ -141,7 +145,7 @@ public class PluginStorage extends BlankForestryPlugin { public void registerItemsAndBlocks() { items = new ItemRegistryStorage(); } - + @Override public void preInit() { registerFenceAndFenceGatesToOreDict(); @@ -163,7 +167,7 @@ public class PluginStorage extends BlankForestryPlugin { setDefaultsForConfig(); - for (String backpackUid : forestryBackpackUids) { + for (String backpackUid : forestryBackpackUids) { handleBackpackConfig(config, backpackUid); } @@ -171,6 +175,9 @@ public class PluginStorage extends BlankForestryPlugin { } private void setDefaultsForConfig() { + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); + backpackAcceptedOreDictRegexpDefaults.get(BackpackManager.MINER_UID).addAll(Arrays.asList( "obsidian", "ore[A-Z].*", @@ -245,9 +252,9 @@ public class PluginStorage extends BlankForestryPlugin { backpackAcceptedItemDefaults.get(BackpackManager.MINER_UID).addAll(getItemStrings(Arrays.asList( new ItemStack(Blocks.COAL_ORE), new ItemStack(Items.COAL), - PluginCore.items.bronzePickaxe.getItemStack(), - PluginCore.items.kitPickaxe.getItemStack(), - PluginCore.items.brokenBronzePickaxe.getItemStack() + coreItems.bronzePickaxe.getItemStack(), + coreItems.kitPickaxe.getItemStack(), + coreItems.brokenBronzePickaxe.getItemStack() ))); backpackAcceptedItemDefaults.get(BackpackManager.DIGGER_UID).addAll(getItemStrings(Arrays.asList( @@ -257,9 +264,9 @@ public class PluginStorage extends BlankForestryPlugin { new ItemStack(Items.CLAY_BALL), new ItemStack(Items.SNOWBALL), new ItemStack(Blocks.SOUL_SAND), - PluginCore.items.bronzeShovel.getItemStack(), - PluginCore.items.kitShovel.getItemStack(), - PluginCore.items.brokenBronzeShovel.getItemStack() + coreItems.bronzeShovel.getItemStack(), + coreItems.kitShovel.getItemStack(), + coreItems.brokenBronzeShovel.getItemStack() ))); backpackAcceptedItemDefaults.get(BackpackManager.FORESTER_UID).addAll(getItemStrings(Arrays.asList( @@ -404,7 +411,6 @@ public class PluginStorage extends BlankForestryPlugin { OreDictionary.registerOre(OreDictUtil.FENCE_GATE_WOOD, Blocks.ACACIA_FENCE_GATE); } - @Nonnull private static Set getItemStrings(List itemStacks) { Set itemStrings = new HashSet<>(itemStacks.size()); for (ItemStack itemStack : itemStacks) { @@ -511,7 +517,7 @@ public class PluginStorage extends BlankForestryPlugin { for (ItemCrated crate : crates) { ItemStack crateStack = new ItemStack(crate); ItemStack uncrated = crate.getContained(); - if (uncrated != null) { + if (!uncrated.isEmpty()) { if (crate.getOreDictName() != null) { addCrating(crateStack, crate.getOreDictName()); } else { @@ -522,15 +528,17 @@ public class PluginStorage extends BlankForestryPlugin { } } - private static void addCrating(@Nonnull ItemStack crateStack, @Nonnull Object uncrated) { + private static void addCrating(ItemStack crateStack, Object uncrated) { + Preconditions.checkState(items != null); + FluidStack water = new FluidStack(FluidRegistry.WATER, Constants.CARPENTER_CRATING_LIQUID_QUANTITY); ItemStack box = items.crate.getItemStack(); RecipeManagers.carpenterManager.addRecipe(Constants.CARPENTER_CRATING_CYCLES, water, box, crateStack, "###", "###", "###", '#', uncrated); } - private static void addUncrating(@Nonnull ItemStack crateStack, @Nonnull ItemStack uncrated) { + private static void addUncrating(ItemStack crateStack, ItemStack uncrated) { ItemStack product = new ItemStack(uncrated.getItem(), 9, uncrated.getItemDamage()); - RecipeManagers.carpenterManager.addRecipe(Constants.CARPENTER_UNCRATING_CYCLES, null, product, "#", '#', crateStack); + RecipeManagers.carpenterManager.addRecipe(Constants.CARPENTER_UNCRATING_CYCLES, ItemStack.EMPTY, product, "#", '#', crateStack); } @Override @@ -574,6 +582,8 @@ public class PluginStorage extends BlankForestryPlugin { @Override public void registerRecipes() { + Preconditions.checkState(items != null); + BlockRegistryApiculture beeBlocks = PluginApiculture.blocks; if (items.apiaristBackpack != null && beeBlocks != null) { addBackpackRecipe(items.apiaristBackpack, "stickWood", beeBlocks.beeChest); @@ -595,7 +605,7 @@ public class PluginStorage extends BlankForestryPlugin { // / CARPENTER if (ForestryAPI.enabledPlugins.contains(ForestryPluginUids.FACTORY)) { // / CRATES - RecipeManagers.carpenterManager.addRecipe(20, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), null, items.crate.getItemStack(24), + RecipeManagers.carpenterManager.addRecipe(20, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), ItemStack.EMPTY, items.crate.getItemStack(24), " # ", "# #", " # ", '#', "logWood"); // / BACKPACKS WOVEN @@ -624,8 +634,11 @@ public class PluginStorage extends BlankForestryPlugin { } private static void addT2BackpackRecipe(Item backpackT1, Item backpackT2) { - ItemStack wovenSilk = PluginCore.items.craftingMaterial.getWovenSilk(); - RecipeManagers.carpenterManager.addRecipe(200, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), null, new ItemStack(backpackT2), + ItemRegistryCore coreItems = PluginCore.items; + Preconditions.checkState(coreItems != null); + + ItemStack wovenSilk = coreItems.craftingMaterial.getWovenSilk(); + RecipeManagers.carpenterManager.addRecipe(200, new FluidStack(FluidRegistry.WATER, Fluid.BUCKET_VOLUME), ItemStack.EMPTY, new ItemStack(backpackT2), "WXW", "WTW", "WWW", @@ -633,7 +646,7 @@ public class PluginStorage extends BlankForestryPlugin { 'W', wovenSilk, 'T', backpackT1); } - + @SubscribeEvent @SideOnly(Side.CLIENT) public void onBakeModel(ModelBakeEvent event) { diff --git a/src/main/java/forestry/storage/ResupplyHandler.java b/src/main/java/forestry/storage/ResupplyHandler.java index 08d933a83..967c13e07 100755 --- a/src/main/java/forestry/storage/ResupplyHandler.java +++ b/src/main/java/forestry/storage/ResupplyHandler.java @@ -32,7 +32,7 @@ public class ResupplyHandler implements IResupplyHandler { private static List backpacks(InventoryPlayer playerInventory) { List backpacks = new ArrayList<>(); for (ItemStack itemStack : playerInventory.mainInventory) { - if (itemStack != null && itemStack.stackSize > 0 && itemStack.getItem() instanceof ItemBackpack) { + if (itemStack.getItem() instanceof ItemBackpack) { backpacks.add(itemStack); } } @@ -74,7 +74,7 @@ public class ResupplyHandler implements IResupplyHandler { for (int i = 0; i < backpackInventory.getSizeInventory(); i++) { ItemStack itemStack = backpackInventory.getStackInSlot(i); - if (itemStack == null || itemStack.stackSize <= 0) { + if (itemStack.isEmpty()) { continue; } @@ -98,18 +98,18 @@ public class ResupplyHandler implements IResupplyHandler { for (int i = 0; i < player.inventory.getSizeInventory(); i++) { ItemStack inventoryStack = player.inventory.getStackInSlot(i); // We only add to existing stacks. - if (inventoryStack == null) { + if (inventoryStack.isEmpty()) { continue; } // Already full - if (inventoryStack.stackSize >= inventoryStack.getMaxStackSize()) { + if (inventoryStack.getCount() >= inventoryStack.getMaxStackSize()) { continue; } if (inventoryStack.isItemEqual(itemstack) && ItemStack.areItemStackTagsEqual(inventoryStack, itemstack)) { - inventoryStack.stackSize++; - itemstack.stackSize--; + inventoryStack.grow(1); + itemstack.shrink(1); return true; } } diff --git a/src/main/java/forestry/storage/compat/StorageJeiPlugin.java b/src/main/java/forestry/storage/compat/StorageJeiPlugin.java index 7884371a5..851e61587 100644 --- a/src/main/java/forestry/storage/compat/StorageJeiPlugin.java +++ b/src/main/java/forestry/storage/compat/StorageJeiPlugin.java @@ -1,7 +1,5 @@ package forestry.storage.compat; -import javax.annotation.Nonnull; - import forestry.core.utils.JeiUtil; import forestry.storage.PluginStorage; import forestry.storage.items.ItemRegistryStorage; @@ -12,7 +10,7 @@ import mezz.jei.api.JEIPlugin; @JEIPlugin public class StorageJeiPlugin extends BlankModPlugin { @Override - public void register(@Nonnull IModRegistry registry) { + public void register(IModRegistry registry) { ItemRegistryStorage items = PluginStorage.items; JeiUtil.addDescription(registry, "minerBag", diff --git a/src/main/java/forestry/storage/compat/package-info.java b/src/main/java/forestry/storage/compat/package-info.java new file mode 100644 index 000000000..054e41309 --- /dev/null +++ b/src/main/java/forestry/storage/compat/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.storage.compat; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java index 69e1ce44f..f5a8f69b6 100755 --- a/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java +++ b/src/main/java/forestry/storage/gui/ContainerNaturalistBackpack.java @@ -10,14 +10,12 @@ ******************************************************************************/ package forestry.storage.gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; - import forestry.core.gui.ContainerItemInventory; import forestry.core.gui.ContainerNaturalistInventory; import forestry.core.gui.IGuiSelectable; -import forestry.core.network.packets.PacketGuiSelectRequest; import forestry.storage.inventory.ItemInventoryBackpackPaged; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; public class ContainerNaturalistBackpack extends ContainerItemInventory implements IGuiSelectable { @@ -28,7 +26,7 @@ public class ContainerNaturalistBackpack extends ContainerItemInventory onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) { + public ActionResult onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) { if (!playerIn.isSneaking()) { - return super.onItemRightClick(itemStackIn, worldIn, playerIn, hand); + return super.onItemRightClick(worldIn, playerIn, handIn); } else { - switchMode(itemStackIn); - return ActionResult.newResult(EnumActionResult.SUCCESS, itemStackIn); + ItemStack heldItem = playerIn.getHeldItem(handIn); + switchMode(heldItem); + return ActionResult.newResult(EnumActionResult.SUCCESS, heldItem); } } @Override - public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { + public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (getInventoryHit(worldIn, pos, facing) != null) { return EnumActionResult.SUCCESS; } @@ -94,12 +96,13 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { } @Override - public EnumActionResult onItemUseFirst(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { + public EnumActionResult onItemUseFirst(EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, EnumHand hand) { // We only do this when shift is clicked if (player.isSneaking()) { - return evaluateTileHit(stack, player, world, pos, side) ? EnumActionResult.PASS : EnumActionResult.FAIL; + ItemStack heldItem = player.getHeldItem(hand); + return evaluateTileHit(heldItem, player, world, pos, side) ? EnumActionResult.PASS : EnumActionResult.FAIL; } - return super.onItemUseFirst(stack, player, world, pos, side, hitX, hitY, hitZ, hand); + return super.onItemUseFirst(player, world, pos, side, hitX, hitY, hitZ, hand); } public static void tryStowing(EntityPlayer player, ItemStack backpackStack, ItemStack stack) { @@ -113,7 +116,7 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { if (MinecraftForge.EVENT_BUS.post(new BackpackStowEvent(player, backpack.getDefinition(), inventory, stack))) { return; } - if (stack.stackSize <= 0) { + if (stack.isEmpty()) { return; } @@ -121,7 +124,7 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { ItemHandlerInventoryManipulator manipulator = new ItemHandlerInventoryManipulator(itemHandler); ItemStack remainder = manipulator.addStack(stack); - stack.stackSize = remainder == null ? 0 : remainder.stackSize; + stack.setCount(remainder == null ? 0 : remainder.getCount()); } private static void switchMode(ItemStack itemstack) { @@ -134,9 +137,10 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { itemstack.setItemDamage(nextMode); } + @Nullable private static IItemHandler getInventoryHit(World world, BlockPos pos, EnumFacing side) { TileEntity targeted = world.getTileEntity(pos); - return TileUtil.getInventoryFromTile(targeted, null); + return TileUtil.getInventoryFromTile(targeted, side); } private boolean evaluateTileHit(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side) { @@ -263,11 +267,8 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { } } - @Nullable public static BackpackMode getMode(ItemStack backpack) { - if (!(backpack.getItem() instanceof ItemBackpack)) { - return null; - } + Preconditions.checkArgument(backpack.getItem() instanceof ItemBackpack, "Item must be a backpack"); int meta = backpack.getItemDamage(); @@ -291,6 +292,7 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { @SuppressWarnings("incomplete-switch") @Override + @Nullable public Object getGui(EntityPlayer player, ItemStack heldItem, int data) { if (data > EnumBackpackType.values().length) { return null; @@ -307,6 +309,7 @@ public class ItemBackpack extends ItemWithGui implements IColoredItem { @SuppressWarnings("incomplete-switch") @Override + @Nullable public Object getContainer(EntityPlayer player, ItemStack heldItem, int data) { if (data > EnumBackpackType.values().length) { return null; diff --git a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java index 4a2cf35bd..f0adda877 100644 --- a/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java +++ b/src/main/java/forestry/storage/items/ItemBackpackNaturalist.java @@ -10,8 +10,6 @@ ******************************************************************************/ package forestry.storage.items; -import javax.annotation.Nonnull; - import forestry.api.genetics.ISpeciesRoot; import forestry.api.storage.EnumBackpackType; import forestry.api.storage.IBackpackDefinition; @@ -24,10 +22,9 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public class ItemBackpackNaturalist extends ItemBackpack { - @Nonnull private final ISpeciesRoot speciesRoot; - public ItemBackpackNaturalist(@Nonnull ISpeciesRoot speciesRoot, IBackpackDefinition definition) { + public ItemBackpackNaturalist(ISpeciesRoot speciesRoot, IBackpackDefinition definition) { super(definition, EnumBackpackType.NATURALIST); this.speciesRoot = speciesRoot; } diff --git a/src/main/java/forestry/storage/items/ItemRegistryStorage.java b/src/main/java/forestry/storage/items/ItemRegistryStorage.java index bd3f687ec..d2e2aae88 100644 --- a/src/main/java/forestry/storage/items/ItemRegistryStorage.java +++ b/src/main/java/forestry/storage/items/ItemRegistryStorage.java @@ -10,6 +10,8 @@ ******************************************************************************/ package forestry.storage.items; +import javax.annotation.Nullable; + import forestry.api.apiculture.BeeManager; import forestry.api.core.ForestryAPI; import forestry.api.core.Tabs; @@ -21,11 +23,15 @@ import forestry.core.items.ItemCrated; import forestry.core.items.ItemRegistry; import forestry.plugins.ForestryPluginUids; import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; public class ItemRegistryStorage extends ItemRegistry { public final ItemCrated crate; + @Nullable public final Item apiaristBackpack; + @Nullable public final Item lepidopteristBackpack; + public final Item minerBackpack; public final Item minerBackpackT2; public final Item diggerBackpack; @@ -41,7 +47,7 @@ public class ItemRegistryStorage extends ItemRegistry { public ItemRegistryStorage() { // CRATE - crate = registerItem(new ItemCrated(null, null), "crate"); + crate = registerItem(new ItemCrated(ItemStack.EMPTY, null), "crate"); // BACKPACKS IBackpackInterface backpackInterface = BackpackManager.backpackInterface; diff --git a/src/main/java/forestry/storage/items/package-info.java b/src/main/java/forestry/storage/items/package-info.java new file mode 100644 index 000000000..9b5df9a92 --- /dev/null +++ b/src/main/java/forestry/storage/items/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.storage.items; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/storage/package-info.java b/src/main/java/forestry/storage/package-info.java new file mode 100644 index 000000000..a0d748f5e --- /dev/null +++ b/src/main/java/forestry/storage/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.storage; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file diff --git a/src/main/java/forestry/storage/proxy/ProxyStorageClient.java b/src/main/java/forestry/storage/proxy/ProxyStorageClient.java index b41b2ba92..6b9a5afb3 100644 --- a/src/main/java/forestry/storage/proxy/ProxyStorageClient.java +++ b/src/main/java/forestry/storage/proxy/ProxyStorageClient.java @@ -5,6 +5,7 @@ import forestry.core.models.ModelEntry; import forestry.core.proxy.Proxies; import net.minecraft.client.renderer.block.model.ModelResourceLocation; +@SuppressWarnings("unused") public class ProxyStorageClient extends ProxyStorage { @Override diff --git a/src/main/java/forestry/storage/proxy/package-info.java b/src/main/java/forestry/storage/proxy/package-info.java new file mode 100644 index 000000000..711d6e393 --- /dev/null +++ b/src/main/java/forestry/storage/proxy/package-info.java @@ -0,0 +1,9 @@ +@ParametersAreNonnullByDefault +@FieldsAreNonnullByDefault +@MethodsReturnNonnullByDefault +package forestry.storage.proxy; + +import javax.annotation.ParametersAreNonnullByDefault; + +import forestry.core.utils.FieldsAreNonnullByDefault; +import mcp.MethodsReturnNonnullByDefault; \ No newline at end of file