<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-GB">
	<id>https://forge.gemwire.uk/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=TheSilkMiner</id>
	<title>Forge Community Wiki - User contributions [en-gb]</title>
	<link rel="self" type="application/atom+xml" href="https://forge.gemwire.uk/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=TheSilkMiner"/>
	<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/wiki/Special:Contributions/TheSilkMiner"/>
	<updated>2026-06-02T07:36:40Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.35.0</generator>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Codecs&amp;diff=3417</id>
		<title>Codecs</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Codecs&amp;diff=3417"/>
		<updated>2024-01-10T18:20:14Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Keep the only change made by Blabliblubpaul that made sense&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Codecs are a serialization tool from mojang's DataFixerUpper library. Codecs are used alongside [[DynamicOps|DynamicOps]] to allow objects to be serialized to different formats and back, such as JSON or [[Using_NBT|NBT]]. While the DynamicOps describes the format the object is to be serialized to, the Codec describes the manner in which the object is to be serialized; a single Codec can be used to serialize an object to any format for which a DynamicOps exists. Codecs and DynamicOps jointly form an abstraction layer over data serialization, simplifying the effort needed to serialize or deserialize data.&lt;br /&gt;
&lt;br /&gt;
= Using Codecs =&lt;br /&gt;
&lt;br /&gt;
== Serialization and Deserialization ==&lt;br /&gt;
&lt;br /&gt;
The primary use for Codecs is to serialize java objects to some serialized type, such as a JsonElement or a Tag, and to deserialize a serialized object back to its proper java type. This is accomplished with &amp;lt;code&amp;gt;Codec#encodeStart&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Codec#parse&amp;lt;/code&amp;gt;, respectively. Given a Codec&amp;lt;SomeJavaType&amp;gt; and a DynamicOps&amp;lt;SomeSerializedType&amp;gt;, we can convert instances of SomeJavaType to instances of SomeSerializedType and back.&lt;br /&gt;
&lt;br /&gt;
Each of these methods take a [[DynamicOps]] instance and an instance of the object we are serializing or deserializing, and returns a DataResult:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// let someCodec be a Codec&amp;lt;SomeJavaType&amp;gt;&lt;br /&gt;
// let someJavaObject be an instance of SomeJavaType&lt;br /&gt;
// let someTag and someJsonElement be instances of Tag and JsonElement, respectively&lt;br /&gt;
&lt;br /&gt;
// serialize some java object to Tag&lt;br /&gt;
DataResult&amp;lt;Tag&amp;gt; result = someCodec.encodeStart(NBTOps.INSTANCE, someJavaObject);&lt;br /&gt;
&lt;br /&gt;
// deserialize some Tag instance back to a proper java object&lt;br /&gt;
DataResult&amp;lt;SomeJavaType&amp;gt; result = someCodec.parse(NBTOps.INSTANCE, someTag);&lt;br /&gt;
&lt;br /&gt;
// serialize some java object to a JsonElement&lt;br /&gt;
DataResult&amp;lt;JsonElement&amp;gt; result = someCodec.encodeStart(JsonOps.INSTANCE, someJavaObject);&lt;br /&gt;
&lt;br /&gt;
// deserialize a JsonElement back to a proper java object&lt;br /&gt;
DataResult&amp;lt;SomeJavaType&amp;gt; result = someCodec.parse(JsonOps.INSTANCE, someJsonElement);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A DataResult either holds the converted instance, or it holds some error data, depending on whether the conversion was successful or not, respectively. There are several things we can do with this DataResult; &amp;lt;code&amp;gt;DataResult#result&amp;lt;/code&amp;gt; simply returns an Optional containing the converted object if the conversion was successful, while &amp;lt;code&amp;gt;DataResult#resultOrPartial&amp;lt;/code&amp;gt; also runs a given function if the conversion was unsuccessful (in addition to returning the Optional). #resultOrPartial is particularly useful for logging errors during datapack deserialization:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// deserialize something from json&lt;br /&gt;
someCodec.parse(JsonOps.INSTANCE, someJsonElement)&lt;br /&gt;
	.resultOrPartial(errorMessage -&amp;gt; doSomethingIfBadData(errorMessage))&lt;br /&gt;
	.ifPresent(someJavaObject -&amp;gt; doSomethingIfGoodData(someJavaObject))&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Builtin Codecs ==&lt;br /&gt;
