Difference between revisions of "User:TheSilkMiner/Capabilities"

From Forge Community Wiki
User:TheSilkMiner/Capabilities
(Reword Terminology section and titles to make more sense)
(Redirect to actual page; we don't want to break links that are already bookmarked or shared around)
Tag: New redirect
 
(6 intermediate revisions by the same user not shown)
Line 1: Line 1:
'''Capabilities''' are a Forge system that allows cross-mod interactions by allowing capability ''providers'' to dynamically respect contracts and provide specialized behavior without requiring the implementation of many interfaces or hard dependencies on mods.
+
#REDIRECT [[Capabilities]]
 
 
== History ==
 
In an ideal world, all that would be needed for a mod to provide the equivalent of a capability would be implementing an interface. This is in fact how cross-mod interaction used to work prior to the introduction of capabilities.
 
 
 
The real world, though, is often much more complicated: users wanted to be free to combine mods the way they wanted and saw fit, and developers wanted to be able to declare ''soft'' dependencies on other mods, thus reducing the need of having a huge mod pack just for testing.
 
 
 
The first approach used by Forge was conditional stripping of interfaces and methods, but this proved to be problematic. While the idea works well in theory, in practice the ASM editing of classes relied on complex mechanics and could lead to hard to spot bugs.
 
 
 
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.
 
 
 
== The Concept ==
 
A capability allows any capability provider to conditionally expose a certain ability to do something, e.g. accepting power or handling items. A capability provider, moreover, can decide to expose a capability only on certain sides, allowing for easy interactions with hoppers, cables, etc.
 
 
 
Capabilities may also be added and removed dynamically both from the "owner" of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with
 
Forge Energy could be converted into one by dynamically attaching the Forge Energy capability and handling the conversion to a third-party energy system without having to alter the original mod.
 
 
 
== Terminology ==
 
The high flexibility of the system comes with a cost, though, which is terminology. The following section wants to be a dictionary of sorts, defining all the terms that you may come across when dealing with capabilities.
 
 
 
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.
 
 
 
* '''Capability''': the ability to perform something. In-code this is represented by the <code>Capability</code> class.
 
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of <code>ICapabilityProvider</code>. There are multiple kinds of capability providers:
 
** ''Volatile Provider'': a provider that doesn't persist data to disk; once the provider ceases to exist for any number of reasons, all capability data gets deleted.
 
** ''Persistent Provider'': a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts. They implement the <code>INBTSerializable</code> interface.
 
** ''Agnostic Provider'': a provider that isn't neither volatile nor persistent, rather delegates the decision either to the capability directly or to sub-implementations. They also implement the <code>INBTSerializable</code> interface.
 
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.
 
* '''Capability Implementation''': one of the possibly many implementations of the capability interface, that actually carries out the work; one of the various implementations may also be considered the '''default capability implementation'''.
 
* '''Capability Storage''': the manager that handles loading and storing persistent capabilities data from and to disk, guaranteeing preservation of information; in-code this is represented by an implementation of the <code>Capability.IStorage</code> interface.
 
 
 
The wary reader may note that both ''persistent'' and ''agnostic'' providers are represented the same way in code. In fact, the only difference between them comes from pure semantics in how their serialization methods are designed. This will be further discussed in their respective sections.
 
 
 
== Forge-provided Capabilities and Providers ==
 
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.
 
 
 
The default capability providers in a Forge environment are: <code>TileEntity</code>, <code>Entity</code>, <code>ItemStack</code>, <code>World</code>, and <code>Chunk</code>. These are all agnostic providers, since they don't mandate any sort of capability persistency requirements. Rather, it is the job of whoever subclasses these providers to deal with either volatile or non-volatile capabilities.
 
 
 
The default capabilities that forge provides are <code>IItemHandler</code>, <code>IFluidHandler</code>, and <code>IEnergyStorage</code>. Each one of these capabilities will be discussed in the corresponding section.
 
 
 
=== <code>IItemHandler</code> ===
 
 
 
=== <code>IFluidHandler</code> ===
 
 
 
=== <code>IEnergyStorage</code> ===
 
 
 
== Working with Capabilities ==
 
 
 
=== Exposing a Capability ===
 
 
 
=== Attaching a Capability ===
 
 
 
=== Accessing a Capability ===
 
 
 
== Creating Custom Capabilities ==
 
 
 
=== The Capability Interface and the Capability Implementation ===
 
 
 
=== The Capability Storage ===
 
 
 
=== The Capability Provider ===
 
 
 
=== Tying it All Together ===
 
 
 
== Code Examples ==
 
 
 
 
 
 
 
 
 
= OLD SHIT FOLLOWS =
 
 
 
 
 
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.
 
 
 
In general terms, each capability provides a feature in the form of an interface, alongside with a default implementation which can be requested, and a storage handler for at least this default implementation. The storage handler can support other implementations, but this is up to the capability implementor, so look it up in their documentation before trying to use the default storage with non-default implementations.
 
 
 
Forge adds capability support to <code>TileEntities</code>, <code>Entities</code>, <code>ItemStack</code>s, <code>World</code>s and <code>Chunk</code>s, which can be exposed either by attaching them through an event or by overriding the capability methods in your own implementations of the objects. This will be explained in more detail in the following sections.
 
 
 
== Forge-provided Capabilities ==
 
Forge provides three capabilities: <code>IItemHandler</code>, <code>IFluidHandler</code> and <code>IEnergyStorage</code>.
 
 
 
<code>IItemHandler</code> exposes an interface for handling inventory slots. It can be applied to <code>TileEntities</code> (chests, machines, etc.), <code>Entities</code> (extra player slots, mob/creature inventories/bags), or <code>ItemStacks</code> (portable backpacks and such). It replaces the old <code>IInventory</code> and <code>ISidedInventory</code> with an automation-friendly system.
 
 
 
<code>IFluidHandler</code> exposes an interface for handling fluid inventories. It can also be applied to <code>TileEntities</code> <code>Entities</code>, or <code>ItemStacks</code>. It replaces the old <code>IFluidHandler</code> with a more consistent and automation-friendly system.
 
 
 
<code>IEnergyStorage</code> exposes an interface for handling energy containers. It can be applied to <code>TileEntities</code>, <code>Entities</code> or <code>ItemStacks</code>. It is based on the RedstoneFlux API by TeamCoFH.
 
 
 
== Using an Existing Capability  ==
 
As mentioned earlier, <code>TileEntities</code>, <code>Entities</code>, and <code>ItemStacks</code> implement the capability provider feature, through the <code>ICapabilityProvider</code> interface. This interface adds the method <code>getCapability</code>, which can be used to query the capabilities present in the objects.
 
 
 
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the <code>IItemHandler</code>, this capability is primarily stored in <code><nowiki>CapabilityItemHandler#ITEM_HANDLER_CAPABILITY</nowiki></code>, but it is possible to get other instance references by using the <code>@CapabilityInject</code> annotation.
 
<syntaxhighlight lang="java">
 
@CapabilityInject(IItemHandler.class)
 
static Capability<IItemHandler> ITEM_HANDLER_CAPABILITY = null;
 
</syntaxhighlight>
 
This annotation can be applied to fields and methods. When applied to a field, it will assign the instance of the capability (the same one gets assigned to all fields) upon registration of the capability, and left to the existing value (<code>null</code>), if the capability was never registered. Because local static field accesses are fast, it is a good idea to keep your own local copy of the reference for objects that work with capabilities. This annotation can also be used on a method, in order to get notified when a capability is registered, so that certain features can be enabled conditionally.
 
 
 
Both the <code>getCapability</code> methods have a second parameter, of type <code>Direction</code>, which can be used in the to request the specific instance for that one face. If passed <code>null</code>, it can be assumed that the request comes either from within the block, or from some place where the side has no meaning, such as a different dimension. In this case a general capability instance that does not care about sides will be requested instead. The return type of <code>getCapability</code> will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed <code>IItemHandler</code>.
 
 
 
==Exposing a Capability==
 
In order to expose a capability, you will first need an instance of the underlying capability type. Note that you should assign a separate instance to each object that keeps the capability, since the capability will most probably be tied to the containing object.
 
 
 
There’s two ways to obtain such an instance, through the <code>Capability</code> itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via <code>Capability#getDefaultInstance</code>, if those default values are useful for you. In the case of the item handler capability, the default implementation will expose a single slot inventory, which is most probably not what you want.
 
 
 
The second method can be used to provide custom implementations. In the case of <code>IItemHandler</code>, the default implementation uses the <code>ItemStackHandler</code> class, which has an optional argument in the constructor, to specify a number of slots. However, relying on the existence of these default implementations should be avoided, as the purpose of the capability system is to prevent loading errors in contexts where the capability is not present, so instantiation should be protected behind a check testing if the capability has been registered (see the remarks about <code>@CapabilityInject</code> in the previous section).
 
 
 
Once you have your own instance of the capability interface, you will want to notify users of the capability system that you expose this capability and provide a holder of the instance. This is done by overriding the <code>getCapability</code> method, and comparing the instance with the capability you are exposing. If your machine has different slots based on which side is being queried, you can test this with the <code>side</code> parameter. For <code>Entities</code> and <code>ItemStack</code>s, this parameter can be ignored, but it is still possible to have side as a context, such as different armor slots on a player (top side => head slot?), or about the surrounding blocks in the inventory (west => slot on the left?). Don’t forget to fall back to <code>super</code>, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.
 
 
 
<syntaxhighlight lang="java">
 
// Somewhere in your TileEntity subclass
 
LazyOptional<IItemHandler> inventoryHandlerLazyOptional;
 
 
 
// After initializing inventoryHandler
 
inventoryHandlerLazyOptional = LazyOptional.of(() -> inventoryHandler);
 
 
 
public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) {
 
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
 
    return inventoryHandlerLazyOptional.cast();
 
  }
 
  return super.getCapability(cap, side);
 
}
 
 
 
@Override
 
protected void invalidateCaps() {
 
  super.invalidateCaps();
 
  inventoryHandlerLazyOptional.invalidate();
 
}
 
</syntaxhighlight>
 
 
 
<code>Item</code>s are a special case since their capability providers are stored on an <code>ItemStack</code>. Instead, a provider should be attached through <code>Item#initCapabilities</code> when applicable. This should hold your capabilities for the lifecycle of the stack.
 
 
 
It is strongly suggested that direct checks in code are used to test for capabilities instead of attempting to rely on maps or other data structures, since capability tests can be done by many objects every tick, and they need to be as fast as possible in order to avoid slowing down the game.
 

Latest revision as of 08:28, 6 May 2021

Redirect to: