Remove old paulscode libraries.

Re-work EnumHelper and ObjectHolder systems to bypass JITer of final fields.
Other cleanups.
This commit is contained in:
LexManos committed 2018-09-06 04:39:01 -07:00
1 parent 2798080f60
commit 12869710de
55 files changed
+495 -5859

No files matched your search

@@ -30,7 +30,7 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.world.biome.*;
import static net.minecraftforge.common.BiomeDictionary.Type.*;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistries;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
@@ -32,6 +32,11 @@ import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
@@ -50,9 +55,6 @@ import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.ModContainer;
import com.google.common.cache.Cache;
@@ -87,11 +89,11 @@ import com.google.common.collect.Sets;
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
public static Marker CHUNK_MANAGER = MarkerManager.getMarker("CHUNKMANAGER");
private static Logger LOGGER = LogManager.getLogger();
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
@@ -143,7 +145,7 @@ public class ForgeChunkManager
final ImmutableSetMultimap<ChunkPos, Ticket> persistentChunksFor = getPersistentChunksFor(world);
final ImmutableSet.Builder<Chunk> builder = ImmutableSet.builder();
world.profiler.startSection("forcedChunkLoading");
builder.addAll(persistentChunksFor.keys().stream().filter(Objects::nonNull).map(input -> world.getChunkFromChunkCoords(input.x, input.z)).iterator());
builder.addAll(persistentChunksFor.keys().stream().filter(Objects::nonNull).map(input -> world.getChunk(input.x, input.z)).iterator());
world.profiler.endStartSection("regularChunkLoading");
builder.addAll(chunkIterator);
world.profiler.endSection();
@@ -265,7 +267,7 @@ public class ForgeChunkManager
}
else
{
FMLLog.log.error("Attempt to create a player ticket without a valid player");
LOGGER.error(CHUNK_MANAGER, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
@@ -279,7 +281,7 @@ public class ForgeChunkManager
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.log.warn("The mod {} tried to modify the chunk ticket depth to: {}, its allowed maximum is: {}", modId, depth, getMaxChunkDepthFor(modId));
LOGGER.warn(CHUNK_MANAGER, "The mod {} tried to modify the chunk ticket depth to: {}, its allowed maximum is: {}", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
@@ -453,7 +455,7 @@ public class ForgeChunkManager
try
{
NBTTagCompound forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
return forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND).tagCount() > 0;
return forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND).size() > 0;
}
catch (IOException e)
{
@@ -493,11 +495,11 @@ public class ForgeChunkManager
}
catch (IOException e)
{
FMLLog.log.warn("Unable to read forced chunk data at {} - it will be ignored", chunkLoaderData.getAbsolutePath(), e);
LOGGER.warn(CHUNK_MANAGER, "Unable to read forced chunk data at {} - it will be ignored", chunkLoaderData.getAbsolutePath(), e);
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < ticketList.tagCount(); i++)
for (int i = 0; i < ticketList.size(); i++)
{
NBTTagCompound ticketHolder = ticketList.getCompoundTagAt(i);
String modId = ticketHolder.getString("Owner");
@@ -505,18 +507,18 @@ public class ForgeChunkManager
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.log.warn("Found chunkloading data for mod {} which is currently not available or active - it will be removed from the world save", modId);
LOGGER.warn(CHUNK_MANAGER, "Found chunkloading data for mod {} which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.log.warn("The mod {} has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
LOGGER.warn(CHUNK_MANAGER, "The mod {} has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets", Constants.NBT.TAG_COMPOUND);
for (int j = 0; j < tickets.tagCount(); j++)
for (int j = 0; j < tickets.size(); j++)
{
NBTTagCompound ticket = tickets.getCompoundTagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
@@ -558,14 +560,14 @@ public class ForgeChunkManager
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
world.getChunk(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.log.warn("Failed to load persistent chunkloading entity {} from store.", pendingEntities.inverse().get(tick));
LOGGER.warn(CHUNK_MANAGER, "Failed to load persistent chunkloading entity {} from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
@@ -587,7 +589,7 @@ public class ForgeChunkManager
}
if (tickets.size() > maxTicketLength)
{
FMLLog.log.warn("The mod {} has too many open chunkloading tickets {}. Excess will be dropped", modId, tickets.size());
LOGGER.warn(CHUNK_MANAGER, "The mod {} has too many open chunkloading tickets {}. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
@@ -645,7 +647,7 @@ public class ForgeChunkManager
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log.warn("Unable to register a callback for an unknown mod {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.warn(CHUNK_MANAGER, "Unable to register a callback for an unknown mod {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return;
}
@@ -703,12 +705,12 @@ public class ForgeChunkManager
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log.error("Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.error(CHUNK_MANAGER, "Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return null;
}
if (playerTickets.get(player).size()>playerTicketLength)
{
FMLLog.log.warn("Unable to assign further chunkloading tickets to player {} (on behalf of mod {})", player, mc.getModId());
LOGGER.warn(CHUNK_MANAGER, "Unable to assign further chunkloading tickets to player {} (on behalf of mod {})", player, mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
@@ -730,13 +732,13 @@ public class ForgeChunkManager
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log.error("Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
LOGGER.error(CHUNK_MANAGER, "Failed to locate the container for mod instance {} ({} : {})", mod, mod.getClass().getName(), Integer.toHexString(System.identityHashCode(mod)));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.log.fatal("The mod {} has attempted to request a ticket without a listener in place", modId);
LOGGER.fatal(CHUNK_MANAGER, "The mod {} has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
@@ -746,7 +748,7 @@ public class ForgeChunkManager
{
if (!warnedMods.contains(modId))
{
FMLLog.log.info("The mod {} has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum: {}", modId, allowedCount);
LOGGER.info(CHUNK_MANAGER, "The mod {} has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum: {}", modId, allowedCount);
warnedMods.add(modId);
}
return null;
@@ -810,7 +812,7 @@ public class ForgeChunkManager
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.log.fatal("The mod {} attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
LOGGER.fatal(CHUNK_MANAGER, "The mod {} attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
@@ -913,7 +915,7 @@ public class ForgeChunkManager
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketList.add(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
@@ -939,11 +941,11 @@ public class ForgeChunkManager
ticket.setInteger("chunkZ", MathHelper.floor(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
tickets.add(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
tickets.add(ticket);
}
}
}
@@ -956,7 +958,7 @@ public class ForgeChunkManager
}
catch (IOException e)
{
FMLLog.log.warn("Unable to write forced chunk data to {} - chunkloading won't work", chunkLoaderData.getAbsolutePath(), e);
LOGGER.warn(CHUNK_MANAGER, "Unable to write forced chunk data to {} - chunkloading won't work", chunkLoaderData.getAbsolutePath(), e);
}
return false;
});
@@ -1025,14 +1027,14 @@ public class ForgeChunkManager
private static void loadChunkEntities(Chunk chunk, NBTTagCompound nbt, World world)
{
NBTTagList entities = nbt.getTagList("Entities", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < entities.tagCount(); ++i)
for (int i = 0; i < entities.size(); ++i)
{
AnvilChunkLoader.readChunkEntity(entities.getCompoundTagAt(i), world, chunk);
chunk.setHasEntities(true);
}
NBTTagList tileEntities = nbt.getTagList("TileEntities", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tileEntities.tagCount(); ++i)
for (int i = 0; i < tileEntities.size(); ++i)
{
TileEntity tileEntity = TileEntity.create(world, tileEntities.getCompoundTagAt(i));
if (tileEntity != null) chunk.addTileEntity(tileEntity);
@@ -1055,7 +1057,7 @@ public class ForgeChunkManager
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log.error("A critical error occurred reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak", e);
LOGGER.error(CHUNK_MANAGER, "A critical error occurred reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak", e);
}
syncConfigDefaults();
}
@@ -1108,7 +1110,7 @@ public class ForgeChunkManager
temp.setMinValue(0);
dormantChunkCacheSize = temp.getInt(0);
propOrder.add("dormantChunkCacheSize");
FMLLog.log.info("Configured a dormant chunk cache size of {}", temp.getInt(0));
LOGGER.info(CHUNK_MANAGER, "Configured a dormant chunk cache size of {}", temp.getInt(0));
temp = config.get("defaults", "asyncChunkLoading", true);
temp.setComment("Load chunks asynchronously for players, reducing load on the server thread.\n" +
@@ -149,13 +149,13 @@ import net.minecraftforge.fml.common.LoaderState;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher;
import net.minecraftforge.fml.common.network.handshake.NetworkDispatcher.ConnectionType;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.network.ConnectionType;
import net.minecraftforge.fml.loading.moddiscovery.ModFile;
import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.RegistryManager;
@@ -0,0 +1,105 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.asm;
import java.nio.file.Path;
import java.util.List;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Removes the final modifier from fields with the @ObjectHolder annotation, prevents the JITer from in lining them so our runtime replacements can work.
* Will also de-finalize all fields in on class level annotations.
*/
public class ObjectHolderDefinalize implements ILaunchPluginService {
private final String OBJECT_HOLDER = "Lnet/minecraftforge/registries/ObjectHolder;"; //Don't directly reference this to prevent class loading.
@Override
public String name() {
return "object_holder_definalize";
}
@Override public void addResource(Path resource, String name) { }
@Override public <T> T getExtension() { return null; } // ?
@Override
public boolean handlesClass(Type classType, boolean isEmpty)
{
return !isEmpty; //Check for annotations?
}
private boolean hasHolder(List<AnnotationNode> lst)
{
return lst != null && lst.stream().anyMatch(n -> n.desc.equals(OBJECT_HOLDER));
}
private String getValue(List<AnnotationNode> lst)
{
AnnotationNode ann = lst.stream().filter(n -> n.desc.equals(OBJECT_HOLDER)).findFirst().get();
if (ann.values != null)
{
for (int x = 0; x < ann.values.size() - 1; x += 2) {
if (ann.values.get(x).equals("value")) {
return (String)ann.values.get(x + 1);
}
}
}
return null;
}
@Override
public ClassNode processClass(ClassNode classNode, Type classType)
{
//Must be public static finals, and non-array objects
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
//Fix Annotated Fields before injecting from class level
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L") && hasHolder(f.visibleAnnotations)).forEach(f ->
{
f.access &= ~Opcodes.ACC_FINAL; //Strip final
f.access |= Opcodes.ACC_SYNTHETIC; //Add Synthetic so we can check in runtime. ? Good idea?
});
if (hasHolder(classNode.visibleAnnotations)) //Class level, de-finalize all fields and add @ObjectHolder to them!
{
@SuppressWarnings("unused")
String value = getValue(classNode.visibleAnnotations);
classNode.fields.stream().filter(f -> ((f.access & flags) == flags) && f.desc.startsWith("L")).forEach(f ->
{
f.access &= ~Opcodes.ACC_FINAL;
f.access |= Opcodes.ACC_SYNTHETIC;
/*if (!hasHolder(f.visibleAnnotations)) //Add field level annotation, doesn't do anything until after we figure out how ASMDataTable is gatherered
{
if (value == null)
f.visitAnnotation(OBJECT_HOLDER, true);
else
f.visitAnnotation(OBJECT_HOLDER, true).visit("value", value + ":" + f.name.toLowerCase());
}*/
});
}
return classNode;
}
}
@@ -0,0 +1,134 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.asm;
import java.nio.file.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.InstructionAdapter;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import cpw.mods.modlauncher.serviceapi.ILaunchPluginService;
/**
* Modifies specified enums to allow runtime extension by making the $VALUES field non-final and
* injecting constructor calls which are not valid in normal java code.
*/
public class RuntimeEnumExtender implements ILaunchPluginService {
private static final Logger LOGGER = LogManager.getLogger();
private final Type STRING = Type.getType(String.class);
private final Type ARRAY_UTILS = Type.getType("Lorg/apache/commons/lang3/ArrayUtils;"); //Don't directly reference this to prevent class loading.
private final String ADD_DESC = Type.getMethodDescriptor(Type.getType(Object[].class), Type.getType(Object[].class), Type.getType(Object.class));
private final Type ENUM_HELPER = Type.getType("Lnet/minecraftforge/common/util/EnumHelper;"); //Again, not direct reference to prevent class loading.
private final String CLEAN_DESC = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class));
@Override
public String name() {
return "runtime_enum_extender";
}
@Override public void addResource(Path resource, String name) { }
@Override public <T> T getExtension() { return null; } // ?
@Override
public boolean handlesClass(Type classType, boolean isEmpty)
{
return !isEmpty; //Any way to determine if its a enum at this level?
}
@Override
public ClassNode processClass(ClassNode classNode, Type classType)
{
if ((classNode.access & Opcodes.ACC_ENUM) == 0)
return classNode;
Type array = Type.getType("[" + classType.getInternalName());
final int flags = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC;
FieldNode values = classNode.fields.stream().filter(f -> f.desc.contentEquals(array.getDescriptor()) && ((f.access & flags) == flags)).findFirst().orElse(null);
//Static methods named "create", with first argument as a string, and returning this type
classNode.methods.stream().filter(m -> ((m.access & Opcodes.ACC_STATIC) != 0) && m.name.equals("create") && Type.getReturnType(m.desc).equals(classType)).forEach(mtd ->
{
Type[] args = Type.getArgumentTypes(mtd.desc);
if (args.length == 0 || !args[0].equals(STRING))
return;
Type[] ctrArgs = new Type[args.length + 1];
ctrArgs[0] = STRING;
ctrArgs[1] = Type.INT_TYPE;
for (int x = 1; x < args.length; x++)
ctrArgs[1 + x] = args[x];
String desc = Type.getMethodDescriptor(Type.VOID_TYPE, ctrArgs);
MethodNode ctr = classNode.methods.stream().filter(m -> m.name.equals("<init>") && m.desc.equals(desc)).findFirst().orElse(null);
if (ctr == null)
{
LOGGER.error("Enum has create method with no matching constructor:");
LOGGER.error(" Target: " + desc);
classNode.methods.stream().filter(m -> m.name.equals("<init>")).forEach(m -> LOGGER.error(" :" + m.desc));
throw new IllegalStateException("Enum has create method with no matching constructor: " + desc);
}
if (values == null)
{
LOGGER.error("Enum has create method but we could not find $VALUES:");
classNode.fields.stream().filter(f -> (f.access & Opcodes.ACC_STATIC) != 0).forEach(m -> LOGGER.error(" " + m.name + " " + m.desc));
throw new IllegalStateException("Enum has create method but we could not find $VALUES");
}
values.access &= values.access & ~Opcodes.ACC_FINAL; //Strip the final so JITer doesn't inline things.
mtd.instructions.clear();
InstructionAdapter ins = new InstructionAdapter(mtd);
//ret = new ThisType(name, VALUES.length + 1, args..)
ins.anew(classType);
ins.dup();
ins.load(0, STRING);
ins.getstatic(classType.getInternalName(), values.name, values.desc);
ins.iconst(1);
ins.add(Type.INT_TYPE);
for (int x = 1; x < args.length; x++)
ins.load(x, args[x]);
ins.invokespecial(classType.getDescriptor(), "<init>", desc, false);
ins.store(1, classType);
// VALUES = ArrayUtils.add(VALUES, ret)
ins.getstatic(classType.getInternalName(), values.name, values.desc);
ins.load(1, classType);
ins.invokestatic(ARRAY_UTILS.getDescriptor(), "add", ADD_DESC, false);
ins.checkcast(array);
ins.putstatic(classType.getInternalName(), values.name, values.desc);
//EnumHelper.cleanEnumCache(ThisType.class)
ins.visitLdcInsn(classType);
ins.invokestatic(ENUM_HELPER.getInternalName(), "cleanEnumCache", CLEAN_DESC, false);
//return ret
ins.load(1, classType);
ins.areturn(classType);
});
return classNode;
}
}
@@ -65,11 +65,11 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.OreIngredient;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import net.minecraftforge.registries.GameData;
import net.minecraftforge.registries.RegistryManager;
@@ -29,7 +29,7 @@ import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
@@ -27,207 +27,21 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraft.block.BlockPressurePlate.Sensitivity;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EnumCreatureAttribute;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.entity.item.EntityPainting.EnumArt;
import net.minecraft.entity.passive.HorseArmorType;
import net.minecraft.entity.passive.IAnimals;
import net.minecraft.entity.player.EntityPlayer.SleepResult;
import net.minecraft.item.EnumAction;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.gen.structure.StructureStrongholdPieces.Stronghold.Door;
import net.minecraftforge.classloading.FMLForgePlugin;
import org.apache.commons.lang3.ArrayUtils;
import javax.annotation.Nullable;
public class EnumHelper
{
private static Object reflectionFactory = null;
private static Method newConstructorAccessor = null;
private static Method newInstance = null;
private static Method newFieldAccessor = null;
private static Method fieldAccessorSet = null;
private static boolean isSetup = false;
//Some enums are decompiled with extra arguments, so lets check for that
private static Class<?>[][] commonTypes =
{
{EnumAction.class},
{ArmorMaterial.class, String.class, int.class, int[].class, int.class, SoundEvent.class, float.class},
{EnumArt.class, String.class, int.class, int.class, int.class, int.class},
{EnumCreatureAttribute.class},
{EnumCreatureType.class, Class.class, int.class, Material.class, boolean.class, boolean.class},
{Door.class},
{EnumEnchantmentType.class, Predicate.class},
{Sensitivity.class},
{RayTraceResult.Type.class},
{EnumSkyBlock.class, int.class},
{SleepResult.class},
{ToolMaterial.class, int.class, int.class, float.class, float.class, int.class},
{EnumRarity.class, TextFormatting.class, String.class},
{HorseArmorType.class, String.class, int.class},
{EntityLiving.SpawnPlacementType.class, BiPredicate.class}
};
@Nullable
public static EnumAction addAction(String name)
{
return addEnum(EnumAction.class, name);
}
@Nullable
public static ArmorMaterial addArmorMaterial(String name, String textureName, int durability, int[] reductionAmounts, int enchantability, SoundEvent soundOnEquip, float toughness)
{
return addEnum(ArmorMaterial.class, name, textureName, durability, reductionAmounts, enchantability, soundOnEquip, toughness);
}
@Nullable
public static EnumArt addArt(String name, String tile, int sizeX, int sizeY, int offsetX, int offsetY)
{
return addEnum(EnumArt.class, name, tile, sizeX, sizeY, offsetX, offsetY);
}
@Nullable
public static EnumCreatureAttribute addCreatureAttribute(String name)
{
return addEnum(EnumCreatureAttribute.class, name);
}
@Nullable
public static EnumCreatureType addCreatureType(String name, Class<? extends IAnimals> typeClass, int maxNumber, Material material, boolean peaceful, boolean animal)
{
return addEnum(EnumCreatureType.class, name, typeClass, maxNumber, material, peaceful, animal);
}
@Nullable
public static Door addDoor(String name)
{
return addEnum(Door.class, name);
}
@Nullable
public static EnumEnchantmentType addEnchantmentType(String name, Predicate<Item> delegate)
{
return addEnum(EnumEnchantmentType.class, name, delegate);
}
@Nullable
public static Sensitivity addSensitivity(String name)
{
return addEnum(Sensitivity.class, name);
}
@Nullable
public static RayTraceResult.Type addMovingObjectType(String name)
{
return addEnum(RayTraceResult.Type.class, name);
}
@Nullable
public static EnumSkyBlock addSkyBlock(String name, int lightValue)
{
return addEnum(EnumSkyBlock.class, name, lightValue);
}
@Nullable
public static SleepResult addStatus(String name)
{
return addEnum(SleepResult.class, name);
}
@Nullable
public static ToolMaterial addToolMaterial(String name, int harvestLevel, int maxUses, float efficiency, float damage, int enchantability)
{
return addEnum(ToolMaterial.class, name, harvestLevel, maxUses, efficiency, damage, enchantability);
}
@Nullable
public static EnumRarity addRarity(String name, TextFormatting color, String displayName)
{
return addEnum(EnumRarity.class, name, color, displayName);
}
@Nullable
public static EntityLiving.SpawnPlacementType addSpawnPlacementType(String name, BiPredicate<IBlockAccess, BlockPos> predicate)
{
return addEnum(EntityLiving.SpawnPlacementType.class, name, predicate);
}
/**
*
* @param name the name of the new {@code HorseArmorType}
* @param textureLocation the path to the texture for this armor type. It must follow the format domain:path and be relative to the assets folder.
* @param armorStrength how much protection this armor type should give
* @return the new {@code HorseArmorType}, or null if it could not be created
*/
@Nullable
public static HorseArmorType addHorseArmor(String name, String textureLocation, int armorStrength)
{
return addEnum(HorseArmorType.class, name, textureLocation, armorStrength);
}
private static void setup()
{
if (isSetup)
{
return;
}
try
{
Method getReflectionFactory = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("getReflectionFactory");
reflectionFactory = getReflectionFactory.invoke(null);
newConstructorAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newConstructorAccessor", Constructor.class);
newInstance = Class.forName("sun.reflect.ConstructorAccessor").getDeclaredMethod("newInstance", Object[].class);
newFieldAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newFieldAccessor", Field.class, boolean.class);
fieldAccessorSet = Class.forName("sun.reflect.FieldAccessor").getDeclaredMethod("set", Object.class, Object.class);
}
catch (Exception e)
{
FMLLog.log.error("Error setting up EnumHelper.", e);
}
isSetup = true;
}
/*
/*
* Everything below this is found at the site below, and updated to be able to compile in Eclipse/Java 1.6+
* Also modified for use in decompiled code.
* Found at: http://niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically
*/
private static Object getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes) throws Exception
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return newConstructorAccessor.invoke(reflectionFactory, enumClass.getDeclaredConstructor(parameterTypes));
}
private static < T extends Enum<? >> T makeEnum(Class<T> enumClass, @Nullable String value, int ordinal, Class<?>[] additionalTypes, @Nullable Object[] additionalValues) throws Exception
{
int additionalParamsCount = additionalValues == null ? 0 : additionalValues.length;
Object[] params = new Object[additionalParamsCount + 2];
params[0] = value;
params[1] = ordinal;
if (additionalValues != null)
{
System.arraycopy(additionalValues, 0, params, 2, additionalValues.length);
}
return enumClass.cast(newInstance.invoke(getConstructorAccessor(enumClass, additionalTypes), new Object[] {params}));
}
public static void setFailsafeFieldValue(Field field, @Nullable Object target, @Nullable Object value) throws Exception
{
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
fieldAccessorSet.invoke(fieldAccessor, target, value);
//new Enum(name, values.size() + 1, params)
}
private static void blankField(Class<?> enumClass, String fieldName) throws Exception
@@ -237,190 +51,35 @@ public class EnumHelper
if (field.getName().contains(fieldName))
{
field.setAccessible(true);
setFailsafeFieldValue(field, enumClass, null);
field.set(enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass) throws Exception
//Class holds caches of the enum constants used for Enum.valueOf() and reflection magic. So we need to invalidate those caches when we add something new. They will automtically be re-built.
public static void cleanEnumCache(Class<?> enumClass) throws Exception
{
blankField(enumClass, "enumConstantDirectory");
blankField(enumClass, "enumConstants");
}
@Nullable
private static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Object... paramValues)
{
setup();
return addEnum(commonTypes, enumType, enumName, paramValues);
}
@Nullable
protected static <T extends Enum<? >> T addEnum(Class<?>[][] map, Class<T> enumType, String enumName, Object... paramValues)
{
for (Class<?>[] lookup : map)
{
if (lookup[0] == enumType)
{
Class<?>[] paramTypes = new Class<?>[lookup.length - 1];
if (paramTypes.length > 0)
{
System.arraycopy(lookup, 1, paramTypes, 0, paramTypes.length);
}
return addEnum(enumType, enumName, paramTypes, paramValues);
}
}
return null;
}
//Tests an enum is compatible with these args, throws an error if not.
public static void testEnum(Class<? extends Enum<?>> enumType, Class<?>[] paramTypes)
{
addEnum(true, enumType, null, paramTypes, (Object[])null);
}
@Nullable
public static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Class<?>[] paramTypes, Object... paramValues)
{
return addEnum(false, enumType, enumName, paramTypes, paramValues);
}
@SuppressWarnings({ "unchecked", "serial" })
@Nullable
private static <T extends Enum<? >> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName, final Class<?>[] paramTypes, @Nullable Object[] paramValues)
private static <T extends Enum<?> & IExpandableEnum<?>> T addEnum(boolean test, final Class<T> enumType, T newValue)
{
if (!isSetup)
{
setup();
}
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields)
{
String name = field.getName();
if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
{
valuesField = field;
break;
}
}
int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
if (valuesField == null)
{
String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));
for (Field field : fields)
{
if ((field.getModifiers() & flags) == flags &&
field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
{
valuesField = field;
break;
}
}
}
if (valuesField == null)
{
final List<String> lines = Lists.newArrayList();
lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
lines.add(String.format("Flags: %s", String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
lines.add( "Fields:");
for (Field field : fields)
{
String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
lines.add(String.format(" %s %s: %s", mods, field.getName(), field.getType().getName()));
}
for (String line : lines)
FMLLog.log.fatal(line);
if (test)
{
throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName())
{
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
for (String line : lines)
stream.println(line);
}
};
}
return null;
}
if (test)
{
Object ctr = null;
Exception ex = null;
try
{
ctr = getConstructorAccessor(enumType, paramTypes);
}
catch (Exception e)
{
ex = e;
}
if (ctr == null || ex != null)
{
throw new EnhancedRuntimeException(String.format("Could not find constructor for Enum %s", enumType.getName()), ex)
{
private String toString(Class<?>[] cls)
{
StringBuilder b = new StringBuilder();
for (int x = 0; x < cls.length; x++)
{
b.append(cls[x].getName());
if (x != cls.length - 1)
b.append(", ");
}
return b.toString();
}
@Override
protected void printStackTrace(WrappedPrintStream stream)
{
stream.println("Target Arguments:");
stream.println(" java.lang.String, int, " + toString(paramTypes));
stream.println("Found Constructors:");
for (Constructor<?> ctr : enumType.getDeclaredConstructors())
{
stream.println(" " + toString(ctr.getParameterTypes()));
}
}
};
}
return null;
}
valuesField.setAccessible(true);
try
{
T[] previousValues = (T[])valuesField.get(enumType);
T[] previousValues = enumType.getEnumConstants();
T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
newValue.__set_values__(ArrayUtils.add(previousValues, newValue));
cleanEnumCache(enumType);
return newValue;
}
catch (Exception e)
{
FMLLog.log.error("Error adding enum with EnumHelper.", e);
throw new RuntimeException(e);
}
}
static
{
if (!isSetup)
{
setup();
}
}
}