Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update docs for capability rework #34

Merged
merged 6 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/concepts/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ private void modEventHandler(RegisterEvent event) {
}

// This event is on the forge bus
private static void forgeEventHandler(AttachCapabilitiesEvent<Entity> event) {
private static void forgeEventHandler(ExplosionEvent.Detonate event) {
// ...
}

// In the mod constructor
modEventBus.addListener(this::modEventHandler);
forgeEventBus.addGenericListener(Entity.class, ExampleMod::forgeEventHandler);
forgeEventBus.addListener(ExampleMod::forgeEventHandler);
```

### Instance Annotated Event Handlers
Expand Down
5 changes: 3 additions & 2 deletions docs/concepts/lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ If the game is setup to run [data generators][datagen], then the `GatherDataEven
Common Setup
------------

`FMLCommonSetupEvent` is for actions that are common to both physical client and server, such as registering [capabilities][capabilities].
`FMLCommonSetupEvent` is for actions that are common to both physical client and server.
This event is fired for multiple mods in parallel, so be careful.
You can use `event.enqueueWork(() -> /* do something */)` to run code that is not thread-safe.

Sided Setup
-----------
Expand All @@ -70,7 +72,6 @@ There are two other lifecycle events: `FMLConstructModEvent`, fired directly aft
:::

[registering]: ./registries.md#methods-for-registering
[capabilities]: ../datastorage/capabilities.md
[datagen]: ../datagen/index.md
[imc]: ./lifecycle.md#intermodcomms
[sides]: ./sides.md
109 changes: 109 additions & 0 deletions docs/datastorage/attachments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# Data Attachments

The data attachment system allows mods to attach and store additional data on block entities, chunks, entities, and item stacks.

_To store additional level data, you can use [SavedData](saveddata)._

## Creating an attachment type

To use the system, you need to register an `AttachmentType`.
The attachment type contains the following configuration:
- A default value supplier to create the instance when the data is first accessed. Also used to compare stacks that have the data with stacks that don't have it.
- An optional serializer if the attachment should be persisted.
- (If a serializer was configured) The `copyOnDeath` flag to automatically copy entity data on death (see below).
- (Advanced) (If a serializer was configured) A custom `comparator` to use when checking if the data is the same for two item stacks.

:::tip
If you don't want your attachment to persist, do not provide a serializer.
:::

There are a few ways to provide an attachment serializer: directly implementing `IAttachmentSerializer`, implementing `INBTSerializable` and using the static `AttachmentSerializer.serializable()` method to create the builder, or providing a codec to the builder.

:::warning
Avoid serialization with codecs for item stack attachments, as it is comparatively slow.
:::

In any case, the attachment **must be registered** to the `NeoForgeRegistries.ATTACHMENT_TYPES` registry. Here is an example:
```java
// Create the DeferredRegister for attachment types
private static final DeferredRegister<AttachmentType<?>> ATTACHMENT_TYPES = DeferredRegister.create(NeoForgeRegistries.ATTACHMENT_TYPES, MOD_ID);

// Serialization via INBTSerializable
private static final Supplier<AttachmentType<ItemStackHandler>> HANDLER = ATTACHMENT_TYPES.register(
"handler", () -> AttachmentType.serializable(() -> new ItemStackHandler(1)).build());
// Serialization via codec
private static final Supplier<AttachmentType<Integer>> MANA = ATTACHMENT_TYPES.register(
"mana", () -> AttachmentType.builder(() -> 0).serialize(Codec.INT).build());
// No serialization
private static final Supplier<AttachmentType<SomeCache>> SOME_CACHE = ATTACHMENT_TYPES.register(
"some_cache", () -> AttachmentType.builder(() -> new SomeCache()).build()
);

// In your mod constructor, don't forget to register the DeferredRegister to your mod bus:
ATTACHMENT_TYPES.register(modBus);
```

## Using the attachment type

Once the attachment type is registered, it can be used on any holder object.
Calling `getData` if no data is present will attach a new default instance.

```java
// Get the ItemStackHandler if it already exists, else attach a new one:
ItemStackHandler stackHandler = stack.getData(HANDLER);
// Get the current player mana if it is available, else attach 0:
int playerMana = player.getData(MANA);
// And so on...
```

If attaching a default instance is not desired, a `hasData` check can be added:
```java
// Check if the stack has the HANDLER attachment before doing anything.
if (stack.hasData(HANDLER)) {
ItemStackHandler stackHandler = stack.getData(HANDLER);
// Do something with stack.getData(HANDLER).
}
```

The data can also be updated with `setData`:
```java
// Increment mana by 10.
player.setData(MANA, player.getData(MANA) + 10);
```

:::important
Usually, block entities and chunks need to be marked as dirty when they are modified (with `setChanged` and `setUnsaved(true)`). This is done automatically for calls to `setData`:
```java
chunk.setData(MANA, chunk.getData(MANA) + 10); // will call setUnsaved automatically
```
but if you modify some data that you obtained from `getData` (including a newly created default instance) then you must mark block entities and chunks as dirty explicitly:
```java
var mana = chunk.getData(MUTABLE_MANA);
mana.set(10);
chunk.setUnsaved(true); // must be done manually because we did not use setData
```
:::

## Sharing data with the client
Currently, only serializable item stack attachments are synced between the client and the server.
This is done automatically.

To sync block entity, chunk, or entity attachments to a client, you need to [send a packet to the client][network] yourself.
For chunks, you can use `ChunkWatchEvent.Sent` to know when to send chunk data to a player.

## Copying data on player death
By default, entity data attachments are not copied on player death.
To automatically copy an attachment on player death, set `.copyOnDeath()` in the attachment builder.

More complex handling can be implemented via `PlayerEvent.Clone` by reading the data from the original entity and assigning it to the new entity. In this event, the `#isWasDeath` method can be used to distinguish between respawning after death and returning from the End. This is important because the data will already exist when returning from the End, so care has to be taken to not duplicate values in this case.
Technici4n marked this conversation as resolved.
Show resolved Hide resolved

For example:
```java
NeoForge.EVENT_BUS.register(PlayerEvent.Clone.class, event -> {
if (event.isWasDeath() && event.getOriginal().hasData(MY_DATA)) {
event.getEntity().getData(MY_DATA).fieldToCopy = event.getOriginal().getData(MY_DATA).fieldToCopy;
}
});
```

[network]: ../networking/index.md
Loading