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

@@ -0,0 +1,67 @@
/*
* 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.registries;
import net.minecraft.block.Block;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.Entity;
import net.minecraft.init.Bootstrap;
import net.minecraft.item.Item;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionType;
import net.minecraft.util.SoundEvent;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.common.registry.VillagerRegistry;
import net.minecraftforge.fml.common.registry.VillagerRegistry.VillagerProfession;
/**
* A class that exposes static references to all vanilla and Forge registries.
* Created to have a central place to access the registries directly if modders need.
* It is still advised that if you are registering things to go through {@link GameRegistry} register methods, but queries and iterations can use this.
*/
public class ForgeRegistries
{
static { init(); } // This must be above the fields so we guarantee it's run before findRegistry is called. Yay static inializers
public static final IForgeRegistry<Block> BLOCKS = RegistryManager.ACTIVE.getRegistry(Block.class);
public static final IForgeRegistry<Item> ITEMS = RegistryManager.ACTIVE.getRegistry(Item.class);
public static final IForgeRegistry<Potion> POTIONS = RegistryManager.ACTIVE.getRegistry(Potion.class);
public static final IForgeRegistry<Biome> BIOMES = RegistryManager.ACTIVE.getRegistry(Biome.class);
public static final IForgeRegistry<SoundEvent> SOUND_EVENTS = RegistryManager.ACTIVE.getRegistry(SoundEvent.class);
public static final IForgeRegistry<PotionType> POTION_TYPES = RegistryManager.ACTIVE.getRegistry(PotionType.class);
public static final IForgeRegistry<Enchantment> ENCHANTMENTS = RegistryManager.ACTIVE.getRegistry(Enchantment.class);
public static final IForgeRegistry<VillagerProfession> VILLAGER_PROFESSIONS = RegistryManager.ACTIVE.getRegistry(VillagerProfession.class);
public static final IForgeRegistry<EntityEntry> ENTITIES = RegistryManager.ACTIVE.getRegistry(EntityEntry.class);
public static final IForgeRegistry<IRecipe> RECIPES = RegistryManager.ACTIVE.getRegistry(IRecipe.class);
/**
* This function is just to make sure static inializers in other classes have run and setup their registries before we query them.
*/
private static void init()
{
GameData.init();
VillagerRegistry.instance();
Bootstrap.register();
}
}
@@ -198,19 +198,9 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
return Collections.unmodifiableSet(this.names.keySet());
}
/**
* @deprecated use {@link #getValuesCollection} to avoid copying
*/
@Deprecated
@Override
public List<V> getValues()
{
return ImmutableList.copyOf(this.names.values());
}
@Nonnull
@Override
public Collection<V> getValuesCollection()
public Collection<V> getValues()
{
return Collections.unmodifiableSet(this.names.values());
}
@@ -793,7 +783,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setInteger("V", e.getValue());
ids.appendTag(tag);
ids.add(tag);
});
data.setTag("ids", ids);
@@ -803,7 +793,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setString("V", e.getKey().toString());
aliases.appendTag(tag);
aliases.add(tag);
});
data.setTag("aliases", aliases);
@@ -813,7 +803,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
NBTTagCompound tag = new NBTTagCompound();
tag.setString("K", e.getKey().toString());
tag.setString("V", e.getValue());
overrides.appendTag(tag);
overrides.add(tag);
});
data.setTag("overrides", overrides);
@@ -821,7 +811,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
data.setIntArray("blocked", blocked);
NBTTagList dummied = new NBTTagList();
this.dummied.stream().sorted().forEach(e -> dummied.appendTag(new NBTTagString(e.toString())));
this.dummied.stream().sorted().forEach(e -> dummied.add(new NBTTagString(e.toString())));
data.setTag("dummied", dummied);
return data;
@@ -846,24 +836,7 @@ public class ForgeRegistry<V extends IForgeRegistryEntry<V>> implements IForgeRe
list.forEach(e ->
{
NBTTagCompound comp = (NBTTagCompound)e;
String v = comp.getString("V");
if (v.indexOf(':') == -1) //Forge Bug: https://github.com/MinecraftForge/MinecraftForge/issues/4894 TODO: Remove in 1.13
{
ret.overrides.put(new ResourceLocation(comp.getString("K")), v);
}
else
{
ResourceLocation aliask = new ResourceLocation(comp.getString("K"));
ResourceLocation aliasv = new ResourceLocation(v);
if (aliasv.equals(aliask))
{
FMLLog.log.warn("Found unrecoverable 4894 bugged alias/override: {} -> {}, skipping.", aliask, aliasv);
}
else
{
ret.aliases.put(aliask, aliasv);
}
}
ret.overrides.put(new ResourceLocation(comp.getString("K")), comp.getString("V"));
});
list = nbt.getTagList("overrides", 10);
@@ -30,7 +30,7 @@ import javax.annotation.Nullable;
* if another entry overrides existing ones in the registry.
*/
@SuppressWarnings("unchecked")
public abstract class ForgeRegistryEntry<V extends ForgeRegistryEntry<V>> implements IForgeRegistryEntry<V>
public abstract class ForgeRegistryEntry<V extends IForgeRegistryEntry<V>> implements IForgeRegistryEntry<V>
{
@SuppressWarnings("serial")
private final TypeToken<V> token = new TypeToken<V>(getClass()){};
@@ -21,7 +21,7 @@ package net.minecraftforge.registries;
import net.minecraft.util.ResourceLocation;
public interface IForgeRegistryModifiable<V extends ForgeRegistryEntry<V>> extends IForgeRegistry<V>
public interface IForgeRegistryModifiable<V extends IForgeRegistryEntry<V>> extends IForgeRegistry<V>
{
void clear();
V remove(ResourceLocation key);
@@ -122,7 +122,7 @@ class NamespacedDefaultedWrapper<V extends IForgeRegistryEntry<V>> extends Regis
@Nullable
public V getRandomObject(Random random)
{
Collection<V> values = this.delegate.getValuesCollection();
Collection<V> values = this.delegate.getValues();
return values.stream().skip(random.nextInt(values.size())).findFirst().orElse(null);
}
@@ -117,7 +117,7 @@ class NamespacedWrapper<V extends IForgeRegistryEntry<V>> extends RegistryNamesp
@Nullable
public V getRandomObject(Random random)
{
Collection<V> values = this.delegate.getValuesCollection();
Collection<V> values = this.delegate.getValues();
return values.stream().skip(random.nextInt(values.size())).findFirst().orElse(null);
}
@@ -0,0 +1,42 @@
/*
* 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.registries;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* ObjectHolder can be used to automatically populate public static final fields with entries
* from the registry. These values can then be referred within mod code directly.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface ObjectHolder
{
/**
* If used on a class, this represents a modid only.
* If used on a field, it represents a name, which can be abbreviated or complete.
* Abbreviated names derive their modid from an enclosing ObjectHolder at the class level.
*
* @return either a modid or a name based on the rules above
*/
String value();
}
@@ -20,7 +20,6 @@
package net.minecraftforge.registries;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.LinkedList;
@@ -28,23 +27,23 @@ import java.util.Queue;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Internal class used in tracking {@link ObjectHolder} references
*/
@SuppressWarnings("rawtypes")
class ObjectHolderRef
{
private static final Logger LOGGER = LogManager.getLogger();
private Field field;
private ResourceLocation injectedObject;
private boolean isValid;
private ForgeRegistry<?> registry;
@SuppressWarnings("unchecked")
ObjectHolderRef(Field field, ResourceLocation injectedObject, boolean extractFromExistingValues)
{
registry = getRegistryForType(field);
@@ -66,7 +65,7 @@ class ObjectHolderRef
}
else
{
this.injectedObject = ((ForgeRegistryEntry)existing).getRegistryName();
this.injectedObject = ((IForgeRegistryEntry)existing).getRegistryName();
}
}
catch (IllegalAccessException e)
@@ -83,13 +82,12 @@ class ObjectHolderRef
{
throw new IllegalStateException(String.format("The ObjectHolder annotation cannot apply to a field that does not map to a registry. Ensure the registry was created during the RegistryEvent.NewRegistry event. (found : %s at %s.%s)", field.getType().getName(), field.getClass().getName(), field.getName()));
}
try
field.setAccessible(true);
if (Modifier.isFinal(field.getModifiers()))
{
FinalFieldHelper.makeWritable(field);
}
catch (ReflectiveOperationException e)
{
throw new RuntimeException(e);
throw new RuntimeException("@ObjectHolder on final field, our transformer did not run? " + field.getDeclaringClass().getName() + "/" + field.getName());
}
}
@@ -137,46 +135,16 @@ class ObjectHolderRef
if (thing == null)
{
FMLLog.log.debug("Unable to lookup {} for {}. This means the object wasn't registered. It's likely just mod options.", injectedObject, field);
LOGGER.debug("Unable to lookup {} for {}. This means the object wasn't registered. It's likely just mod options.", injectedObject, field);
return;
}
try
{
FinalFieldHelper.setField(field, null, thing);
field.set(null, thing);
}
catch (IllegalArgumentException | ReflectiveOperationException e)
{
FMLLog.log.warn("Unable to set {} with value {} ({})", this.field, thing, this.injectedObject, e);
}
}
private static class FinalFieldHelper
{
private static Field modifiersField;
private static Object reflectionFactory;
private static Method newFieldAccessor;
private static Method fieldAccessorSet;
static Field makeWritable(Field f) throws ReflectiveOperationException
{
f.setAccessible(true);
if (modifiersField == null)
{
Method getReflectionFactory = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("getReflectionFactory");
reflectionFactory = getReflectionFactory.invoke(null);
newFieldAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newFieldAccessor", Field.class, boolean.class);
fieldAccessorSet = Class.forName("sun.reflect.FieldAccessor").getDeclaredMethod("set", Object.class, Object.class);
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
}
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
return f;
}
static void setField(Field field, @Nullable Object instance, Object thing) throws ReflectiveOperationException
{
Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
fieldAccessorSet.invoke(fieldAccessor, instance, thing);
LOGGER.warn("Unable to set {} with value {} ({})", this.field, thing, this.injectedObject, e);
}
}
}
@@ -26,66 +26,48 @@ import java.util.Map;
import java.util.Set;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry.ObjectHolder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.objectweb.asm.Opcodes;
/**
* Internal registry for tracking {@link ObjectHolder} references
*/
public enum ObjectHolderRegistry
{
INSTANCE;
private static final Logger LOGGER = LogManager.getLogger();
private List<ObjectHolderRef> objectHolders = Lists.newArrayList();
public void findObjectHolders(ASMDataTable table)
{
FMLLog.log.info("Processing ObjectHolder annotations");
Set<ASMData> allObjectHolders = table.getAll(GameRegistry.ObjectHolder.class.getName());
LOGGER.info("Processing ObjectHolder annotations");
Set<ASMData> allObjectHolders = table.getAll(ObjectHolder.class.getName());
Map<String, String> classModIds = Maps.newHashMap();
Map<String, Class<?>> classCache = Maps.newHashMap();
for (ASMData data : table.getAll(Mod.class.getName()))
{
String modid = (String)data.getAnnotationInfo().get("modid");
classModIds.put(data.getClassName(), modid);
}
for (ASMData data : allObjectHolders)
{
String className = data.getClassName();
String annotationTarget = data.getObjectName();
String value = (String) data.getAnnotationInfo().get("value");
boolean isClass = className.equals(annotationTarget);
if (isClass)
{
scanTarget(classModIds, classCache, className, annotationTarget, value, isClass, false);
}
}
table.getAll(Mod.class.getName()).forEach(data -> classModIds.put(data.getClassName(), (String)data.getAnnotationInfo().get("value")));
// double pass - get all the class level annotations first, then the field level annotations
for (ASMData data : allObjectHolders)
allObjectHolders.stream().filter(data -> data.getObjectName().equals(data.getClassName())).forEach(data ->
{
String className = data.getClassName();
String annotationTarget = data.getObjectName();
String value = (String) data.getAnnotationInfo().get("value");
boolean isClass = className.equals(annotationTarget);
if (!isClass)
{
scanTarget(classModIds, classCache, className, annotationTarget, value, isClass, false);
}
}
scanTarget(classModIds, classCache, "net.minecraft.init.Blocks", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Items", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.MobEffects", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Biomes", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.Enchantments", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.SoundEvents", null, "minecraft", true, true);
scanTarget(classModIds, classCache, "net.minecraft.init.PotionTypes", null, "minecraft", true, true);
FMLLog.log.info("Found {} ObjectHolder annotations", objectHolders.size());
String value = (String)data.getAnnotationInfo().get("value");
scanTarget(classModIds, classCache, data.getClassName(), data.getObjectName(), value, true, data.getClassName().startsWith("net.minecraft.init"));
});
allObjectHolders.stream().filter(data -> !data.getObjectName().equals(data.getClassName())).forEach(data ->
{
String value = (String)data.getAnnotationInfo().get("value");
scanTarget(classModIds, classCache, data.getClassName(), data.getObjectName(), value, false, false);
});
LOGGER.info("Found {} ObjectHolder annotations", objectHolders.size());
}
private void scanTarget(Map<String, String> classModIds, Map<String, Class<?>> classCache, String className, @Nullable String annotationTarget, String value, boolean isClass, boolean extractFromValue)
@@ -119,7 +101,7 @@ public enum ObjectHolderRegistry
String prefix = classModIds.get(className);
if (prefix == null)
{
FMLLog.log.warn("Found an unqualified ObjectHolder annotation ({}) without a modid context at {}.{}, ignoring", value, className, annotationTarget);
LOGGER.warn("Found an unqualified ObjectHolder annotation ({}) without a modid context at {}.{}, ignoring", value, className, annotationTarget);
throw new IllegalStateException("Unqualified reference to ObjectHolder");
}
value = prefix + ":" + value;
@@ -140,11 +122,10 @@ public enum ObjectHolderRegistry
private void scanClassForFields(Map<String, String> classModIds, String className, String value, Class<?> clazz, boolean extractFromExistingValues)
{
classModIds.put(className, value);
final int flags = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC;
for (Field f : clazz.getFields())
{
int mods = f.getModifiers();
boolean isMatch = Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods);
if (!isMatch || f.isAnnotationPresent(ObjectHolder.class))
if (((f.getModifiers() & flags) != flags) || f.isAnnotationPresent(ObjectHolder.class))
{
continue;
}
@@ -162,12 +143,9 @@ public enum ObjectHolderRegistry
public void applyObjectHolders()
{
FMLLog.log.info("Applying holder lookups");
for (ObjectHolderRef ohr : objectHolders)
{
ohr.apply();
}
FMLLog.log.info("Holder lookups applied");
LOGGER.info("Applying holder lookups");
objectHolders.forEach(ObjectHolderRef::apply);
LOGGER.info("Holder lookups applied");
}
}