package net.minecraft.world.entity.variant; import java.util.Optional; import java.util.stream.Stream; import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.storage.ValueInput; import net.minecraft.world.level.storage.ValueOutput; public class VariantUtils { public static final String TAG_VARIANT = "variant"; public static Holder getDefaultOrAny(RegistryAccess registryAccess, ResourceKey key) { Registry registry = registryAccess.lookupOrThrow(key.registryKey()); return (Holder)registry.get(key).or(registry::getAny).orElseThrow(); } public static Holder getAny(RegistryAccess registryAccess, ResourceKey> registryKey) { return (Holder)registryAccess.lookupOrThrow(registryKey).getAny().orElseThrow(); } public static void writeVariant(ValueOutput output, Holder variant) { variant.unwrapKey().ifPresent(resourceKey -> output.store("variant", ResourceLocation.CODEC, resourceKey.location())); } public static Optional> readVariant(ValueInput input, ResourceKey> registryKey) { return input.read("variant", ResourceLocation.CODEC).map(resourceLocation -> ResourceKey.create(registryKey, resourceLocation)).flatMap(input.lookup()::get); } public static > Optional> selectVariantToSpawn( SpawnContext context, ResourceKey> registryKey ) { ServerLevelAccessor serverLevelAccessor = context.level(); Stream> stream = serverLevelAccessor.registryAccess().lookupOrThrow(registryKey).listElements(); return PriorityProvider.pick(stream, Holder::value, serverLevelAccessor.getRandom(), context); } }