Skip to content

Commit dfa7282

Browse files
committed
[Entity Creation API] @NetworkSync
1 parent 7ebeffd commit dfa7282

14 files changed

Lines changed: 336 additions & 7 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package pl.olafcio.avoid_impl.mixininterface;
2+
3+
import net.minecraft.network.syncher.SynchedEntityData;
4+
5+
public interface ISynchedEntityData {
6+
SynchedEntityData.Builder avoidlib$builder();
7+
void avoidlib$builder(SynchedEntityData.Builder value);
8+
}

‎src/impl/java/pl/olafcio/avoid_impl/net/entity/custom_internal/AvoidEntity.java‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package pl.olafcio.avoid_impl.net.entity.custom_internal;
22

3+
import net.minecraft.network.syncher.EntityDataAccessor;
34
import net.minecraft.network.syncher.SynchedEntityData;
45
import net.minecraft.server.level.ServerLevel;
56
import net.minecraft.world.damagesource.DamageSource;
@@ -43,11 +44,17 @@ public AvoidEntity(EntityType<?> entityType, Level level, EntityConstructor<pl.o
4344
name,
4445
this
4546
);
47+
48+
avoid_injectSynchedData();
4649
}
4750

4851
@Override
49-
protected void defineSynchedData(SynchedEntityData.Builder builder) {
50-
//
52+
protected void defineSynchedData(SynchedEntityData.Builder builder) {}
53+
54+
@Override
55+
public void onSyncedDataUpdated(EntityDataAccessor<?> entityDataAccessor) {
56+
super.onSyncedDataUpdated(entityDataAccessor);
57+
avoid_onSyncedDataUpdated(entityDataAccessor);
5158
}
5259

5360
@Override

‎src/impl/java/pl/olafcio/avoid_impl/net/entity/custom_internal/AvoidLivingEntity.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package pl.olafcio.avoid_impl.net.entity.custom_internal;
22

3+
import net.minecraft.network.syncher.EntityDataAccessor;
34
import net.minecraft.network.syncher.SynchedEntityData;
45
import net.minecraft.server.level.ServerLevel;
56
import net.minecraft.world.damagesource.DamageSource;
@@ -45,11 +46,14 @@ public AvoidLivingEntity(EntityType<? extends LivingEntity> entityType, Level le
4546
name,
4647
this
4748
);
49+
50+
avoid_injectSynchedData();
4851
}
4952

5053
@Override
51-
protected void defineSynchedData(SynchedEntityData.Builder builder) {
52-
super.defineSynchedData(builder);
54+
public void onSyncedDataUpdated(EntityDataAccessor<?> entityDataAccessor) {
55+
super.onSyncedDataUpdated(entityDataAccessor);
56+
avoid_onSyncedDataUpdated(entityDataAccessor);
5357
}
5458

5559
@Override

‎src/impl/java/pl/olafcio/avoid_impl/net/entity/custom_internal/AvoidMerchant.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package pl.olafcio.avoid_impl.net.entity.custom_internal;
22

33
import com.mojang.logging.LogUtils;
4+
import net.minecraft.network.syncher.EntityDataAccessor;
45
import net.minecraft.network.syncher.SynchedEntityData;
56
import net.minecraft.server.level.ServerLevel;
67
import net.minecraft.world.Difficulty;
@@ -50,11 +51,14 @@ public AvoidMerchant(EntityType<? extends Villager> entityType, Level level, Ent
5051
name,
5152
this
5253
);
54+
55+
avoid_injectSynchedData();
5356
}
5457

