87 lines
3.1 KiB
Java
87 lines
3.1 KiB
Java
package org.blz.adminmode.utils;
|
|
|
|
import org.bukkit.NamespacedKey;
|
|
import org.bukkit.Registry;
|
|
import org.bukkit.potion.PotionEffect;
|
|
import org.bukkit.potion.PotionEffectType;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Collection;
|
|
import java.util.List;
|
|
import java.util.Locale;
|
|
import java.util.function.Consumer;
|
|
|
|
/** Encodes potion effects with registry keys and reads the legacy enum-name format. */
|
|
public final class PotionEffectCodec {
|
|
|
|
private static final String FORMAT_PREFIX = "potion-v2:";
|
|
|
|
private PotionEffectCodec() {
|
|
}
|
|
|
|
public static String serialize(Collection<PotionEffect> effects) {
|
|
StringBuilder builder = new StringBuilder(FORMAT_PREFIX);
|
|
if (effects == null) {
|
|
return builder.toString();
|
|
}
|
|
|
|
for (PotionEffect effect : effects) {
|
|
NamespacedKey key = Registry.MOB_EFFECT.getKey(effect.getType());
|
|
builder.append(key).append('|')
|
|
.append(effect.getDuration()).append('|')
|
|
.append(effect.getAmplifier()).append('|')
|
|
.append(effect.isAmbient()).append('|')
|
|
.append(effect.hasParticles()).append('|')
|
|
.append(effect.hasIcon()).append(';');
|
|
}
|
|
return builder.toString();
|
|
}
|
|
|
|
public static Collection<PotionEffect> deserialize(String data, Consumer<String> warningSink) {
|
|
List<PotionEffect> effects = new ArrayList<>();
|
|
if (data == null || data.isEmpty()) {
|
|
return effects;
|
|
}
|
|
|
|
boolean currentFormat = data.startsWith(FORMAT_PREFIX);
|
|
String payload = currentFormat ? data.substring(FORMAT_PREFIX.length()) : data;
|
|
for (String encodedEffect : payload.split(";")) {
|
|
if (encodedEffect.isEmpty()) {
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
String[] parts = currentFormat
|
|
? encodedEffect.split("\\|", -1)
|
|
: encodedEffect.split(":", -1);
|
|
if (parts.length != 6) {
|
|
throw new IllegalArgumentException("Expected 6 fields");
|
|
}
|
|
|
|
PotionEffectType type = resolveType(parts[0], currentFormat);
|
|
if (type == null) {
|
|
throw new IllegalArgumentException("Unknown effect " + parts[0]);
|
|
}
|
|
|
|
effects.add(new PotionEffect(
|
|
type,
|
|
Integer.parseInt(parts[1]),
|
|
Integer.parseInt(parts[2]),
|
|
Boolean.parseBoolean(parts[3]),
|
|
Boolean.parseBoolean(parts[4]),
|
|
Boolean.parseBoolean(parts[5])));
|
|
} catch (RuntimeException exception) {
|
|
warningSink.accept(encodedEffect);
|
|
}
|
|
}
|
|
return effects;
|
|
}
|
|
|
|
private static PotionEffectType resolveType(String identifier, boolean currentFormat) {
|
|
NamespacedKey key = currentFormat
|
|
? NamespacedKey.fromString(identifier)
|
|
: NamespacedKey.minecraft(identifier.toLowerCase(Locale.ROOT));
|
|
return key == null ? null : Registry.MOB_EFFECT.get(key);
|
|
}
|
|
}
|