New Capability system allowing for more manageable world object features.

When combined with @Optional this should address all issues of soft dependancy on mods/apis.
This also addresses the issue of dynamic functionality in TileEntities/Entities.

Current capability providers: TileEntity, Entity, ItemStack

Also added INBTSerializeable, a generic interface for game objects that can be written to/from NBT tags.

Vanilla capabilities will be coming soon, mostly on request and review.
So start requesting capabiliteis on vanilla/Forge features.
This commit is contained in:
LexManos committed 2016-01-11 16:04:22 -08:00
1 parent 4672f7bab0
commit 17db34ae31
16 files changed
+988 -44

No files matched your search

@@ -0,0 +1,106 @@
package net.minecraftforge.common.capabilities;
import java.util.concurrent.Callable;
import com.google.common.base.Throwables;
import net.minecraft.nbt.NBTBase;
import net.minecraft.util.EnumFacing;
/**
* This is the core holder object Capabilities.
* Each capability will have ONE instance of this class,
* and it will the the one passed into the ICapabilityProvider functions.
*
* The CapabilityManager is in charge of creating this class.
*/
public class Capability<T>
{
public static interface IStorage<T>
{
/**
* Serialize the capability instance to a NBTTag.
* This allows for a central implementation of saving the data.
*
* It is important to note that it is up to the API defining
* the capability what requirements the 'instance' value must have.
*
* Due to the possibility of manipulating internal data, some
* implementations MAY require that the 'instance' be an instance
* of the 'default' implementation.
*
* Review the API docs for more info.
*
* @param capability The Capability being stored.
* @param instance An instance of that capabilities interface.
* @param side The side of the object the instance is associated with.
* @return a NBT holding the data. Null if no data needs to be stored.
*/
NBTBase writeNBT(Capability<T> capability, T instance, EnumFacing side);
/**
* Read the capability instance from a NBT tag.
*
* This allows for a central implementation of saving the data.
*
* It is important to note that it is up to the API defining
* the capability what requirements the 'instance' value must have.
*
* Due to the possibility of manipulating internal data, some
* implementations MAY require that the 'instance' be an instance
* of the 'default' implementation.
*
* Review the API docs for more info. *
*
* @param capability The Capability being stored.
* @param instance An instance of that capabilities interface.
* @param side The side of the object the instance is associated with.
* @param A NBT holding the data. Must not be null, as doesn't make sense to call this function with nothing to read...
*/
void readNBT(Capability<T> capability, T instance, EnumFacing side, NBTBase nbt);
}
/**
* @return The unique name of this capability, typically this is
* the fully qualified class name for the target interface.
*/
public String getName() { return name; }
/**
* @return An instance of the default storage handler. You can safely use this store your default implementation in NBT.
*/
public IStorage<T> getStorage() { return storage; }
/**
* A NEW instance of the default implementation.
*
* If it important to note that if you want to use the default storage
* you may be required to use this exact implementation.
* Refer to the owning API of the Capability in question.
*
* @return A NEW instance of the default implementation.
*/
public T getDefaultInstance()
{
try
{
return this.factory.call();
}
catch (Exception e)
{
Throwables.propagate(e);
}
return null;
}
// INTERNAL
private final String name;
private final IStorage<T> storage;
private final Callable<? extends T> factory;
Capability(String name, IStorage<T> storage, Callable<? extends T> factory)
{
this.name = name;
this.storage = storage;
this.factory = factory;
}
}
@@ -0,0 +1,117 @@
package net.minecraftforge.common.capabilities;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.util.INBTSerializable;
/**
* A high-speed implementation of a capability delegator.
* This is used to wrap the results of the AttachCapabilitiesEvent.
* It is HIGHLY recommended that you DO NOT use this approach unless
* you MUST delegate to multiple providers instead just implement y
* our handlers using normal if statements.
*
* Internally the handlers are baked into arrays for fast iteration.
* The ResourceLocations will be used for the NBT Key when serializing.
*/
public final class CapabilityDispatcher implements INBTSerializable<NBTTagCompound>, ICapabilityProvider
{
private ICapabilityProvider[] caps;
private INBTSerializable<NBTBase>[] writers;
private String[] names;
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list)
{
this(list, null);
}
@SuppressWarnings("unchecked")
public CapabilityDispatcher(Map<ResourceLocation, ICapabilityProvider> list, ICapabilityProvider parent)
{
List<ICapabilityProvider> lstCaps = Lists.newArrayList();
List<INBTSerializable<NBTBase>> lstWriters = Lists.newArrayList();
List<String> lstNames = Lists.newArrayList();
if (parent != null) // Parents go first!
{
lstCaps.add(parent);
if (parent instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<NBTBase>)parent);
lstNames.add("Parent");
}
}
for (Map.Entry<ResourceLocation, ICapabilityProvider> entry : list.entrySet())
{
ICapabilityProvider prov = entry.getValue();
lstCaps.add(prov);
if (prov instanceof INBTSerializable)
{
lstWriters.add((INBTSerializable<NBTBase>)prov);
lstNames.add(entry.getKey().toString());
}
}
caps = lstCaps.toArray(new ICapabilityProvider[lstCaps.size()]);
writers = lstWriters.toArray(new INBTSerializable[lstWriters.size()]);
names = lstNames.toArray(new String[lstNames.size()]);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
for (ICapabilityProvider cap : caps)
{
if (cap.hasCapability(capability, facing))
{
return true;
}
}
return false;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
for (ICapabilityProvider cap : caps)
{
T ret = cap.getCapability(capability, facing);
if (ret != null)
{
return ret;
}
}
return null;
}
@Override
public NBTTagCompound serializeNBT()
{
NBTTagCompound nbt = new NBTTagCompound();
for (int x = 0; x < writers.length; x++)
{
nbt.setTag(names[x], writers[x].serializeNBT());
}
return nbt;
}
@Override
public void deserializeNBT(NBTTagCompound nbt)
{
for (int x = 0; x < writers.length; x++)
{
if (nbt.hasKey(names[x]))
{
writers[x].deserializeNBT(nbt.getTag(names[x]));
}
}
}
}
@@ -0,0 +1,34 @@
package net.minecraftforge.common.capabilities;
import java.lang.annotation.*;
/**
* When placed on a FIELD, the field will be set to an
* instance of Capability once that capability is registered.
* That field must be static and be able to hold a instance
* of 'Capability'
*
* Example:
* @CapabilityInject(IExampleCapability.class)
* private static final Capability<IExampleCapability> TEST_CAP = null;
*
* When placed on a METHOD, the method will be invoked once the
* capability is registered. This allows you to have a 'enable features'
* callback. It MUST have one parameter of type 'Capability;
*
* Example:
* @CapabilityInject(IExampleCapability.class)
* private static void capRegistered(Capability<IExampleCapability> cap) {}
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface CapabilityInject
{
/**
* The capability interface to listen for registration.
* Note:
* When reading annotations, DO NOT call this function as it will cause a hard dependency on the class.
*/
Class<?> value();
}
@@ -0,0 +1,170 @@
package net.minecraftforge.common.capabilities;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.logging.log4j.Level;
import org.objectweb.asm.Type;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.fml.common.FMLLog;
import net.minecraftforge.fml.common.discovery.ASMDataTable;
public enum CapabilityManager
{
INSTANCE;
/**
* Registers a capability to be consumed by others.
* APIs who define the capability should call this.
* To retrieve the Capability instance, use the @CapabilityInject annotation.
*
* @param type The Interface to be registered
* @param storage A default implementation of the storage handler.
* @param implementation A default implementation of the interface.
*/
public <T> void register(Class<T> type, Capability.IStorage<T> storage, final Class<? extends T> implementation)
{
Preconditions.checkArgument(implementation != null, "Attempted to register a capability with no default implementation");
register(type, storage, new Callable<T>()
{
@Override
public T call() throws Exception
{
try {
return (T)implementation.newInstance();
} catch (InstantiationException e) {
Throwables.propagate(e);
} catch (IllegalAccessException e) {
Throwables.propagate(e);
}
return null;
}
});
}
/**
* Registers a capability to be consumed by others.
* APIs who define the capability should call this.
* To retrieve the Capability instance, use the @CapabilityInject annotation.
*
* @param type The Interface to be registered
* @param storage A default implementation of the storage handler.
* @param factor A Factory that will produce new instances of the default implementation.
*/
public <T> void register(Class<T> type, Capability.IStorage<T> storage, Callable<? extends T> factory)
{
Preconditions.checkArgument(type != null, "Attempted to register a capability with invalid type");
Preconditions.checkArgument(storage != null, "Attempted to register a capability with no storage implementation");
Preconditions.checkArgument(factory != null, "Attempted to register a capability with no default implementation factory");
String realName = type.getName().intern();
Preconditions.checkState(!providers.containsKey(realName), "Can not register a capability implementation multiple times: %s", realName);
Capability<T> cap = new Capability<T>(realName, storage, factory);
providers.put(realName, cap);
List<Function<Capability<?>, Object>> list = callbacks.get(realName);
if (list != null)
{
for (Function<Capability<?>, Object> func : list)
{
func.apply(cap);
}
}
}
// INTERNAL
private IdentityHashMap<String, Capability<?>> providers = Maps.newIdentityHashMap();
private IdentityHashMap<String, List<Function<Capability<?>, Object>>> callbacks = Maps.newIdentityHashMap();
public void injectCapabilities(ASMDataTable data)
{
for (ASMDataTable.ASMData entry : data.getAll(CapabilityInject.class.getName()))
{
final String targetClass = entry.getClassName();
final String targetName = entry.getObjectName();
Type type = (Type)entry.getAnnotationInfo().get("value");
if (type == null)
{
FMLLog.log(Level.WARN, "Unable to inject capability at %s.%s (Invalid Annotation)", targetClass, targetName);
}
final String capabilityName = type.getInternalName().replace('/', '.').intern();
List<Function<Capability<?>, Object>> list = callbacks.get(capabilityName);
if (list == null)
{
list = Lists.newArrayList();
callbacks.put(capabilityName, list);
}
if (entry.getObjectName().indexOf('(') > 0)
{
list.add(new Function<Capability<?>, Object>()
{
@Override
public Object apply(Capability<?> input)
{
try
{
for (Method mtd : Class.forName(targetClass).getDeclaredMethods())
{
if (targetName.equals(mtd.getName() + Type.getMethodDescriptor(mtd)))
{
if ((mtd.getModifiers() & Modifier.STATIC) != Modifier.STATIC)
{
FMLLog.log(Level.WARN, "Unable to inject capability %s at %s.%s (Non-Static)", capabilityName, targetClass, targetName);
return null;
}
mtd.setAccessible(true);
mtd.invoke(null, input);
return null;
}
}
FMLLog.log(Level.WARN, "Unable to inject capability %s at %s.%s (Method Not Found)", capabilityName, targetClass, targetName);
}
catch (Exception e)
{
FMLLog.log(Level.WARN, e, "Unable to inject capability %s at %s.%s", capabilityName, targetClass, targetName);
}
return null;
}
});
}
else
{
list.add(new Function<Capability<?>, Object>()
{
@Override
public Object apply(Capability<?> input)
{
try
{
Field field = Class.forName(targetClass).getDeclaredField(targetName);
if ((field.getModifiers() & Modifier.STATIC) != Modifier.STATIC)
{
FMLLog.log(Level.WARN, "Unable to inject capability %s at %s.%s (Non-Static)", capabilityName, targetClass, targetName);
return null;
}
EnumHelper.setFailsafeFieldValue(field, null, input);
}
catch (Exception e)
{
FMLLog.log(Level.WARN, e, "Unable to inject capability %s at %s.%s", capabilityName, targetClass, targetName);
}
return null;
}
});
}
}
}
}
@@ -0,0 +1,35 @@
package net.minecraftforge.common.capabilities;
import net.minecraft.util.EnumFacing;
public interface ICapabilityProvider
{
/**
* Determines if this object has support for the capability in question on the specific side.
* The return value of this MIGHT change during runtime if this object gains or looses support
* for a capability.
*
* Example:
* A Pipe getting a cover placed on one side causing it loose the Inventory attachment function for that side.
*
* This is a light weight version of getCapability, intended for metadata uses.
*
* @param capability The capability to check
* @param facing The Side to check from:
* CAN BE NULL. Null is defined to represent 'internal' or 'self'
* @return True if this object supports the capability.
*/
boolean hasCapability(Capability<?> capability, EnumFacing facing);
/**
* Retrieves the handler for the capability requested on the specific side.
* The return value CAN be null if the object does not support the capability.
* The return value CAN be the same for multiple faces.
*
* @param capability The capability to check
* @param facing The Side to check from:
* CAN BE NULL. Null is defined to represent 'internal' or 'self'
* @return True if this object supports the capability.
*/
<T> T getCapability(Capability<T> capability, EnumFacing facing);
}
@@ -0,0 +1,7 @@
package net.minecraftforge.common.capabilities;
import net.minecraft.nbt.NBTBase;
import net.minecraftforge.common.util.INBTSerializable;
//Just a mix of the two, useful in patches to lower the size.
public interface ICapabilitySerializable<T extends NBTBase> extends ICapabilityProvider, INBTSerializable<T>{}
@@ -0,0 +1,13 @@
package net.minecraftforge.common.util;
import net.minecraft.nbt.NBTBase;
/**
* An interface designed to unify various things in the Minecraft
* code base that can be serialized to and from a NBT tag.
*/
public interface INBTSerializable<T extends NBTBase>
{
T serializeNBT();
void deserializeNBT(T nbt);
}
@@ -0,0 +1,117 @@
package net.minecraftforge.event;
import java.util.Collections;
import java.util.Map;
import com.google.common.collect.Maps;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.fml.common.eventhandler.Event;
/**
* Fired whenever an object with Capabilities support {currently TileEntity/Item/Entity)
* is created. Allowing for the attachment of arbitrary capability providers.
*
* Please note that as this is fired for ALL object creations efficient code is recommended.
* And if possible use one of the sub-classes to filter your intended objects.
*/
public class AttachCapabilitiesEvent extends Event
{
private final Object obj;
private final Map<ResourceLocation, ICapabilityProvider> caps = Maps.newLinkedHashMap();
private final Map<ResourceLocation, ICapabilityProvider> view = Collections.unmodifiableMap(caps);
public AttachCapabilitiesEvent(Object obj)
{
this.obj = obj;
}
/**
* Retrieves the object that is being created, Not much state is set.
*/
public Object getObject()
{
return this.obj;
}
/**
* Adds a capability to be attached to this object.
* Keys MUST be unique, it is suggested that you set the domain to your mod ID.
* If the capability is an instance of INBTSerializeable, this key will be used when serializing this capability.
*
* @param key The name of owner of this capability provider.
* @param cap The capability provider
*/
public void addCapability(ResourceLocation key, ICapabilityProvider cap)
{
if (caps.containsKey(key))
throw new IllegalStateException("Duplicate Capability Key: " + key + " " + cap);
this.caps.put(key, cap);
}
/**
* A unmodifiable view of the capabilities that will be attached to this object.
*/
public Map<ResourceLocation, ICapabilityProvider> getCapabilities()
{
return view;
}
/**
* A version of the parent event which is only fired for Tile Entities.
*/
public static class TileEntity extends AttachCapabilitiesEvent
{
private final net.minecraft.tileentity.TileEntity te;
public TileEntity(net.minecraft.tileentity.TileEntity te)
{
super(te);
this.te = te;
}
public net.minecraft.tileentity.TileEntity getTileEntity()
{
return this.te;
}
}
/**
* A version of the parent event which is only fired for Entities.
*/
public static class Entity extends AttachCapabilitiesEvent
{
private final net.minecraft.entity.Entity entity;
public Entity(net.minecraft.entity.Entity entity)
{
super(entity);
this.entity = entity;
}
public net.minecraft.entity.Entity getEntity()
{
return this.entity;
}
}
/**
* A version of the parent event which is only fired for ItemStacks.
*/
public static class Item extends AttachCapabilitiesEvent
{
private final net.minecraft.item.ItemStack stack;
private final net.minecraft.item.Item item;
public Item(net.minecraft.item.Item item, net.minecraft.item.ItemStack stack)
{
super(item);
this.item = item;
this.stack = stack;
}
public net.minecraft.item.Item getItem()
{
return this.item;
}
public net.minecraft.item.ItemStack getItemStack()
{
return this.stack;
}
}
}
@@ -16,7 +16,9 @@ import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayer.EnumStatus;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumFacing;
@@ -33,6 +35,8 @@ import net.minecraftforge.client.event.ClientChatReceivedEvent;
import net.minecraftforge.client.event.RenderBlockOverlayEvent;
import net.minecraftforge.client.event.RenderBlockOverlayEvent.OverlayType;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.event.brewing.PotionBrewEvent;
import net.minecraftforge.event.entity.EntityEvent;
@@ -91,7 +95,7 @@ public class ForgeEventFactory
MinecraftForge.EVENT_BUS.post(event);
return event;
}
public static NeighborNotifyEvent onNeighborNotify(World world, BlockPos pos, IBlockState state, EnumSet<EnumFacing> notifiedSides)
{
NeighborNotifyEvent event = new NeighborNotifyEvent(world, pos, state, notifiedSides);
@@ -142,7 +146,7 @@ public class ForgeEventFactory
MinecraftForge.EVENT_BUS.post(event);
return event.getResult();
}
public static int getExperienceDrop(EntityLivingBase entity, EntityPlayer attackingPlayer, int originalExperience)
{
LivingExperienceDropEvent event = new LivingExperienceDropEvent(entity, attackingPlayer, originalExperience);
@@ -323,7 +327,7 @@ public class ForgeEventFactory
MinecraftForge.EVENT_BUS.post(event);
return event.name;
}
public static PlaySoundAtEntityEvent onPlaySoundAtEntity(Entity entity, String name, float volume, float pitch)
{
PlaySoundAtEntityEvent event = new PlaySoundAtEntityEvent(entity, name, volume, pitch);
@@ -362,18 +366,18 @@ public class ForgeEventFactory
{
return !MinecraftForge.EVENT_BUS.post(new EntityInteractEvent(player, entity));
}
public static boolean canMountEntity(Entity entityMounting, Entity entityBeingMounted, boolean isMounting)
{
boolean isCanceled = MinecraftForge.EVENT_BUS.post(new EntityMountEvent(entityMounting, entityBeingMounted, entityMounting.worldObj, isMounting));
if(isCanceled)
{
entityMounting.setPositionAndRotation(entityMounting.posX, entityMounting.posY, entityMounting.posZ, entityMounting.prevRotationYaw, entityMounting.prevRotationPitch);
return false;
}
else
return true;
else
return true;
}
public static EnumStatus onPlayerSleepInBed(EntityPlayer player, BlockPos pos)
@@ -392,7 +396,7 @@ public class ForgeEventFactory
{
MinecraftForge.EVENT_BUS.post(new PlayerFlyableFallEvent(player, distance, multiplier));
}
public static boolean onPlayerSpawnSet(EntityPlayer player, BlockPos pos, boolean forced) {
return MinecraftForge.EVENT_BUS.post(new PlayerSetSpawnEvent(player, pos, forced));
}
@@ -460,20 +464,40 @@ public class ForgeEventFactory
{
MinecraftForge.EVENT_BUS.post(new PotionBrewEvent.Post(brewingItemStacks));
}
public static boolean renderFireOverlay(EntityPlayer player, float renderPartialTicks)
{
return renderBlockOverlay(player, renderPartialTicks, OverlayType.FIRE, Blocks.fire.getDefaultState(), new BlockPos(player));
}
public static boolean renderWaterOverlay(EntityPlayer player, float renderPartialTicks)
{
return renderBlockOverlay(player, renderPartialTicks, OverlayType.WATER, Blocks.water.getDefaultState(), new BlockPos(player));
}
public static boolean renderBlockOverlay(EntityPlayer player, float renderPartialTicks, OverlayType type, IBlockState block, BlockPos pos)
{
return MinecraftForge.EVENT_BUS.post(new RenderBlockOverlayEvent(player, renderPartialTicks, type, block, pos));
}
public static CapabilityDispatcher gatherCapabilities(TileEntity tileEntity)
{
return gatherCapabilities(new AttachCapabilitiesEvent.TileEntity(tileEntity), null);
}
public static CapabilityDispatcher gatherCapabilities(Entity entity)
{
return gatherCapabilities(new AttachCapabilitiesEvent.Entity(entity), null);
}
public static CapabilityDispatcher gatherCapabilities(Item item, ItemStack stack, ICapabilityProvider parent)
{
return gatherCapabilities(new AttachCapabilitiesEvent.Item(item, stack), parent);
}
private static CapabilityDispatcher gatherCapabilities(AttachCapabilitiesEvent event, ICapabilityProvider parent)
{
MinecraftForge.EVENT_BUS.post(event);
return event.getCapabilities().size() > 0 ? new CapabilityDispatcher(event.getCapabilities(), parent) : null;
}
}
@@ -27,6 +27,7 @@ import java.util.Properties;
import java.util.Set;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.fml.common.LoaderState.ModState;
import net.minecraftforge.fml.common.ModContainer.Disableable;
import net.minecraftforge.fml.common.ProgressManager.ProgressBar;
@@ -551,6 +552,7 @@ public class Loader
}
ObjectHolderRegistry.INSTANCE.findObjectHolders(discoverer.getASMTable());
ItemStackHolderInjector.INSTANCE.findHolders(discoverer.getASMTable());
CapabilityManager.INSTANCE.injectCapabilities(discoverer.getASMTable());
modController.distributeStateMessage(LoaderState.PREINITIALIZATION, discoverer.getASMTable(), canonicalConfigDir);
ObjectHolderRegistry.INSTANCE.applyObjectHolders();
ItemStackHolderInjector.INSTANCE.inject();