5558
@Override
56-
protected void defineSynchedData(SynchedEntityData.Builder builder) {
57-
super.defineSynchedData(builder);
59+
public void onSyncedDataUpdated(EntityDataAccessor<?> entityDataAccessor) {
60+
super.onSyncedDataUpdated(entityDataAccessor);
61+
avoid_onSyncedDataUpdated(entityDataAccessor);
5862
}
5963

6064
@Override
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,84 @@
11
package pl.olafcio.avoid_impl.net.entity.custom_internal;
22

3+
import net.minecraft.network.syncher.EntityDataAccessor;
4+
import net.minecraft.network.syncher.SynchedEntityData;
5+
import org.jetbrains.annotations.NotNull;
36
import pl.olafcio.avoid.net.entity.Entity;
7+
import pl.olafcio.avoid_impl.mixininterface.ISynchedEntityData;
8+
import pl.olafcio.avoid_impl.net.entity_type.AvoidEntityType;
9+
import pl.olafcio.avoid_impl.net.entity_type.sync.Controller;
10+
11+
import java.lang.reflect.Field;
12+
import java.util.HashMap;
13+
import java.util.Map;
14+
import java.util.function.Function;
415

516
public interface IAvoidEntity {
617
Entity getAvoidEntity();
718
void parentTick();
19+
20+
default void avoid_injectSynchedData() {
21+
// I have to do this as the default values for custom entity data depend on the entity itself
22+
23+
var self = getEntity();
24+
var builder = ((ISynchedEntityData) self.entityData).avoidlib$builder();
25+
26+
avoid_defineSynchedData(builder);
27+
28+
self.entityData = builder.build();
29+
}
30+
31+
private void avoid_defineSynchedData(SynchedEntityData.Builder builder) {
32+
var synched = getSynchs();
33+
34+
for (var sync : synched.entrySet()) {
35+
try {
36+
unsafeDefine(builder, sync);
37+
} catch (IllegalAccessException e) {
38+
throw new RuntimeException("Failed to define @NetworkSync field: '%s' on '%s'".formatted(sync.getValue().getName(), sync.getValue().getDeclaringClass().getName()), e);
39+
}
40+
}
41+
}
42+
43+
private HashMap<Controller<?, ?, ?>, Field> getSynchs() {
44+
return ((AvoidEntityType<?>) getEntity().getType()).synchs;
45+
}
46+
47+
private @NotNull net.minecraft.world.entity.Entity getEntity() {
48+
return (net.minecraft.world.entity.Entity) this;
49+
}
50+
51+
@SuppressWarnings("unchecked")
52+
private <I, O> void unsafeDefine(SynchedEntityData.Builder builder, Map.Entry<Controller<?, ?, ?>, Field> sync) throws IllegalAccessException {
53+
sync.getValue().setAccessible(true);
54+
55+
var accessor = (EntityDataAccessor<O>) sync.getKey().accessor;
56+
57+
// builder.itemsById[accessor.id()] = null;
58+
builder.define(
59+
accessor,
60+
((Function<I, O>) sync.getKey().converterTo).apply((I) sync.getValue().get(getAvoidEntity()))
61+
);
62+
}
63+
64+
default void avoid_onSyncedDataUpdated(EntityDataAccessor<?> entityDataAccessor) {
65+
var synched = getSynchs();
66+
67+
for (var sync : synched.entrySet()) {
68+
if (sync.getKey().accessor.equals(entityDataAccessor)) {
69+
unsafeSet(entityDataAccessor, sync);
70+
}
71+
}
72+
}
73+
74+
@SuppressWarnings("unchecked")
75+
private <T> void unsafeSet(EntityDataAccessor<T> entityDataAccessor, Map.Entry<Controller<?, ?, ?>, Field> sync) {
76+
try {
77+
sync.getValue().setAccessible(true);
78+
79+
((Controller<?, T, ?>) sync.getKey()).set(getAvoidEntity(), sync.getValue(), getEntity().entityData.get(entityDataAccessor));
80+
} catch (IllegalAccessException e) {
81+
throw new RuntimeException("Failed to update @NetworkSync field: '%s' on '%s'".formatted(sync.getValue().getName(), sync.getValue().getDeclaringClass().getName()), e);
82+
}
83+
}
884
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package pl.olafcio.avoid_impl.net.entity_type;
2+
3+
import com.google.common.collect.ImmutableSet;
4+
import net.minecraft.resources.ResourceKey;
5+
import net.minecraft.world.entity.Entity;
6+
import net.minecraft.world.entity.EntityDimensions;
7+
import net.minecraft.world.entity.EntityType;
8+
import net.minecraft.world.entity.MobCategory;
9+
import net.minecraft.world.flag.FeatureFlagSet;
10+
import net.minecraft.world.level.block.Block;
11+
import net.minecraft.world.level.storage.loot.LootTable;
12+
import org.jetbrains.annotations.ApiStatus;
13+
import org.jetbrains.annotations.NotNull;
14+
import pl.olafcio.avoid_impl.net.entity_type.sync.Controller;
15+
16+
import java.lang.reflect.Field;
17+
import java.util.HashMap;
18+
import java.util.Optional;
19+
20+
@ApiStatus.Internal
21+
public final class AvoidEntityType<T extends @NotNull Entity> extends EntityType<T> {
22+
public final HashMap<Controller<?, ?, ?>, Field> synchs;
23+
24+
AvoidEntityType(HashMap<Controller<?, ?, ?>, Field> synchs, EntityFactory<T> entityFactory, MobCategory mobCategory, boolean bl, boolean bl2, boolean bl3, boolean bl4, ImmutableSet<Block> immutableSet, EntityDimensions entityDimensions, float f, int i, int j, String string, Optional<ResourceKey<LootTable>> optional, FeatureFlagSet featureFlagSet, boolean bl5) {
25+
super(entityFactory, mobCategory, bl, bl2, bl3, bl4, immutableSet, entityDimensions, f, i, j, string, optional, featureFlagSet, bl5);
26+
this.synchs = synchs;
27+
}
28+
}

‎src/impl/java/pl/olafcio/avoid_impl/net/entity_type/EntityTypes.java‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import net.minecraft.core.Registry;
55
import net.minecraft.core.registries.BuiltInRegistries;
66
import net.minecraft.core.registries.Registries;
7+
import net.minecraft.network.syncher.SynchedEntityData;
78
import net.minecraft.resources.Identifier;
89
import net.minecraft.resources.ResourceKey;
910
import net.minecraft.util.Util;
@@ -19,19 +20,23 @@
1920
import org.jetbrains.annotations.NotNull;
2021
import pl.olafcio.avoid.net.entity.Entity;
2122
import pl.olafcio.avoid.net.entity.custom.Merchant;
23+
import pl.olafcio.avoid.net.entity.sync.NetworkSync;
2224
import pl.olafcio.avoid_impl.net.entity.custom_internal.AvoidEntity;
2325
import pl.olafcio.avoid_impl.net.entity.custom_internal.AvoidLivingEntity;
2426
import pl.olafcio.avoid_impl.net.entity.custom_internal.AvoidMerchant;
2527
import pl.olafcio.avoid_impl.net.entity.custom_internal.EntityConstructor;
2628
import pl.olafcio.avoid.net.entity_type.properties.*;
2729
import pl.olafcio.avoid.net.entity_type.properties.attachment.AttachmentOperation;
2830
import pl.olafcio.avoid.net.entity_type.properties.attribute.AttributeBase;
31+
import pl.olafcio.avoid_impl.net.entity_type.sync.Controller;
32+
import pl.olafcio.avoid_impl.net.entity_type.sync.Controllers;
2933
import pl.olafcio.avoid_impl.net.entity_type.values.AttachmentTypeNative;
3034
import pl.olafcio.avoid.net.entity_type.values.Category;
3135
import pl.olafcio.avoid_impl.net.entity_type.values.CategoryNative;
3236
import pl.olafcio.avoid.net.id.Identification;
3337
import pl.olafcio.avoid_impl.net.id.IdentificationNative;
3438

39+
import java.lang.reflect.Field;
3540
import java.util.Arrays;
3641
import java.util.HashMap;
3742
import java.util.Optional;
@@ -106,6 +111,7 @@ public static <T extends pl.olafcio.avoid.net.entity.Entity> void register(Ident
106111
var Type = createType(
107112
klass,
108113
id,
114+
AvoidMerchant.class,
109115
(EntityType<@NotNull Villager> type, Level level)
110116
-> new AvoidMerchant(type, level, (EntityConstructor<Merchant>) constructor),
111117
category,
@@ -121,6 +127,7 @@ public static <T extends pl.olafcio.avoid.net.entity.Entity> void register(Ident
121127
var Type = createType(
122128
klass,
123129
id,
130+
AvoidLivingEntity.class,
124131
(EntityType<@NotNull LivingEntity> type, Level level)
125132
-> new AvoidLivingEntity(type, level, (EntityConstructor<pl.olafcio.avoid.net.entity.custom.Entity>) constructor),
126133
category,
@@ -133,6 +140,7 @@ public static <T extends pl.olafcio.avoid.net.entity.Entity> void register(Ident
133140
createType(
134141
klass,
135142
id,
143+
AvoidEntity.class,
136144
(EntityType<net.minecraft.world.entity.@NotNull Entity> type, Level level)
137145
-> new AvoidEntity(type, level, (EntityConstructor<pl.olafcio.avoid.net.entity.custom.Entity>) constructor),
138146
category,
@@ -143,18 +151,52 @@ public static <T extends pl.olafcio.avoid.net.entity.Entity> void register(Ident
143151
}
144152
}
145153

154+
private static final HashMap<Class<?>, Integer> lastIDs
155+
= new HashMap<>();
156+
146157
private static <T extends net.minecraft.world.entity.Entity> @NotNull EntityType<T> createType(
147158
Class<? extends pl.olafcio.avoid.net.entity.Entity> klass,
148159
Identifier id,
160+
Class<?> destination,
149161
EntityType.EntityFactory<T> factory,
150162
Category category,
151163
EntityDimensions dimensions,
152164
EntityAttachments.Builder attachments
153165
) {
166+
var fields = klass.getDeclaredFields();
167+
var synchs = new HashMap<Controller<?, ?, ?>, Field>();
168+
169+
// Minecraft tf is ts class shit
170+
int lastID = lastIDs.computeIfAbsent(destination, SynchedEntityData.ID_REGISTRY::getLastIdFor);
171+
172+
for (var field : fields) {
173+
if (field.isAnnotationPresent(NetworkSync.class)) {
174+
var serializer = Controllers.convert(field.getType());
175+
int valueID = ++lastID;
176+
177+
if (valueID > 254) {
178+
throw new IllegalArgumentException("Data value id is too big with " + valueID + "! (Max is 254)");
179+
}
180+
181+
var accessor = serializer.serializer.createAccessor(valueID);
182+
serializer.accessor = accessor;
183+
184+
synchs.put(serializer, field);
185+
}
186+
}
187+
188+
// FIXME Doing this 2 times because otherwise it didn't work
189+
for (int i = 0; i < 2; i++)
190+
SynchedEntityData.ID_REGISTRY.classToLastIdCache.put(
191+
destination,
192+
Math.max(SynchedEntityData.ID_REGISTRY.classToLastIdCache.getOrDefault(destination, -1), lastID)
193+
);
194+
154195
EntityType<T> Type;
155196

156197
// TODO: Should I use the builder? Guess we'll see when there are issues in cross-version compatibility ;d
157-
Registry.register(BuiltInRegistries.ENTITY_TYPE, id, Type = new EntityType<T>(
198+
Registry.register(BuiltInRegistries.ENTITY_TYPE, id, Type = new AvoidEntityType<T>(
199+
synchs,
158200
factory,
159201
CategoryNative.convertFrom(category),
160202
!klass.isAnnotationPresent(_noSave.class),
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package pl.olafcio.avoid_impl.net.entity_type.sync;
2+
3+
import net.minecraft.network.syncher.EntityDataAccessor;
4+
import net.minecraft.network.syncher.EntityDataSerializer;
5+
import org.apache.commons.lang3.function.FailableBiConsumer;
6+
7+
import java.lang.reflect.Field;
8+
import java.util.function.Function;
9+
10+
public class Controller<Avoid, Native, T extends EntityDataSerializer<Native>> {
11+
public final T serializer;
12+
public final Function<Avoid, Native> converterTo;
13+
public final Function<Native, Avoid> converterFrom;
14+
15+
public Controller(T serializer, Function<Avoid, Native> converterTo, Function<Native, Avoid> converterFrom) {
16+
this.serializer = serializer;
17+
this.converterTo = converterTo;
18+
this.converterFrom = converterFrom;
19+
}
20+
21+
public static <T, S extends EntityDataSerializer<T>> Controller<T, T, S> create(S serializer) {
22+
return new Controller<>(serializer, Function.identity(), Function.identity());
23+
}
24+
25+
//TODO Can this setter parameter be simplified?
26+
public static <T, S extends EntityDataSerializer<T>> Controller<T, T, S> create(S serializer, Function<Field, FailableBiConsumer<Object, T, IllegalAccessException>> setter) {
27+
return new Controller<>(serializer, Function.identity(), Function.identity()) {
28+
@Override
29+
public void set(Object parent, Field field, T value) throws IllegalAccessException {
30+
setter.apply(field).accept(parent, value);
31+
}
32+
};
33+
}
34+
35+
public EntityDataAccessor<?> accessor;
36+
37+
public void set(Object parent, Field field, Native value) throws IllegalAccessException {
38+
field.set(parent, value);
39+
}
40+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package pl.olafcio.avoid_impl.net.entity_type.sync;
2+
3+
import net.minecraft.network.syncher.EntityDataSerializer;
4+
import net.minecraft.network.syncher.EntityDataSerializers;
5+
import org.jetbrains.annotations.ApiStatus;
6+
import org.joml.Vector3fc;
7+
import pl.olafcio.avoid.net._3d.Direction;
8+
import pl.olafcio.avoid.net.block.pos.BlockPos;
9+
import pl.olafcio.avoid.net.chat.component.BaseComponent;
10+
import pl.olafcio.avoid.net.world.block_data.BlockData;
11+
import pl.olafcio.avoid_impl.net._3d.DirectionNative;
12+
import pl.olafcio.avoid_impl.net.block.pos.BlockPosNative;
13+
import pl.olafcio.avoid_impl.net.chat.converter.COFromNative;
14+
import pl.olafcio.avoid_impl.net.chat.converter.COToNative;
15+
import pl.olafcio.avoid_impl.net.world.block_data.BlockDataNative;
16+
17+
public final class Controllers {
18+
@ApiStatus.Internal
19+
private Controllers() {}
20+
21+
public static Controller<?, ?, ?> convert(Class<?> klass) {
22+
EntityDataSerializer<?> x;
23+
24+
if (klass == String.class) x = EntityDataSerializers.STRING;
25+
else if (klass == byte.class || klass == Byte.class) return Controller.create(EntityDataSerializers.BYTE, f -> f::setByte);
26+
else if (klass == int.class || klass == Integer.class) return Controller.create(EntityDataSerializers.INT, f -> f::setInt);
27+
else if (klass == float.class || klass == Float.class) return Controller.create(EntityDataSerializers.FLOAT, f -> f::setFloat);
28+
else if (klass == long.class || klass == Long.class) return Controller.create(EntityDataSerializers.LONG, f -> f::setLong);
29+
else if (klass == boolean.class || klass == Boolean.class) return Controller.create(EntityDataSerializers.BOOLEAN, f -> f::setBoolean);
30+
else if (klass == Direction.class) return new Controller<>(EntityDataSerializers.DIRECTION, DirectionNative::convertFrom, DirectionNative::convert);
31+
else if (BaseComponent.class.isAssignableFrom(klass)) return new Controller<>(EntityDataSerializers.COMPONENT, COToNative::from, COFromNative::from);
32+
else if (klass == BlockPos.class) return new Controller<>(EntityDataSerializers.BLOCK_POS, BlockPosNative::convertFrom, BlockPosNative::convert);
33+
else if (BlockData.class.isAssignableFrom(klass)) return new Controller<>(EntityDataSerializers.BLOCK_STATE, BlockDataNative::convert, BlockDataNative::convertFrom);
34+
else if (Vector3fc.class.isAssignableFrom(klass)) x = EntityDataSerializers.VECTOR3;
35+
else throw new RuntimeException("Unserializable type '%s'".formatted(klass.getName()));
36+
37+
return Controller.create(x);
38+
}
39+
}

0 commit comments

Comments
 (0)