Skip to content

Commit

Permalink
Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexProgrammerDE committed May 18, 2024
1 parent 51cdfdf commit acd78db
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,36 @@

@Slf4j
public class DefaultPacksDataGenerator implements IDataGenerator {
public static void packRegistries(
FriendlyByteBuf friendlyByteBuf,
DynamicOps<Tag> ops,
RegistryAccess registryAccess
) {
friendlyByteBuf.writeCollection(RegistryDataLoader.SYNCHRONIZED_REGISTRIES, (buf, registry) -> {
friendlyByteBuf.writeResourceKey(registry.key());
packRegistry(friendlyByteBuf, ops, (RegistryDataLoader.RegistryData<?>) registry, registryAccess);
});
}

private static <T> void packRegistry(
FriendlyByteBuf friendlyByteBuf,
DynamicOps<Tag> ops,
RegistryDataLoader.RegistryData<T> registryData,
RegistryAccess registryAccess
) {
var registry = registryAccess.registry(registryData.key()).orElseThrow();
friendlyByteBuf.writeCollection(registry.holders().toList(), (buf, holder) -> {
var holderPack = registry.registrationInfo(holder.key()).flatMap(RegistrationInfo::knownPackInfo).orElseThrow();
var holderData = registryData.elementCodec()
.encodeStart(ops, holder.value())
.getOrThrow(string -> new IllegalArgumentException("Failed to serialize " + holder.key() + ": " + string));

KnownPack.STREAM_CODEC.encode(friendlyByteBuf, holderPack);
RegistrySynchronization.PackedRegistryEntry.STREAM_CODEC.encode(friendlyByteBuf,
new RegistrySynchronization.PackedRegistryEntry(holder.key().location(), Optional.of(holderData)));
});
}

@Override
public String getDataName() {
return "data/builtin_packs.bin.zip";
Expand Down Expand Up @@ -73,34 +103,4 @@ public byte[] generateDataJson() {

return byteOutputStream.toByteArray();
}

public static void packRegistries(
FriendlyByteBuf friendlyByteBuf,
DynamicOps<Tag> ops,
RegistryAccess registryAccess
) {
friendlyByteBuf.writeCollection(RegistryDataLoader.SYNCHRONIZED_REGISTRIES, (buf, registry) -> {
friendlyByteBuf.writeResourceKey(registry.key());
packRegistry(friendlyByteBuf, ops, (RegistryDataLoader.RegistryData<?>) registry, registryAccess);
});
}

private static <T> void packRegistry(
FriendlyByteBuf friendlyByteBuf,
DynamicOps<Tag> ops,
RegistryDataLoader.RegistryData<T> registryData,
RegistryAccess registryAccess
) {
var registry = registryAccess.registry(registryData.key()).orElseThrow();
friendlyByteBuf.writeCollection(registry.holders().toList(), (buf, holder) -> {
var holderPack = registry.registrationInfo(holder.key()).flatMap(RegistrationInfo::knownPackInfo).orElseThrow();
var holderData = registryData.elementCodec()
.encodeStart(ops, holder.value())
.getOrThrow(string -> new IllegalArgumentException("Failed to serialize " + holder.key() + ": " + string));

KnownPack.STREAM_CODEC.encode(friendlyByteBuf, holderPack);
RegistrySynchronization.PackedRegistryEntry.STREAM_CODEC.encode(friendlyByteBuf,
new RegistrySynchronization.PackedRegistryEntry(holder.key().location(), Optional.of(holderData)));
});
}
}
2 changes: 0 additions & 2 deletions data-generator/src/main/resources/templates/RegistryKeys.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
*/
package com.soulfiremc.data;

import net.kyori.adventure.key.Key;

@SuppressWarnings("unused")
public class RegistryKeys {
//@formatter:off
Expand Down
124 changes: 62 additions & 62 deletions server/src/main/java/com/soulfiremc/server/data/JsonToMCPLCodecs.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,34 +39,48 @@
import org.geysermc.mcprotocollib.protocol.data.game.item.component.MobEffectInstance;

public class JsonToMCPLCodecs {
public static UUID uuidFromIntArray(int[] bits) {
return new UUID((long) bits[0] << 32 | (long) bits[1] & 4294967295L, (long) bits[2] << 32 | (long) bits[3] & 4294967295L);
}

public static int[] uuidToIntArray(UUID uuid) {
var l = uuid.getMostSignificantBits();
var m = uuid.getLeastSignificantBits();
return leastMostToIntArray(l, m);
}

private static int[] leastMostToIntArray(long most, long least) {
return new int[] {(int) (most >> 32), (int) most, (int) (least >> 32), (int) least};
}

public static DataResult<int[]> fixedSize(IntStream stream, int size) {
var is = stream.limit(size + 1).toArray();
if (is.length != size) {
Supplier<String> supplier = () -> "Input is not a list of " + size + " ints";
return is.length >= size ? DataResult.error(supplier, Arrays.copyOf(is, size)) : DataResult.error(supplier);
} else {
return DataResult.success(is);
}
}

public static final Codec<UUID> UUID_CODEC = Codec.INT_STREAM
.comapFlatMap(uuids -> fixedSize(uuids, 4).map(JsonToMCPLCodecs::uuidFromIntArray), uuid -> Arrays.stream(uuidToIntArray(uuid)));
public static final MapCodec<MobEffectDetails> MOB_EFFECT_DETAILS_MAP_CODEC = MapCodec.recursive(
"MobEffectInstance.Details",
codec -> RecordCodecBuilder.mapCodec(
instance -> instance.group(
ExtraCodecs.UNSIGNED_BYTE.optionalFieldOf("amplifier", 0).forGetter(MobEffectDetails::getAmplifier),
Codec.INT.optionalFieldOf("duration", 0).forGetter(MobEffectDetails::getDuration),
Codec.BOOL.optionalFieldOf("ambient", false).forGetter(MobEffectDetails::isAmbient),
Codec.BOOL.optionalFieldOf("show_particles", true).forGetter(MobEffectDetails::isShowParticles),
Codec.BOOL.optionalFieldOf("show_icon").forGetter(arg -> Optional.of(arg.isShowIcon())),
codec.optionalFieldOf("hidden_effect").forGetter(d -> Optional.ofNullable(d.getHiddenEffect()))
)
.apply(instance, (a, b, c, d, e, f) -> new MobEffectDetails(a, b, c, d, e.orElse(d), f.orElse(null)))
)
);
@SuppressWarnings("PatternValidation")
private static final Codec<Effect> MCPL_EFFECT_CODEC = Codec.STRING.xmap(s -> Effect.valueOf(Key.key(s).value().toUpperCase(Locale.ROOT)), e -> Key.key(e.name().toLowerCase(Locale.ROOT)).toString());
public static final Codec<MobEffectInstance> MOB_EFFECT_INSTANCE_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
MCPL_EFFECT_CODEC.fieldOf("id").forGetter(MobEffectInstance::getEffect),
MOB_EFFECT_DETAILS_MAP_CODEC.forGetter(MobEffectInstance::getDetails)
)
.apply(instance, MobEffectInstance::new)
);
public static final Codec<FoodProperties.PossibleEffect> POSSIBLE_EFFECT_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
MOB_EFFECT_INSTANCE_CODEC.fieldOf("effect").forGetter(FoodProperties.PossibleEffect::getEffect),
Codec.floatRange(0.0F, 1.0F).optionalFieldOf("probability", 1.0F).forGetter(FoodProperties.PossibleEffect::getProbability)
)
.apply(instance, FoodProperties.PossibleEffect::new)
);
public static final Codec<FoodProperties> FOOD_PROPERTIES_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
ExtraCodecs.NON_NEGATIVE_INT.fieldOf("nutrition").forGetter(FoodProperties::getNutrition),
Codec.FLOAT.fieldOf("saturation").forGetter(FoodProperties::getSaturationModifier),
Codec.BOOL.optionalFieldOf("can_always_eat", false).forGetter(FoodProperties::isCanAlwaysEat),
ExtraCodecs.POSITIVE_FLOAT.optionalFieldOf("eat_seconds", 1.6F).forGetter(FoodProperties::getEatSeconds),
POSSIBLE_EFFECT_CODEC.listOf().optionalFieldOf("effects", List.of()).forGetter(FoodProperties::getEffects)
)
.apply(instance, FoodProperties::new)
);
private static final Codec<ItemAttributeModifiers.EquipmentSlotGroup> MCPL_EQUIPMENT_SLOT_GROUP_CODEC = DualMap.keyCodec(
DualMap.forEnumSwitch(ItemAttributeModifiers.EquipmentSlotGroup.class, g -> switch (g) {
case ANY -> "any";
Expand Down Expand Up @@ -113,42 +127,28 @@ public static DataResult<int[]> fixedSize(IntStream stream, int size) {
public static final Codec<ItemAttributeModifiers> ITEM_ATTRIBUTE_MODIFIERS_CODEC = Codec.withAlternative(
ITEM_ATTRIBUTE_MODIFIERS_FULL_CODEC, Item_ATTRIBUTE_MODIFIERS_ENTRY_CODEC.listOf(), list -> new ItemAttributeModifiers(list, true)
);
public static final MapCodec<MobEffectDetails> MOB_EFFECT_DETAILS_MAP_CODEC = MapCodec.recursive(
"MobEffectInstance.Details",
codec -> RecordCodecBuilder.mapCodec(
instance -> instance.group(
ExtraCodecs.UNSIGNED_BYTE.optionalFieldOf("amplifier", 0).forGetter(MobEffectDetails::getAmplifier),
Codec.INT.optionalFieldOf("duration", 0).forGetter(MobEffectDetails::getDuration),
Codec.BOOL.optionalFieldOf("ambient", false).forGetter(MobEffectDetails::isAmbient),
Codec.BOOL.optionalFieldOf("show_particles", true).forGetter(MobEffectDetails::isShowParticles),
Codec.BOOL.optionalFieldOf("show_icon").forGetter(arg -> Optional.of(arg.isShowIcon())),
codec.optionalFieldOf("hidden_effect").forGetter(d -> Optional.ofNullable(d.getHiddenEffect()))
)
.apply(instance, (a, b, c, d, e, f) -> new MobEffectDetails(a, b, c, d, e.orElse(d), f.orElse(null)))
)
);
public static final Codec<MobEffectInstance> MOB_EFFECT_INSTANCE_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
MCPL_EFFECT_CODEC.fieldOf("id").forGetter(MobEffectInstance::getEffect),
MOB_EFFECT_DETAILS_MAP_CODEC.forGetter(MobEffectInstance::getDetails)
)
.apply(instance, MobEffectInstance::new)
);
public static final Codec<FoodProperties.PossibleEffect> POSSIBLE_EFFECT_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
MOB_EFFECT_INSTANCE_CODEC.fieldOf("effect").forGetter(FoodProperties.PossibleEffect::getEffect),
Codec.floatRange(0.0F, 1.0F).optionalFieldOf("probability", 1.0F).forGetter(FoodProperties.PossibleEffect::getProbability)
)
.apply(instance, FoodProperties.PossibleEffect::new)
);
public static final Codec<FoodProperties> FOOD_PROPERTIES_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
ExtraCodecs.NON_NEGATIVE_INT.fieldOf("nutrition").forGetter(FoodProperties::getNutrition),
Codec.FLOAT.fieldOf("saturation").forGetter(FoodProperties::getSaturationModifier),
Codec.BOOL.optionalFieldOf("can_always_eat", false).forGetter(FoodProperties::isCanAlwaysEat),
ExtraCodecs.POSITIVE_FLOAT.optionalFieldOf("eat_seconds", 1.6F).forGetter(FoodProperties::getEatSeconds),
POSSIBLE_EFFECT_CODEC.listOf().optionalFieldOf("effects", List.of()).forGetter(FoodProperties::getEffects)
)
.apply(instance, FoodProperties::new)
);