=== Primitive Codecs ===&lt;br /&gt;
The Codec class itself contains static instances of codecs for all supported primitive types, e.g. &amp;lt;code&amp;gt;Codec.STRING&amp;lt;/code&amp;gt; is the canonical &amp;lt;code&amp;gt;Codec&amp;lt;String&amp;gt;&amp;lt;/code&amp;gt; implementation. Primitive codecs include:&lt;br /&gt;
* BOOL, which serializes to a boolean value&lt;br /&gt;
* BYTE, SHORT, INT, LONG, FLOAT, and DOUBLE, which serialize to numeric values&lt;br /&gt;
* STRING, which serializes to a string&lt;br /&gt;
* BYTE_BUFFER, INT_STREAM, and LONG_STREAM, which serialize to lists of numbers&lt;br /&gt;
* EMPTY, which represents null objects&lt;br /&gt;
&lt;br /&gt;
=== Other Builtin Codecs ===&lt;br /&gt;
Vanilla minecraft has many builtin codecs for objects that it frequently serializes. These codecs are typically static instances in the class the codec is serializing; e.g. &amp;lt;code&amp;gt;ResourceLocation.CODEC&amp;lt;/code&amp;gt; is the canonical &amp;lt;code&amp;gt;Codec&amp;lt;ResourceLocation&amp;gt;&amp;lt;/code&amp;gt;, while &amp;lt;code&amp;gt;BlockPos.CODEC&amp;lt;/code&amp;gt; is the codec used for serializing a BlockPos.&lt;br /&gt;
&lt;br /&gt;
Each vanilla &amp;lt;code&amp;gt;Registry&amp;lt;/code&amp;gt; acts as the Codec for the type of object the registry contains; e.g. &amp;lt;code&amp;gt;Registry.BLOCK&amp;lt;/code&amp;gt; is itself a &amp;lt;code&amp;gt;Codec&amp;lt;Block&amp;gt;&amp;lt;/code&amp;gt;. Forge Registries, however, do not currently implement Codec and cannot yet be used in this way; custom codecs must be created for forge-specific registries that are not tied to specific vanilla registries.&lt;br /&gt;
&lt;br /&gt;
Of particular note here is the CompoundTag.CODEC, which can be used to e.g. serialize a CompoundTag into a json file. This has a notable limitation in that CompoundTag.CODEC *cannot* safely deserialize lists of numbers from json, due to the strong typing of ListTag and the way that the NBTOps deserializer reads numeric values.&lt;br /&gt;
&lt;br /&gt;
= Creating Codecs =&lt;br /&gt;
&lt;br /&gt;
Suppose we have the following class, and we want to deserialize json files to instances of this class:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class ExampleCodecClass {&lt;br /&gt;
&lt;br /&gt;
    private final int someInt;&lt;br /&gt;
    private final Item item;&lt;br /&gt;
    private final List&amp;lt;BlockPos&amp;gt; blockPositions;&lt;br /&gt;
&lt;br /&gt;
    public ExampleCodecClass(int someInt, Item item, List&amp;lt;BlockPos&amp;gt; blockPositions) {...}&lt;br /&gt;
&lt;br /&gt;
    public int getSomeInt() { return this.someInt; }&lt;br /&gt;
    public Item getItem() { return this.item; }&lt;br /&gt;
    public List&amp;lt;BlockPos&amp;gt; getBlockPositions() { return this.blockPositions; }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Where a json file for an instance of this class might look like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
	&amp;quot;some_int&amp;quot;: 42,&lt;br /&gt;
	&amp;quot;item&amp;quot;: &amp;quot;minecraft:gold_ingot&amp;quot;,&lt;br /&gt;
	&amp;quot;block_positions&amp;quot;:&lt;br /&gt;
	[&lt;br /&gt;
		[0,0,0],&lt;br /&gt;
		[10,20,-100]&lt;br /&gt;
	]&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We can assemble a codec for this class by building a new codec out of smaller codecs. We'll need a codec for each of these fields:&lt;br /&gt;
* a &amp;lt;code&amp;gt;Codec&amp;lt;Integer&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
* a &amp;lt;code&amp;gt;Codec&amp;lt;Item&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
* a &amp;lt;code&amp;gt;Codec&amp;lt;List&amp;lt;BlockPos&amp;gt;&amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
And then we'll need to assemble these into a &amp;lt;code&amp;gt;Codec&amp;lt;ExampleCodecClass&amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
As previously mentioned, we can use &amp;lt;code&amp;gt;Codec.INT&amp;lt;/code&amp;gt; for the integer codec, and &amp;lt;code&amp;gt;Registry.ITEM&amp;lt;/code&amp;gt; for the Item codec. We don't have a builtin codec for list-of-blockpos, but we can use BlockPos.CODEC to create one.&lt;br /&gt;
&lt;br /&gt;
== Lists ==&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec#listOf&amp;lt;/code&amp;gt; instance method can be used to generate a codec for a List from an existing codec:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// BlockPos.CODEC is a Codec&amp;lt;BlockPos&amp;gt;&lt;br /&gt;
Codec&amp;lt;List&amp;lt;BlockPos&amp;gt;&amp;gt; = BlockPos.CODEC.listOf();&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Codecs created via listOf() serialize things to listlike objects, such as [] json arrays or ListTags.&lt;br /&gt;
&lt;br /&gt;
Deserializing a list in this manner produces an ''immutable'' list. If a mutable list is needed, [[Codecs#Equivalent_Types_and_xmap|xmap]] can be used to convert the list after deserializing.&lt;br /&gt;
&lt;br /&gt;
== Records ==&lt;br /&gt;
RecordCodecBuilder is used to generate codecs that serialize instances of classes with explicitly named fields, like our example above. Codecs created via RecordCodecBuilder serialize things to maplike objects, such as {} json objects or CompoundTags.&lt;br /&gt;
&lt;br /&gt;
RecordCodecBuilder can be used in several ways, but the simplest form is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;SomeJavaClass&amp;gt; = RecordCodecBuilder.create(instance -&amp;gt; instance.group(&lt;br /&gt;
		someFieldCodecA.fieldOf(&amp;quot;field_name_a&amp;quot;).forGetter(SomeJavaClass::getFieldA),&lt;br /&gt;
		someFieldCodecB.fieldOf(&amp;quot;field_name_b&amp;quot;).forGetter(SomeJavaClass::getFieldB),&lt;br /&gt;
		someFieldCodecC.fieldOf(&amp;quot;field_name_c&amp;quot;).forGetter(SomeJavaClass::getFieldC),&lt;br /&gt;
		// up to 16 fields can be declared here&lt;br /&gt;
	).apply(instance, SomeJavaClass::new));&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Where each line in the group specifies a codec instance for the type of that field, the field name in the serialized object, and the corresponding getter function in the java class. The builder is concluded by specifying a constructor or factory for the java class whose arguments are the previously defined fields in the same order.&lt;br /&gt;
&lt;br /&gt;
For example, using RecordCodecBuilder to create a codec for our example class above:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;ExampleCodecClass&amp;gt; = RecordCodecBuilder.create(instance -&amp;gt; instance.group(&lt;br /&gt;
		Codec.INT.fieldOf(&amp;quot;some_int&amp;quot;).forGetter(ExampleCodecClass::getSomeInt),&lt;br /&gt;
		Registry.ITEM.fieldOf(&amp;quot;item&amp;quot;).forGetter(ExampleCodecClass::getItem),&lt;br /&gt;
		BlockPos.CODEC.listOf().fieldOf(&amp;quot;block_positions&amp;quot;).forGetter(ExampleCodecClass::getBlockPositions)&lt;br /&gt;
	).apply(instance, ExampleCodecClass::new));&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Optional and Default Values in Record Fields===&lt;br /&gt;
When RecordCodecBuilder is used as shown above, all of the fields are *required* to be in the serialized object (the JsonObject/CompoundTag/etc), or the entire thing will fail to parse when the codec tries to deserialize it. If we wish to have optional or default values, we have several alternatives of fieldOf() we can use.&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;someCodec.optionalFieldOf(&amp;quot;field_name&amp;quot;)&amp;lt;/code&amp;gt; creates a field for an Optional. If the field in the json/nbt is not present or invalid, it will deserialize as an empty optional. Empty optionals will not be serialized; the field will be omitted from the json or nbt.&lt;br /&gt;
* &amp;lt;code&amp;gt;someCodec.optionalFieldOf(&amp;quot;field_name&amp;quot;, someDefaultValue)&amp;lt;/code&amp;gt; creates an optional field that deserializes as the given default value if the field is not present in the json/nbt. When serializing, if the field in the java object equals the default value, the value will not be serialized and the field will be omitted from the json or nbt.&lt;br /&gt;
&lt;br /&gt;
When using optional fields, be wary that if the field contains bad data or otherwise fails to serialize, the error will be silently caught, and the field will serialize as the default value instead!&lt;br /&gt;
&lt;br /&gt;
===Boxing values as objects===&lt;br /&gt;
In some situations, we may need to serialize a single value as a single-field object. We can use fieldOf to box a single value in this way without needing the entire RecordCodecBuilder process:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;Integer&amp;gt; BOXED_INT_CODEC = Codec.INT.fieldOf(&amp;quot;value&amp;quot;).codec();&lt;br /&gt;
&lt;br /&gt;
JsonElement value = BOXED_INT_CODEC.encodeStart(JsonOps.INSTANCE, 5).result().get();&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Which serializes the following output:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
{&amp;quot;value&amp;quot;:5}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Unit==&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec.unit(defaultValue)&amp;lt;/code&amp;gt; codec creates a Codec that always deserializes a specified default value, regardless of input. When serializing, it serializes nothing.&lt;br /&gt;
&lt;br /&gt;
==Pair==&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec.pair(codecA, codecB)&amp;lt;/code&amp;gt; static method takes two codecs and generates a Codec&amp;lt;Pair&amp;lt;A,B&amp;gt;&amp;gt; from them.&lt;br /&gt;
&lt;br /&gt;
The only valid arguments for this method are codecs that serialize to objects with explicit fields, such as codecs created using [[Codecs#Records|RecordCodecBuilder]] or [[Codecs#Boxing_values_as_objects|fieldOf]]. Codecs that serialize nothing (such as [[Codecs#Unit|unit codecs]]) are also valid as they act as objects-with-no-fields.&lt;br /&gt;
&lt;br /&gt;
The resulting Pair codec will serialize a single object that has all of the fields of the two original codecs. For example:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;Pair&amp;lt;Integer,String&amp;gt;&amp;gt; PAIR_CODEC = Codec.pair(&lt;br /&gt;
	Codec.INT.fieldOf(&amp;quot;value&amp;quot;).codec(),&lt;br /&gt;
	Codec.STRING.fieldOf(&amp;quot;name&amp;quot;).codec());&lt;br /&gt;
&lt;br /&gt;
JsonElement encodedPair = PAIR_CODEC.encodeStart(JsonOps.INSTANCE, Pair.of(5, &amp;quot;cheese&amp;quot;).result().get();&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
This codec serializes the above value to:&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
{&lt;br /&gt;
	&amp;quot;value&amp;quot;: 5,&lt;br /&gt;
	&amp;quot;name&amp;quot;: &amp;quot;cheese&amp;quot;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Codecs that serialize to objects with undefined fields such as [[Codecs#Maps|unboundedMap]] may cause strange and unpredictable behaviour when used here; these objects should be boxed via fieldOf when used in a pair codec.&lt;br /&gt;
&lt;br /&gt;
==Either==&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec.either(codecA, codecB)&amp;lt;/code&amp;gt; static method takes two codecs and generates a Codec&amp;lt;Either&amp;lt;A,B&amp;gt;&amp;gt; from them.&lt;br /&gt;
&lt;br /&gt;
When this codec is used to de/serialize an object, it first attempts to use the first codec; if and only if that conversion fails, it then attempts to use the second codec. If that conversion also fails, then the returned DataResult will contain the error data from the *second* codec's conversion attempt.&lt;br /&gt;
&lt;br /&gt;
==Numeric Ranges==&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec.intRange(min,max)&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Codec.floatRange(min,max)&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Codec.doubleRange(min,max)&amp;lt;/code&amp;gt; static methods generate Codecs for Integers, Floats, or Doubles, respectively, for which only a specified inclusive range is valid, and values outside that range will fail to de/serialize.&lt;br /&gt;
&lt;br /&gt;
==Maps==&lt;br /&gt;
Suppose we want to serialize a HashMap or other Map type, where we could have indefinitely many key-value pairs and we don't know what the keys are ahead of time.&lt;br /&gt;
&lt;br /&gt;
We can create a &amp;lt;code&amp;gt;Codec&amp;lt;Map&amp;lt;KEY,VALUE&amp;gt;&amp;gt;&amp;lt;/code&amp;gt; using the &amp;lt;code&amp;gt;Codec.unboundedMap&amp;lt;/code&amp;gt; static method, which takes a key codec and a value codec and creates a codec for a map type:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;Map&amp;lt;String, BlockPos&amp;gt;&amp;gt; = Codec.unboundedMap(Codec.STRING, BlockPos.CODEC);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The serialized form of maps serialized by this codec will be a JsonObject or CompoundTag, whose fields are the key-value pairs in the map; the map's keys will be used as the field names, and the map's values will be the values of those fields&lt;br /&gt;
&lt;br /&gt;
A limitation of using unboundedMap is that it only supports key codecs that serialize to Strings (including codecs for things like ResourceLocation that aren't Strings themselves but still serialize to strings). To create a codec for a Map whose keys are not fundamentally strings, the Map must be serialized as a list of key-value pairs instead of using unboundedMap.&lt;br /&gt;
&lt;br /&gt;
==Equivalent Types and xmap==&lt;br /&gt;
Suppose we have two java classes, Amalgam and Box; any Amalgam instance can be converted to a Box, and vice-versa. Now suppose we have a Codec&amp;lt;Amalgam&amp;gt;, but we'd also like to have a Codec&amp;lt;Box&amp;gt;. Rather than creating an entirely new codec for Box from scratch, we can simply xmap our Amalgam codec instead.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;Codec#xmap&amp;lt;/code&amp;gt; instance method is used to generate a second codec for a fundamentally equivalent type to the first codec's type. The method takes two function objects as arguments, which are used to convert the first type to the second when deserializing, and converting the second type to the first when serializing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static final Codec&amp;lt;Box&amp;gt; = Amalgam.CODEC.xmap(Amalgam::toBox, Box::toAmalgam);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Codecs created in this manner will serialize objects in the same format as the starting codec.&lt;br /&gt;
&lt;br /&gt;
==Partially Equivalent Types, flatComapMap, comapFlatMap, and flatXMap==&lt;br /&gt;
Consider the ResourceLocation: Any ResourceLocation can be converted to a String, but not all Strings can be converted to a ResourceLocation; ResourceLocations have strict limits on their format and allowed characters.&lt;br /&gt;
&lt;br /&gt;
While we *could* use xmap to convert the Codec.STRING to a codec for ResourceLocations, this would cause attempts to parse an invalid string like &amp;lt;code&amp;gt;SHOUTY:MOD:Invalid$Characters&amp;lt;/code&amp;gt; to throw a runtime exception, when we really should be returning a failed DataResult to the parser instead -- which indeed is what the vanilla ResourceLocation codec does.&lt;br /&gt;
&lt;br /&gt;
Codecs have three additional instance methods for creating equivalent codecs for when we can *potentially* convert one type to another, but are not guaranteed to be able to do so. These take conversion function arguments that return DataResults, allowing validation to be performed during serialization and deserialization.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|+ Codec Conversion Methods&lt;br /&gt;
|-&lt;br /&gt;
! Can A always be converted to B? !! Can B always be converted to A? !! Which method of codecA should be used to create codecB?&lt;br /&gt;
|-&lt;br /&gt;
| yes || yes || codecA.xmap&lt;br /&gt;
|-&lt;br /&gt;
| yes || no || codecA.flatComapMap&lt;br /&gt;
|-&lt;br /&gt;
| no || yes || codecA.comapFlatMap&lt;br /&gt;
|-&lt;br /&gt;
| no || no || codecA.flatXmap&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Registry Dispatch ==&lt;br /&gt;
Registry Dispatch Codecs allow us to define a registry of codecs and delegate to a specific codec to deserialize a particular json based on a type field in that json. Dispatch codecs are used extensively when deserializing worldgen data.&lt;br /&gt;
&lt;br /&gt;
To create a dispatch codec for a Thing class, the following steps can be performed:&lt;br /&gt;
# Create a Thing abstract class class and ThingType interface. The ThingType interface should have a method that supplies a Codec&amp;lt;Thing&amp;gt;, while Thing subclasses must define a method that supplies a ThingType.&lt;br /&gt;
# Create a map or registry of ThingTypes, and register a ThingType for each sub-codec we want to have.&lt;br /&gt;
# Create a Codec&amp;lt;ThingType&amp;gt;, or have the ThingType registry implement Codec.&lt;br /&gt;
# Create our Codec&amp;lt;Thing&amp;gt; master codec by invoking &amp;lt;code&amp;gt;Codec#dispatch&amp;lt;/code&amp;gt; on our ThingType codec. This method's arguments are:&lt;br /&gt;
## A field name for the ID of the sub-codec (the example json below is using &amp;quot;type&amp;quot;)&lt;br /&gt;
## A function to retrieve a ThingType from a Thing&lt;br /&gt;
## A function to retrieve a Codec&amp;lt;Thing&amp;gt; from a ThingType&lt;br /&gt;
&lt;br /&gt;
We can then use our Codec&amp;lt;Thing&amp;gt; to create Thing fields in other codecs whose serialized format depends on the specific sub-codec used by a Thing instance.&lt;br /&gt;
&lt;br /&gt;
As an example of this, consider the ExampleCodecClass earlier. Suppose we make this class extend Thing and register our codec for it to a codec dispatch registry with the id &amp;quot;ourmod:exampleclass&amp;quot;. If we were to define an instance of this class in a Thing field in some json, it would look like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;some_thing&amp;quot;:&lt;br /&gt;
{&lt;br /&gt;
	&amp;quot;type&amp;quot;: &amp;quot;ourmod:exampleclass&amp;quot;,&lt;br /&gt;
	&amp;quot;some_int&amp;quot;: 42,&lt;br /&gt;
	&amp;quot;item&amp;quot;: &amp;quot;minecraft:gold_ingot&amp;quot;,&lt;br /&gt;
	&amp;quot;block_positions&amp;quot;:&lt;br /&gt;
	[&lt;br /&gt;
		[0,0,0],&lt;br /&gt;
		[10,20,-100]&lt;br /&gt;
	]&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Other ThingTypes we register would have different fields in this json object, but would still be valid for the &amp;quot;some_thing&amp;quot; field.&lt;br /&gt;
&lt;br /&gt;
Several examples of vanilla classes that use dispatch codecs:&lt;br /&gt;
* RuleTest and RuleTestType&lt;br /&gt;
* BlockPlacer and BlockPlacerType&lt;br /&gt;
* ConfiguredDecorator and FeatureDecorator&lt;br /&gt;
&lt;br /&gt;
=== Registering MapCodecCodecs for Dispatch Subcodecs ===&lt;br /&gt;
&lt;br /&gt;
When registering a subcodec to any dispatch codec registry, the registered subcodec should be an instance of MapCodecCodec, or the subcodec will be nested in its own object when serialized.&lt;br /&gt;
&lt;br /&gt;
For example, suppose we register a single-field subcodec, where we use fieldOf-and-xmap to convert an int to our int-holding Thing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public record Thing(int n){}&lt;br /&gt;
public static Codec&amp;lt;Thing&amp;gt; CODEC = Codec.INT.fieldOf(&amp;quot;n&amp;quot;).codec().xmap(Thing::new, Thing::n);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This results in this json when serialized:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;some_thing&amp;quot;:&lt;br /&gt;
{&lt;br /&gt;
	&amp;quot;type&amp;quot;: &amp;quot;ourmod:thing&amp;quot;,&lt;br /&gt;
	&amp;quot;value&amp;quot;: {&lt;br /&gt;
		&amp;quot;n&amp;quot;: 5&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This occurs because xmap does not produce a MapCodecCodec, and if this nested object is not desired, then our registered subcodec must be a MapCodecCodec.&lt;br /&gt;
&lt;br /&gt;
However, fieldOf() produces a MapCodec, which has a codec() method, which does produce a MapCodecCodec. We can rearrange our codec builder, which then produces a cleaner json:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Codec&amp;lt;Thing&amp;gt; CODEC = Codec.INT // Primitive codec&lt;br /&gt;
	.fieldOf(&amp;quot;n&amp;quot;) // MapCodec&lt;br /&gt;
	.xmap(Thing::new, Thing::n) // MapCodec&lt;br /&gt;
	.codec(); // MapCodecCodec! That's what we want.&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;json&amp;quot;&amp;gt;&lt;br /&gt;
&amp;quot;some_thing&amp;quot;:&lt;br /&gt;
{&lt;br /&gt;
	&amp;quot;type&amp;quot;: &amp;quot;ourmod:thing&amp;quot;,&lt;br /&gt;
	&amp;quot;n&amp;quot;: 5&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
RecordCodecBuilder also produces MapCodecCodecs.&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
* [https://github.com/Mojang/DataFixerUpper/blob/master/src/main/java/com/mojang/serialization/Codec.java Codecs in Mojang's official public DataFixerUpper repository]&lt;br /&gt;
* [https://kvverti.github.io/Documented-DataFixerUpper/snapshot/com/mojang/serialization/Codec.html#flatXmap-java.util.function.Function-java.util.function.Function- Unofficial Codec Javadocs]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Datagen&amp;diff=3397</id>
		<title>Datagen</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Datagen&amp;diff=3397"/>
		<updated>2023-03-30T13:57:26Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Create redirect to Datageneration page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;#REDIRECT [[Datageneration]]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2589</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2589"/>
		<updated>2021-05-06T08:28:58Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Redirect to actual page; we don't want to break links that are already bookmarked or shared around&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;#REDIRECT [[Capabilities]]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=Capabilities&amp;diff=2588</id>
		<title>Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=Capabilities&amp;diff=2588"/>
		<updated>2021-05-06T08:27:10Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Rewrite Capability documentation to be better in documenting stuff&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Capabilities''' are a Forge system that allows cross-mod interactions by allowing capability ''providers'' to&lt;br /&gt;
dynamically respect contracts and provide specialized behavior without requiring the implementation of many interfaces&lt;br /&gt;
or hard dependencies on mods.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
In an ideal world, all that would be needed for a mod to provide the equivalent of a capability would be implementing an&lt;br /&gt;
interface. This is in fact how cross-mod interaction used to work prior to the introduction of capabilities.&lt;br /&gt;
&lt;br /&gt;
The real world, though, is often much more complicated: users wanted to be free to combine mods the way they wanted and&lt;br /&gt;
saw fit, and developers wanted to be able to declare ''soft'' dependencies on other mods, thus reducing the need of&lt;br /&gt;
having a huge mod pack just for testing.&lt;br /&gt;
&lt;br /&gt;
The first approach used by Forge was conditional stripping of interfaces and methods, but this proved to be problematic.&lt;br /&gt;
While the idea works well in theory, in practice the ASM editing of classes relied on complex mechanics and could lead&lt;br /&gt;
to hard to spot bugs.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
A capability allows any capability provider to conditionally expose a certain ability to do something, e.g. accepting&lt;br /&gt;
power or handling items. A capability provider, moreover, can decide to expose a capability only on certain sides,&lt;br /&gt;
allowing for easy interactions with hoppers, cables, etc.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods,&lt;br /&gt;
allowing even easier cross-mod interaction. For example, a mod that isn't compatible with Forge Energy could be&lt;br /&gt;
converted into one by dynamically attaching the Forge Energy capability and handling the conversion to a third-party&lt;br /&gt;
energy system without having to alter the original mod.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
The high flexibility of the system comes with a cost, though, which is terminology. The following section wants to be a&lt;br /&gt;
dictionary of sorts, defining all the terms that you may come across when dealing with capabilities.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
; Capability&lt;br /&gt;
: the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
; Capability Provider&lt;br /&gt;
: something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
:; Volatile Provider&lt;br /&gt;
:: 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.&lt;br /&gt;
:; Persistent Provider&lt;br /&gt;
:: a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts. They implement the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
:; Agnostic Provider&lt;br /&gt;
:: 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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
; Capability Interface&lt;br /&gt;
: the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
; Capability Implementation&lt;br /&gt;
: 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'''.&lt;br /&gt;
; Capability Storage&lt;br /&gt;
: 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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The wary reader may note that both ''persistent'' and ''agnostic'' providers are represented the same way in code. In&lt;br /&gt;
fact, the only difference between them comes from pure semantics in how their serialization methods are designed. This&lt;br /&gt;
will be further discussed in their respective sections.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly&lt;br /&gt;
correct, due to common usage we will also use this convention. So, to refer to the capability interface&lt;br /&gt;
&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability&lt;br /&gt;
providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. These are all agnostic providers, since they don't&lt;br /&gt;
mandate any sort of capability persistency requirements. Rather, it is the job of whoever subclasses these providers to&lt;br /&gt;
deal with either volatile or non-volatile capabilities.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and&lt;br /&gt;
&amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal&lt;br /&gt;
'''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible,&lt;br /&gt;
though, to expose this capability even if no such inventory is present as long as the capability provider can emulate&lt;br /&gt;
its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These&lt;br /&gt;
interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends&lt;br /&gt;
to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids&lt;br /&gt;
in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;&lt;br /&gt;
capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider&lt;br /&gt;
to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and&lt;br /&gt;
produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or&lt;br /&gt;
FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux&lt;br /&gt;
Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the&lt;br /&gt;
Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework,&lt;br /&gt;
otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and&lt;br /&gt;
capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''' or '''users''',&lt;br /&gt;
need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object&lt;br /&gt;
itself. Since these objects are created by Forge and there is only '''one''' unique instance for each capability that&lt;br /&gt;
may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such&lt;br /&gt;
instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as it gets created by Forge, following the&lt;br /&gt;
principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user&lt;br /&gt;
that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method&lt;br /&gt;
instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with&lt;br /&gt;
&amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the&lt;br /&gt;
unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to&lt;br /&gt;
provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the desired&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a&lt;br /&gt;
number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the &lt;br /&gt;
capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of&lt;br /&gt;
style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of&lt;br /&gt;
type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also&lt;br /&gt;
be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a&lt;br /&gt;
&amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable&lt;br /&gt;
fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and&lt;br /&gt;
accessed by users.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains&lt;br /&gt;
consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide&lt;br /&gt;
many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the&lt;br /&gt;
accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to&lt;br /&gt;
[[#Accessing a Capability|Accessing a Capability]] for more information), it is the provider's responsibility to trigger&lt;br /&gt;
a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be&lt;br /&gt;
performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private final LazyOptional&amp;lt;IItemhandler&amp;gt; inventoryOptional = LazyOptional.of(() -&amp;gt; this.inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null || direction == Direction.UP || direction == Direction.DOWN)) {&lt;br /&gt;
        return this.inventoryOptional.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    this.inventoryOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts&lt;br /&gt;
access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the&lt;br /&gt;
block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the world or unloaded due to distance.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what&lt;br /&gt;
allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke&lt;br /&gt;
&amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
Attaching a Capability is a process by which external agents &amp;quot;modify&amp;quot; a Capability Provider, making it expose additional&lt;br /&gt;
capabilities other than the already available ones.&lt;br /&gt;
&lt;br /&gt;
To do so, the '''attaching agent''' (which means the thing that wants to attach a capability to another provider) must&lt;br /&gt;
listen to the &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; in this case represents the capability&lt;br /&gt;
provider you want to attach the capability to. Note that the type of &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; '''must''' be the base type of the&lt;br /&gt;
capability provider, not a subclass. As an example, if you want to attach a capability to a &amp;lt;code&amp;gt;MyTileEntity&amp;lt;/code&amp;gt;,&lt;br /&gt;
which extends &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, you'll have to listen to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;TileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;,&lt;br /&gt;
'''NOT''' to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;MyTileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, since the latter will never fire.&lt;br /&gt;
&lt;br /&gt;
The attaching agent can use the provided methods &amp;lt;code&amp;gt;getObject&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;addCapability&amp;lt;/code&amp;gt;, and &lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; to check whether the capability should be attached to the current object and perform the&lt;br /&gt;
desired action.&lt;br /&gt;
&lt;br /&gt;
When attaching a capability, the attaching agent should also provide a name in the form of a&lt;br /&gt;
&amp;lt;code&amp;gt;ResourceLocation&amp;lt;/code&amp;gt;. The name '''must''' be under the attaching agent's namespace, but no restrictions are&lt;br /&gt;
placed on the actual name, as long as it is unique inside the given namespace.&lt;br /&gt;
&lt;br /&gt;
Maybe a little counter-intuitively, the process of attaching does not attach a capability nor a capability interface&lt;br /&gt;
directly. Rather, the attaching agent should create its own implementation of a '''Capability Provider''' and attach it&lt;br /&gt;
via the event. This is done so that the attaching agent can have control over when, how, and where its capabilities are&lt;br /&gt;
exposed, instead of relying on the game itself deciding these parameters. For this reason, all considerations given in&lt;br /&gt;
the [[#Exposing a Capability|Exposing a Capability]] section on how to correctly create a Capability Provider.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an attaching agent may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilityProvider() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == CapabilityEnergy.ENERGY) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapability(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an attaching agent attaches a &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability to all&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; instance that are a subclass of &amp;lt;code&amp;gt;EnergyBasedTileEntity&amp;lt;/code&amp;gt;. It also sets up the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; for invalidation if the parent capability provider gets invalidated.&lt;br /&gt;
&lt;br /&gt;
Note also the call of &amp;lt;code&amp;gt;LazyOptional.empty()&amp;lt;/code&amp;gt; rather than a &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;. This is needed because when&lt;br /&gt;
attaching a capability, the parent capability provider isn't known. For this reason, it is necessary to return an empty&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;. The game will then handle automatic merging of the various different providers into a single&lt;br /&gt;
one.&lt;br /&gt;
&lt;br /&gt;
The above example is one of a '''Volatile''' Capability Provider. On the other hand, mods may want to persist their&lt;br /&gt;
data across sessions. In this case, they should attach a '''Persistent''' Capability Provider: this can be done either&lt;br /&gt;
by implementing the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface along with &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; or by&lt;br /&gt;
implementing the &amp;lt;code&amp;gt;ICapabilitySerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The previous example reworked to use a Persistent Capability Provider may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
    Capability&amp;lt;IEnergyStorage&amp;gt; capability = CapabilityEnergy.ENERGY;&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilitySerializable&amp;lt;IntNBT&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == capability) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public IntNBT serializeNBT() {&lt;br /&gt;
            return capability.getStorage().writeNbt(capability, backend, null);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void deserializeNBT(IntNBT nbt) {&lt;br /&gt;
            capability.getStorage().readNBT(capability, backend, null, nbt);&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Accessing a Capability is the process by which a user is able to '''query''' a Capability Provider for a specific&lt;br /&gt;
instance of a capability.&lt;br /&gt;
&lt;br /&gt;
This is perhaps the second most important part of the entire capability system, since it is what allows cross-mod&lt;br /&gt;
interaction. To obtain an instance of a Capability, the user must first get a hold of the Capability Provider that&lt;br /&gt;
should be queried. This can be done in a variety of ways and is outside the scope of this article. The user should&lt;br /&gt;
then invoke the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method passing the unique instance of the capability that should be queried&lt;br /&gt;
(see [[#Obtaining a Capability|Obtaining a Capability]] for more information) and the querying &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;,&lt;br /&gt;
if applicable.&lt;br /&gt;
&lt;br /&gt;
The returned object is a &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; wrapping the queried Capability, if the capability provider exposes&lt;br /&gt;
it, otherwise it will be empty. The &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; can be either unwrapped via an &amp;lt;code&amp;gt;orElse&amp;lt;/code&amp;gt; or&lt;br /&gt;
used directly via &amp;lt;code&amp;gt;ifPresent&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It is '''highly suggested''' to cache the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; to avoid querying the same provider every&lt;br /&gt;
time, in order to improve performance. The user should thus register itself to the invalidation listener via the&lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; method. This ensures that the user will be able to react to the invalidation of the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and remove it from the cache.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an user may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
private final Map&amp;lt;Direction, LazyOptional&amp;lt;IEnergyStorage&amp;gt;&amp;gt; cache = new HashMap&amp;lt;&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
private void sendPowerTo(int power, Direction direction) {&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; targetCapability = cache.get(direction);&lt;br /&gt;
&lt;br /&gt;
    if (targetCapability == null) {&lt;br /&gt;
        ICapabilityProvider provider = world.getTileEntity(pos.offset(direction));&lt;br /&gt;
        targetCapability = provider.getCapability(CapabilityEnergy.ENERGY, direction.getOpposite());&lt;br /&gt;
        cache.put(direction, targetCapability);&lt;br /&gt;
        targetCapability.addListener(self -&amp;gt; cache.put(direction, null));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    targetCapability.ifPresent(storage -&amp;gt; storage.receiveEnergy(power, false));&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an user is querying via a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; the neighboring capability provider&lt;br /&gt;
for an &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability. Before obtaining the provider, the code performs a cache lookup for the&lt;br /&gt;
targeted capability. If the check succeeds, then no lookup is performed; if the check fails, the targeted Capability&lt;br /&gt;
Provider is obtained and queried for the Capability. The obtained &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; is then cached and a&lt;br /&gt;
listener is attached to it so that the cache would be emptied on invalidation. The code then continues with the&lt;br /&gt;
interaction with the capability, which is outside the scope of this article.&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
While the various capabilities provided by Forge may satisfy the most common use cases, there is always the chance that&lt;br /&gt;
a mod may require a custom solution. For this reason, Forge provides a way to define a custom Capability.&lt;br /&gt;
&lt;br /&gt;
Defining a custom Capability requires the user to provide three main components: the Capability Interface, at least one&lt;br /&gt;
Capability Implementation, and the Capability Storage. Optionally, a Capability Provider can also be created. In this&lt;br /&gt;
case, the provider will be used as described in [[#Attaching a Capability|Attaching a Capability]]. The various details &lt;br /&gt;
for all these components are described in the respective sections of this article.&lt;br /&gt;
&lt;br /&gt;
In this section, we will refer to the implementation of a &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability, that can be used to&lt;br /&gt;
store a single mutable &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Refer also to [[#Code Examples|Code Examples]] for an example on how the various components may be implemented in a&lt;br /&gt;
real-world scenario.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
The Capability Interface is one of the most important parts of a Capability: without it, the Capability effectively does&lt;br /&gt;
not exist. Designing a Capability Interface is exactly like designing any Java interface, so the particular details will&lt;br /&gt;
be glossed over in this section.&lt;br /&gt;
&lt;br /&gt;
The Capability Implementation, on the other hand, is the implementation of the previously defined Capability Interface.&lt;br /&gt;
Usual rules for interface implementations follow. There can be more than one Capability Implementation for each&lt;br /&gt;
capability, but no less than one.&lt;br /&gt;
&lt;br /&gt;
Note that a '''well-formed''' capability implementation should '''not store''' the Capability Provider inside of it: we&lt;br /&gt;
call the capability implementation ''provider-agnostic''. This is not a hard-requirement, though, rather it should act&lt;br /&gt;
more as a guideline. There are in fact certain situations where this cannot be avoided (e.g. attaching a client-synced&lt;br /&gt;
capability to an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
One of the various Capability Implementation should also act as the default implementation. Other mods can ask the&lt;br /&gt;
capability to create an instance of the default implementation without ever referring to such an implementation&lt;br /&gt;
themselves. This guarantees separation of API code from implementation code, which is also one of the goals of the&lt;br /&gt;
capability system. &lt;br /&gt;
&lt;br /&gt;
Given all of the above information, this may be an example implementation of both a Capability Interface and a&lt;br /&gt;
Capability Implementation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public interface MyCapability {&lt;br /&gt;
    String getValue();&lt;br /&gt;
    void setValue(String value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class MyCapabilityImplementation implements MyCapability {&lt;br /&gt;
    private String value;&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public String getValue() {&lt;br /&gt;
        return this.value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void setValue(String value) {&lt;br /&gt;
        this.value = value;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that in this case, only a single implementation is provided, which will also act as the default implementation for&lt;br /&gt;
the &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
The Capability Storage is that component of the Capability System that is responsible for serializing and deserializing&lt;br /&gt;
a capability. All capabilities must provide one, since certain providers may or may not require that their capabilities&lt;br /&gt;
are serializable.&lt;br /&gt;
&lt;br /&gt;
The Capability Storage implements the &amp;lt;code&amp;gt;Capability.IStorage&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt; interface, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; is the&lt;br /&gt;
generic type of the Capability Interface the storage refers to. Each capability must have '''one and exactly one'''&lt;br /&gt;
Capability Storage.&lt;br /&gt;
&lt;br /&gt;
The Storage is usually called by the Capability Provider when serialization or deserialization needs to happen. The&lt;br /&gt;
Storage is then responsible of reading the data from the given capability instance and convert that into an NBT-based&lt;br /&gt;
structure that can be serialized. A Storage may also return &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to indicate that no serialization is&lt;br /&gt;
necessary, although some providers may require an empty tag to be supplied instead. At the same time, the Storage is&lt;br /&gt;
also responsible for restoring the original state of the capability when deserialization happens. In this case, the&lt;br /&gt;
given NBT structure is guaranteed not to be &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
In all cases, a &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; is provided for context, if available.&lt;br /&gt;
&lt;br /&gt;
Although discouraged as a matter of code cleanliness, it is legal for a Capability Storage to require a specific&lt;br /&gt;
Capability Implementation for the serialization and deserialization to be successful. If this is the case, this&lt;br /&gt;
requirement '''must''' be documented, though the code should be refactored wherever possible to remove this requirement.&lt;br /&gt;
&lt;br /&gt;
Given the above information, an example of an implementation of a Capability Storage may be the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class MyCapabilityStorage implements Capability.IStorage&amp;lt;MyCapability&amp;gt; {&lt;br /&gt;
    @Override&lt;br /&gt;
    @Nullable&lt;br /&gt;
    INBT writeNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction) {&lt;br /&gt;
        return StringNBT.valueOf(instance.getValue());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void readNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction, INBT nbtData) {&lt;br /&gt;
        if (!(nbtData instanceof StringNBT)) {&lt;br /&gt;
            throw new IllegalArgumentException(&amp;quot;Unable to deserialize 'MyCapability' from a non-String NBT structure&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
        instance.setValue(((StringNBT) nbtData).getString());&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the &amp;lt;code&amp;gt;instanceof&amp;lt;/code&amp;gt; check needed to ensure that the given &amp;lt;code&amp;gt;INBT&amp;lt;/code&amp;gt; instance is valid for&lt;br /&gt;
deserialization. A Capability Storage should always perform this check prior to the cast in order to provide a&lt;br /&gt;
meaningful error message, rather than a cryptic &amp;lt;code&amp;gt;ClassCastException&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
The Capability Provider is an optional component of the capability that allows the Capability to be attached to a&lt;br /&gt;
component. The details on how a Capability Provider should behave have already been discussed in the two previous&lt;br /&gt;
sections [[#Exposing a Capability|Exposing a Capability]] and [[#Attaching a Capability|Attaching a Capability]]: refer&lt;br /&gt;
to those for more information.&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
Once all components of a Capability have been created, they must be registered so that the game is aware of the&lt;br /&gt;
capability's presence. The registration requires specifying the Capability Interface, the Capability Storage, and a&lt;br /&gt;
factory for the default capability implementation.&lt;br /&gt;
&lt;br /&gt;
The registration can be performed by calling the &amp;lt;code&amp;gt;register&amp;lt;/code&amp;gt; method on the &amp;lt;code&amp;gt;CapabilityManager&amp;lt;/code&amp;gt;.&lt;br /&gt;
This '''needs''' to happen when the &amp;lt;code&amp;gt;FMLCommonSetupEvent&amp;lt;/code&amp;gt; is fired on the &amp;lt;code&amp;gt;MOD&amp;lt;/code&amp;gt; event bus. The&lt;br /&gt;
registration will also automatically inject the created Capability into all relevant fields and methods: refer to&lt;br /&gt;
[[#Obtaining a Capability|Obtaining a Capability]] for more information.&lt;br /&gt;
&lt;br /&gt;
An example of registration can be found in the snippet that follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public void onCommonSetup(FMLCommonSetupEvent event) {&lt;br /&gt;
    CapabilityManager.INSTANCE.register(MyCapability.class, new MyCapabilityStorage(), MyCapabilityImplementation::new);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Custom Capability Providers ==&lt;br /&gt;
&lt;br /&gt;
Much like custom Capabilities, Forge also allows the creation of custom Capability Providers. The main advantage of this&lt;br /&gt;
is allowing mods to create custom providers for their custom objects, in order to promote not only cross-mod&lt;br /&gt;
compatibility, but also uniformity in the way users may interact with different mod APIs.&lt;br /&gt;
&lt;br /&gt;
This section will only give the basic outline of what is necessary to implement a custom Capability Provider: for more&lt;br /&gt;
in-depth explanation, people are referred to the game code.&lt;br /&gt;
&lt;br /&gt;
By definition, a custom Capability Provider is everything that implements the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;&lt;br /&gt;
interface. In this section, though, we will only cover people that may want to replicate the functionality of one of&lt;br /&gt;
the default providers, such as &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The easiest way of doing this is extending the &amp;lt;code&amp;gt;CapabilityProvider&amp;lt;/code&amp;gt; class provided by Forge. This will&lt;br /&gt;
automatically set up an ''agnostic'' Capability Provider. To fully initialize the capability provider, the subclass&lt;br /&gt;
should then invoke the &amp;lt;code&amp;gt;gatherCapabilities&amp;lt;/code&amp;gt; method as the last instruction in its constructor, to ensure that&lt;br /&gt;
the game is able to recollect and attach all capabilities that other mods may want to attach to the capability provider.&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
* [https://gist.github.com/TheSilkMiner/5cc92ba573e7bdd871dfdbffdd5c2806 A Gist showing a quick and dirty example on how to implement a Capability effectively]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2587</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2587"/>
		<updated>2021-05-06T08:26:12Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: client -&amp;gt; user&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Capabilities''' are a Forge system that allows cross-mod interactions by allowing capability ''providers'' to&lt;br /&gt;
dynamically respect contracts and provide specialized behavior without requiring the implementation of many interfaces&lt;br /&gt;
or hard dependencies on mods.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
In an ideal world, all that would be needed for a mod to provide the equivalent of a capability would be implementing an&lt;br /&gt;
interface. This is in fact how cross-mod interaction used to work prior to the introduction of capabilities.&lt;br /&gt;
&lt;br /&gt;
The real world, though, is often much more complicated: users wanted to be free to combine mods the way they wanted and&lt;br /&gt;
saw fit, and developers wanted to be able to declare ''soft'' dependencies on other mods, thus reducing the need of&lt;br /&gt;
having a huge mod pack just for testing.&lt;br /&gt;
&lt;br /&gt;
The first approach used by Forge was conditional stripping of interfaces and methods, but this proved to be problematic.&lt;br /&gt;
While the idea works well in theory, in practice the ASM editing of classes relied on complex mechanics and could lead&lt;br /&gt;
to hard to spot bugs.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
A capability allows any capability provider to conditionally expose a certain ability to do something, e.g. accepting&lt;br /&gt;
power or handling items. A capability provider, moreover, can decide to expose a capability only on certain sides,&lt;br /&gt;
allowing for easy interactions with hoppers, cables, etc.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods,&lt;br /&gt;
allowing even easier cross-mod interaction. For example, a mod that isn't compatible with Forge Energy could be&lt;br /&gt;
converted into one by dynamically attaching the Forge Energy capability and handling the conversion to a third-party&lt;br /&gt;
energy system without having to alter the original mod.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
The high flexibility of the system comes with a cost, though, which is terminology. The following section wants to be a&lt;br /&gt;
dictionary of sorts, defining all the terms that you may come across when dealing with capabilities.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
; Capability&lt;br /&gt;
: the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
; Capability Provider&lt;br /&gt;
: something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
:; Volatile Provider&lt;br /&gt;
:: 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.&lt;br /&gt;
:; Persistent Provider&lt;br /&gt;
:: a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts. They implement the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
:; Agnostic Provider&lt;br /&gt;
:: 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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
; Capability Interface&lt;br /&gt;
: the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
; Capability Implementation&lt;br /&gt;
: 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'''.&lt;br /&gt;
; Capability Storage&lt;br /&gt;
: 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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The wary reader may note that both ''persistent'' and ''agnostic'' providers are represented the same way in code. In&lt;br /&gt;
fact, the only difference between them comes from pure semantics in how their serialization methods are designed. This&lt;br /&gt;
will be further discussed in their respective sections.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly&lt;br /&gt;
correct, due to common usage we will also use this convention. So, to refer to the capability interface&lt;br /&gt;
&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability&lt;br /&gt;
providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. These are all agnostic providers, since they don't&lt;br /&gt;
mandate any sort of capability persistency requirements. Rather, it is the job of whoever subclasses these providers to&lt;br /&gt;
deal with either volatile or non-volatile capabilities.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and&lt;br /&gt;
&amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal&lt;br /&gt;
'''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible,&lt;br /&gt;
though, to expose this capability even if no such inventory is present as long as the capability provider can emulate&lt;br /&gt;
its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These&lt;br /&gt;
interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends&lt;br /&gt;
to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids&lt;br /&gt;
in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;&lt;br /&gt;
capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider&lt;br /&gt;
to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and&lt;br /&gt;
produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or&lt;br /&gt;
FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux&lt;br /&gt;
Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the&lt;br /&gt;
Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework,&lt;br /&gt;
otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and&lt;br /&gt;
capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''' or '''users''',&lt;br /&gt;
need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object&lt;br /&gt;
itself. Since these objects are created by Forge and there is only '''one''' unique instance for each capability that&lt;br /&gt;
may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such&lt;br /&gt;
instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as it gets created by Forge, following the&lt;br /&gt;
principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user&lt;br /&gt;
that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method&lt;br /&gt;
instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with&lt;br /&gt;
&amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the&lt;br /&gt;
unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to&lt;br /&gt;
provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the desired&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a&lt;br /&gt;
number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the &lt;br /&gt;
capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of&lt;br /&gt;
style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of&lt;br /&gt;
type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also&lt;br /&gt;
be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a&lt;br /&gt;
&amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable&lt;br /&gt;
fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and&lt;br /&gt;
accessed by users.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains&lt;br /&gt;
consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide&lt;br /&gt;
many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the&lt;br /&gt;
accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to&lt;br /&gt;
[[#Accessing a Capability|Accessing a Capability]] for more information), it is the provider's responsibility to trigger&lt;br /&gt;
a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be&lt;br /&gt;
performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private final LazyOptional&amp;lt;IItemhandler&amp;gt; inventoryOptional = LazyOptional.of(() -&amp;gt; this.inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null || direction == Direction.UP || direction == Direction.DOWN)) {&lt;br /&gt;
        return this.inventoryOptional.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    this.inventoryOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts&lt;br /&gt;
access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the&lt;br /&gt;
block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the world or unloaded due to distance.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what&lt;br /&gt;
allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke&lt;br /&gt;
&amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
Attaching a Capability is a process by which external agents &amp;quot;modify&amp;quot; a Capability Provider, making it expose additional&lt;br /&gt;
capabilities other than the already available ones.&lt;br /&gt;
&lt;br /&gt;
To do so, the '''attaching agent''' (which means the thing that wants to attach a capability to another provider) must&lt;br /&gt;
listen to the &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; in this case represents the capability&lt;br /&gt;
provider you want to attach the capability to. Note that the type of &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; '''must''' be the base type of the&lt;br /&gt;
capability provider, not a subclass. As an example, if you want to attach a capability to a &amp;lt;code&amp;gt;MyTileEntity&amp;lt;/code&amp;gt;,&lt;br /&gt;
which extends &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, you'll have to listen to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;TileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;,&lt;br /&gt;
'''NOT''' to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;MyTileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, since the latter will never fire.&lt;br /&gt;
&lt;br /&gt;
The attaching agent can use the provided methods &amp;lt;code&amp;gt;getObject&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;addCapability&amp;lt;/code&amp;gt;, and &lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; to check whether the capability should be attached to the current object and perform the&lt;br /&gt;
desired action.&lt;br /&gt;
&lt;br /&gt;
When attaching a capability, the attaching agent should also provide a name in the form of a&lt;br /&gt;
&amp;lt;code&amp;gt;ResourceLocation&amp;lt;/code&amp;gt;. The name '''must''' be under the attaching agent's namespace, but no restrictions are&lt;br /&gt;
placed on the actual name, as long as it is unique inside the given namespace.&lt;br /&gt;
&lt;br /&gt;
Maybe a little counter-intuitively, the process of attaching does not attach a capability nor a capability interface&lt;br /&gt;
directly. Rather, the attaching agent should create its own implementation of a '''Capability Provider''' and attach it&lt;br /&gt;
via the event. This is done so that the attaching agent can have control over when, how, and where its capabilities are&lt;br /&gt;
exposed, instead of relying on the game itself deciding these parameters. For this reason, all considerations given in&lt;br /&gt;
the [[#Exposing a Capability|Exposing a Capability]] section on how to correctly create a Capability Provider.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an attaching agent may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilityProvider() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == CapabilityEnergy.ENERGY) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapability(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an attaching agent attaches a &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability to all&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; instance that are a subclass of &amp;lt;code&amp;gt;EnergyBasedTileEntity&amp;lt;/code&amp;gt;. It also sets up the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; for invalidation if the parent capability provider gets invalidated.&lt;br /&gt;
&lt;br /&gt;
Note also the call of &amp;lt;code&amp;gt;LazyOptional.empty()&amp;lt;/code&amp;gt; rather than a &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;. This is needed because when&lt;br /&gt;
attaching a capability, the parent capability provider isn't known. For this reason, it is necessary to return an empty&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;. The game will then handle automatic merging of the various different providers into a single&lt;br /&gt;
one.&lt;br /&gt;
&lt;br /&gt;
The above example is one of a '''Volatile''' Capability Provider. On the other hand, mods may want to persist their&lt;br /&gt;
data across sessions. In this case, they should attach a '''Persistent''' Capability Provider: this can be done either&lt;br /&gt;
by implementing the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface along with &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; or by&lt;br /&gt;
implementing the &amp;lt;code&amp;gt;ICapabilitySerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The previous example reworked to use a Persistent Capability Provider may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
    Capability&amp;lt;IEnergyStorage&amp;gt; capability = CapabilityEnergy.ENERGY;&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilitySerializable&amp;lt;IntNBT&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == capability) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public IntNBT serializeNBT() {&lt;br /&gt;
            return capability.getStorage().writeNbt(capability, backend, null);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void deserializeNBT(IntNBT nbt) {&lt;br /&gt;
            capability.getStorage().readNBT(capability, backend, null, nbt);&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Accessing a Capability is the process by which a user is able to '''query''' a Capability Provider for a specific&lt;br /&gt;
instance of a capability.&lt;br /&gt;
&lt;br /&gt;
This is perhaps the second most important part of the entire capability system, since it is what allows cross-mod&lt;br /&gt;
interaction. To obtain an instance of a Capability, the user must first get a hold of the Capability Provider that&lt;br /&gt;
should be queried. This can be done in a variety of ways and is outside the scope of this article. The user should&lt;br /&gt;
then invoke the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method passing the unique instance of the capability that should be queried&lt;br /&gt;
(see [[#Obtaining a Capability|Obtaining a Capability]] for more information) and the querying &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;,&lt;br /&gt;
if applicable.&lt;br /&gt;
&lt;br /&gt;
The returned object is a &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; wrapping the queried Capability, if the capability provider exposes&lt;br /&gt;
it, otherwise it will be empty. The &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; can be either unwrapped via an &amp;lt;code&amp;gt;orElse&amp;lt;/code&amp;gt; or&lt;br /&gt;
used directly via &amp;lt;code&amp;gt;ifPresent&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It is '''highly suggested''' to cache the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; to avoid querying the same provider every&lt;br /&gt;
time, in order to improve performance. The user should thus register itself to the invalidation listener via the&lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; method. This ensures that the user will be able to react to the invalidation of the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and remove it from the cache.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an user may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
private final Map&amp;lt;Direction, LazyOptional&amp;lt;IEnergyStorage&amp;gt;&amp;gt; cache = new HashMap&amp;lt;&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
private void sendPowerTo(int power, Direction direction) {&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; targetCapability = cache.get(direction);&lt;br /&gt;
&lt;br /&gt;
    if (targetCapability == null) {&lt;br /&gt;
        ICapabilityProvider provider = world.getTileEntity(pos.offset(direction));&lt;br /&gt;
        targetCapability = provider.getCapability(CapabilityEnergy.ENERGY, direction.getOpposite());&lt;br /&gt;
        cache.put(direction, targetCapability);&lt;br /&gt;
        targetCapability.addListener(self -&amp;gt; cache.put(direction, null));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    targetCapability.ifPresent(storage -&amp;gt; storage.receiveEnergy(power, false));&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an user is querying via a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; the neighboring capability provider&lt;br /&gt;
for an &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability. Before obtaining the provider, the code performs a cache lookup for the&lt;br /&gt;
targeted capability. If the check succeeds, then no lookup is performed; if the check fails, the targeted Capability&lt;br /&gt;
Provider is obtained and queried for the Capability. The obtained &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; is then cached and a&lt;br /&gt;
listener is attached to it so that the cache would be emptied on invalidation. The code then continues with the&lt;br /&gt;
interaction with the capability, which is outside the scope of this article.&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
While the various capabilities provided by Forge may satisfy the most common use cases, there is always the chance that&lt;br /&gt;
a mod may require a custom solution. For this reason, Forge provides a way to define a custom Capability.&lt;br /&gt;
&lt;br /&gt;
Defining a custom Capability requires the user to provide three main components: the Capability Interface, at least one&lt;br /&gt;
Capability Implementation, and the Capability Storage. Optionally, a Capability Provider can also be created. In this&lt;br /&gt;
case, the provider will be used as described in [[#Attaching a Capability|Attaching a Capability]]. The various details &lt;br /&gt;
for all these components are described in the respective sections of this article.&lt;br /&gt;
&lt;br /&gt;
In this section, we will refer to the implementation of a &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability, that can be used to&lt;br /&gt;
store a single mutable &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Refer also to [[#Code Examples|Code Examples]] for an example on how the various components may be implemented in a&lt;br /&gt;
real-world scenario.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
The Capability Interface is one of the most important parts of a Capability: without it, the Capability effectively does&lt;br /&gt;
not exist. Designing a Capability Interface is exactly like designing any Java interface, so the particular details will&lt;br /&gt;
be glossed over in this section.&lt;br /&gt;
&lt;br /&gt;
The Capability Implementation, on the other hand, is the implementation of the previously defined Capability Interface.&lt;br /&gt;
Usual rules for interface implementations follow. There can be more than one Capability Implementation for each&lt;br /&gt;
capability, but no less than one.&lt;br /&gt;
&lt;br /&gt;
Note that a '''well-formed''' capability implementation should '''not store''' the Capability Provider inside of it: we&lt;br /&gt;
call the capability implementation ''provider-agnostic''. This is not a hard-requirement, though, rather it should act&lt;br /&gt;
more as a guideline. There are in fact certain situations where this cannot be avoided (e.g. attaching a client-synced&lt;br /&gt;
capability to an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
One of the various Capability Implementation should also act as the default implementation. Other mods can ask the&lt;br /&gt;
capability to create an instance of the default implementation without ever referring to such an implementation&lt;br /&gt;
themselves. This guarantees separation of API code from implementation code, which is also one of the goals of the&lt;br /&gt;
capability system. &lt;br /&gt;
&lt;br /&gt;
Given all of the above information, this may be an example implementation of both a Capability Interface and a&lt;br /&gt;
Capability Implementation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public interface MyCapability {&lt;br /&gt;
    String getValue();&lt;br /&gt;
    void setValue(String value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class MyCapabilityImplementation implements MyCapability {&lt;br /&gt;
    private String value;&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public String getValue() {&lt;br /&gt;
        return this.value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void setValue(String value) {&lt;br /&gt;
        this.value = value;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that in this case, only a single implementation is provided, which will also act as the default implementation for&lt;br /&gt;
the &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
The Capability Storage is that component of the Capability System that is responsible for serializing and deserializing&lt;br /&gt;
a capability. All capabilities must provide one, since certain providers may or may not require that their capabilities&lt;br /&gt;
are serializable.&lt;br /&gt;
&lt;br /&gt;
The Capability Storage implements the &amp;lt;code&amp;gt;Capability.IStorage&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt; interface, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; is the&lt;br /&gt;
generic type of the Capability Interface the storage refers to. Each capability must have '''one and exactly one'''&lt;br /&gt;
Capability Storage.&lt;br /&gt;
&lt;br /&gt;
The Storage is usually called by the Capability Provider when serialization or deserialization needs to happen. The&lt;br /&gt;
Storage is then responsible of reading the data from the given capability instance and convert that into an NBT-based&lt;br /&gt;
structure that can be serialized. A Storage may also return &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to indicate that no serialization is&lt;br /&gt;
necessary, although some providers may require an empty tag to be supplied instead. At the same time, the Storage is&lt;br /&gt;
also responsible for restoring the original state of the capability when deserialization happens. In this case, the&lt;br /&gt;
given NBT structure is guaranteed not to be &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
In all cases, a &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; is provided for context, if available.&lt;br /&gt;
&lt;br /&gt;
Although discouraged as a matter of code cleanliness, it is legal for a Capability Storage to require a specific&lt;br /&gt;
Capability Implementation for the serialization and deserialization to be successful. If this is the case, this&lt;br /&gt;
requirement '''must''' be documented, though the code should be refactored wherever possible to remove this requirement.&lt;br /&gt;
&lt;br /&gt;
Given the above information, an example of an implementation of a Capability Storage may be the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class MyCapabilityStorage implements Capability.IStorage&amp;lt;MyCapability&amp;gt; {&lt;br /&gt;
    @Override&lt;br /&gt;
    @Nullable&lt;br /&gt;
    INBT writeNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction) {&lt;br /&gt;
        return StringNBT.valueOf(instance.getValue());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void readNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction, INBT nbtData) {&lt;br /&gt;
        if (!(nbtData instanceof StringNBT)) {&lt;br /&gt;
            throw new IllegalArgumentException(&amp;quot;Unable to deserialize 'MyCapability' from a non-String NBT structure&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
        instance.setValue(((StringNBT) nbtData).getString());&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the &amp;lt;code&amp;gt;instanceof&amp;lt;/code&amp;gt; check needed to ensure that the given &amp;lt;code&amp;gt;INBT&amp;lt;/code&amp;gt; instance is valid for&lt;br /&gt;
deserialization. A Capability Storage should always perform this check prior to the cast in order to provide a&lt;br /&gt;
meaningful error message, rather than a cryptic &amp;lt;code&amp;gt;ClassCastException&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
The Capability Provider is an optional component of the capability that allows the Capability to be attached to a&lt;br /&gt;
component. The details on how a Capability Provider should behave have already been discussed in the two previous&lt;br /&gt;
sections [[#Exposing a Capability|Exposing a Capability]] and [[#Attaching a Capability|Attaching a Capability]]: refer&lt;br /&gt;
to those for more information.&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
Once all components of a Capability have been created, they must be registered so that the game is aware of the&lt;br /&gt;
capability's presence. The registration requires specifying the Capability Interface, the Capability Storage, and a&lt;br /&gt;
factory for the default capability implementation.&lt;br /&gt;
&lt;br /&gt;
The registration can be performed by calling the &amp;lt;code&amp;gt;register&amp;lt;/code&amp;gt; method on the &amp;lt;code&amp;gt;CapabilityManager&amp;lt;/code&amp;gt;.&lt;br /&gt;
This '''needs''' to happen when the &amp;lt;code&amp;gt;FMLCommonSetupEvent&amp;lt;/code&amp;gt; is fired on the &amp;lt;code&amp;gt;MOD&amp;lt;/code&amp;gt; event bus. The&lt;br /&gt;
registration will also automatically inject the created Capability into all relevant fields and methods: refer to&lt;br /&gt;
[[#Obtaining a Capability|Obtaining a Capability]] for more information.&lt;br /&gt;
&lt;br /&gt;
An example of registration can be found in the snippet that follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public void onCommonSetup(FMLCommonSetupEvent event) {&lt;br /&gt;
    CapabilityManager.INSTANCE.register(MyCapability.class, new MyCapabilityStorage(), MyCapabilityImplementation::new);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Custom Capability Providers ==&lt;br /&gt;
&lt;br /&gt;
Much like custom Capabilities, Forge also allows the creation of custom Capability Providers. The main advantage of this&lt;br /&gt;
is allowing mods to create custom providers for their custom objects, in order to promote not only cross-mod&lt;br /&gt;
compatibility, but also uniformity in the way users may interact with different mod APIs.&lt;br /&gt;
&lt;br /&gt;
This section will only give the basic outline of what is necessary to implement a custom Capability Provider: for more&lt;br /&gt;
in-depth explanation, people are referred to the game code.&lt;br /&gt;
&lt;br /&gt;
By definition, a custom Capability Provider is everything that implements the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;&lt;br /&gt;
interface. In this section, though, we will only cover people that may want to replicate the functionality of one of&lt;br /&gt;
the default providers, such as &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The easiest way of doing this is extending the &amp;lt;code&amp;gt;CapabilityProvider&amp;lt;/code&amp;gt; class provided by Forge. This will&lt;br /&gt;
automatically set up an ''agnostic'' Capability Provider. To fully initialize the capability provider, the subclass&lt;br /&gt;
should then invoke the &amp;lt;code&amp;gt;gatherCapabilities&amp;lt;/code&amp;gt; method as the last instruction in its constructor, to ensure that&lt;br /&gt;
the game is able to recollect and attach all capabilities that other mods may want to attach to the capability provider.&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
* [https://gist.github.com/TheSilkMiner/5cc92ba573e7bdd871dfdbffdd5c2806 A Gist showing a quick and dirty example on how to implement a Capability effectively]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2586</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2586"/>
		<updated>2021-05-01T20:40:47Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Finish Capability docs&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Capabilities''' are a Forge system that allows cross-mod interactions by allowing capability ''providers'' to&lt;br /&gt;
dynamically respect contracts and provide specialized behavior without requiring the implementation of many interfaces&lt;br /&gt;
or hard dependencies on mods.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
In an ideal world, all that would be needed for a mod to provide the equivalent of a capability would be implementing an&lt;br /&gt;
interface. This is in fact how cross-mod interaction used to work prior to the introduction of capabilities.&lt;br /&gt;
&lt;br /&gt;
The real world, though, is often much more complicated: users wanted to be free to combine mods the way they wanted and&lt;br /&gt;
saw fit, and developers wanted to be able to declare ''soft'' dependencies on other mods, thus reducing the need of&lt;br /&gt;
having a huge mod pack just for testing.&lt;br /&gt;
&lt;br /&gt;
The first approach used by Forge was conditional stripping of interfaces and methods, but this proved to be problematic.&lt;br /&gt;
While the idea works well in theory, in practice the ASM editing of classes relied on complex mechanics and could lead&lt;br /&gt;
to hard to spot bugs.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
A capability allows any capability provider to conditionally expose a certain ability to do something, e.g. accepting&lt;br /&gt;
power or handling items. A capability provider, moreover, can decide to expose a capability only on certain sides,&lt;br /&gt;
allowing for easy interactions with hoppers, cables, etc.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods,&lt;br /&gt;
allowing even easier cross-mod interaction. For example, a mod that isn't compatible with Forge Energy could be&lt;br /&gt;
converted into one by dynamically attaching the Forge Energy capability and handling the conversion to a third-party&lt;br /&gt;
energy system without having to alter the original mod.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
The high flexibility of the system comes with a cost, though, which is terminology. The following section wants to be a&lt;br /&gt;
dictionary of sorts, defining all the terms that you may come across when dealing with capabilities.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
; Capability&lt;br /&gt;
: the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
; Capability Provider&lt;br /&gt;
: something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
:; Volatile Provider&lt;br /&gt;
:: 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.&lt;br /&gt;
:; Persistent Provider&lt;br /&gt;
:: a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts. They implement the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
:; Agnostic Provider&lt;br /&gt;
:: 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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
; Capability Interface&lt;br /&gt;
: the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
; Capability Implementation&lt;br /&gt;
: 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'''.&lt;br /&gt;
; Capability Storage&lt;br /&gt;
: 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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The wary reader may note that both ''persistent'' and ''agnostic'' providers are represented the same way in code. In&lt;br /&gt;
fact, the only difference between them comes from pure semantics in how their serialization methods are designed. This&lt;br /&gt;
will be further discussed in their respective sections.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly&lt;br /&gt;
correct, due to common usage we will also use this convention. So, to refer to the capability interface&lt;br /&gt;
&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability&lt;br /&gt;
providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. These are all agnostic providers, since they don't&lt;br /&gt;
mandate any sort of capability persistency requirements. Rather, it is the job of whoever subclasses these providers to&lt;br /&gt;
deal with either volatile or non-volatile capabilities.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;,&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and&lt;br /&gt;
&amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal&lt;br /&gt;
'''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible,&lt;br /&gt;
though, to expose this capability even if no such inventory is present as long as the capability provider can emulate&lt;br /&gt;
its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These&lt;br /&gt;
interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends&lt;br /&gt;
to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids&lt;br /&gt;
in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;&lt;br /&gt;
capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider&lt;br /&gt;
to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and&lt;br /&gt;
produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or&lt;br /&gt;
FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux&lt;br /&gt;
Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the&lt;br /&gt;
Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework,&lt;br /&gt;
otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and&lt;br /&gt;
capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''',&lt;br /&gt;
need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object&lt;br /&gt;
itself. Since these objects are created by Forge and there is only '''one''' unique instance for each capability that&lt;br /&gt;
may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such&lt;br /&gt;
instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as it gets created by Forge, following the&lt;br /&gt;
principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user&lt;br /&gt;
that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method&lt;br /&gt;
instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with&lt;br /&gt;
&amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the&lt;br /&gt;
unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to&lt;br /&gt;
provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the desired&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a&lt;br /&gt;
number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the &lt;br /&gt;
capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of&lt;br /&gt;
style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of&lt;br /&gt;
type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also&lt;br /&gt;
be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a&lt;br /&gt;
&amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable&lt;br /&gt;
fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through&lt;br /&gt;
&amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and&lt;br /&gt;
accessed by clients.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains&lt;br /&gt;
consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide&lt;br /&gt;
many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the&lt;br /&gt;
accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to&lt;br /&gt;
[[#Accessing a Capability|Accessing a Capability]] for more information), it is the provider's responsibility to trigger&lt;br /&gt;
a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be&lt;br /&gt;
performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private final LazyOptional&amp;lt;IItemhandler&amp;gt; inventoryOptional = LazyOptional.of(() -&amp;gt; this.inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null || direction == Direction.UP || direction == Direction.DOWN)) {&lt;br /&gt;
        return this.inventoryOptional.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    this.inventoryOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts&lt;br /&gt;
access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the&lt;br /&gt;
block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the world or unloaded due to distance.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what&lt;br /&gt;
allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke&lt;br /&gt;
&amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
Attaching a Capability is a process by which external agents &amp;quot;modify&amp;quot; a Capability Provider, making it expose additional&lt;br /&gt;
capabilities other than the already available ones.&lt;br /&gt;
&lt;br /&gt;
To do so, the '''attaching agent''' (which means the thing that wants to attach a capability to another provider) must&lt;br /&gt;
listen to the &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; in this case represents the capability&lt;br /&gt;
provider you want to attach the capability to. Note that the type of &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; '''must''' be the base type of the&lt;br /&gt;
capability provider, not a subclass. As an example, if you want to attach a capability to a &amp;lt;code&amp;gt;MyTileEntity&amp;lt;/code&amp;gt;,&lt;br /&gt;
which extends &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, you'll have to listen to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;TileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;,&lt;br /&gt;
'''NOT''' to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;MyTileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, since the latter will never fire.&lt;br /&gt;
&lt;br /&gt;
The attaching agent can use the provided methods &amp;lt;code&amp;gt;getObject&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;addCapability&amp;lt;/code&amp;gt;, and &lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; to check whether the capability should be attached to the current object and perform the&lt;br /&gt;
desired action.&lt;br /&gt;
&lt;br /&gt;
Maybe a little counter-intuitively, the process of attaching does not attach a capability nor a capability interface&lt;br /&gt;
directly. Rather, the attaching agent should create its own implementation of a '''Capability Provider''' and attach it&lt;br /&gt;
via the event. This is done so that the attaching agent can have control over when, how, and where its capabilities are&lt;br /&gt;
exposed, instead of relying on the game itself deciding these parameters. For this reason, all considerations given in&lt;br /&gt;
the [[#Exposing a Capability|Exposing a Capability]] section on how to correctly create a Capability Provider.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an attaching agent may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilityProvider() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == CapabilityEnergy.ENERGY) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an attaching agent attaches a &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability to all&lt;br /&gt;
&amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; instance that are a subclass of &amp;lt;code&amp;gt;EnergyBasedTileEntity&amp;lt;/code&amp;gt;. It also sets up the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; for invalidation if the parent capability provider gets invalidated.&lt;br /&gt;
&lt;br /&gt;
Note also the call of &amp;lt;code&amp;gt;LazyOptional.empty()&amp;lt;/code&amp;gt; rather than a &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;. This is needed because when&lt;br /&gt;
attaching a capability, the parent capability provider isn't known. For this reason, it is necessary to return an empty&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;. The game will then handle automatic merging of the various different providers into a single&lt;br /&gt;
one.&lt;br /&gt;
&lt;br /&gt;
The above example is one of a '''Volatile''' Capability Provider. On the other hand, mods may want to persist their&lt;br /&gt;
data across sessions. In this case, they should attach a '''Persistent''' Capability Provider: this can be done either&lt;br /&gt;
by implementing the &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface along with &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; or by&lt;br /&gt;
implementing the &amp;lt;code&amp;gt;ICapabilitySerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
The previous example reworked to use a Persistent Capability Provider may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
    Capability&amp;lt;IEnergyStorage&amp;gt; capability = CapabilityEnergy.ENERGY;&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilitySerializable&amp;lt;IntNBT&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == capability) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public IntNBT serializeNBT() {&lt;br /&gt;
            return capability.getStorage().writeNbt(capability, backend, null);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void deserializeNBT(IntNBT nbt) {&lt;br /&gt;
            capability.getStorage().readNBT(capability, backend, null, nbt);&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Accessing a Capability is the process by which a client is able to '''query''' a Capability Provider for a specific&lt;br /&gt;
instance of a capability.&lt;br /&gt;
&lt;br /&gt;
This is perhaps the second most important part of the entire capability system, since it is what allows cross-mod&lt;br /&gt;
interaction. To obtain an instance of a Capability, the client must first get a hold of the Capability Provider that&lt;br /&gt;
should be queried. This can be done in a variety of ways and is outside the scope of this article. The client should&lt;br /&gt;
then invoke the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method passing the unique instance of the capability that should be queried&lt;br /&gt;
(see [[#Obtaining a Capability|Obtaining a Capability]] for more information) and the querying &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;,&lt;br /&gt;
if applicable.&lt;br /&gt;
&lt;br /&gt;
The returned object is a &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; wrapping the queried Capability, if the capability provider exposes&lt;br /&gt;
it, otherwise it will be empty. The &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; can be either unwrapped via an &amp;lt;code&amp;gt;orElse&amp;lt;/code&amp;gt; or&lt;br /&gt;
used directly via &amp;lt;code&amp;gt;ifPresent&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
It is '''highly suggested''' to cache the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; to avoid querying the same provider every&lt;br /&gt;
time, in order to improve performance. The client should thus register itself to the invalidation listener via the&lt;br /&gt;
&amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; method. This ensures that the client will be able to react to the invalidation of the&lt;br /&gt;
&amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and remove it from the cache.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of a client may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
private final Map&amp;lt;Direction, LazyOptional&amp;lt;IEnergyStorage&amp;gt;&amp;gt; cache = new HashMap&amp;lt;&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
private void sendPowerTo(int power, Direction direction) {&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; targetCapability = cache.get(direction);&lt;br /&gt;
&lt;br /&gt;
    if (targetCapability == null) {&lt;br /&gt;
        ICapabilityProvider provider = world.getTileEntity(pos.offset(direction));&lt;br /&gt;
        targetCapability = provider.getCapability(CapabilityEnergy.ENERGY, direction.getOpposite());&lt;br /&gt;
        cache.put(direction, targetCapability);&lt;br /&gt;
        targetCapability.addListener(self -&amp;gt; cache.put(direction, null));&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    targetCapability.ifPresent(storage -&amp;gt; storage.receiveEnergy(power, false));&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of a client is querying via a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; the neighboring capability provider&lt;br /&gt;
for an &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability. Before obtaining the provider, the code performs a cache lookup for the&lt;br /&gt;
targeted capability. If the check succeeds, then no lookup is performed; if the check fails, the targeted Capability&lt;br /&gt;
Provider is obtained and queried for the Capability. The obtained &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; is then cached and a&lt;br /&gt;
listener is attached to it so that the cache would be emptied on invalidation. The code then continues with the&lt;br /&gt;
interaction with the capability, which is outside the scope of this article.&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
While the various capabilities provided by Forge may satisfy the most common use cases, there is always the chance that&lt;br /&gt;
a mod may require a custom solution. For this reason, Forge provides a way to define a custom Capability.&lt;br /&gt;
&lt;br /&gt;
Defining a custom Capability requires the user to provide three main components: the Capability Interface, at least one&lt;br /&gt;
Capability Implementation, and the Capability Storage. Optionally, a Capability Provider can also be created. In this&lt;br /&gt;
case, the provider will be used as described in [[#Attaching a Capability|Attaching a Capability]]. The various details &lt;br /&gt;
for all these components are described in the respective sections of this article.&lt;br /&gt;
&lt;br /&gt;
In this section, we will refer to the implementation of a &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability, that can be used to&lt;br /&gt;
store a single mutable &amp;lt;code&amp;gt;String&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Refer also to [[#Code Examples|Code Examples]] for an example on how the various components may be implemented in a&lt;br /&gt;
real-world scenario.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
The Capability Interface is one of the most important parts of a Capability: without it, the Capability effectively does&lt;br /&gt;
not exist. Designing a Capability Interface is exactly like designing any Java interface, so the particular details will&lt;br /&gt;
be glossed over in this section.&lt;br /&gt;
&lt;br /&gt;
The Capability Implementation, on the other hand, is the implementation of the previously defined Capability Interface.&lt;br /&gt;
Usual rules for interface implementations follow. There can be more than one Capability Implementation for each&lt;br /&gt;
capability, but no less than one.&lt;br /&gt;
&lt;br /&gt;
Note that a '''well-formed''' capability implementation should '''not store''' the Capability Provider inside of it: we&lt;br /&gt;
call the capability implementation ''provider-agnostic''. This is not a hard-requirement, though, rather it should act&lt;br /&gt;
more as a guideline. There are in fact certain situations where this cannot be avoided (e.g. attaching a client-synced&lt;br /&gt;
capability to an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
One of the various Capability Implementation should also act as the default implementation. Other mods can ask the&lt;br /&gt;
capability to create an instance of the default implementation without ever referring to such an implementation&lt;br /&gt;
themselves. This guarantees separation of API code from implementation code, which is also one of the goals of the&lt;br /&gt;
capability system. &lt;br /&gt;
&lt;br /&gt;
Given all of the above information, this may be an example implementation of both a Capability Interface and a&lt;br /&gt;
Capability Implementation:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public interface MyCapability {&lt;br /&gt;
    String getValue();&lt;br /&gt;
    void setValue(String value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class MyCapabilityImplementation implements MyCapability {&lt;br /&gt;
    private String value;&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public String getValue() {&lt;br /&gt;
        return this.value;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void setValue(String value) {&lt;br /&gt;
        this.value = value;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that in this case, only a single implementation is provided, which will also act as the default implementation for&lt;br /&gt;
the &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
The Capability Storage is that component of the Capability System that is responsible for serializing and deserializing&lt;br /&gt;
a capability. All capabilities must provide one, since certain providers may or may not require that their capabilities&lt;br /&gt;
are serializable.&lt;br /&gt;
&lt;br /&gt;
The Capability Storage implements the &amp;lt;code&amp;gt;Capability.IStorage&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt; interface, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; is the&lt;br /&gt;
generic type of the Capability Interface the storage refers to. Each capability must have '''one and exactly one'''&lt;br /&gt;
Capability Storage.&lt;br /&gt;
&lt;br /&gt;
The Storage is usually called by the Capability Provider when serialization or deserialization needs to happen. The&lt;br /&gt;
Storage is then responsible of reading the data from the given capability instance and convert that into an NBT-based&lt;br /&gt;
structure that can be serialized. A Storage may also return &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to indicate that no serialization is&lt;br /&gt;
necessary, although some providers may require an empty tag to be supplied instead. At the same time, the Storage is&lt;br /&gt;
also responsible for restoring the original state of the capability when deserialization happens. In this case, the&lt;br /&gt;
given NBT structure is guaranteed not to be &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
In all cases, a &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; is provided for context, if available.&lt;br /&gt;
&lt;br /&gt;
Although discouraged as a matter of code cleanliness, it is legal for a Capability Storage to require a specific&lt;br /&gt;
Capability Implementation for the serialization and deserialization to be successful. If this is the case, this&lt;br /&gt;
requirement '''must''' be documented, though the code should be refactored wherever possible to remove this requirement.&lt;br /&gt;
&lt;br /&gt;
Given the above information, an example of an implementation of a Capability Storage may be the following:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public class MyCapabilityStorage implements Capability.IStorage&amp;lt;MyCapability&amp;gt; {&lt;br /&gt;
    @Override&lt;br /&gt;
    @Nullable&lt;br /&gt;
    INBT writeNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction) {&lt;br /&gt;
        return StringNBT.valueOf(instance.getValue());&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    @Override&lt;br /&gt;
    public void readNBT(Capability&amp;lt;MyCapability&amp;gt; capability, MyCapability instance, Direction direction, INBT nbtData) {&lt;br /&gt;
        if (!(nbtData instanceof StringNBT)) {&lt;br /&gt;
            throw new IllegalArgumentException(&amp;quot;Unable to deserialize 'MyCapability' from a non-String NBT structure&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
        instance.setValue(((StringNBT) nbtData).getString());&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the &amp;lt;code&amp;gt;instanceof&amp;lt;/code&amp;gt; check needed to ensure that the given &amp;lt;code&amp;gt;INBT&amp;lt;/code&amp;gt; instance is valid for&lt;br /&gt;
deserialization. A Capability Storage should always perform this check prior to the cast in order to provide a&lt;br /&gt;
meaningful error message, rather than a cryptic &amp;lt;code&amp;gt;ClassCastException&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
The Capability Provider is an optional component of the capability that allows the Capability to be attached to a&lt;br /&gt;
component. The details on how a Capability Provider should behave have already been discussed in the two previous&lt;br /&gt;
sections [[#Exposing a Capability|Exposing a Capability]] and [[#Attaching a Capability|Attaching a Capability]]: refer&lt;br /&gt;
to those for more information.&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
Once all components of a Capability have been created, they must be registered so that the game is aware of the&lt;br /&gt;
capability's presence. The registration requires specifying the Capability Interface, the Capability Storage, and a&lt;br /&gt;
factory for the default capability implementation.&lt;br /&gt;
&lt;br /&gt;
The registration can be performed by calling the &amp;lt;code&amp;gt;register&amp;lt;/code&amp;gt; method on the &amp;lt;code&amp;gt;CapabilityManager&amp;lt;/code&amp;gt;.&lt;br /&gt;
This '''needs''' to happen when the &amp;lt;code&amp;gt;FMLCommonSetupEvent&amp;lt;/code&amp;gt; is fired on the &amp;lt;code&amp;gt;MOD&amp;lt;/code&amp;gt; event bus. The&lt;br /&gt;
registration will also automatically inject the created Capability into all relevant fields and methods: refer to&lt;br /&gt;
[[#Obtaining a Capability|Obtaining a Capability]] for more information.&lt;br /&gt;
&lt;br /&gt;
An example of registration can be found in the snippet that follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public void onCommonSetup(FMLCommonSetupEvent event) {&lt;br /&gt;
    CapabilityManager.INSTANCE.register(MyCapability.class, new MyCapabilityStorage(), MyCapabilityImplementation::new);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Custom Capability Providers ==&lt;br /&gt;
&lt;br /&gt;
Much like custom Capabilities, Forge also allows the creation of custom Capability Providers. The main advantage of this&lt;br /&gt;
is allowing mods to create custom providers for their custom objects, in order to promote not only cross-mod&lt;br /&gt;
compatibility, but also uniformity in the way clients may interact with different mod APIs.&lt;br /&gt;
&lt;br /&gt;
This section will only give the basic outline of what is necessary to implement a custom Capability Provider: for more&lt;br /&gt;
in-depth explanation, people are referred to the game code.&lt;br /&gt;
&lt;br /&gt;
By definition, a custom Capability Provider is everything that implements the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;&lt;br /&gt;
interface. In this section, though, we will only cover people that may want to replicate the functionality of one of&lt;br /&gt;
the default providers, such as &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The easiest way of doing this is extending the &amp;lt;code&amp;gt;CapabilityProvider&amp;lt;/code&amp;gt; class provided by Forge. This will&lt;br /&gt;
automatically set up an ''agnostic'' Capability Provider. To fully initialize the capability provider, the subclass&lt;br /&gt;
should then invoke the &amp;lt;code&amp;gt;gatherCapabilities&amp;lt;/code&amp;gt; method as the last instruction in its constructor, to ensure that&lt;br /&gt;
the game is able to recollect and attach all capabilities that other mods may want to attach to the capability provider.&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
* [https://gist.github.com/TheSilkMiner/5cc92ba573e7bdd871dfdbffdd5c2806 A Gist showing a quick and dirty example on how to implement a Capability effectively]&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2439</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2439"/>
		<updated>2021-02-15T14:56:13Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Add description on how to attach a capability&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly correct, due to common usage we will also use this convention. So, to refer to the capability interface &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal '''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible, though, to expose this capability even if no such inventory is present as long as the capability provider can emulate its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework, otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''', need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object itself. Since these objects are created by Forge and there is only '''one''' unique instance for each capability that may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as they get created by Forge, following the principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the&lt;br /&gt;
desired &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a &amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and accessed by clients.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to ''Accessing a Capability'' for more information), it is the provider's responsibility to trigger a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=java&amp;quot;&amp;gt;&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private final LazyOptional&amp;lt;IItemhandler&amp;gt; inventoryOptional = LazyOptional.of(() -&amp;gt; this.inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null || direction == Direction.UP || direction == Direction.DOWN)) {&lt;br /&gt;
        return this.inventoryOptional.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    this.inventoryOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the world, either because it's too far away or it simply got broken.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned. For more information on when and why this is needed refer to '''The Capability Provider''' section.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
Attaching a Capability is a process by which external agents &amp;quot;modify&amp;quot; a Capability Provider, making it expose additional capabilities other than the already available ones.&lt;br /&gt;
&lt;br /&gt;
To do so, the '''attaching agent''' (which means the thing that wants to attach a capability to another provider) must listen to the &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; in this case represents the capability provider you want to attach the capability to. Note that the type of &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; '''must''' be the base type of the capability provider, not a subclass. As an example, if you want to attach a capability to a &amp;lt;code&amp;gt;MyTileEntity&amp;lt;/code&amp;gt;, which extends &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, you'll have to listen to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;TileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, '''NOT''' to &amp;lt;code&amp;gt;AttachCapabilitiesEvent&amp;amp;lt;MyTileEntity&amp;amp;gt;&amp;lt;/code&amp;gt;, since the latter will never fire.&lt;br /&gt;
&lt;br /&gt;
The attaching agent can use the provided methods &amp;lt;code&amp;gt;getObject&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;addCapability&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;addListener&amp;lt;/code&amp;gt; to check whether the capability should be attached to the current object and perform the desired action.&lt;br /&gt;
&lt;br /&gt;
Maybe a little counter-intuitively, the process of attaching does not attach a capability nor a capability interface, directly. Rather, the attaching agent should create its own implementation of a '''Capability Provider''' and attach it via the event. This is done so that the attaching agent can have control over when, how, and where its capabilities are exposed, instead of relying on the game itself deciding these parameters. For this reason, all considerations given in the '''Exposing a Capability''' section on how to correctly create a Capability Provider.&lt;br /&gt;
&lt;br /&gt;
With the above in mind, part of an attaching agent may be similar to the following snippet of code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=java&amp;quot;&amp;gt;&lt;br /&gt;
@SubscribeEvent&lt;br /&gt;
public void onAttachingCapabilities(final AttachCapabilitiesEvent&amp;lt;TileEntity&amp;gt; event) {&lt;br /&gt;
    if (!(event.getObject() instanceof EnergyBasedTileEntity)) return;&lt;br /&gt;
&lt;br /&gt;
    EnergyStorage backend = new EnergyStorage(((EnergyBasedTileEntity) event.getObject()).capacity);&lt;br /&gt;
    LazyOptional&amp;lt;IEnergyStorage&amp;gt; optionalStorage = LazyOptional.of(() -&amp;gt; backend);&lt;br /&gt;
&lt;br /&gt;
    ICapabilityProvider provider = new ICapabilityProvider() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, @Nullable Direction direction) {&lt;br /&gt;
            if (cap == CapabilityEnergy.ENERGY) {&lt;br /&gt;
                return optionalStorage.cast();&lt;br /&gt;
            }&lt;br /&gt;
            return LazyOptional.empty();&lt;br /&gt;
        }&lt;br /&gt;
    };&lt;br /&gt;
&lt;br /&gt;
    event.addCapabilities(new ResourceLocation(&amp;quot;examplemod&amp;quot;, &amp;quot;fe_compatibility&amp;quot;), provider);&lt;br /&gt;
    event.addListener(optionalStorage::invalidate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This example implementation of an attaching agent attaches a &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability to all &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt; instance that are a subclass of &amp;lt;code&amp;gt;EnergyBasedTileEntity&amp;lt;/code&amp;gt;. It also sets up the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; for invalidation if the parent capability provider gets invalidated.&lt;br /&gt;
&lt;br /&gt;
Note also the call of &amp;lt;code&amp;gt;LazyOptional.empty()&amp;lt;/code&amp;gt; rather than a &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;. This is needed because when attaching a capability, the parent capability provider isn't known. For this reason, it is necessary to return an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;. The game will then handle automatic merging of the various different providers into a single one.&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2364</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2364"/>
		<updated>2021-01-10T15:28:44Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Finish Capability Exposure documentation&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly correct, due to common usage we will also use this convention. So, to refer to the capability interface &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal '''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible, though, to expose this capability even if no such inventory is present as long as the capability provider can emulate its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework, otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''', need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object itself. Since these objects are created by Forge and there is only '''one''' unique instance for each capability that may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as they get created by Forge, following the principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the&lt;br /&gt;
desired &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a &amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and accessed by clients.&lt;br /&gt;
&lt;br /&gt;
To do so, a capability provider needs to juggle a couple more moving pieces to ensure that the capability state remains consistent and that the lookup remains fast. It is in fact possible for a capability provider to be asked to provide many capabilities many times in the same tick. For this reason, a provider is asked to do the following:&lt;br /&gt;
* the &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt;s that get returned '''must be cached''';&lt;br /&gt;
* if a capability changes exposure state (more on this later), all listeners '''must be notified''';&lt;br /&gt;
* if a capability gets invalidated (more on this later), all listeners '''must be notified'''&lt;br /&gt;
* the lookup inside &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; must be performed with '''an &amp;lt;code&amp;gt;if&amp;lt;/code&amp;gt;-&amp;lt;code&amp;gt;else&amp;lt;/code&amp;gt; chain''';&lt;br /&gt;
* all unexposed but still present capabilities '''should be available''' if the provider is queried with a &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; direction (see ''Accessing a Capability'' for more information);&lt;br /&gt;
* if no capability of a given type is available or accessible, the provider '''must call &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; as long as it is possible to do so'''.&lt;br /&gt;
&lt;br /&gt;
Capability providers must also reflect changes in the ''exposure state'' of a capability, meaning that if the accessibility of a capability from a certain &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt; changes (refer to ''Accessing a Capability'' for more information), it is the provider's responsibility to trigger a state response by invalidating the returned &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; and caching a new one. This should also be performed when a capability gets ''invalidated'', such as when a capability provider gets removed.&lt;br /&gt;
&lt;br /&gt;
With all of the above in mind, part of a capability provider implementation may be similar to the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=java&amp;quot;&amp;gt;&lt;br /&gt;
// suppose the presence of a field 'inventory' of type 'IItemHandler'&lt;br /&gt;
&lt;br /&gt;
private static final LazyOptional&amp;lt;IItemhandler&amp;gt; INVENTORY_OPTIONAL = LazyOptional.of(() -&amp;gt; inventory);&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; capability, @Nullable Direction direction) {&lt;br /&gt;
    if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY&lt;br /&gt;
            &amp;amp;&amp;amp; (direction == null || direction == Direction.UP || direction == Direction.DOWN)) {&lt;br /&gt;
        return INVENTORY_OPTIONAL.cast();&lt;br /&gt;
    }&lt;br /&gt;
    return super.getCapability(capability, direction); // See note after snippet&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
    super.invalidateCaps();&lt;br /&gt;
    INVENTORY_OPTIONAL.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This possible implementation of a capability provider exposes an &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability and restricts access only to the &amp;lt;code&amp;gt;UP&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;DOWN&amp;lt;/code&amp;gt; directions. If we assume this capability provider is a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, then we may also say that the inventory is only accessible from the top and the bottom of the block.&lt;br /&gt;
&lt;br /&gt;
Moreover, the capability gets automatically invalidated when the provider gets invalidated. Assuming this is a &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, this usually happens when the block gets removed from the world, either because it's too far away or it simply got broken.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt; call at the end of the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method is extremely important, since it's what allows Attaching external Capabilities to capability providers. Nevertheless, it is not always possible to invoke &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;: in those cases, an empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; should be returned. For more information on when and why this is needed refer to '''The Capability Provider''' section.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2363</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2363"/>
		<updated>2021-01-10T14:52:29Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Additional edits&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly correct, due to common usage we will also use this convention. So, to refer to the capability interface &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal '''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible, though, to expose this capability even if no such inventory is present as long as the capability provider can emulate its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;TileFluidHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandlerItem&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandlerItem&amp;lt;/code&amp;gt; capability referes to the ability for an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt; capability provider to handle and store fluids in one or multiple fluid tanks. It is basically a specialized version of the &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability that allows &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s to define a custom container.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
A default reference implementation for this capability interface is provided in &amp;lt;code&amp;gt;EnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IAnimationStateMachine&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IAnimationStateMachine&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to leverage the Forge Animation State Machine API for animations.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
Both capability providers and users need to be able to provide and access capabilities through a common framework, otherwise the ideal of dynamic and mod-agnostic would not really exist. For this reason, both capability providers and capability ''accessors'' (which we define as everything that wants to access a capability), also known as '''clients''', need to work together and with Forge to ensure that the common interface is used sensibly and correctly by all parties.&lt;br /&gt;
&lt;br /&gt;
=== Obtaining a Capability ===&lt;br /&gt;
&lt;br /&gt;
Before being able to work with a capability, it is necessary to obtain an instance of the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; object itself. Since these objects are created by Forge and there is only '''one'' unique instance for each capability that may exist, this instance cannot be obtained by &amp;quot;common&amp;quot; means. Forge provides two different methods of obtaining such instances: '''injecting''' into a field, or a '''callback method'''.&lt;br /&gt;
&lt;br /&gt;
==== Injecting into a Field ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; can be injected automatically into a field as soon as they get created by Forge, following the principle commonly known as '''dependency injection'''. This provides less flexibility, since it doesn't notify the user that the capability has been injected nor runs arbitrary code. Nevertheless, it is '''suggested''' to use this method instead of the callback approach.&lt;br /&gt;
&lt;br /&gt;
To inject the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; into a field, all that's needed is to declare a &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; field of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface, and annotate it with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
public static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code will let Forge know that the field &amp;lt;code&amp;gt;ITEM_HANDLER_CAPABILITY&amp;lt;/code&amp;gt; should be injected with the unique instance of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability. Assigning the field to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; allows us to provide a reasonable fallback in case the capability we want hasn't been registered yet.&lt;br /&gt;
&lt;br /&gt;
This injection is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==== Declaring a Callback ====&lt;br /&gt;
&lt;br /&gt;
Another option is to declare a callback method, meaning a method that will be called with the value of the&lt;br /&gt;
desired &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; once the instance is available. This gives more flexibility since the method may perform a number of arbitrary actions with the received instance prior to storing it in a field, or may even discard the capability entirely if wanted. Nevertheless, the usage of a field instead of a method is encouraged as a matter of style.&lt;br /&gt;
&lt;br /&gt;
To use a method as a callback, the method must be declared as &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; and accepting a single parameter of type &amp;lt;code&amp;gt;Capability&amp;amp;lt;T&amp;amp;gt;&amp;lt;/code&amp;gt;, where &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt; represents the capability interface. The method should also be annotated with &amp;lt;code&amp;gt;@CapabilityInject(T.class)&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
For a more practical example, consider the following snippet:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
public static Capability&amp;lt;IEnergyStorage&amp;gt; ENERGY = null;&lt;br /&gt;
&lt;br /&gt;
@CapabilityInject(IEnergyStorage.class)&lt;br /&gt;
private static void onEnergyStorageInit(Capability&amp;lt;IEnergyStorage&amp;gt; capability) {&lt;br /&gt;
    LOGGER.info(&amp;quot;Received IEnergyStorage capability '{}': enabling Forge Energy support&amp;quot;, capability);&lt;br /&gt;
    ENERGY = capability;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code declares a callback method that will be invoked when a &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; instance for &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; is available. The callback then prints a log message and stores the capability into a &amp;lt;code&amp;gt;public&amp;lt;/code&amp;gt; field for accessibility. The field is initialized to &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt; to provide a reasonable fallback in case the capability does not exist. &lt;br /&gt;
&lt;br /&gt;
This callback is, for obvious reasons, redundant, since that capability is also available through &amp;lt;code&amp;gt;CapabilityEnergy&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
Exposing a capability is a voluntary act by a capability provider that allows the capability to be discovered and accessed by clients. This is simply done by returning a non-empty &amp;lt;code&amp;gt;LazyOptional&amp;lt;/code&amp;gt; when the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; method of a capability provider gets invoked.&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2362</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2362"/>
		<updated>2021-01-10T13:24:40Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Add descriptions for the various Forge provided capabilities&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Moreover, it is also common to refer to the capability interface as simply the ''capability''. While not strictly correct, due to common usage we will also use this convention. So, to refer to the capability interface &amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt;, we will usually talk about the &amp;quot;&amp;lt;code&amp;gt;MyCapability&amp;lt;/code&amp;gt; capability&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are represented by the interfaces &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IItemHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to have some sort of internal '''inventory''' with a certain number of slots, from which items can be inserted and extracted. It is also possible, though, to expose this capability even if no such inventory is present as long as the capability provider can emulate its presence (e.g. tools that allow accessing remote inventories).&lt;br /&gt;
&lt;br /&gt;
This effectively '''replaces''' the vanilla interfaces &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt;. These interfaces are in fact retained only to allow vanilla code to compile and should not be used in mod code. This extends to anything that implements those vanilla interfaces, such as &amp;lt;code&amp;gt;LockableLootTileEntity&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IFluidHandler&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to handle and store fluids in one or multiple fluid tanks. It is effectively the equivalent in terms of fluids of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; capability.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;tt&amp;gt;IEnergyStorage&amp;lt;/tt&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; capability refers to the ability for any capability provider to store, consume, and produce energy. This capability is the base capability for what's commonly known in the modded world as Forge Energy (or FE), i.e. the energy system most mods use. Its internal design is heavily based on the (now defunct) Redstone Flux Energy API, supporting both a push and pull system.&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2359</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2359"/>
		<updated>2021-01-08T13:24:28Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Reword Terminology section and titles to make more sense&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something. In-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them. In-code they are represented by implementations of &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt;. There are multiple kinds of capability providers:&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
** ''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 &amp;lt;code&amp;gt;INBTSerializable&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
== Working with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== Exposing a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Attaching a Capability ===&lt;br /&gt;
&lt;br /&gt;
=== Accessing a Capability ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== The Capability Interface and the Capability Implementation ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Storage ===&lt;br /&gt;
&lt;br /&gt;
=== The Capability Provider ===&lt;br /&gt;
&lt;br /&gt;
=== Tying it All Together ===&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2358</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2358"/>
		<updated>2021-01-08T13:15:28Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Set up structure for the page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
In the rest of this article, we will refer to these terms frequently, so make sure you are familiar with them.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something; in-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': something that is able to support capabilities and provides a mean of accessing them; capability providers come in multiple kinds.&lt;br /&gt;
** ''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.&lt;br /&gt;
** ''Persistent Provider'': a provider that requires all capabilities to serialize data to disk, in order to persist data even across game restarts.&lt;br /&gt;
** ''Agnostic Provider'': a provider that isn't neither volatile nor persistent, rather delegates the decision either to the capability directly or to sub-implementations.&lt;br /&gt;
* '''Capability Interface''': the interface that defines the contract of the capability, so what operations the capability exposes.&lt;br /&gt;
* '''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'''.&lt;br /&gt;
* '''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 &amp;lt;code&amp;gt;Capability.IStorage&amp;lt;/code&amp;gt; interface.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities and Providers ==&lt;br /&gt;
In order to ensure mods can work together seamlessly, Forge provides a set of default capabilities and capability providers.&lt;br /&gt;
&lt;br /&gt;
The default capability providers in a Forge environment are: &amp;lt;code&amp;gt;TileEntity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entity&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;. 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.&lt;br /&gt;
&lt;br /&gt;
The default capabilities that forge provides are &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;. Each one of these capabilities will be discussed in the corresponding section.&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
=== &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; ===&lt;br /&gt;
&lt;br /&gt;
== Operating with Capabilities ==&lt;br /&gt;
&lt;br /&gt;
=== Exposing ===&lt;br /&gt;
&lt;br /&gt;
=== Attaching ===&lt;br /&gt;
&lt;br /&gt;
== Creating Custom Capabilities ==&lt;br /&gt;
&lt;br /&gt;
== Code Examples ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2355</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2355"/>
		<updated>2021-01-08T11:34:07Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Start rewrite of Capability page&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''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.&lt;br /&gt;
&lt;br /&gt;
== History ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
For this reason, the entire system was redesigned and the concept of '''capabilities''' was born.&lt;br /&gt;
&lt;br /&gt;
== The Concept ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Capabilities may also be added and removed dynamically both from the &amp;quot;owner&amp;quot; of the capability provider and other mods, allowing even easier cross-mod interaction. For example, a mod that isn't compatible with&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Terminology ==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
* '''Capability''': the ability to perform something; in-code this is represented by the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; class.&lt;br /&gt;
* '''Capability Provider''': &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= OLD SHIT FOLLOWS =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
	<entry>
		<id>https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2322</id>
		<title>User:TheSilkMiner/Capabilities</title>
		<link rel="alternate" type="text/html" href="https://forge.gemwire.uk/index.php?title=User:TheSilkMiner/Capabilities&amp;diff=2322"/>
		<updated>2021-01-04T19:36:54Z</updated>

		<summary type="html">&lt;p&gt;TheSilkMiner: Let's get started with the rewrite, shall we?&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Capabilities allow exposing features in a dynamic and flexible way, without having to resort to directly implementing many interfaces.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Forge adds capability support to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;s, &amp;lt;code&amp;gt;World&amp;lt;/code&amp;gt;s and &amp;lt;code&amp;gt;Chunk&amp;lt;/code&amp;gt;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.&lt;br /&gt;
&lt;br /&gt;
== Forge-provided Capabilities ==&lt;br /&gt;
Forge provides three capabilities: &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt; exposes an interface for handling inventory slots. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; (chests, machines, etc.), &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; (extra player slots, mob/creature inventories/bags), or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; (portable backpacks and such). It replaces the old &amp;lt;code&amp;gt;IInventory&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ISidedInventory&amp;lt;/code&amp;gt; with an automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; exposes an interface for handling fluid inventories. It can also be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt; &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It replaces the old &amp;lt;code&amp;gt;IFluidHandler&amp;lt;/code&amp;gt; with a more consistent and automation-friendly system.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;IEnergyStorage&amp;lt;/code&amp;gt; exposes an interface for handling energy containers. It can be applied to &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt;. It is based on the RedstoneFlux API by TeamCoFH.&lt;br /&gt;
&lt;br /&gt;
== Using an Existing Capability  ==&lt;br /&gt;
As mentioned earlier, &amp;lt;code&amp;gt;TileEntities&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;ItemStacks&amp;lt;/code&amp;gt; implement the capability provider feature, through the &amp;lt;code&amp;gt;ICapabilityProvider&amp;lt;/code&amp;gt; interface. This interface adds the method &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt;, which can be used to query the capabilities present in the objects.&lt;br /&gt;
&lt;br /&gt;
In order to obtain a capability, you will need to refer it by its unique instance. In the case of the &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, this capability is primarily stored in &amp;lt;code&amp;gt;&amp;lt;nowiki&amp;gt;CapabilityItemHandler#ITEM_HANDLER_CAPABILITY&amp;lt;/nowiki&amp;gt;&amp;lt;/code&amp;gt;, but it is possible to get other instance references by using the &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; annotation.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
@CapabilityInject(IItemHandler.class)&lt;br /&gt;
static Capability&amp;lt;IItemHandler&amp;gt; ITEM_HANDLER_CAPABILITY = null;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
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 (&amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;), 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.&lt;br /&gt;
&lt;br /&gt;
Both the &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; methods have a second parameter, of type &amp;lt;code&amp;gt;Direction&amp;lt;/code&amp;gt;, which can be used in the to request the specific instance for that one face. If passed &amp;lt;code&amp;gt;null&amp;lt;/code&amp;gt;, 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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; will correspond to the type declared in the capability passed to the method. For the item handler capability, this is indeed &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Exposing a Capability==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
There’s two ways to obtain such an instance, through the &amp;lt;code&amp;gt;Capability&amp;lt;/code&amp;gt; itself, or by explicitly instantiating an implementation of it. The first method is designed to use a default implementation via &amp;lt;code&amp;gt;Capability#getDefaultInstance&amp;lt;/code&amp;gt;, 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.&lt;br /&gt;
&lt;br /&gt;
The second method can be used to provide custom implementations. In the case of &amp;lt;code&amp;gt;IItemHandler&amp;lt;/code&amp;gt;, the default implementation uses the &amp;lt;code&amp;gt;ItemStackHandler&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;@CapabilityInject&amp;lt;/code&amp;gt; in the previous section).&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;code&amp;gt;getCapability&amp;lt;/code&amp;gt; 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 &amp;lt;code&amp;gt;side&amp;lt;/code&amp;gt; parameter. For &amp;lt;code&amp;gt;Entities&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;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 =&amp;gt; head slot?), or about the surrounding blocks in the inventory (west =&amp;gt; slot on the left?). Don’t forget to fall back to &amp;lt;code&amp;gt;super&amp;lt;/code&amp;gt;, otherwise the attached capabilities will stop working. Make sure to invalidate the holder of the instance at the end of the provider's lifecycle.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;java&amp;quot;&amp;gt;&lt;br /&gt;
// Somewhere in your TileEntity subclass&lt;br /&gt;
LazyOptional&amp;lt;IItemHandler&amp;gt; inventoryHandlerLazyOptional;&lt;br /&gt;
&lt;br /&gt;
// After initializing inventoryHandler&lt;br /&gt;
inventoryHandlerLazyOptional = LazyOptional.of(() -&amp;gt; inventoryHandler);&lt;br /&gt;
&lt;br /&gt;
public &amp;lt;T&amp;gt; LazyOptional&amp;lt;T&amp;gt; getCapability(Capability&amp;lt;T&amp;gt; cap, Direction side) {&lt;br /&gt;
  if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {&lt;br /&gt;
    return inventoryHandlerLazyOptional.cast();&lt;br /&gt;
  }&lt;br /&gt;
  return super.getCapability(cap, side);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
@Override&lt;br /&gt;
protected void invalidateCaps() {&lt;br /&gt;
  super.invalidateCaps();&lt;br /&gt;
  inventoryHandlerLazyOptional.invalidate();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;Item&amp;lt;/code&amp;gt;s are a special case since their capability providers are stored on an &amp;lt;code&amp;gt;ItemStack&amp;lt;/code&amp;gt;. Instead, a provider should be attached through &amp;lt;code&amp;gt;Item#initCapabilities&amp;lt;/code&amp;gt; when applicable. This should hold your capabilities for the lifecycle of the stack.&lt;br /&gt;
&lt;br /&gt;
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.&lt;/div&gt;</summary>
		<author><name>TheSilkMiner</name></author>
	</entry>
</feed>