public static UUID uuidFromIntArray(int[] bits) {
return new UUID((long) bits[0] << 32 | (long) bits[1] & 4294967295L, (long) bits[2] << 32 | (long) bits[3] & 4294967295L);
}

public static int[] uuidToIntArray(UUID uuid) {
var l = uuid.getMostSignificantBits();
var m = uuid.getLeastSignificantBits();
return leastMostToIntArray(l, m);
}

private static int[] leastMostToIntArray(long most, long least) {
return new int[] {(int) (most >> 32), (int) most, (int) (least >> 32), (int) least};
}

public static DataResult<int[]> fixedSize(IntStream stream, int size) {
var is = stream.limit(size + 1).toArray();
if (is.length != size) {
Supplier<String> supplier = () -> "Input is not a list of " + size + " ints";
return is.length >= size ? DataResult.error(supplier, Arrays.copyOf(is, size)) : DataResult.error(supplier);
} else {
return DataResult.success(is);
}
}
}
4 changes: 2 additions & 2 deletions server/src/main/java/com/soulfiremc/server/data/Registry.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@
public class Registry<T extends RegistryValue> {
@Getter
private final Key key;
private final Object2ReferenceMap<Key, T> FROM_KEY = new Object2ReferenceOpenHashMap<>();
@Getter
private final Codec<T> keyCodec = ExtraCodecs.KYORI_KEY_CODEC.xmap(this::getByKey, RegistryValue::key);
private final Int2ReferenceMap<T> FROM_ID = new Int2ReferenceOpenHashMap<>();
@Getter
private final Codec<T> idCodec = Codec.INT.xmap(this::getById, RegistryValue::id);
private final Object2ReferenceMap<Key, T> FROM_KEY = new Object2ReferenceOpenHashMap<>();
private final Int2ReferenceMap<T> FROM_ID = new Int2ReferenceOpenHashMap<>();

public T register(final T value) {
FROM_KEY.put(value.key(), value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import net.kyori.adventure.key.KeyPattern;

public record TagKey<T extends RegistryValue>(Key key) {
public static <T extends RegistryValue> TagKey<T> key(@KeyPattern String key) {
public static <T extends RegistryValue> TagKey<T> key(@KeyPattern String key) {
return new TagKey<>(Key.key(key));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public void refresh(RefreshRequest request, StreamObserver<RefreshResponse> resp
try {
var receivedAccount = MinecraftAccount.fromProto(request.getAccount());
var account = convertService(request.getAccount().getType()).refresh(receivedAccount,
convertProxy(request::hasProxy, request::getProxy)).join();
convertProxy(request::hasProxy, request::getProxy)).join();

responseObserver.onNext(RefreshResponse.newBuilder().setAccount(account.toProto()).build());
responseObserver.onCompleted();
Expand Down
52 changes: 26 additions & 26 deletions server/src/main/java/com/soulfiremc/server/util/DualMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,37 +31,37 @@
@SuppressWarnings("unused")
@RequiredArgsConstructor
public class DualMap<L, R> {
private final Map<L, R> map;
private final Map<R, L> reverseMap;
private final Map<L, R> map;
private final Map<R, L> reverseMap;

public DualMap(Map<L, R> map) {
this.map = map;
this.reverseMap = new HashMap<>();
for (var entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
public DualMap(Map<L, R> map) {
this.map = map;
this.reverseMap = new HashMap<>();
for (var entry : map.entrySet()) {
reverseMap.put(entry.getValue(), entry.getKey());
}
}

public static <L extends Enum<L>, R> DualMap<L, R> forEnumSwitch(Class<L> clazz, Function<L, R> mapper) {
return new DualMap<>(
Arrays.stream(clazz.getEnumConstants())
.collect(Collectors.toMap(Function.identity(), mapper))
);
}
public static <L extends Enum<L>, R> DualMap<L, R> forEnumSwitch(Class<L> clazz, Function<L, R> mapper) {
return new DualMap<>(
Arrays.stream(clazz.getEnumConstants())
.collect(Collectors.toMap(Function.identity(), mapper))
);
}

public R getRight(L key) {
return map.get(key);
}
public static <T> Codec<T> keyCodec(DualMap<T, String> map) {
return Codec.STRING.xmap(map::getLeft, map::getRight);
}

public L getLeft(R value) {
return reverseMap.get(value);
}
public static <T> Codec<T> valueCodec(DualMap<String, T> map) {
return Codec.STRING.xmap(map::getRight, map::getLeft);
}

public static <T> Codec<T> keyCodec(DualMap<T, String> map) {
return Codec.STRING.xmap(map::getLeft, map::getRight);
}
public R getRight(L key) {
return map.get(key);
}

public static <T> Codec<T> valueCodec(DualMap<String, T> map) {
return Codec.STRING.xmap(map::getRight, map::getLeft);
}
public L getLeft(R value) {
return reverseMap.get(value);
}
}

0 comments on commit acd78db

Please sign in to comment.