mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-11-27 16:35:31 +00:00
feat: add environment attribute system
This commit is contained in:
1 parent
8a940f7e1f
commit
4e37c361ea
127 files changed
+9022
-19
No files matched your search
@@ -67,6 +67,7 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.util.generic.pair.Pair;
|
||||
import com.dfsek.terra.api.util.mutable.MutableBoolean;
|
||||
import com.dfsek.terra.api.util.reflection.TypeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.config.GenericLoaders;
|
||||
import com.dfsek.terra.config.PluginConfigImpl;
|
||||
import com.dfsek.terra.event.EventManagerImpl;
|
||||
@@ -77,6 +78,7 @@ import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.registry.master.ConfigRegistry;
|
||||
import com.dfsek.terra.registry.master.ConfigRegistry.PackLoadFailuresException;
|
||||
import com.dfsek.terra.registry.master.MetaConfigRegistry;
|
||||
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
|
||||
|
||||
|
||||
/**
|
||||
@@ -103,6 +105,8 @@ public abstract class AbstractPlatform implements Platform {
|
||||
private final GenericLoaders loaders = new GenericLoaders(this);
|
||||
private final PluginConfigImpl config = new PluginConfigImpl();
|
||||
private final CheckedRegistry<BaseAddon> addonRegistry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(TypeKey.of(BaseAddon.class)));
|
||||
// Must exist before addons initialize: it creates the attribute context keys.
|
||||
private final AttributeHandle attributeHandle = new AttributeHandleImpl();
|
||||
private final Registry<BaseAddon> lockedAddonRegistry = new LockedRegistryImpl<>(addonRegistry);
|
||||
|
||||
public static int getGenerationThreadsWithReflection(String className, String fieldName, String project) {
|
||||
@@ -434,6 +438,11 @@ public abstract class AbstractPlatform implements Platform {
|
||||
return profiler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull AttributeHandle getAttributeHandle() {
|
||||
return attributeHandle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getGenerationThreads() {
|
||||
return 1;
|
||||
|
||||
+1
-2
@@ -68,8 +68,7 @@ public class MetaListLikePreprocessor extends MetaPreprocessor<Meta> {
|
||||
|
||||
if(!(metaValue instanceof List)) {
|
||||
throw new LoadException(
|
||||
"Meta list / set injection (via <<) must point to a list. '" + meta + "' points to type " +
|
||||
metaValue.getClass().getCanonicalName(),
|
||||
"Meta list / set injection (via <<) must point to a list. '" + meta + "' points to " + describe(metaValue),
|
||||
depthTracker);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ public class MetaMapPreprocessor extends MetaPreprocessor<Meta> {
|
||||
Object meta = pair.getRight();
|
||||
if(!(meta instanceof Map)) {
|
||||
throw new LoadException(
|
||||
"MetaMap injection candidate must be list, is type " + meta.getClass().getCanonicalName(),
|
||||
"MetaMap injection candidate must be map, is " + describe(meta),
|
||||
depthTracker);
|
||||
}
|
||||
newMap.putAll((Map<?, ?>) meta);
|
||||
|
||||
+15
-4
@@ -35,8 +35,13 @@ public abstract class MetaPreprocessor<A extends Annotation> implements ValuePre
|
||||
this.configs = configs;
|
||||
}
|
||||
|
||||
protected static String describe(Object value) {
|
||||
return value == null ? "null" : "type " + value.getClass().getCanonicalName();
|
||||
}
|
||||
|
||||
protected Pair<Configuration, Object> getMetaValue(String meta, DepthTracker depthTracker) {
|
||||
int sep = meta.indexOf(':');
|
||||
if(sep < 0) throw new LoadException("meta reference \"" + meta + "\" must have the form file:key", depthTracker);
|
||||
String file = meta.substring(0, sep);
|
||||
String key = meta.substring(sep + 1);
|
||||
|
||||
@@ -44,10 +49,16 @@ public abstract class MetaPreprocessor<A extends Annotation> implements ValuePre
|
||||
|
||||
Configuration config = configs.get(file);
|
||||
|
||||
if(!config.contains(key)) {
|
||||
throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(), depthTracker);
|
||||
try {
|
||||
if(!config.contains(key)) {
|
||||
throw new LoadException("Cannot fetch metavalue: No such key " + key + " in configuration " + config.getName(),
|
||||
depthTracker);
|
||||
}
|
||||
return Pair.of(config, config.get(key));
|
||||
} catch(IllegalArgumentException e) {
|
||||
// Tectonic's key path messages are Java-style.
|
||||
throw new LoadException("meta reference \"" + meta + "\" has an invalid key path: use \\. for a dot in a key and \\\\ "
|
||||
+ "for a backslash", e, depthTracker);
|
||||
}
|
||||
|
||||
return Pair.of(config, config.get(key));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -43,8 +43,8 @@ public class MetaStringPreprocessor extends MetaPreprocessor<Meta> {
|
||||
StringSubstitutor substitutor = new StringSubstitutor(key -> {
|
||||
Object meta = getMetaValue(key, depthTracker).getRight();
|
||||
if(!(meta instanceof String) && !(meta instanceof Number) && !(meta instanceof Character) && !(meta instanceof Boolean)) {
|
||||
throw new LoadException("MetaString template injection candidate must be string or primitive, is type " +
|
||||
meta.getClass().getCanonicalName(), depthTracker);
|
||||
throw new LoadException("MetaString template injection candidate must be string or primitive, is " + describe(meta),
|
||||
depthTracker);
|
||||
}
|
||||
return meta.toString();
|
||||
});
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.RawValue;
|
||||
|
||||
|
||||
final class AttributeCodecsImpl implements AttributeCodecs {
|
||||
static final AttributeCodecsImpl INSTANCE = new AttributeCodecsImpl();
|
||||
|
||||
private AttributeCodecsImpl() { }
|
||||
|
||||
@Override
|
||||
public <T> AttributeCodec<T> of(Decoder<T> decoder, Encoder<T> encoder) {
|
||||
return ValueDecoders.codec(decoder, encoder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String describe(@Nullable Object value) {
|
||||
return ValueDecoders.got(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Boolean> booleanCodec() {
|
||||
return ValueDecoders.BOOLEAN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Float> floatCodec() {
|
||||
return ValueDecoders.FLOAT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Double> doubleCodec() {
|
||||
return ValueDecoders.DOUBLE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Integer> intCodec() {
|
||||
return ValueDecoders.INT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Integer> nonNegativeInt() {
|
||||
return ValueDecoders.NON_NEGATIVE_INT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Float> unitFloat() {
|
||||
return ValueDecoders.UNIT_FLOAT;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<String> string(String expected) {
|
||||
return ValueDecoders.string(expected);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<RawValue> raw() {
|
||||
return ValueDecoders.RAW;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> AttributeCodec<List<V>> list(AttributeCodec<V> element) {
|
||||
return ValueDecoders.list(element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> AttributeCodec<List<V>> compactList(AttributeCodec<V> element) {
|
||||
return ValueDecoders.compactList(element);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Enum<E> & StringIdentifiable> AttributeCodec<E> enumCodec(String name, Class<E> type) {
|
||||
return ValueDecoders.identifiableEnum(name, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<RegistryKey> identifier(String defaultNamespace) {
|
||||
return ValueDecoders.identifier(defaultNamespace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag(String defaultNamespace) {
|
||||
return ValueDecoders.identifierOrTag(defaultNamespace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException {
|
||||
return new ValueDecoders.Fields(what, raw, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ObjectWriter writer() {
|
||||
return new ValueDecoders.Encoded();
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.properties.Context;
|
||||
import com.dfsek.terra.api.properties.Properties;
|
||||
import com.dfsek.terra.api.properties.PropertyKey;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeLookup;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
|
||||
import com.dfsek.terra.world.attribute.format.EntryFormat;
|
||||
import com.dfsek.terra.world.attribute.format.ScheduleFormat;
|
||||
|
||||
|
||||
/**
|
||||
* Create one per platform, at construction: {@link Context#create} is not thread safe.
|
||||
*/
|
||||
public final class AttributeHandleImpl implements AttributeHandle {
|
||||
private final PropertyKey<PackAttributes> packKey = Context.create(PackAttributes.class);
|
||||
private final AtomicInteger attributeIndices = new AtomicInteger();
|
||||
|
||||
private static <T extends Properties> Optional<T> read(Context context, PropertyKey<T> key) {
|
||||
if(!context.has(key)) return Optional.empty();
|
||||
return Optional.ofNullable(context.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeTypes types() {
|
||||
return AttributeTypesImpl.INSTANCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeCodecs codecs() {
|
||||
return AttributeCodecsImpl.INSTANCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DecodeContext plainContext() {
|
||||
return PlainDecodeContext.INSTANCE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> AttributeType.Builder<T> typeBuilder(String id, AttributeCodec<T> codec) {
|
||||
return AttributeTypeImpl.builder(id, codec);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Attribute.Builder<T> attributeBuilder(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue) {
|
||||
return AttributeImpl.builder(key, type, defaultValue, attributeIndices);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int attributeCount() {
|
||||
return attributeIndices.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
@SafeVarargs
|
||||
@SuppressWarnings("varargs")
|
||||
public final <T> @Nullable T resolve(Attribute<T> attribute, AttributeEntry<T>... layersBottomToTop) {
|
||||
return AttributeLayers.resolve(attribute, layersBottomToTop);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolve(Attribute<T> attribute, @Nullable AttributeEntry<T> first, @Nullable AttributeEntry<T> second,
|
||||
@Nullable AttributeEntry<T> third) {
|
||||
return AttributeLayers.resolve(attribute, first, second, third, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolve(Attribute<T> attribute, @Nullable AttributeEntry<T> first, @Nullable AttributeEntry<T> second,
|
||||
@Nullable AttributeEntry<T> third, @Nullable AttributeEntry<T> fourth) {
|
||||
return AttributeLayers.resolve(attribute, first, second, third, fourth);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> Optional<AttributeEntry<T>> compose(Attribute<T> attribute, @Nullable AttributeEntry<T> lower,
|
||||
@Nullable AttributeEntry<T> upper) {
|
||||
if(lower == null) return Optional.ofNullable(upper);
|
||||
if(upper == null) return Optional.of(lower);
|
||||
if(upper.isOverride()) return Optional.of(upper);
|
||||
if(lower.isOverride()) {
|
||||
T value = (T) lower.argument();
|
||||
if(value == null) return Optional.of(lower);
|
||||
return Optional.of(AttributeEntry.override(upper.apply(attribute.type(), value)));
|
||||
}
|
||||
Operation op = upper.operation();
|
||||
if(op != lower.operation()) return Optional.empty();
|
||||
return attribute.type().compose(op, lower.argument(), upper.argument()).map(argument -> AttributeEntry.of(op, argument));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> AttributeEntry<T> decodeEntry(Attribute<T> attribute, @Nullable Object raw, DecodeContext context)
|
||||
throws DecodeException {
|
||||
return EntryFormat.decode(attribute, raw, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Object encodeEntry(Attribute<T> attribute, AttributeEntry<T> entry) {
|
||||
return EntryFormat.encode(attribute, entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ScheduleDecodeResult decodeSchedule(RegistryKey id, Map<String, Object> raw, AttributeLookup attributes,
|
||||
DecodeContext context) {
|
||||
return ScheduleFormat.decode(id, raw, attributes, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> encodeSchedule(AttributeSchedule schedule) {
|
||||
return ScheduleFormat.encode(schedule);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PackAttributes> pack(ConfigPack pack) {
|
||||
return read(pack.getContext(), packKey);
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeScope;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
final class AttributeImpl<T> implements Attribute<T> {
|
||||
private final AttributeKey<T> key;
|
||||
private final AttributeType<T> type;
|
||||
private final @Nullable T defaultValue;
|
||||
private final AttributeScope scope;
|
||||
private final boolean ranged;
|
||||
private final double min;
|
||||
private final double max;
|
||||
private final int multipleOf;
|
||||
private final int index;
|
||||
|
||||
private AttributeImpl(Builder<T> builder, int index) {
|
||||
this.key = builder.key;
|
||||
this.type = builder.type;
|
||||
this.defaultValue = builder.defaultValue;
|
||||
this.scope = builder.scope;
|
||||
this.ranged = builder.ranged;
|
||||
this.min = builder.min;
|
||||
this.max = builder.max;
|
||||
this.multipleOf = builder.multipleOf;
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
static <T> Builder<T> builder(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue, AtomicInteger indices) {
|
||||
return new Builder<>(key, type, defaultValue, indices);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeKey<T> key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<T> type() {
|
||||
return type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable T defaultValue() {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeScope scope() {
|
||||
return scope;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int index() {
|
||||
return index;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T validate(T value) throws DecodeException {
|
||||
if(value instanceof Number number) {
|
||||
if(ranged && !inRange(number)) {
|
||||
throw new DecodeException("value " + value + " is outside " + rangeString());
|
||||
}
|
||||
if(multipleOf > 1 && number.intValue() % multipleOf != 0) {
|
||||
throw new DecodeException("value " + value + " is not a multiple of " + multipleOf);
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public T sanitize(T value) {
|
||||
if(!ranged) return value;
|
||||
if(value instanceof Float f) {
|
||||
if(f.isNaN()) return value;
|
||||
return (T) Float.valueOf(Math.max((float) min, Math.min((float) max, f)));
|
||||
}
|
||||
if(value instanceof Integer i) {
|
||||
return (T) Integer.valueOf((int) Math.max(min, Math.min(max, i)));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private boolean inRange(Number number) {
|
||||
if(number instanceof Float f) return f >= (float) min && f <= (float) max;
|
||||
double d = number.doubleValue();
|
||||
return d >= min && d <= max;
|
||||
}
|
||||
|
||||
private String rangeString() {
|
||||
String upper = Double.isInfinite(max) ? "∞)" : format(max) + "]";
|
||||
return "[" + format(min) + ", " + upper;
|
||||
}
|
||||
|
||||
private static String format(double d) {
|
||||
if(d == Math.rint(d) && Math.abs(d) < 1e15) return Long.toString((long) d);
|
||||
return Double.toString(d);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Attribute[" + key + "]";
|
||||
}
|
||||
|
||||
|
||||
static final class Builder<T> implements Attribute.Builder<T> {
|
||||
private final AttributeKey<T> key;
|
||||
private final AttributeType<T> type;
|
||||
private final @Nullable T defaultValue;
|
||||
private final AtomicInteger indices;
|
||||
private AttributeScope scope = AttributeScope.ANYWHERE;
|
||||
private boolean ranged;
|
||||
private double min;
|
||||
private double max;
|
||||
private int multipleOf = 1;
|
||||
|
||||
private Builder(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue, AtomicInteger indices) {
|
||||
this.key = Objects.requireNonNull(key, "key");
|
||||
this.type = Objects.requireNonNull(type, "type");
|
||||
this.defaultValue = defaultValue;
|
||||
this.indices = indices;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder<T> range(Number min, Number max) {
|
||||
this.ranged = true;
|
||||
this.min = min.doubleValue();
|
||||
this.max = max.doubleValue();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder<T> multipleOf(int multipleOf) {
|
||||
this.multipleOf = multipleOf;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder<T> packOnly() {
|
||||
this.scope = AttributeScope.PACK_ONLY;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attribute<T> build() {
|
||||
return new AttributeImpl<>(this, indices.getAndIncrement());
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
|
||||
|
||||
final class AttributeLayers {
|
||||
private AttributeLayers() { }
|
||||
|
||||
@SafeVarargs
|
||||
static <T> @Nullable T resolve(Attribute<T> attribute, AttributeEntry<T>... layersBottomToTop) {
|
||||
T value = attribute.defaultValue();
|
||||
boolean applied = false;
|
||||
for(AttributeEntry<T> entry : layersBottomToTop) {
|
||||
if(entry == null) continue;
|
||||
if(value == null) {
|
||||
if(!entry.isOverride()) continue;
|
||||
value = entry.apply(attribute.type(), null);
|
||||
} else {
|
||||
value = entry.apply(attribute.type(), value);
|
||||
}
|
||||
applied = true;
|
||||
}
|
||||
if(value == null || !applied) return value;
|
||||
return attribute.sanitize(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unrolled to allocate nothing.
|
||||
*/
|
||||
static <T> @Nullable T resolve(Attribute<T> attribute, @Nullable AttributeEntry<T> first, @Nullable AttributeEntry<T> second,
|
||||
@Nullable AttributeEntry<T> third, @Nullable AttributeEntry<T> fourth) {
|
||||
T value = attribute.defaultValue();
|
||||
boolean applied = false;
|
||||
if(applies(value, first)) {
|
||||
value = first.apply(attribute.type(), value);
|
||||
applied = true;
|
||||
}
|
||||
if(applies(value, second)) {
|
||||
value = second.apply(attribute.type(), value);
|
||||
applied = true;
|
||||
}
|
||||
if(applies(value, third)) {
|
||||
value = third.apply(attribute.type(), value);
|
||||
applied = true;
|
||||
}
|
||||
if(applies(value, fourth)) {
|
||||
value = fourth.apply(attribute.type(), value);
|
||||
applied = true;
|
||||
}
|
||||
if(value == null || !applied) return value;
|
||||
return attribute.sanitize(value);
|
||||
}
|
||||
|
||||
private static <T> boolean applies(@Nullable T value, @Nullable AttributeEntry<T> entry) {
|
||||
return entry != null && (value != null || entry.isOverride());
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.BinaryOperator;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeModifier;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
|
||||
|
||||
final class AttributeTypeImpl<T> implements AttributeType<T> {
|
||||
private record Op<T>(AttributeCodec<Object> argumentCodec, AttributeModifier<T, Object> modifier,
|
||||
@Nullable BinaryOperator<Object> composer) {
|
||||
Op<T> withComposer(BinaryOperator<Object> composer) {
|
||||
return new Op<>(argumentCodec, modifier, composer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final Operation[] OPERATIONS = Operation.values();
|
||||
|
||||
private final String id;
|
||||
private final AttributeCodec<T> codec;
|
||||
private final Op<T>[] ops;
|
||||
private final Set<Operation> operations;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AttributeTypeImpl(String id, AttributeCodec<T> codec, Map<Operation, Op<T>> ops) {
|
||||
this.id = id;
|
||||
this.codec = codec;
|
||||
this.ops = (Op<T>[]) new Op<?>[OPERATIONS.length];
|
||||
ops.forEach((op, o) -> this.ops[op.ordinal()] = o);
|
||||
this.operations = Collections.unmodifiableSet(EnumSet.copyOf(ops.keySet()));
|
||||
}
|
||||
|
||||
static <T> Builder<T> builder(String id, AttributeCodec<T> codec) {
|
||||
return new Builder<>(id, codec);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Operation> operations() {
|
||||
return operations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T decode(Object raw, DecodeContext context) throws DecodeException {
|
||||
return codec.decode(raw, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encode(T value) {
|
||||
return codec.encode(value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException {
|
||||
Op<T> o = ops[op.ordinal()];
|
||||
if(o == null) throw new DecodeException(invalid(op));
|
||||
return o.argumentCodec().decode(raw, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encodeArgument(Operation op, Object argument) {
|
||||
return op(op).argumentCodec().encode(argument);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T apply(Operation op, T subject, Object argument) {
|
||||
return op(op).modifier().apply(subject, argument);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Object> compose(Operation op, Object lower, Object upper) {
|
||||
Op<T> o = ops[op.ordinal()];
|
||||
if(o == null || o.composer() == null) return Optional.empty();
|
||||
Object composed = o.composer().apply(lower, upper);
|
||||
if(composed == null) throw new NullPointerException("composer for " + op.getID() + " of " + id + " returned null");
|
||||
return Optional.of(composed);
|
||||
}
|
||||
|
||||
private Op<T> op(Operation op) {
|
||||
Op<T> o = ops[op.ordinal()];
|
||||
if(o == null) throw new IllegalArgumentException(invalid(op));
|
||||
return o;
|
||||
}
|
||||
|
||||
private String invalid(Operation op) {
|
||||
return "modifier " + op.getID() + " is not valid for " + id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AttributeType[" + id + "]";
|
||||
}
|
||||
|
||||
|
||||
static final class Builder<T> implements AttributeType.Builder<T> {
|
||||
private final String id;
|
||||
private final AttributeCodec<T> codec;
|
||||
private final Map<Operation, Op<T>> ops = new EnumMap<>(Operation.class);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Builder(String id, AttributeCodec<T> codec) {
|
||||
this.id = Objects.requireNonNull(id, "id");
|
||||
this.codec = Objects.requireNonNull(codec, "codec");
|
||||
ops.put(Operation.OVERRIDE, new Op<>((AttributeCodec<Object>) codec, (s, a) -> (T) a, null));
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <A> Builder<T> op(Operation op, AttributeCodec<A> argumentCodec, AttributeModifier<T, A> modifier) {
|
||||
if(op == Operation.OVERRIDE) {
|
||||
throw new IllegalArgumentException("modifier override cannot be replaced");
|
||||
}
|
||||
Objects.requireNonNull(argumentCodec, "argumentCodec");
|
||||
Objects.requireNonNull(modifier, "modifier");
|
||||
ops.put(op, new Op<>((AttributeCodec<Object>) argumentCodec, (s, a) -> modifier.apply(s, (A) a), null));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <A> Builder<T> composable(Operation op, BinaryOperator<A> combine) {
|
||||
if(op == Operation.OVERRIDE) {
|
||||
throw new IllegalArgumentException("modifier override cannot be composed");
|
||||
}
|
||||
Objects.requireNonNull(combine, "combine");
|
||||
Op<T> o = ops.get(op);
|
||||
if(o == null) throw new IllegalArgumentException("modifier " + op.getID() + " must be added before it is made composable");
|
||||
ops.put(op, o.withComposer((a, b) -> combine.apply((A) a, (A) b)));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<T> build() {
|
||||
return new AttributeTypeImpl<>(id, codec, ops);
|
||||
}
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.world.attribute.value.BlendToGray;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.api.world.attribute.value.TriState;
|
||||
|
||||
|
||||
final class AttributeTypesImpl implements AttributeTypes {
|
||||
static final AttributeTypesImpl INSTANCE = new AttributeTypesImpl();
|
||||
|
||||
private final AttributeType<Boolean> booleanType = AttributeTypeImpl.builder("boolean", ValueDecoders.BOOLEAN)
|
||||
.op(Operation.AND, ValueDecoders.BOOLEAN, (s, a) -> a && s)
|
||||
.op(Operation.NAND, ValueDecoders.BOOLEAN, (s, a) -> !a || !s)
|
||||
.op(Operation.OR, ValueDecoders.BOOLEAN, (s, a) -> a || s)
|
||||
.op(Operation.NOR, ValueDecoders.BOOLEAN, (s, a) -> !a && !s)
|
||||
.op(Operation.XOR, ValueDecoders.BOOLEAN, (s, a) -> a ^ s)
|
||||
.op(Operation.XNOR, ValueDecoders.BOOLEAN, (s, a) -> a == s)
|
||||
.build();
|
||||
|
||||
private final AttributeType<TriState> triState = AttributeTypeImpl.builder("tri_state", ValueDecoders.TRI_STATE).build();
|
||||
|
||||
private final AttributeType<Float> floatType = floatType("float");
|
||||
|
||||
private final AttributeType<Float> angleDegrees = floatType("angle_degrees");
|
||||
|
||||
private final AttributeType<Color> rgbColor = AttributeTypeImpl.builder("rgb_color", ValueDecoders.RGB)
|
||||
.op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::rgbAlphaBlend)
|
||||
.op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f),
|
||||
Math.min(s.b() + a.b(), 1f), 1f))
|
||||
.op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f),
|
||||
Math.max(s.b() - a.b(), 0f), 1f))
|
||||
.op(Operation.MULTIPLY, ValueDecoders.RGB, (s, a) -> multiply(s, a, false))
|
||||
.op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray)
|
||||
.build();
|
||||
|
||||
private final AttributeType<Color> argbColor = AttributeTypeImpl.builder("argb_color", ValueDecoders.ARGB)
|
||||
.op(Operation.ALPHA_BLEND, ValueDecoders.ARGB, AttributeTypesImpl::argbAlphaBlend)
|
||||
.op(Operation.ADD, ValueDecoders.RGB, (s, a) -> new Color(Math.min(s.r() + a.r(), 1f), Math.min(s.g() + a.g(), 1f),
|
||||
Math.min(s.b() + a.b(), 1f), s.a()))
|
||||
.op(Operation.SUBTRACT, ValueDecoders.RGB, (s, a) -> new Color(Math.max(s.r() - a.r(), 0f), Math.max(s.g() - a.g(), 0f),
|
||||
Math.max(s.b() - a.b(), 0f), s.a()))
|
||||
.op(Operation.MULTIPLY, ValueDecoders.ARGB, (s, a) -> multiply(s, a, true))
|
||||
.op(Operation.BLEND_TO_GRAY, ValueDecoders.BLEND_TO_GRAY, AttributeTypesImpl::blendToGray)
|
||||
.build();
|
||||
|
||||
private final AttributeType<Integer> integer = integerType("integer");
|
||||
|
||||
private final AttributeType<Integer> integerOverrideOnly = AttributeTypeImpl.builder("integer_override_only", ValueDecoders.INT)
|
||||
.build();
|
||||
|
||||
private final Map<String, AttributeType<RegistryKey>> identifiers = new ConcurrentHashMap<>();
|
||||
|
||||
private final Map<String, AttributeType<Either<RegistryKey, TagKey>>> identifiersOrTags = new ConcurrentHashMap<>();
|
||||
|
||||
private AttributeTypesImpl() { }
|
||||
|
||||
@Override
|
||||
public AttributeType<Boolean> booleanType() {
|
||||
return booleanType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<TriState> triState() {
|
||||
return triState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Float> floatType() {
|
||||
return floatType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Float> angleDegrees() {
|
||||
return angleDegrees;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Color> rgbColor() {
|
||||
return rgbColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Color> argbColor() {
|
||||
return argbColor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Integer> integer() {
|
||||
return integer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Integer> integerOverrideOnly() {
|
||||
return integerOverrideOnly;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<RegistryKey> identifier(String defaultNamespace) {
|
||||
return identifiers.computeIfAbsent(defaultNamespace,
|
||||
ns -> AttributeTypeImpl.builder("identifier", ValueDecoders.identifier(ns)).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeType<Either<RegistryKey, TagKey>> identifierOrTag(String defaultNamespace) {
|
||||
return identifiersOrTags.computeIfAbsent(defaultNamespace,
|
||||
ns -> AttributeTypeImpl.builder("identifier_or_tag", ValueDecoders.identifierOrTag(ns)).build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <E extends Enum<E> & StringIdentifiable> AttributeType<E> enumType(String id, Class<E> type) {
|
||||
return AttributeTypeImpl.builder(id, ValueDecoders.identifiableEnum(id.replace('_', ' '), type)).build();
|
||||
}
|
||||
|
||||
private static AttributeType<Float> floatType(String id) {
|
||||
return AttributeTypeImpl.builder(id, ValueDecoders.FLOAT)
|
||||
.op(Operation.ALPHA_BLEND, ValueDecoders.FLOAT_WITH_ALPHA, (s, a) -> s + a.alpha() * (a.value() - s))
|
||||
.op(Operation.ADD, ValueDecoders.FLOAT, (s, a) -> s + a)
|
||||
.op(Operation.SUBTRACT, ValueDecoders.FLOAT, (s, a) -> s - a)
|
||||
.op(Operation.MULTIPLY, ValueDecoders.FLOAT, (s, a) -> s * a)
|
||||
.op(Operation.MINIMUM, ValueDecoders.FLOAT, (s, a) -> Math.min(s, a))
|
||||
.op(Operation.MAXIMUM, ValueDecoders.FLOAT, (s, a) -> Math.max(s, a))
|
||||
.composable(Operation.ADD, Float::sum)
|
||||
.<Float>composable(Operation.MULTIPLY, (a, b) -> a * b)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static AttributeType<Integer> integerType(String id) {
|
||||
return AttributeTypeImpl.builder(id, ValueDecoders.INT)
|
||||
.op(Operation.ADD, ValueDecoders.INT, (s, a) -> s + a)
|
||||
.op(Operation.SUBTRACT, ValueDecoders.INT, (s, a) -> s - a)
|
||||
.op(Operation.MULTIPLY, ValueDecoders.INT, (s, a) -> s * a)
|
||||
.op(Operation.MINIMUM, ValueDecoders.INT, (s, a) -> Math.min(s, a))
|
||||
.op(Operation.MAXIMUM, ValueDecoders.INT, (s, a) -> Math.max(s, a))
|
||||
.composable(Operation.ADD, Integer::sum)
|
||||
.<Integer>composable(Operation.MULTIPLY, (a, b) -> a * b)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static float lerp(float t, float from, float to) {
|
||||
return from + t * (to - from);
|
||||
}
|
||||
|
||||
private static float clamp01(float v) {
|
||||
return Math.max(0f, Math.min(1f, v));
|
||||
}
|
||||
|
||||
private static boolean white(Color c, boolean withAlpha) {
|
||||
return c.r() == 1f && c.g() == 1f && c.b() == 1f && (!withAlpha || c.a() == 1f);
|
||||
}
|
||||
|
||||
private static Color multiply(Color s, Color a, boolean withAlpha) {
|
||||
if(white(s, withAlpha)) return a;
|
||||
if(white(a, withAlpha)) return s;
|
||||
return new Color(s.r() * a.r(), s.g() * a.g(), s.b() * a.b(), withAlpha ? s.a() * a.a() : 1f);
|
||||
}
|
||||
|
||||
private static Color rgbAlphaBlend(Color dst, Color src) {
|
||||
if(src.a() == 0f) return dst;
|
||||
return new Color(lerp(src.a(), dst.r(), src.r()), lerp(src.a(), dst.g(), src.g()), lerp(src.a(), dst.b(), src.b()), 1f);
|
||||
}
|
||||
|
||||
private static Color argbAlphaBlend(Color dst, Color src) {
|
||||
float sa = src.a();
|
||||
if(sa == 1f) return src;
|
||||
if(sa == 0f) return dst;
|
||||
float a = sa + dst.a() * (1f - sa);
|
||||
return new Color((src.r() * sa + dst.r() * (a - sa)) / a, (src.g() * sa + dst.g() * (a - sa)) / a,
|
||||
(src.b() * sa + dst.b() * (a - sa)) / a, a);
|
||||
}
|
||||
|
||||
private static Color blendToGray(Color s, BlendToGray arg) {
|
||||
float g = 0.3f * s.r() + 0.59f * s.g() + 0.11f * s.b();
|
||||
float grey = clamp01(g * arg.brightness());
|
||||
return new Color(lerp(arg.factor(), s.r(), grey), lerp(arg.factor(), s.g(), grey), lerp(arg.factor(), s.b(), grey), s.a());
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
import static com.dfsek.terra.world.attribute.ValueDecoders.got;
|
||||
|
||||
|
||||
final class PlainDecodeContext implements DecodeContext {
|
||||
static final PlainDecodeContext INSTANCE = new PlainDecodeContext();
|
||||
|
||||
private PlainDecodeContext() { }
|
||||
|
||||
private static Class<?> rawClass(Type type) {
|
||||
if(type instanceof Class<?> c) return c;
|
||||
if(type instanceof ParameterizedType p && p.getRawType() instanceof Class<?> c) return c;
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(Object raw) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <V> V load(Type type, Object raw) throws DecodeException {
|
||||
Class<?> c = rawClass(type);
|
||||
Object value;
|
||||
if(c == Object.class) value = raw;
|
||||
else if(c == Float.class) value = number(raw).floatValue();
|
||||
else if(c == Double.class) value = number(raw).doubleValue();
|
||||
else if(c == Integer.class) {
|
||||
if(!(raw instanceof Number n)) throw new DecodeException("expected an integer, got " + got(raw));
|
||||
value = ValueDecoders.integer(n, raw);
|
||||
} else if(c == Boolean.class) {
|
||||
if(!(raw instanceof Boolean)) throw new DecodeException("expected a boolean (true or false), got " + got(raw));
|
||||
value = raw;
|
||||
} else if(c == String.class) {
|
||||
if(!(raw instanceof String)) throw new DecodeException("expected a string, got " + got(raw));
|
||||
value = raw;
|
||||
} else if(c == List.class) {
|
||||
if(!(raw instanceof List<?>)) throw new DecodeException("expected a list, got " + got(raw));
|
||||
value = raw;
|
||||
} else if(c == Map.class) {
|
||||
if(!(raw instanceof Map<?, ?>)) throw new DecodeException("expected an object, got " + got(raw));
|
||||
value = raw;
|
||||
} else {
|
||||
throw new DecodeException("cannot load this kind of value");
|
||||
}
|
||||
return (V) value;
|
||||
}
|
||||
|
||||
private static Number number(Object raw) throws DecodeException {
|
||||
if(raw instanceof Number n) return n;
|
||||
throw new DecodeException("expected a number, got " + got(raw));
|
||||
}
|
||||
}
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.util.reflection.TypeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs.Decoder;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs.Encoder;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectWriter;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.RawValue;
|
||||
import com.dfsek.terra.api.world.attribute.value.BlendToGray;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha;
|
||||
import com.dfsek.terra.api.world.attribute.value.TriState;
|
||||
|
||||
|
||||
/**
|
||||
* Colours encode as hex, or as float channels when a channel isn't a multiple of 1/255.
|
||||
*/
|
||||
final class ValueDecoders {
|
||||
private static final Type LIST = new TypeKey<List<Object>>() { }.getType();
|
||||
private static final Type MAP = new TypeKey<Map<String, Object>>() { }.getType();
|
||||
|
||||
private ValueDecoders() { }
|
||||
|
||||
private record Codec<T>(Decoder<T> decoder, Encoder<T> encoder) implements AttributeCodec<T> {
|
||||
@Override
|
||||
public T decode(Object raw, DecodeContext context) throws DecodeException {
|
||||
return decoder.decode(raw, context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encode(T value) {
|
||||
return encoder.encode(value);
|
||||
}
|
||||
}
|
||||
|
||||
static <T> AttributeCodec<T> codec(Decoder<T> decoder, Encoder<T> encoder) {
|
||||
return new Codec<>(decoder, encoder);
|
||||
}
|
||||
|
||||
private static <T> Object identity(T value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
static String got(Object o) {
|
||||
if(o == null) return "nothing";
|
||||
if(o instanceof String s) return "\"" + s + "\"";
|
||||
if(o instanceof Map<?, ?>) return "an object";
|
||||
if(o instanceof List<?>) return "a list";
|
||||
return String.valueOf(o);
|
||||
}
|
||||
|
||||
static int integer(Number n, Object raw) throws DecodeException {
|
||||
if(n instanceof Integer || n instanceof Short || n instanceof Byte) return n.intValue();
|
||||
if(n instanceof Long l) {
|
||||
if(l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) throw new DecodeException("expected an integer, got " + l);
|
||||
return (int) (long) l;
|
||||
}
|
||||
try {
|
||||
return exact(n).intValueExact();
|
||||
} catch(ArithmeticException | NumberFormatException e) {
|
||||
throw new DecodeException("expected an integer, got " + got(raw));
|
||||
}
|
||||
}
|
||||
|
||||
private static BigDecimal exact(Number n) {
|
||||
if(n instanceof BigDecimal d) return d;
|
||||
if(n instanceof BigInteger i) return new BigDecimal(i);
|
||||
if(n instanceof Double || n instanceof Float) {
|
||||
double d = n.doubleValue();
|
||||
if(!Double.isFinite(d)) throw new NumberFormatException();
|
||||
return new BigDecimal(d);
|
||||
}
|
||||
return new BigDecimal(n.toString());
|
||||
}
|
||||
|
||||
private static String string(Object raw, DecodeContext context, String expected) throws DecodeException {
|
||||
Object value = context.resolve(raw);
|
||||
if(!(value instanceof String)) throw new DecodeException(expected + ", got " + got(value));
|
||||
return context.load(String.class, value);
|
||||
}
|
||||
|
||||
static AttributeCodec<String> string(String expected) {
|
||||
return codec((raw, context) -> string(raw, context, expected), ValueDecoders::identity);
|
||||
}
|
||||
|
||||
private static List<?> loadList(Object raw, DecodeContext context, String expected) throws DecodeException {
|
||||
Object value = context.resolve(raw);
|
||||
try {
|
||||
return context.load(LIST, value);
|
||||
} catch(DecodeException e) {
|
||||
if(value instanceof List<?>) throw e;
|
||||
throw new DecodeException(expected + ", got " + got(value), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<?, ?> loadMap(Object raw, DecodeContext context, String expected) throws DecodeException {
|
||||
Object value = context.resolve(raw);
|
||||
try {
|
||||
return context.load(MAP, value);
|
||||
} catch(DecodeException e) {
|
||||
if(value instanceof Map<?, ?>) throw e;
|
||||
throw new DecodeException(expected + ", got " + got(value), e);
|
||||
}
|
||||
}
|
||||
|
||||
static final AttributeCodec<Boolean> BOOLEAN = codec((raw, context) -> context.load(Boolean.class, raw), ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<Float> FLOAT = codec((raw, context) -> context.load(Float.class, raw), ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<Double> DOUBLE = codec((raw, context) -> context.load(Double.class, raw), ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<Integer> INT = codec((raw, context) -> {
|
||||
Object value = context.resolve(raw);
|
||||
if(value instanceof Number n) integer(n, value);
|
||||
return context.load(Integer.class, value);
|
||||
}, ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<Integer> NON_NEGATIVE_INT = codec((raw, context) -> {
|
||||
int i = INT.decode(raw, context);
|
||||
if(i < 0) throw new DecodeException("expected a non-negative integer, got " + i);
|
||||
return i;
|
||||
}, ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<Float> UNIT_FLOAT = codec((raw, context) -> {
|
||||
float f = FLOAT.decode(raw, context);
|
||||
if(!(f >= 0f && f <= 1f)) throw new DecodeException("value " + f + " is outside [0, 1]");
|
||||
return f;
|
||||
}, ValueDecoders::identity);
|
||||
|
||||
static final AttributeCodec<RawValue> RAW = codec((raw, context) -> {
|
||||
Object value = context.resolve(raw);
|
||||
try {
|
||||
return new RawValue(value);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException(e.getMessage(), e);
|
||||
}
|
||||
}, RawValue::value);
|
||||
|
||||
private static String expectedIdentifier(String defaultNamespace) {
|
||||
return "expected an identifier like \"" + defaultNamespace + ":id\"";
|
||||
}
|
||||
|
||||
static AttributeCodec<RegistryKey> identifier(String defaultNamespace) {
|
||||
String expected = expectedIdentifier(defaultNamespace);
|
||||
return codec((raw, context) -> {
|
||||
String s = string(raw, context, expected);
|
||||
if(s.startsWith("#")) throw new DecodeException("expected an identifier, not a tag, got " + got(s));
|
||||
try {
|
||||
return RegistryKey.parse(s, defaultNamespace);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException(expected + ", got " + got(s), e);
|
||||
}
|
||||
}, RegistryKey::toString);
|
||||
}
|
||||
|
||||
static AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag(String defaultNamespace) {
|
||||
String expected = expectedIdentifier(defaultNamespace);
|
||||
return codec((raw, context) -> {
|
||||
String s = string(raw, context, expected);
|
||||
try {
|
||||
if(s.startsWith("#")) return Either.right(TagKey.parse(s, defaultNamespace));
|
||||
return Either.left(RegistryKey.parse(s, defaultNamespace));
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException(expected + ", got " + got(s), e);
|
||||
}
|
||||
}, either -> either.hasLeft() ? either.getLeft().orElseThrow().toString() : either.getRight().orElseThrow().toString());
|
||||
}
|
||||
|
||||
private static Object colorParts(Object value, DecodeContext context) throws DecodeException {
|
||||
if(value instanceof String) return context.load(String.class, value);
|
||||
if(value instanceof Number) return context.load(Double.class, value);
|
||||
if(value instanceof List<?>) {
|
||||
List<?> channels = context.load(LIST, value);
|
||||
List<Object> out = new ArrayList<>(channels.size());
|
||||
for(Object channel : channels) out.add(context.load(Float.class, channel));
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static boolean hexExact(float channel) {
|
||||
return channel >= 0f && channel <= 1f && Math.round(channel * 255) / 255f == channel;
|
||||
}
|
||||
|
||||
static final AttributeCodec<Color> RGB = codec((raw, context) -> {
|
||||
Object value = context.resolve(raw);
|
||||
try {
|
||||
return Color.parseRgb(colorParts(value, context));
|
||||
} catch(IllegalArgumentException | DecodeException e) {
|
||||
throw new DecodeException("expected a color like \"#rrggbb\", got " + got(value), e);
|
||||
}
|
||||
}, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b())
|
||||
? String.format(Locale.ROOT, "#%06x", color.toRgbInt())
|
||||
: List.of(color.r(), color.g(), color.b()));
|
||||
|
||||
static final AttributeCodec<Color> ARGB = codec((raw, context) -> {
|
||||
Object value = context.resolve(raw);
|
||||
try {
|
||||
return Color.parseArgb(colorParts(value, context));
|
||||
} catch(IllegalArgumentException | DecodeException e) {
|
||||
throw new DecodeException("expected a color like \"#aarrggbb\", got " + got(value), e);
|
||||
}
|
||||
}, color -> hexExact(color.r()) && hexExact(color.g()) && hexExact(color.b()) && hexExact(color.a())
|
||||
? String.format(Locale.ROOT, "#%08x", color.toArgbInt())
|
||||
: List.of(color.r(), color.g(), color.b(), color.a()));
|
||||
|
||||
@FunctionalInterface
|
||||
interface Parser<E> {
|
||||
E parse(String name);
|
||||
}
|
||||
|
||||
static <E> AttributeCodec<E> stringEnum(String what, Parser<E> parser, Encoder<E> encoder) {
|
||||
return codec((raw, context) -> {
|
||||
String s = string(raw, context, "expected a " + what + " name");
|
||||
try {
|
||||
return parser.parse(s);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException(e.getMessage(), e);
|
||||
}
|
||||
}, encoder);
|
||||
}
|
||||
|
||||
static <E extends Enum<E> & StringIdentifiable> AttributeCodec<E> identifiableEnum(String what, Class<E> type) {
|
||||
Map<String, E> byId = new LinkedHashMap<>();
|
||||
for(E constant : type.getEnumConstants()) {
|
||||
E previous = byId.put(constant.getID(), constant);
|
||||
if(previous != null) {
|
||||
throw new IllegalArgumentException(type.getCanonicalName() + " constants " + previous + " and " + constant
|
||||
+ " share the ID \"" + constant.getID() + "\"");
|
||||
}
|
||||
}
|
||||
Map<String, E> ids = Collections.unmodifiableMap(byId);
|
||||
return stringEnum(what, name -> {
|
||||
E value = ids.get(name);
|
||||
if(value == null) throw new IllegalArgumentException("unknown " + what + " \"" + name + "\", expected one of " + ids.keySet());
|
||||
return value;
|
||||
}, StringIdentifiable::getID);
|
||||
}
|
||||
|
||||
static final AttributeCodec<TriState> TRI_STATE = triState(identifiableEnum("tri-state", TriState.class));
|
||||
|
||||
private static AttributeCodec<TriState> triState(AttributeCodec<TriState> byId) {
|
||||
return codec((raw, context) -> {
|
||||
Object resolved = context.resolve(raw);
|
||||
if(resolved instanceof Boolean) return context.<Boolean>load(Boolean.class, resolved) ? TriState.TRUE : TriState.FALSE;
|
||||
if(resolved instanceof String) return byId.decode(resolved, context);
|
||||
throw new DecodeException("expected true, false or a tri-state name (\"true\", \"false\", \"default\"), got " + got(resolved));
|
||||
}, value -> switch(value) {
|
||||
case TRUE -> true;
|
||||
case FALSE -> false;
|
||||
case DEFAULT -> byId.encode(value);
|
||||
});
|
||||
}
|
||||
|
||||
static final class Fields implements ObjectReader {
|
||||
private final String what;
|
||||
private final DecodeContext context;
|
||||
private final Map<String, Object> map;
|
||||
private final Set<String> used = new LinkedHashSet<>();
|
||||
|
||||
Fields(String what, Object raw, DecodeContext context) throws DecodeException {
|
||||
this.what = what;
|
||||
this.context = context;
|
||||
Map<?, ?> m = loadMap(raw, context, "expected an object for " + what);
|
||||
Map<String, Object> copy = new LinkedHashMap<>();
|
||||
for(Map.Entry<?, ?> e : m.entrySet()) {
|
||||
if(!(e.getKey() instanceof String k)) {
|
||||
throw new DecodeException("keys of " + what + " must be strings, got " + got(e.getKey()));
|
||||
}
|
||||
copy.put(k, e.getValue());
|
||||
}
|
||||
this.map = copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> keys() {
|
||||
return List.copyOf(map.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> V required(String key, AttributeCodec<V> codec) throws DecodeException {
|
||||
if(!map.containsKey(key)) throw new DecodeException(what + " is missing required key \"" + key + "\"");
|
||||
return read(key, codec);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> Optional<V> optional(String key, AttributeCodec<V> codec) throws DecodeException {
|
||||
if(!map.containsKey(key)) return Optional.empty();
|
||||
return Optional.of(read(key, codec));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> V orDefault(String key, AttributeCodec<V> codec, V fallback) throws DecodeException {
|
||||
if(!map.containsKey(key)) return fallback;
|
||||
return read(key, codec);
|
||||
}
|
||||
|
||||
private <V> V read(String key, AttributeCodec<V> codec) throws DecodeException {
|
||||
used.add(key);
|
||||
try {
|
||||
return codec.decode(map.get(key), context);
|
||||
} catch(DecodeException e) {
|
||||
throw new DecodeException("\"" + key + "\" of " + what + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish() throws DecodeException {
|
||||
for(String k : map.keySet()) {
|
||||
if(!used.contains(k)) throw new DecodeException("unknown key \"" + k + "\" in " + what);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static final class Encoded implements ObjectWriter {
|
||||
private final Map<String, Object> map = new LinkedHashMap<>();
|
||||
|
||||
@Override
|
||||
public <V> Encoded put(String key, AttributeCodec<V> codec, V value) {
|
||||
map.put(key, codec.encode(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> Encoded optional(String key, AttributeCodec<V> codec, Optional<V> value) {
|
||||
value.ifPresent(v -> map.put(key, codec.encode(v)));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> map() {
|
||||
return map;
|
||||
}
|
||||
}
|
||||
|
||||
static <V> AttributeCodec<List<V>> list(AttributeCodec<V> element) {
|
||||
return codec((raw, context) -> {
|
||||
List<?> l = loadList(raw, context, "expected a list");
|
||||
List<V> out = new ArrayList<>(l.size());
|
||||
for(int i = 0; i < l.size(); i++) {
|
||||
try {
|
||||
out.add(element.decode(l.get(i), context));
|
||||
} catch(DecodeException e) {
|
||||
throw new DecodeException("element " + i + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
return Collections.unmodifiableList(out);
|
||||
}, values -> {
|
||||
List<Object> out = new ArrayList<>(values.size());
|
||||
for(V value : values) out.add(element.encode(value));
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
static <V> AttributeCodec<List<V>> compactList(AttributeCodec<V> element) {
|
||||
AttributeCodec<List<V>> asList = list(element);
|
||||
return codec((raw, context) -> {
|
||||
Object value = context.resolve(raw);
|
||||
return value instanceof List<?> ? asList.decode(value, context) : List.of(element.decode(value, context));
|
||||
}, asList::encode);
|
||||
}
|
||||
|
||||
static final AttributeCodec<FloatWithAlpha> FLOAT_WITH_ALPHA = codec((raw, context) -> {
|
||||
Object resolved = context.resolve(raw);
|
||||
if(resolved instanceof Map<?, ?>) {
|
||||
Fields f = new Fields("alpha_blend argument", resolved, context);
|
||||
float value = f.required("value", FLOAT);
|
||||
float alpha = f.orDefault("alpha", UNIT_FLOAT, 1f);
|
||||
f.finish();
|
||||
return new FloatWithAlpha(value, alpha);
|
||||
}
|
||||
try {
|
||||
return new FloatWithAlpha(FLOAT.decode(resolved, context), 1f);
|
||||
} catch(DecodeException e) {
|
||||
throw new DecodeException("expected a number or a {value, alpha} object, got " + got(resolved), e);
|
||||
}
|
||||
}, value -> new Encoded()
|
||||
.put("value", FLOAT, value.value())
|
||||
.put("alpha", UNIT_FLOAT, value.alpha())
|
||||
.map());
|
||||
|
||||
static final AttributeCodec<BlendToGray> BLEND_TO_GRAY = codec((raw, context) -> {
|
||||
Fields f = new Fields("blend_to_gray argument", raw, context);
|
||||
float brightness = f.required("brightness", UNIT_FLOAT);
|
||||
float factor = f.required("factor", UNIT_FLOAT);
|
||||
f.finish();
|
||||
return new BlendToGray(brightness, factor);
|
||||
}, value -> new Encoded()
|
||||
.put("brightness", UNIT_FLOAT, value.brightness())
|
||||
.put("factor", UNIT_FLOAT, value.factor())
|
||||
.map());
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.dfsek.terra.world.attribute.format;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
|
||||
|
||||
public final class EntryFormat {
|
||||
private static final String MODIFIER = "modifier";
|
||||
private static final String ARGUMENT = "argument";
|
||||
private static final Set<String> MODIFIER_KEYS = Set.of(MODIFIER, ARGUMENT);
|
||||
|
||||
private EntryFormat() { }
|
||||
|
||||
public static <T> AttributeEntry<T> decode(Attribute<T> attribute, @Nullable Object raw, DecodeContext context)
|
||||
throws DecodeException {
|
||||
if(raw == null) throw new DecodeException("missing value");
|
||||
Object value = context.resolve(raw);
|
||||
if(value == null) throw new DecodeException("missing value");
|
||||
if(value instanceof Map<?, ?> map && map.containsKey(MODIFIER)) {
|
||||
return decodeModifier(attribute, map, context);
|
||||
}
|
||||
return AttributeEntry.override(attribute.validate(attribute.type().decode(value, context)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Object encode(Attribute<T> attribute, AttributeEntry<T> entry) {
|
||||
if(entry.isOverride()) {
|
||||
if(entry.argument() == null) {
|
||||
throw new IllegalArgumentException("a null override has no pack-format form");
|
||||
}
|
||||
return attribute.type().encode((T) entry.argument());
|
||||
}
|
||||
Map<String, Object> encoded = new LinkedHashMap<>();
|
||||
encoded.put(MODIFIER, entry.operation().getID());
|
||||
encoded.put(ARGUMENT, attribute.type().encodeArgument(entry.operation(), entry.argument()));
|
||||
return encoded;
|
||||
}
|
||||
|
||||
private static <T> AttributeEntry<T> decodeModifier(Attribute<T> attribute, Map<?, ?> map, DecodeContext context)
|
||||
throws DecodeException {
|
||||
if(!map.keySet().equals(MODIFIER_KEYS)) {
|
||||
throw new DecodeException("modifier entry must have exactly the keys \"modifier\" and \"argument\"");
|
||||
}
|
||||
Operation operation;
|
||||
try {
|
||||
operation = Operation.parse(context.load(String.class, map.get(MODIFIER)));
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException(e.getMessage(), e);
|
||||
} catch(DecodeException e) {
|
||||
throw new DecodeException("\"modifier\": " + e.getMessage(), e);
|
||||
}
|
||||
if(!attribute.type().operations().contains(operation)) {
|
||||
throw new DecodeException("modifier " + operation.getID() + " is not valid for " + attribute.key());
|
||||
}
|
||||
Object argument = attribute.type().decodeArgument(operation, map.get(ARGUMENT), context);
|
||||
if(argument == null && operation != Operation.OVERRIDE) throw new DecodeException("\"argument\": missing value");
|
||||
if(operation == Operation.OVERRIDE) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T value = (T) argument;
|
||||
attribute.validate(value);
|
||||
}
|
||||
return AttributeEntry.of(operation, argument);
|
||||
}
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
package com.dfsek.terra.world.attribute.format;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeLookup;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Easing;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Keyframe;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
|
||||
|
||||
|
||||
public final class ScheduleFormat {
|
||||
private static final String CLOCK = "clock";
|
||||
private static final String PERIOD_TICKS = "period_ticks";
|
||||
private static final String TIME_MARKERS = "time_markers";
|
||||
private static final String TRACKS = "tracks";
|
||||
private static final String TICKS = "ticks";
|
||||
private static final String SHOW_IN_COMMANDS = "show_in_commands";
|
||||
private static final String MODIFIER = "modifier";
|
||||
private static final String EASE = "ease";
|
||||
private static final String CUBIC_BEZIER = "cubic_bezier";
|
||||
private static final String KEYFRAMES = "keyframes";
|
||||
private static final String VALUE = "value";
|
||||
private static final Easing LINEAR = new Easing.Named("linear");
|
||||
|
||||
private ScheduleFormat() { }
|
||||
|
||||
|
||||
private static final class Invalid extends Exception {
|
||||
Invalid(String message) {
|
||||
super(message, null, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static final class TrackDropped extends Exception {
|
||||
TrackDropped(String message) {
|
||||
super(message, null, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static ScheduleDecodeResult decode(RegistryKey id, Map<String, Object> raw, AttributeLookup attributes,
|
||||
DecodeContext context) {
|
||||
List<Problem> dropped = new ArrayList<>();
|
||||
try {
|
||||
AttributeSchedule schedule = readDefinition(raw, attributes, context, dropped);
|
||||
return new ScheduleDecodeResult(Optional.of(schedule), dropped, Optional.empty());
|
||||
} catch(Invalid e) {
|
||||
return new ScheduleDecodeResult(Optional.empty(), dropped, Optional.of(new Problem(id.toString(), e.getMessage())));
|
||||
}
|
||||
}
|
||||
|
||||
public static Map<String, Object> encode(AttributeSchedule schedule) {
|
||||
Map<String, Object> encoded = new LinkedHashMap<>();
|
||||
encoded.put(CLOCK, schedule.clock().toString());
|
||||
schedule.periodTicks().ifPresent(period -> encoded.put(PERIOD_TICKS, period));
|
||||
if(!schedule.tracks().isEmpty()) {
|
||||
Map<String, Object> tracks = new LinkedHashMap<>();
|
||||
schedule.tracks().forEach((attribute, track) -> tracks.put(attribute.getRegistryKey().toString(), encodeTrack(attribute, track)));
|
||||
encoded.put(TRACKS, tracks);
|
||||
}
|
||||
if(!schedule.timeMarkers().isEmpty()) {
|
||||
Map<String, Object> markers = new LinkedHashMap<>();
|
||||
schedule.timeMarkers().forEach((key, marker) -> {
|
||||
Map<String, Object> encodedMarker = new LinkedHashMap<>();
|
||||
encodedMarker.put(TICKS, marker.ticks());
|
||||
if(marker.showInCommands()) encodedMarker.put(SHOW_IN_COMMANDS, true);
|
||||
markers.put(key.toString(), encodedMarker);
|
||||
});
|
||||
encoded.put(TIME_MARKERS, markers);
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
private static AttributeSchedule readDefinition(Map<String, Object> raw, AttributeLookup attributes, DecodeContext context,
|
||||
List<Problem> dropped) throws Invalid {
|
||||
RegistryKey clock = identifier(raw.get(CLOCK), "clock");
|
||||
|
||||
OptionalInt period = OptionalInt.empty();
|
||||
if(raw.get(PERIOD_TICKS) != null) {
|
||||
int ticks = integer(raw.get(PERIOD_TICKS), "period_ticks", context);
|
||||
if(ticks <= 0) throw new Invalid("period_ticks must be positive");
|
||||
period = OptionalInt.of(ticks);
|
||||
}
|
||||
|
||||
Map<RegistryKey, TimeMarker> markers = new LinkedHashMap<>();
|
||||
if(raw.get(TIME_MARKERS) != null) {
|
||||
for(Map.Entry<?, ?> entry : map(raw.get(TIME_MARKERS), "time_markers").entrySet()) {
|
||||
RegistryKey marker = identifier(entry.getKey(), "time marker key");
|
||||
markers.put(marker, marker(marker, entry.getValue(), period, context));
|
||||
}
|
||||
}
|
||||
|
||||
Map<Attribute<?>, ScheduleTrack<?>> tracks = new LinkedHashMap<>();
|
||||
if(raw.get(TRACKS) != null) {
|
||||
for(Map.Entry<?, ?> entry : map(raw.get(TRACKS), "tracks").entrySet()) {
|
||||
String keyString = String.valueOf(entry.getKey());
|
||||
Attribute<?> attribute;
|
||||
try {
|
||||
attribute = attributes.find(keyString);
|
||||
} catch(DecodeException e) {
|
||||
dropped.add(new Problem(keyString, e.getMessage()));
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
tracks.put(attribute, track(attribute, map(entry.getValue(), "track " + keyString), period, context));
|
||||
} catch(TrackDropped e) {
|
||||
dropped.add(new Problem(keyString, e.getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AttributeSchedule(clock, period, tracks, markers);
|
||||
}
|
||||
|
||||
private static TimeMarker marker(RegistryKey key, Object value, OptionalInt period, DecodeContext context) throws Invalid {
|
||||
int ticks;
|
||||
boolean show = false;
|
||||
if(value instanceof Map<?, ?> map) {
|
||||
if(!map.containsKey(TICKS) || !map.keySet().stream().allMatch(k -> TICKS.equals(k) || SHOW_IN_COMMANDS.equals(k))) {
|
||||
throw new Invalid("time marker " + key + " must have \"ticks\" and optionally \"show_in_commands\"");
|
||||
}
|
||||
ticks = integer(map.get(TICKS), "time marker " + key + " ticks", context);
|
||||
Object flag = map.get(SHOW_IN_COMMANDS);
|
||||
if(flag != null) {
|
||||
if(!(flag instanceof Boolean b)) throw new Invalid("time marker " + key + " show_in_commands must be a boolean");
|
||||
show = b;
|
||||
}
|
||||
} else {
|
||||
ticks = integer(value, "time marker " + key, context);
|
||||
}
|
||||
if(ticks < 0) throw new Invalid("time marker " + key + " ticks must not be negative");
|
||||
if(period.isPresent() && ticks >= period.getAsInt()) {
|
||||
throw new Invalid("time marker " + key + " ticks " + ticks + " must be less than period_ticks " + period.getAsInt());
|
||||
}
|
||||
return new TimeMarker(ticks, show);
|
||||
}
|
||||
|
||||
private static <T> ScheduleTrack<T> track(Attribute<T> attribute, Map<?, ?> raw, OptionalInt period, DecodeContext context)
|
||||
throws Invalid, TrackDropped {
|
||||
Operation operation = Operation.OVERRIDE;
|
||||
if(raw.get(MODIFIER) != null) {
|
||||
try {
|
||||
operation = Operation.parse(String.valueOf(raw.get(MODIFIER)));
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new Invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
Easing ease = raw.get(EASE) == null ? LINEAR : easing(raw.get(EASE), context);
|
||||
|
||||
if(!(raw.get(KEYFRAMES) instanceof List<?> frames)) throw new Invalid("keyframes must be a list");
|
||||
if(frames.isEmpty()) throw new Invalid("keyframes must not be empty");
|
||||
List<Integer> ticksList = new ArrayList<>(frames.size());
|
||||
int previous = Integer.MIN_VALUE;
|
||||
int sameTick = 0;
|
||||
for(Object frame : frames) {
|
||||
if(!(frame instanceof Map<?, ?> map) || !map.containsKey(TICKS) || !map.containsKey(VALUE)
|
||||
|| !map.keySet().stream().allMatch(k -> TICKS.equals(k) || VALUE.equals(k))) {
|
||||
throw new Invalid("each keyframe must have exactly \"ticks\" and \"value\"");
|
||||
}
|
||||
int ticks = integer(map.get(TICKS), "keyframe ticks", context);
|
||||
if(ticks < 0) throw new Invalid("keyframe ticks must not be negative");
|
||||
if(ticks < previous) throw new Invalid("keyframes must be sorted by ticks");
|
||||
sameTick = ticks == previous ? sameTick + 1 : 1;
|
||||
if(sameTick > 2) throw new Invalid("at most 2 keyframes may share tick " + ticks);
|
||||
if(period.isPresent() && ticks > period.getAsInt()) {
|
||||
throw new Invalid("keyframe ticks " + ticks + " must be within period_ticks " + period.getAsInt());
|
||||
}
|
||||
previous = ticks;
|
||||
ticksList.add(ticks);
|
||||
}
|
||||
|
||||
// From here on, a failure drops only this track.
|
||||
if(!attribute.type().operations().contains(operation)) {
|
||||
throw new TrackDropped("modifier " + operation.getID() + " is not valid for " + attribute.key());
|
||||
}
|
||||
List<Keyframe> decoded = new ArrayList<>(frames.size());
|
||||
for(int i = 0; i < frames.size(); i++) {
|
||||
Object rawValue = ((Map<?, ?>) frames.get(i)).get(VALUE);
|
||||
decoded.add(new Keyframe(ticksList.get(i), argument(attribute, operation, rawValue, context)));
|
||||
}
|
||||
return new ScheduleTrack<>(operation, decoded, ease);
|
||||
}
|
||||
|
||||
private static <T> Object argument(Attribute<T> attribute, Operation operation, Object raw, DecodeContext context)
|
||||
throws TrackDropped {
|
||||
try {
|
||||
if(raw == null) throw new DecodeException("missing keyframe value");
|
||||
Object argument = attribute.type().decodeArgument(operation, raw, context);
|
||||
if(operation == Operation.OVERRIDE) {
|
||||
@SuppressWarnings("unchecked")
|
||||
T value = (T) argument;
|
||||
attribute.validate(value);
|
||||
}
|
||||
return argument;
|
||||
} catch(DecodeException | RuntimeException e) {
|
||||
throw new TrackDropped(e.getMessage() == null ? "unexpected error" : e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Easing easing(Object raw, DecodeContext context) throws Invalid {
|
||||
if(raw instanceof String name) {
|
||||
try {
|
||||
return new Easing.Named(name);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new Invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
if(raw instanceof Map<?, ?> map && map.size() == 1 && map.containsKey(CUBIC_BEZIER)
|
||||
&& map.get(CUBIC_BEZIER) instanceof List<?> list && list.size() == 4) {
|
||||
float[] v = new float[4];
|
||||
for(int i = 0; i < 4; i++) {
|
||||
Object element = list.get(i);
|
||||
float f;
|
||||
if(element instanceof Number n) {
|
||||
f = n.floatValue();
|
||||
} else if(element instanceof String) {
|
||||
try {
|
||||
f = context.<Float>load(Float.class, element);
|
||||
} catch(DecodeException e) {
|
||||
throw new Invalid("cubic_bezier must be a list of 4 numbers: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
throw new Invalid("cubic_bezier must be a list of 4 numbers");
|
||||
}
|
||||
if(!Float.isFinite(f)) throw new Invalid("cubic_bezier must be a list of 4 numbers");
|
||||
v[i] = f;
|
||||
}
|
||||
try {
|
||||
return new Easing.CubicBezier(v[0], v[1], v[2], v[3]);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new Invalid(e.getMessage());
|
||||
}
|
||||
}
|
||||
throw new Invalid("ease must be an easing name or {cubic_bezier: [x1, y1, x2, y2]}");
|
||||
}
|
||||
|
||||
private static RegistryKey identifier(Object raw, String what) throws Invalid {
|
||||
if(!(raw instanceof String string)) throw new Invalid(what + " must be an identifier string");
|
||||
if(string.startsWith("#")) throw new Invalid(what + " must not be a tag");
|
||||
try {
|
||||
return RegistryKey.parseNamespaced(string);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new Invalid(what + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static int integer(Object raw, String what, DecodeContext context) throws Invalid {
|
||||
try {
|
||||
return context.<Integer>load(Integer.class, raw);
|
||||
} catch(DecodeException e) {
|
||||
throw new Invalid(what + " must be an integer: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<?, ?> map(Object raw, String what) throws Invalid {
|
||||
if(raw instanceof Map<?, ?> map) return map;
|
||||
throw new Invalid(what + " must be a map");
|
||||
}
|
||||
|
||||
private static Map<String, Object> encodeTrack(Attribute<?> attribute, ScheduleTrack<?> track) {
|
||||
Map<String, Object> encoded = new LinkedHashMap<>();
|
||||
Operation operation = track.operation();
|
||||
if(operation != Operation.OVERRIDE) encoded.put(MODIFIER, operation.getID());
|
||||
if(!track.ease().equals(LINEAR)) encoded.put(EASE, encodeEasing(track.ease()));
|
||||
List<Object> keyframes = new ArrayList<>(track.keyframes().size());
|
||||
for(int i = 0; i < track.keyframes().size(); i++) {
|
||||
Keyframe keyframe = track.keyframes().get(i);
|
||||
if(keyframe.argument() == null) {
|
||||
throw new IllegalArgumentException("keyframe " + i + " of " + attribute.key() + ": a null value has no pack-format form");
|
||||
}
|
||||
Map<String, Object> frame = new LinkedHashMap<>();
|
||||
frame.put(TICKS, keyframe.ticks());
|
||||
frame.put(VALUE, attribute.type().encodeArgument(operation, keyframe.argument()));
|
||||
keyframes.add(frame);
|
||||
}
|
||||
encoded.put(KEYFRAMES, keyframes);
|
||||
return encoded;
|
||||
}
|
||||
|
||||
private static Object encodeEasing(Easing ease) {
|
||||
return switch(ease) {
|
||||
case Easing.Named named -> named.name();
|
||||
case Easing.CubicBezier bezier -> Map.of(CUBIC_BEZIER, List.of(bezier.x1(), bezier.y1(), bezier.x2(), bezier.y2()));
|
||||
};
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.world.attribute.value.BlendToGray;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.api.world.attribute.value.FloatWithAlpha;
|
||||
import com.dfsek.terra.api.world.attribute.value.TriState;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
|
||||
class AttributeCodecRoundTripTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeTypes TYPES = HANDLE.types();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
|
||||
record Case<T>(AttributeType<T> type, List<T> values, Map<Operation, List<?>> arguments) { }
|
||||
|
||||
private static <T> Case<T> of(AttributeType<T> type, List<T> values, Object... opArgs) {
|
||||
Map<Operation, List<?>> arguments = new LinkedHashMap<>();
|
||||
for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List<?>) opArgs[i + 1]);
|
||||
return new Case<>(type, values, arguments);
|
||||
}
|
||||
|
||||
static List<Case<?>> cases() {
|
||||
List<Float> floats = List.of(0.25f, -3f, 1.5e7f);
|
||||
List<FloatWithAlpha> withAlpha = List.of(new FloatWithAlpha(2f, 0.5f), new FloatWithAlpha(3f, 1f));
|
||||
List<Color> rgb = List.of(Color.rgb(0x102030), Color.rgb(0xFFFFFF), new Color(0.1f, 0.2f, 0.3f, 1f));
|
||||
List<Color> argb = List.of(Color.argb(0x80112233), Color.argb(0x00000000), new Color(0.1f, 0.2f, 0.3f, 0.4f));
|
||||
List<BlendToGray> gray = List.of(new BlendToGray(0.6f, 0.75f));
|
||||
List<Integer> ints = List.of(7, -2, Integer.MAX_VALUE);
|
||||
List<Boolean> bools = List.of(true, false);
|
||||
|
||||
return List.of(
|
||||
of(TYPES.booleanType(), bools,
|
||||
Operation.AND, bools, Operation.NAND, bools, Operation.OR, bools, Operation.NOR, bools, Operation.XOR, bools,
|
||||
Operation.XNOR, bools),
|
||||
of(TYPES.triState(), List.of(TriState.TRUE, TriState.FALSE, TriState.DEFAULT)),
|
||||
of(TYPES.floatType(), floats,
|
||||
Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats,
|
||||
Operation.MINIMUM, floats, Operation.MAXIMUM, floats),
|
||||
of(TYPES.angleDegrees(), floats,
|
||||
Operation.ALPHA_BLEND, withAlpha, Operation.ADD, floats, Operation.SUBTRACT, floats, Operation.MULTIPLY, floats,
|
||||
Operation.MINIMUM, floats, Operation.MAXIMUM, floats),
|
||||
of(TYPES.rgbColor(), rgb,
|
||||
Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, rgb,
|
||||
Operation.BLEND_TO_GRAY, gray),
|
||||
of(TYPES.argbColor(), argb,
|
||||
Operation.ALPHA_BLEND, argb, Operation.ADD, rgb, Operation.SUBTRACT, rgb, Operation.MULTIPLY, argb,
|
||||
Operation.BLEND_TO_GRAY, gray),
|
||||
of(TYPES.integer(), ints,
|
||||
Operation.ADD, ints, Operation.SUBTRACT, ints, Operation.MULTIPLY, ints, Operation.MINIMUM, ints, Operation.MAXIMUM, ints),
|
||||
of(TYPES.integerOverrideOnly(), ints),
|
||||
of(TYPES.identifier("mypack"), List.of(RegistryKey.parse("mypack:stone"), RegistryKey.parse("my.pack:A/b"))),
|
||||
of(TYPES.identifierOrTag("mypack"), List.<Either<RegistryKey, TagKey>>of(
|
||||
Either.left(RegistryKey.parse("mypack:stone")), Either.right(TagKey.parse("#my.pack:logs")))),
|
||||
of(TYPES.enumType("test_weather", Weather.class), List.of(Weather.values())));
|
||||
}
|
||||
|
||||
private enum Weather implements StringIdentifiable {
|
||||
CLEAR("sunny"),
|
||||
STORM("thunder");
|
||||
|
||||
private final String id;
|
||||
|
||||
Weather(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertPlain(Object encoded, String where) {
|
||||
if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return;
|
||||
if(encoded instanceof List<?> list) {
|
||||
for(Object element : list) assertPlain(element, where);
|
||||
return;
|
||||
}
|
||||
if(encoded instanceof Map<?, ?> m) {
|
||||
m.forEach((k, v) -> {
|
||||
assertTrue(k instanceof String, where + ": map key " + k + " is not a string");
|
||||
assertPlain(v, where);
|
||||
});
|
||||
return;
|
||||
}
|
||||
fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded);
|
||||
}
|
||||
|
||||
private static <T> void assertValuesRoundTrip(Case<T> c) throws DecodeException {
|
||||
for(T value : c.values()) {
|
||||
Object encoded = c.type().encode(value);
|
||||
assertPlain(encoded, c.type().id());
|
||||
assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCoreType() throws DecodeException {
|
||||
for(Case<?> c : cases()) assertValuesRoundTrip(c);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyArgument() throws DecodeException {
|
||||
for(Case<?> c : cases()) {
|
||||
AttributeType<?> type = c.type();
|
||||
List<Operation> unsampled = new ArrayList<>(type.operations());
|
||||
unsampled.remove(Operation.OVERRIDE);
|
||||
unsampled.removeAll(c.arguments().keySet());
|
||||
assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled);
|
||||
|
||||
Map<Operation, List<?>> arguments = new LinkedHashMap<>(c.arguments());
|
||||
arguments.put(Operation.OVERRIDE, c.values());
|
||||
for(Map.Entry<Operation, List<?>> e : arguments.entrySet()) {
|
||||
for(Object argument : e.getValue()) {
|
||||
Object encoded = type.encodeArgument(e.getKey(), argument);
|
||||
assertPlain(encoded, type.id() + " " + e.getKey().getID());
|
||||
assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN),
|
||||
type.id() + " " + e.getKey().getID() + " via " + encoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeArgumentInvalidOperation() {
|
||||
assertThrows(IllegalArgumentException.class, () -> TYPES.booleanType().encodeArgument(Operation.ADD, 1f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalForms() {
|
||||
assertEquals("#102030", TYPES.rgbColor().encode(Color.rgb(0x102030)));
|
||||
assertEquals("#80112233", TYPES.argbColor().encode(Color.argb(0x80112233)));
|
||||
assertEquals("#abcdef", TYPES.rgbColor().encode(Color.rgb(0xABCDEF)));
|
||||
assertEquals("mypack:stone", TYPES.identifier("mypack").encode(RegistryKey.parse("mypack:stone")));
|
||||
assertEquals("#mypack:logs", TYPES.identifierOrTag("mypack").encode(Either.right(TagKey.parse("#mypack:logs"))));
|
||||
assertEquals("mypack:stone", TYPES.identifierOrTag("mypack").encode(Either.left(RegistryKey.parse("mypack:stone"))));
|
||||
assertEquals("thunder", TYPES.enumType("test_weather", Weather.class).encode(Weather.STORM));
|
||||
assertEquals(true, TYPES.triState().encode(TriState.TRUE));
|
||||
assertEquals("default", TYPES.triState().encode(TriState.DEFAULT));
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
|
||||
class AttributeCodecsTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeCodecs CODECS = HANDLE.codecs();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
|
||||
private record Point(int x, float weight) { }
|
||||
|
||||
|
||||
private static final AttributeCodec<Point> POINT = CODECS.of((raw, context) -> {
|
||||
ObjectReader f = CODECS.reader("point", raw, context);
|
||||
int x = f.required("x", CODECS.intCodec());
|
||||
float weight = f.orDefault("weight", CODECS.unitFloat(), 1f);
|
||||
f.finish();
|
||||
return new Point(x, weight);
|
||||
}, value -> CODECS.writer()
|
||||
.put("x", CODECS.intCodec(), value.x())
|
||||
.put("weight", CODECS.unitFloat(), value.weight())
|
||||
.optional("label", CODECS.string("expected a label"), Optional.empty())
|
||||
.map());
|
||||
|
||||
private enum Weather implements StringIdentifiable {
|
||||
CLEAR("sunny"),
|
||||
STORM("thunder");
|
||||
|
||||
private final String id;
|
||||
|
||||
Weather(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> map(Object... kv) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void ofRoundTrips() throws DecodeException {
|
||||
Point point = new Point(3, 0.5f);
|
||||
Object encoded = POINT.encode(point);
|
||||
assertEquals(map("x", 3, "weight", 0.5f), encoded);
|
||||
assertEquals(point, POINT.decode(encoded, PLAIN));
|
||||
assertEquals(new Point(4, 1f), POINT.decode(map("x", 4), PLAIN));
|
||||
|
||||
AttributeCodec<List<Point>> points = CODECS.compactList(POINT);
|
||||
assertEquals(List.of(point), points.decode(encoded, PLAIN));
|
||||
assertEquals(List.of(encoded), points.encode(List.of(point)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void intFailures() {
|
||||
assertEquals("\"x\" of point: expected an integer, got 1.5",
|
||||
assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1.5), PLAIN)).getMessage());
|
||||
assertEquals("expected a non-negative integer, got -1",
|
||||
assertThrows(DecodeException.class, () -> CODECS.nonNegativeInt().decode(-1, PLAIN)).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void readerUnknownField() {
|
||||
assertEquals("unknown key \"y\" in point",
|
||||
assertThrows(DecodeException.class, () -> POINT.decode(map("x", 1, "y", 2), PLAIN)).getMessage());
|
||||
assertEquals("point is missing required key \"x\"",
|
||||
assertThrows(DecodeException.class, () -> POINT.decode(map(), PLAIN)).getMessage());
|
||||
assertEquals("expected an object for point, got a list",
|
||||
assertThrows(DecodeException.class, () -> POINT.decode(List.of(), PLAIN)).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enumUnknownId() throws DecodeException {
|
||||
AttributeCodec<Weather> weather = CODECS.enumCodec("weather", Weather.class);
|
||||
assertSame(Weather.STORM, weather.decode("thunder", PLAIN));
|
||||
assertEquals("thunder", weather.encode(Weather.STORM));
|
||||
assertEquals("unknown weather \"storm\", expected one of [sunny, thunder]",
|
||||
assertThrows(DecodeException.class, () -> weather.decode("storm", PLAIN)).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listFailingElement() {
|
||||
assertEquals("element 1: expected an integer, got 2.5",
|
||||
assertThrows(DecodeException.class, () -> CODECS.list(CODECS.intCodec()).decode(List.of(1, 2.5), PLAIN)).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeValues() {
|
||||
assertEquals("\"a\"", CODECS.describe("a"));
|
||||
assertEquals("an object", CODECS.describe(Map.of()));
|
||||
assertEquals("a list", CODECS.describe(List.of()));
|
||||
assertEquals("nothing", CODECS.describe(null));
|
||||
assertEquals("3", CODECS.describe(3));
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class AttributeComposeTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeTypes TYPES = HANDLE.types();
|
||||
|
||||
private static final Attribute<Float> FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY)
|
||||
.build();
|
||||
private static final Attribute<Float> SUN_ANGLE = attribute("test:sun_angle", TYPES.angleDegrees(), 0f).build();
|
||||
private static final Attribute<Integer> SEA_LEVEL = attribute("test:sea_level", TYPES.integer(), 63).build();
|
||||
private static final Attribute<Color> FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build();
|
||||
private static final Attribute<Color> GRASS_COLOR = attribute("test:grass_color", TYPES.rgbColor(), null).build();
|
||||
|
||||
private static <T> Attribute.Builder<T> attribute(String key, AttributeType<T> type, T defaultValue) {
|
||||
return HANDLE.attributeBuilder(AttributeKey.<T>parse(key), type, defaultValue);
|
||||
}
|
||||
|
||||
private static <T> AttributeEntry<T> composed(Attribute<T> attribute, AttributeEntry<T> lower, AttributeEntry<T> upper) {
|
||||
return HANDLE.compose(attribute, lower, upper).orElseThrow(() -> new AssertionError("empty"));
|
||||
}
|
||||
|
||||
private static void assertEntry(Operation operation, Object argument, AttributeEntry<?> entry) {
|
||||
assertEquals(operation, entry.operation());
|
||||
assertEquals(argument, entry.argument());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOrUpperOverride() {
|
||||
assertTrue(HANDLE.compose(FOG_END, null, null).isEmpty());
|
||||
AttributeEntry<Float> lower = AttributeEntry.override(10f);
|
||||
AttributeEntry<Float> upper = AttributeEntry.of(Operation.MULTIPLY, 2f);
|
||||
assertSame(lower, composed(FOG_END, lower, null));
|
||||
assertSame(upper, composed(FOG_END, null, upper));
|
||||
AttributeEntry<Float> override = AttributeEntry.override(5f);
|
||||
assertSame(override, composed(FOG_END, lower, override));
|
||||
assertSame(override, composed(FOG_END, AttributeEntry.of(Operation.ADD, 3f), override));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lowerOverride() {
|
||||
assertEntry(Operation.OVERRIDE, 30f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.MULTIPLY, 3f)));
|
||||
assertEntry(Operation.OVERRIDE, 13f, composed(FOG_END, AttributeEntry.override(10f), AttributeEntry.of(Operation.ADD, 3f)));
|
||||
assertEntry(Operation.OVERRIDE, 2000f, composed(FOG_END, AttributeEntry.override(1000f), AttributeEntry.of(Operation.MULTIPLY, 2f)));
|
||||
Color base = Color.parseRgb("#102030");
|
||||
Color add = Color.parseRgb("#010101");
|
||||
assertEntry(Operation.OVERRIDE, FOG_COLOR.type().apply(Operation.ADD, base, add),
|
||||
composed(FOG_COLOR, AttributeEntry.override(base), AttributeEntry.of(Operation.ADD, add)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lowerNullOverride() {
|
||||
AttributeEntry<Color> lower = AttributeEntry.override(null);
|
||||
assertSame(lower, composed(GRASS_COLOR, lower, AttributeEntry.of(Operation.MULTIPLY, Color.parseRgb("#808080"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void builtinTypesCompose() {
|
||||
assertEntry(Operation.ADD, 5f, composed(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.ADD, 3f)));
|
||||
assertEntry(Operation.MULTIPLY, 6f,
|
||||
composed(FOG_END, AttributeEntry.of(Operation.MULTIPLY, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f)));
|
||||
assertEntry(Operation.ADD, 50f, composed(SUN_ANGLE, AttributeEntry.of(Operation.ADD, 20f), AttributeEntry.of(Operation.ADD, 30f)));
|
||||
assertEntry(Operation.MULTIPLY, 1.5f,
|
||||
composed(SUN_ANGLE, AttributeEntry.of(Operation.MULTIPLY, 0.5f), AttributeEntry.of(Operation.MULTIPLY, 3f)));
|
||||
assertEntry(Operation.ADD, 7, composed(SEA_LEVEL, AttributeEntry.of(Operation.ADD, 3), AttributeEntry.of(Operation.ADD, 4)));
|
||||
assertEntry(Operation.MULTIPLY, 12,
|
||||
composed(SEA_LEVEL, AttributeEntry.of(Operation.MULTIPLY, 3), AttributeEntry.of(Operation.MULTIPLY, 4)));
|
||||
}
|
||||
|
||||
private static final AttributeCodec<Integer> INT_CODEC = new AttributeCodec<>() {
|
||||
@Override
|
||||
public Integer decode(Object raw, DecodeContext context) throws DecodeException {
|
||||
return context.load(Integer.class, raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encode(Integer value) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
private static Attribute<Integer> counter(AttributeType<Integer> type) {
|
||||
return HANDLE.attributeBuilder(AttributeKey.<Integer>parse("test:counter"), type, 0).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void addonTypeComposes() {
|
||||
AttributeType<Integer> composable = HANDLE.typeBuilder("test:counter", INT_CODEC)
|
||||
.op(Operation.ADD, INT_CODEC, Integer::sum)
|
||||
.composable(Operation.ADD, Integer::sum)
|
||||
.build();
|
||||
assertEntry(Operation.ADD, 5, composed(counter(composable), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3)));
|
||||
|
||||
AttributeType<Integer> plain = HANDLE.typeBuilder("test:counter", INT_CODEC).op(Operation.ADD, INT_CODEC, Integer::sum).build();
|
||||
assertTrue(HANDLE.compose(counter(plain), AttributeEntry.of(Operation.ADD, 2), AttributeEntry.of(Operation.ADD, 3)).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void composerReturningNull() {
|
||||
AttributeType<Integer> broken = HANDLE.typeBuilder("test:counter", INT_CODEC)
|
||||
.op(Operation.ADD, INT_CODEC, Integer::sum)
|
||||
.<Integer>composable(Operation.ADD, (a, b) -> null)
|
||||
.build();
|
||||
NullPointerException e = assertThrows(NullPointerException.class, () -> broken.compose(Operation.ADD, 2, 3));
|
||||
assertEquals("composer for add of test:counter returned null", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void composableWithoutOperation() {
|
||||
AttributeType.Builder<Integer> builder = HANDLE.typeBuilder("test:counter", INT_CODEC);
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.composable(Operation.ADD, Integer::sum));
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.<Integer>composable(Operation.OVERRIDE, (a, b) -> b));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void composedResolvesLikeLayers() {
|
||||
AttributeEntry<Integer> pack = AttributeEntry.override(60);
|
||||
AttributeEntry<Integer> lower = AttributeEntry.of(Operation.ADD, 3);
|
||||
AttributeEntry<Integer> upper = AttributeEntry.of(Operation.ADD, -10);
|
||||
assertEquals(HANDLE.resolve(SEA_LEVEL, pack, lower, upper), HANDLE.resolve(SEA_LEVEL, pack, composed(SEA_LEVEL, lower, upper)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void notComposable() {
|
||||
assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.ADD, 2f), AttributeEntry.of(Operation.MULTIPLY, 3f)).isEmpty());
|
||||
assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.MINIMUM, 2f), AttributeEntry.of(Operation.MINIMUM, 3f)).isEmpty());
|
||||
assertTrue(HANDLE.compose(FOG_END, AttributeEntry.of(Operation.SUBTRACT, 2f), AttributeEntry.of(Operation.SUBTRACT, 3f)).isEmpty());
|
||||
Color add = Color.parseRgb("#010101");
|
||||
assertTrue(HANDLE.compose(FOG_COLOR, AttributeEntry.of(Operation.ADD, add), AttributeEntry.of(Operation.ADD, add)).isEmpty());
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.CheckedRegistry;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.registry.CheckedRegistryImpl;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class AttributeIndexTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
|
||||
private static Attribute<Float> build(String key) {
|
||||
return HANDLE.attributeBuilder(AttributeKey.<Float>parse(key), HANDLE.types().floatType(), 0f).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void denseIndices() {
|
||||
Attribute<Float> a = build("test:a");
|
||||
Attribute<Float> b = build("test:b");
|
||||
Attribute<Float> c = build("test:c");
|
||||
assertEquals(3, Set.of(a.index(), b.index(), c.index()).size());
|
||||
assertEquals(a.index() + 1, b.index());
|
||||
assertEquals(b.index() + 1, c.index());
|
||||
assertTrue(a.index() >= 0);
|
||||
assertTrue(HANDLE.attributeCount() >= c.index() + 1, () -> HANDLE.attributeCount() + " <= " + c.index());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookupIsTyped() {
|
||||
CheckedRegistry<Attribute<?>> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE));
|
||||
Attribute<Float> fog = build("test:visual/fog");
|
||||
registry.register(fog.getRegistryKey(), fog);
|
||||
|
||||
assertSame(fog, fog.key().lookup(registry).orElseThrow());
|
||||
AttributeKey<Float> lookalike = AttributeKey.parse("test:visual/fog");
|
||||
assertEquals(fog.key(), lookalike);
|
||||
assertTrue(lookalike.lookup(registry).isEmpty());
|
||||
assertSame(fog, registry.get(lookalike.getRegistryKey()).orElseThrow());
|
||||
assertTrue(AttributeKey.<Float>parse("test:nothing").lookup(registry).isEmpty());
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.properties.Context;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeParents;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
class AttributeLayersTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeTypes TYPES = HANDLE.types();
|
||||
|
||||
private static final Attribute<Float> FOG_END = attribute("test:fog_end", TYPES.floatType(), 1024f)
|
||||
.range(0, Double.POSITIVE_INFINITY).build();
|
||||
private static final Attribute<Float> WATER_FOG_END = attribute("test:water_fog_end", TYPES.floatType(), 96f)
|
||||
.range(0, Double.POSITIVE_INFINITY).build();
|
||||
private static final Attribute<Color> FOG_COLOR = attribute("test:fog_color", TYPES.rgbColor(), Color.rgb(0)).build();
|
||||
private static final Attribute<Color> FOLIAGE_COLOR = attribute("test:foliage_color", TYPES.rgbColor(), null).build();
|
||||
private static final Attribute<Float> STAR_BRIGHTNESS = attribute("test:star_brightness", TYPES.floatType(), 0f).range(0, 1).build();
|
||||
|
||||
private static <T> Attribute.Builder<T> attribute(String key, AttributeType<T> type, T defaultValue) {
|
||||
return HANDLE.attributeBuilder(AttributeKey.<T>parse(key), type, defaultValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
void layerOrder() {
|
||||
assertEquals(1024f, HANDLE.resolve(FOG_END), "default alone");
|
||||
assertEquals(5f, HANDLE.resolve(FOG_END, null, AttributeEntry.override(5f), null), "null layers are skipped");
|
||||
assertEquals(1f, HANDLE.resolve(STAR_BRIGHTNESS, AttributeEntry.override(2f)), "the range clamps the result");
|
||||
assertEquals(81.6f, HANDLE.resolve(WATER_FOG_END, AttributeEntry.override(96f), AttributeEntry.of(Operation.MULTIPLY, 0.85f)),
|
||||
1e-3f, "pack then biome multiply");
|
||||
|
||||
AttributeEntry<Color> pack = AttributeEntry.override(Color.rgb(0x808080));
|
||||
AttributeEntry<Color> vanilla = AttributeEntry.override(Color.rgb(0xc0d8ff));
|
||||
AttributeEntry<Color> terra = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010));
|
||||
assertEquals(0xc0d8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla).toRgbInt(), "vanilla parent wins over the pack override");
|
||||
assertEquals(0xd0e8ff, HANDLE.resolve(FOG_COLOR, pack, vanilla, terra).toRgbInt(), "Terra modifier on the vanilla parent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifiersOnNull() {
|
||||
AttributeEntry<Color> add = AttributeEntry.of(Operation.ADD, Color.rgb(0x101010));
|
||||
assertNull(HANDLE.resolve(FOLIAGE_COLOR));
|
||||
assertNull(HANDLE.resolve(FOLIAGE_COLOR, add));
|
||||
assertEquals(0x305070, HANDLE.resolve(FOLIAGE_COLOR, add, AttributeEntry.override(Color.rgb(0x204060)), add).toRgbInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentsNoneIsEmpty() {
|
||||
assertNull(AttributeParents.NONE.biomeOrNull(null, FOG_END));
|
||||
assertNull(AttributeParents.NONE.packOrNull(null, FOG_END));
|
||||
}
|
||||
|
||||
@Test
|
||||
void packAttributesFromContext() {
|
||||
Context context = new Context();
|
||||
ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
|
||||
(proxy, method, args) -> switch(method.getName()) {
|
||||
case "getContext" -> context;
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
assertTrue(HANDLE.pack(pack).isEmpty());
|
||||
PackAttributes attributes = (PackAttributes) Proxy.newProxyInstance(PackAttributes.class.getClassLoader(),
|
||||
new Class<?>[]{ PackAttributes.class }, (proxy, method, args) -> {
|
||||
throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
context.put(Context.create(PackAttributes.class), attributes);
|
||||
assertSame(attributes, HANDLE.pack(pack).orElseThrow());
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Named;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeCodec;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.api.world.attribute.value.TriState;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
|
||||
|
||||
public class AttributeTypesTest {
|
||||
private static final float EPS = 1e-6f;
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeTypes TYPES = HANDLE.types();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
private static final AttributeType<Weather> WEATHER = TYPES.enumType("test_weather", Weather.class);
|
||||
private static final AttributeCodec<Float> FLOAT = new AttributeCodec<>() {
|
||||
@Override
|
||||
public Float decode(Object raw, DecodeContext context) throws DecodeException {
|
||||
return context.load(Float.class, raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encode(Float value) {
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
private enum Weather implements StringIdentifiable {
|
||||
CLEAR("sunny"),
|
||||
STORM("thunder");
|
||||
|
||||
private final String id;
|
||||
|
||||
Weather(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> T mod(AttributeType<T> type, Operation op, T subject, Object rawArg) throws DecodeException {
|
||||
return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN));
|
||||
}
|
||||
|
||||
private static void assertColor(float r, float g, float b, float a, Color c) {
|
||||
assertEquals(r, c.r(), EPS, "r");
|
||||
assertEquals(g, c.g(), EPS, "g");
|
||||
assertEquals(b, c.b(), EPS, "b");
|
||||
assertEquals(a, c.a(), EPS, "a");
|
||||
}
|
||||
|
||||
private static void assertValue(Object expected, Object actual) {
|
||||
if(expected instanceof Color e && actual instanceof Color c) assertColor(e.r(), e.g(), e.b(), e.a(), c);
|
||||
else if(expected instanceof Float e && actual instanceof Float f) assertEquals(e, f, EPS);
|
||||
else assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
private static Map<String, Object> map(Object... kv) {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
|
||||
return m;
|
||||
}
|
||||
|
||||
private static Named<AttributeType<?>> named(AttributeType<?> type) {
|
||||
return Named.of(type.id(), type);
|
||||
}
|
||||
|
||||
private static Color color(float r, float g, float b, float a) {
|
||||
return new Color(r, g, b, a);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void booleanOps() throws DecodeException {
|
||||
AttributeType<Boolean> t = TYPES.booleanType();
|
||||
for(boolean s : new boolean[]{ true, false }) {
|
||||
for(boolean a : new boolean[]{ true, false }) {
|
||||
assertEquals(a && s, mod(t, Operation.AND, s, a));
|
||||
assertEquals(!a || !s, mod(t, Operation.NAND, s, a));
|
||||
assertEquals(a || s, mod(t, Operation.OR, s, a));
|
||||
assertEquals(!a && !s, mod(t, Operation.NOR, s, a));
|
||||
assertEquals(a ^ s, mod(t, Operation.XOR, s, a));
|
||||
assertEquals(a == s, mod(t, Operation.XNOR, s, a));
|
||||
}
|
||||
}
|
||||
assertEquals(true, mod(t, Operation.OVERRIDE, false, true));
|
||||
}
|
||||
|
||||
private static Arguments modifier(AttributeType<?> type, Operation op, Object subject, Object rawArg, Object expected) {
|
||||
return arguments(named(type), op, subject, rawArg, expected);
|
||||
}
|
||||
|
||||
static Stream<Arguments> modifiers() {
|
||||
float sa = 0.5f;
|
||||
float da = 0.2f;
|
||||
float a = sa + da * (1 - sa);
|
||||
Color dst = color(0.8f, 0.2f, 0.4f, 0.2f);
|
||||
return Stream.of(
|
||||
modifier(TYPES.floatType(), Operation.ADD, 5f, 2.5, 7.5f),
|
||||
modifier(TYPES.floatType(), Operation.SUBTRACT, 5f, 2.5, 2.5f),
|
||||
modifier(TYPES.floatType(), Operation.MULTIPLY, 5f, 2, 10f),
|
||||
modifier(TYPES.floatType(), Operation.MINIMUM, 5f, 2.5, 2.5f),
|
||||
modifier(TYPES.floatType(), Operation.MAXIMUM, 5f, 2.5, 5f),
|
||||
modifier(TYPES.angleDegrees(), Operation.ADD, 1f, 0.5, 1.5f),
|
||||
modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, 8, 8f),
|
||||
modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6, "alpha", 0.5), 4f),
|
||||
modifier(TYPES.floatType(), Operation.ALPHA_BLEND, 2f, map("value", 6), 6f),
|
||||
modifier(TYPES.integer(), Operation.ADD, 5, 3, 8),
|
||||
modifier(TYPES.integer(), Operation.SUBTRACT, 5, 3, 2),
|
||||
modifier(TYPES.integer(), Operation.MULTIPLY, 5, 3, 15),
|
||||
modifier(TYPES.integer(), Operation.MINIMUM, 5, 3, 3),
|
||||
modifier(TYPES.integer(), Operation.MAXIMUM, 5, 3, 5),
|
||||
modifier(TYPES.rgbColor(), Operation.ADD, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5), color(0.75f, 1f, 0.6f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.SUBTRACT, color(0.5f, 0.9f, 0.1f, 1f), List.of(0.25, 0.25, 0.5),
|
||||
color(0.25f, 0.65f, 0f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.6f, 1f), List.of(0.8, 0.8, 0.8),
|
||||
color(0.4f, 0.4f, 0.48f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(0.3f, 0.4f, 0.5f, 1f), List.of(1, 1, 1), color(0.3f, 0.4f, 0.5f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.3, 0.4, 0.5), color(0.3f, 0.4f, 0.5f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0), color(0f, 0f, 1f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), List.of(1, 0, 0, 0.5), color(0.5f, 0f, 0.5f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.ALPHA_BLEND, color(0f, 0f, 1f, 1f), "#ffff0000", color(1f, 0f, 0f, 1f)),
|
||||
modifier(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 1f), map("brightness", 0.6, "factor", 0.75),
|
||||
color(0.385f, 0.135f, 0.135f, 1f)),
|
||||
modifier(TYPES.argbColor(), Operation.ADD, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75),
|
||||
color(0.75f, 0.75f, 1f, 0.3f)),
|
||||
modifier(TYPES.argbColor(), Operation.SUBTRACT, color(0.5f, 0.5f, 0.5f, 0.3f), List.of(0.25, 0.25, 0.75),
|
||||
color(0.25f, 0.25f, 0f, 0.3f)),
|
||||
modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.5f, 0.5f, 0.5f, 0.5f), List.of(0.5, 0.5, 0.5, 0.3),
|
||||
color(0.25f, 0.25f, 0.25f, 0.15f)),
|
||||
modifier(TYPES.argbColor(), Operation.MULTIPLY, color(0.2f, 0.3f, 0.4f, 0.5f), List.of(1, 1, 1, 1),
|
||||
color(0.2f, 0.3f, 0.4f, 0.5f)),
|
||||
modifier(TYPES.argbColor(), Operation.MULTIPLY, color(1f, 1f, 1f, 1f), List.of(0.2, 0.3, 0.4, 0.5),
|
||||
color(0.2f, 0.3f, 0.4f, 0.5f)),
|
||||
modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 1), color(0f, 1f, 0f, 1f)),
|
||||
modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0), dst),
|
||||
modifier(TYPES.argbColor(), Operation.ALPHA_BLEND, dst, List.of(0, 1, 0, 0.5),
|
||||
color((0f * sa + 0.8f * (a - sa)) / a, (1f * sa + 0.2f * (a - sa)) / a, (0f * sa + 0.4f * (a - sa)) / a, a)),
|
||||
modifier(TYPES.argbColor(), Operation.BLEND_TO_GRAY, color(1f, 0f, 0f, 0.7f), map("brightness", 0.6, "factor", 0.75),
|
||||
color(0.385f, 0.135f, 0.135f, 0.7f)),
|
||||
modifier(TYPES.rgbColor(), Operation.OVERRIDE, color(0f, 0f, 0f, 1f), "#ff0000", color(1f, 0f, 0f, 1f)),
|
||||
modifier(WEATHER, Operation.OVERRIDE, Weather.CLEAR, "thunder", Weather.STORM));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
@SuppressWarnings("unchecked")
|
||||
public void modifiers(AttributeType<Object> type, Operation op, Object subject, Object rawArg, Object expected)
|
||||
throws DecodeException {
|
||||
assertValue(expected, mod(type, op, subject, rawArg));
|
||||
}
|
||||
|
||||
private static Arguments invalid(AttributeType<?> type, Operation op, Object raw, String message) {
|
||||
return arguments(named(type), op, raw, message);
|
||||
}
|
||||
|
||||
static Stream<Arguments> invalidArguments() {
|
||||
return Stream.of(
|
||||
invalid(TYPES.booleanType(), Operation.MULTIPLY, true, "modifier multiply is not valid for boolean"),
|
||||
invalid(TYPES.floatType(), Operation.AND, true, null),
|
||||
invalid(TYPES.triState(), Operation.ADD, 1, null),
|
||||
invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "alpha", 1.5), null),
|
||||
invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("value", 6, "bogus", 1), null),
|
||||
invalid(TYPES.floatType(), Operation.ALPHA_BLEND, map("alpha", 0.5), null),
|
||||
invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 1.5, "factor", 0.5), null),
|
||||
invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5), null),
|
||||
invalid(TYPES.rgbColor(), Operation.BLEND_TO_GRAY, map("brightness", 0.5, "factor", 0.5, "extra", 1), null),
|
||||
invalid(TYPES.argbColor(), Operation.ADD, List.of(0.1, 0.1, 0.1, 0.1), null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void invalidArguments(AttributeType<?> type, Operation op, Object raw, String message) {
|
||||
DecodeException e = assertThrows(DecodeException.class, () -> type.decodeArgument(op, raw, PLAIN));
|
||||
if(message != null) assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
private static Arguments decode(AttributeType<?> type, Object raw, Object expected) {
|
||||
return arguments(named(type), raw, expected);
|
||||
}
|
||||
|
||||
static Stream<Arguments> decodes() {
|
||||
return Stream.of(
|
||||
decode(TYPES.integer(), 7, 7),
|
||||
decode(TYPES.integer(), 7L, 7),
|
||||
decode(TYPES.integer(), (short) 7, 7),
|
||||
decode(TYPES.integer(), (byte) 7, 7),
|
||||
decode(TYPES.integer(), 7.0, 7),
|
||||
decode(TYPES.integer(), 7.0f, 7),
|
||||
decode(TYPES.integer(), BigInteger.valueOf(7), 7),
|
||||
decode(TYPES.integer(), new BigDecimal("7.00"), 7),
|
||||
decode(TYPES.integer(), (double) Integer.MIN_VALUE, Integer.MIN_VALUE),
|
||||
decode(TYPES.integer(), BigInteger.valueOf(Integer.MAX_VALUE), Integer.MAX_VALUE),
|
||||
decode(TYPES.floatType(), 3, 3f),
|
||||
decode(TYPES.floatType(), 0.25, 0.25f),
|
||||
decode(TYPES.rgbColor(), "#050533", Color.rgb(0x050533)),
|
||||
decode(TYPES.rgbColor(), List.of(0.1, 0.2, 0.3), color(0.1f, 0.2f, 0.3f, 1f)),
|
||||
decode(TYPES.rgbColor(), 0xFF0000, color(1f, 0f, 0f, 1f)),
|
||||
decode(TYPES.argbColor(), "#44112233", Color.argb(0x44112233)),
|
||||
decode(TYPES.triState(), "default", TriState.DEFAULT),
|
||||
decode(TYPES.triState(), true, TriState.TRUE),
|
||||
decode(TYPES.identifier("mypack"), "mypack:idle", RegistryKey.parse("mypack:idle")),
|
||||
decode(TYPES.identifier("mypack"), "idle", RegistryKey.parse("mypack:idle")),
|
||||
decode(TYPES.identifier("mypack"), "other:idle", RegistryKey.parse("other:idle")),
|
||||
decode(TYPES.identifier("mypack"), "Mod:Music.Game", RegistryKey.parse("Mod:Music.Game")),
|
||||
decode(TYPES.identifierOrTag("mypack"), "stone", Either.left(RegistryKey.parse("mypack:stone"))),
|
||||
decode(TYPES.identifierOrTag("mypack"), "#logs", Either.right(TagKey.parse("#mypack:logs"))),
|
||||
decode(TYPES.identifierOrTag("mypack"), "#Mod:Logs", Either.right(TagKey.parse("#Mod:Logs"))),
|
||||
decode(WEATHER, "sunny", Weather.CLEAR),
|
||||
decode(WEATHER, "thunder", Weather.STORM));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void decodes(AttributeType<?> type, Object raw, Object expected) throws DecodeException {
|
||||
assertValue(expected, type.decode(raw, PLAIN));
|
||||
}
|
||||
|
||||
private static Arguments reject(AttributeType<?> type, Object raw, String message) {
|
||||
return arguments(named(type), raw, message);
|
||||
}
|
||||
|
||||
static Stream<Arguments> decodeFailures() {
|
||||
return Stream.of(
|
||||
reject(TYPES.integer(), 4.5, "expected an integer, got 4.5"),
|
||||
reject(TYPES.integer(), 99999999999L, "expected an integer, got 99999999999"),
|
||||
reject(TYPES.integer(), new BigDecimal("1.5"), "expected an integer, got 1.5"),
|
||||
reject(TYPES.integer(), BigInteger.valueOf(1L << 31), "expected an integer, got 2147483648"),
|
||||
reject(TYPES.integer(), new BigInteger("100000000000000000000"), null),
|
||||
reject(TYPES.integer(), 2147483648.0, null),
|
||||
reject(TYPES.integer(), Double.NaN, null),
|
||||
reject(TYPES.integer(), Float.POSITIVE_INFINITY, null),
|
||||
reject(TYPES.integer(), 1.5f, null),
|
||||
reject(TYPES.integer(), "4", null),
|
||||
reject(TYPES.floatType(), "1.0", null),
|
||||
reject(TYPES.floatType(), true, null),
|
||||
reject(TYPES.booleanType(), "yes", "expected a boolean (true or false), got \"yes\""),
|
||||
reject(TYPES.booleanType(), 1, null),
|
||||
reject(TYPES.rgbColor(), true, "expected a color like \"#rrggbb\", got true"),
|
||||
reject(TYPES.rgbColor(), "#12345", null),
|
||||
reject(TYPES.rgbColor(), 0.5, null),
|
||||
reject(TYPES.triState(), "maybe", null),
|
||||
reject(TYPES.identifier("mypack"), "Not Valid", "expected an identifier like \"mypack:id\", got \"Not Valid\""),
|
||||
reject(TYPES.identifier("mypack"), "#mypack:logs", "expected an identifier, not a tag, got \"#mypack:logs\""),
|
||||
reject(TYPES.identifier("mypack"), "mypack:", null),
|
||||
reject(TYPES.identifier("mypack"), 3, null),
|
||||
reject(TYPES.identifierOrTag("mypack"), "#", null),
|
||||
reject(WEATHER, "storm", "unknown test weather \"storm\", expected one of [sunny, thunder]"),
|
||||
reject(WEATHER, "CLEAR", null),
|
||||
reject(WEATHER, 1, null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
public void decodeFailures(AttributeType<?> type, Object raw, String message) {
|
||||
DecodeException e = assertThrows(DecodeException.class, () -> type.decode(raw, PLAIN));
|
||||
if(message != null) assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void builder() throws DecodeException {
|
||||
AttributeType.Builder<Float> builder = HANDLE.typeBuilder("test", FLOAT);
|
||||
assertThrows(IllegalArgumentException.class, () -> builder.op(Operation.OVERRIDE, FLOAT, (s, a) -> a));
|
||||
AttributeType<Float> built = builder.build();
|
||||
assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations());
|
||||
builder.op(Operation.ADD, FLOAT, Float::sum);
|
||||
assertEquals(EnumSet.of(Operation.OVERRIDE), built.operations());
|
||||
assertThrows(UnsupportedOperationException.class, () -> built.operations().add(Operation.ADD));
|
||||
assertThrows(DecodeException.class, () -> built.decodeArgument(Operation.ADD, 1, PLAIN));
|
||||
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.ADD), builder.build().operations());
|
||||
assertEquals(3f, builder.build().apply(Operation.ADD, 1f, 2f), EPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nestedLoads() throws DecodeException {
|
||||
List<Object> seen = new ArrayList<>();
|
||||
DecodeContext recording = new DecodeContext() {
|
||||
@Override
|
||||
public <V> V load(Type type, Object raw) throws DecodeException {
|
||||
seen.add(raw);
|
||||
return HANDLE.plainContext().load(type, raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(Object raw) {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
Map<String, Object> argument = map("value", 6, "alpha", 0.5);
|
||||
TYPES.floatType().decodeArgument(Operation.ALPHA_BLEND, argument, recording);
|
||||
TYPES.identifier("mypack").decode("mypack:thing", recording);
|
||||
assertTrue(seen.contains(argument), seen.toString());
|
||||
assertTrue(seen.contains(6), seen.toString());
|
||||
assertTrue(seen.contains(0.5), seen.toString());
|
||||
assertTrue(seen.contains("mypack:thing"), seen.toString());
|
||||
}
|
||||
|
||||
private static DecodeContext referencing(Map<String, Object> targets) {
|
||||
return new DecodeContext() {
|
||||
@Override
|
||||
public <V> V load(Type type, Object raw) throws DecodeException {
|
||||
return HANDLE.plainContext().load(type, raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(Object raw) {
|
||||
if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s));
|
||||
if(raw instanceof Map<?, ?> m) {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
m.forEach((k, v) -> out.put((String) k, resolve(v)));
|
||||
return out;
|
||||
}
|
||||
if(raw instanceof List<?> l) return l.stream().map(this::resolve).toList();
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveBeforeShape() throws DecodeException {
|
||||
DecodeContext context = referencing(map(
|
||||
"@alpha", map("value", "@two", "alpha", 0.5),
|
||||
"@two", 2,
|
||||
"@yes", true,
|
||||
"@channels", List.of(1, 0, 0),
|
||||
"@gray", map("brightness", 0.6, "factor", 0.75)));
|
||||
|
||||
AttributeType<Float> floats = TYPES.floatType();
|
||||
assertEquals(1.5f, floats.apply(Operation.ALPHA_BLEND, 1f, floats.decodeArgument(Operation.ALPHA_BLEND, "@alpha", context)), EPS);
|
||||
assertEquals(TriState.TRUE, TYPES.triState().decode("@yes", context));
|
||||
assertColor(1, 0, 0, 1, TYPES.rgbColor().decode("@channels", context));
|
||||
AttributeType<Color> rgb = TYPES.rgbColor();
|
||||
assertColor(0.385f, 0.135f, 0.135f, 1f,
|
||||
rgb.apply(Operation.BLEND_TO_GRAY, new Color(1f, 0f, 0f, 1f), rgb.decodeArgument(Operation.BLEND_TO_GRAY, "@gray", context)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void plainContext() throws DecodeException {
|
||||
DecodeContext plain = HANDLE.plainContext();
|
||||
Map<String, Object> value = map("a", List.of("$meta.yml:b"));
|
||||
assertSame(value, plain.resolve(value));
|
||||
assertEquals(3f, plain.<Float>load(Float.class, 3), EPS);
|
||||
assertEquals(3.0, plain.<Double>load(Double.class, 3));
|
||||
assertEquals(4, plain.<Integer>load(Integer.class, 4.0));
|
||||
assertEquals("a", plain.load(String.class, "a"));
|
||||
assertEquals(true, plain.load(Boolean.class, true));
|
||||
assertEquals(List.of(1), plain.load(List.class, List.of(1)));
|
||||
assertEquals(Map.of("a", 1), plain.load(Map.class, Map.of("a", 1)));
|
||||
assertEquals("expected a number, got \"${1}\"",
|
||||
assertThrows(DecodeException.class, () -> plain.load(Float.class, "${1}")).getMessage());
|
||||
assertThrows(DecodeException.class, () -> plain.load(String.class, 1));
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.world.attribute.AttributeCodecRoundTripTest.Case;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
|
||||
class EntryFormatTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
|
||||
private static <T> Attribute<T> attribute(Case<T> c) {
|
||||
return HANDLE.attributeBuilder(AttributeKey.<T>parse("test:" + c.type().id()), c.type(), null).build();
|
||||
}
|
||||
|
||||
private static <T> void assertRoundTrip(Case<T> c) throws DecodeException {
|
||||
Attribute<T> attribute = attribute(c);
|
||||
Map<Operation, List<?>> arguments = new LinkedHashMap<>(c.arguments());
|
||||
arguments.put(Operation.OVERRIDE, c.values());
|
||||
assertEquals(c.type().operations(), arguments.keySet(), c.type().id() + " samples every operation");
|
||||
for(Map.Entry<Operation, List<?>> e : arguments.entrySet()) {
|
||||
for(Object argument : e.getValue()) {
|
||||
AttributeEntry<T> entry = AttributeEntry.of(e.getKey(), argument);
|
||||
Object encoded = HANDLE.encodeEntry(attribute, entry);
|
||||
assertEquals(entry, HANDLE.decodeEntry(attribute, encoded, HANDLE.plainContext()),
|
||||
c.type().id() + " " + e.getKey().getID() + " via " + encoded);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTrip() throws DecodeException {
|
||||
for(Case<?> c : AttributeCodecRoundTripTest.cases()) assertRoundTrip(c);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeForms() {
|
||||
Attribute<Color> fog = HANDLE.attributeBuilder(AttributeKey.<Color>parse("test:fog"), HANDLE.types().rgbColor(), null).build();
|
||||
assertEquals("#102030", HANDLE.encodeEntry(fog, AttributeEntry.override(Color.rgb(0x102030))));
|
||||
Attribute<Float> fogEnd = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:fog_end"), HANDLE.types().floatType(), 0f)
|
||||
.build();
|
||||
assertEquals(Map.of("modifier", "multiply", "argument", 0.85f),
|
||||
HANDLE.encodeEntry(fogEnd, AttributeEntry.of(Operation.MULTIPLY, 0.85f)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeNullOverride() {
|
||||
Attribute<Color> colour = HANDLE.attributeBuilder(AttributeKey.<Color>parse("test:sky"), HANDLE.types().rgbColor(), null).build();
|
||||
Attribute<Float> number = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:height"), HANDLE.types().floatType(), null)
|
||||
.build();
|
||||
for(Attribute<?> attribute : List.of(colour, number)) {
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
|
||||
() -> HANDLE.encodeEntry(attribute, AttributeEntry.override(null)));
|
||||
assertEquals("a null override has no pack-format form", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodeInvalidModifier() {
|
||||
Attribute<Boolean> flag = HANDLE.attributeBuilder(AttributeKey.<Boolean>parse("test:flag"), HANDLE.types().booleanType(), false)
|
||||
.build();
|
||||
DecodeException e = assertThrows(DecodeException.class,
|
||||
() -> HANDLE.decodeEntry(flag, Map.of("modifier", "add", "argument", 1), HANDLE.plainContext()));
|
||||
assertEquals("modifier add is not valid for test:flag", e.getMessage());
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
class FixedArityResolveTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
|
||||
private static <T> List<AttributeEntry<T>> choices(AttributeType<T> type, T override, Object... modifiers) throws DecodeException {
|
||||
List<AttributeEntry<T>> choices = new ArrayList<>(Arrays.asList(null, AttributeEntry.override(override)));
|
||||
for(int i = 0; i < modifiers.length; i += 2) {
|
||||
Operation op = (Operation) modifiers[i];
|
||||
choices.add(AttributeEntry.of(op, type.decodeArgument(op, modifiers[i + 1], PLAIN)));
|
||||
}
|
||||
return choices;
|
||||
}
|
||||
|
||||
private static <T> T varargs(Attribute<T> attribute, AttributeEntry<?>... layers) {
|
||||
return HANDLE.resolve(attribute, (AttributeEntry<T>[]) layers);
|
||||
}
|
||||
|
||||
private static <T> void assertSameLayering(Attribute<T> attribute, List<AttributeEntry<T>> choices) {
|
||||
for(AttributeEntry<T> a : choices) {
|
||||
for(AttributeEntry<T> b : choices) {
|
||||
for(AttributeEntry<T> c : choices) {
|
||||
assertEquals(varargs(attribute, a, b, c), HANDLE.resolve(attribute, a, b, c));
|
||||
for(AttributeEntry<T> d : choices) {
|
||||
assertEquals(varargs(attribute, a, b, c, d), HANDLE.resolve(attribute, a, b, c, d),
|
||||
() -> List.of(String.valueOf(a), String.valueOf(b), String.valueOf(c), String.valueOf(d)).toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withDefault() throws DecodeException {
|
||||
AttributeType<Float> type = HANDLE.types().floatType();
|
||||
Attribute<Float> attribute = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:float"), type, 1f).range(0, 10).build();
|
||||
assertSameLayering(attribute, choices(type, 4f, Operation.ADD, 3.0, Operation.MULTIPLY, 2.0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutDefault() throws DecodeException {
|
||||
AttributeType<Color> type = HANDLE.types().rgbColor();
|
||||
Attribute<Color> attribute = HANDLE.attributeBuilder(AttributeKey.<Color>parse("test:color"), type, null).build();
|
||||
assertSameLayering(attribute, choices(type, Color.parseRgb("#102030"), Operation.ADD, "#010101"));
|
||||
}
|
||||
}
|
||||
+416
@@ -0,0 +1,416 @@
|
||||
package com.dfsek.terra.world.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.StringIdentifiable;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeLookup;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeType;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeTypes;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Easing;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Keyframe;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult.Problem;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Named.named;
|
||||
import static org.junit.jupiter.params.provider.Arguments.arguments;
|
||||
|
||||
|
||||
class ScheduleFormatTest {
|
||||
private static final RegistryKey ID = RegistryKey.parse("terra:test");
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final AttributeTypes TYPES = HANDLE.types();
|
||||
private static final Map<String, Attribute<?>> ATTRIBUTES = new LinkedHashMap<>();
|
||||
private static final Attribute<Float> SUN_ANGLE = attribute("minecraft:visual/sun_angle", TYPES.angleDegrees(), 0f);
|
||||
private static final Attribute<MoonPhase> MOON_PHASE = attribute("minecraft:visual/moon_phase",
|
||||
TYPES.enumType("moon_phase", MoonPhase.class), MoonPhase.FULL_MOON);
|
||||
private static final Attribute<Boolean> PATROL = attribute("minecraft:gameplay/can_pillager_patrol_spawn", TYPES.booleanType(),
|
||||
true);
|
||||
private static final Attribute<Float> STAR_BRIGHTNESS = HANDLE.attributeBuilder(
|
||||
AttributeKey.<Float>parse("minecraft:visual/star_brightness"), TYPES.floatType(), 0f).range(0, 1).build();
|
||||
private static final AttributeLookup LOOKUP = ScheduleFormatTest::find;
|
||||
private static final List<String> ORDERED_TRACKS = List.of("minecraft:visual/water_fog_start_distance",
|
||||
"minecraft:visual/sun_angle", "minecraft:visual/fog_start_distance", "minecraft:visual/star_angle",
|
||||
"minecraft:visual/moon_angle", "minecraft:visual/fog_end_distance", "minecraft:visual/cloud_fog_end_distance",
|
||||
"minecraft:visual/sky_fog_end_distance");
|
||||
private static final List<String> ORDERED_MARKERS = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c",
|
||||
"terra:x", "terra:d");
|
||||
|
||||
static {
|
||||
ATTRIBUTES.put(STAR_BRIGHTNESS.key().toString(), STAR_BRIGHTNESS);
|
||||
for(String id : ORDERED_TRACKS) {
|
||||
if(!ATTRIBUTES.containsKey(id)) attribute(id, TYPES.floatType(), 0f);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Attribute<T> attribute(String key, AttributeType<T> type, T defaultValue) {
|
||||
Attribute<T> attribute = HANDLE.attributeBuilder(AttributeKey.<T>parse(key), type, defaultValue).build();
|
||||
ATTRIBUTES.put(key, attribute);
|
||||
return attribute;
|
||||
}
|
||||
|
||||
private static Attribute<?> find(String key) throws DecodeException {
|
||||
Attribute<?> attribute = ATTRIBUTES.get(key);
|
||||
if(attribute == null) throw new DecodeException("unknown attribute");
|
||||
return attribute;
|
||||
}
|
||||
|
||||
private enum MoonPhase implements StringIdentifiable {
|
||||
FULL_MOON("full_moon"),
|
||||
WANING_GIBBOUS("waning_gibbous");
|
||||
|
||||
private final String id;
|
||||
|
||||
MoonPhase(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
private static ScheduleDecodeResult read(Map<String, Object> raw) {
|
||||
return HANDLE.decodeSchedule(ID, raw, LOOKUP, HANDLE.plainContext());
|
||||
}
|
||||
|
||||
private static Map<String, Object> keyframe(int ticks, Object value) {
|
||||
return Map.of("ticks", ticks, "value", value);
|
||||
}
|
||||
|
||||
private static Map<String, Object> schedule(Object period, Map<String, Object> tracks) {
|
||||
Map<String, Object> raw = new LinkedHashMap<>();
|
||||
raw.put("clock", "minecraft:overworld");
|
||||
if(period != null) raw.put("period_ticks", period);
|
||||
raw.put("tracks", tracks);
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static Map<String, Object> sunTrack(Object... frames) {
|
||||
return Map.of("keyframes", List.of(frames));
|
||||
}
|
||||
|
||||
private static Map<String, Object> easedTrack(Object ease, Object... frames) {
|
||||
return Map.of("keyframes", List.of(frames), "ease", ease);
|
||||
}
|
||||
|
||||
private static void assertRejected(ScheduleDecodeResult r, String reasonPart) {
|
||||
assertTrue(r.schedule().isEmpty(), "schedule should be skipped");
|
||||
assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString());
|
||||
Problem skipped = r.skipped().orElseThrow();
|
||||
assertTrue(skipped.reason().contains(reasonPart), skipped.reason());
|
||||
}
|
||||
|
||||
private static void assertClean(ScheduleDecodeResult r) {
|
||||
assertTrue(r.droppedTracks().isEmpty(), r.droppedTracks().toString());
|
||||
assertTrue(r.skipped().isEmpty(), r.skipped().toString());
|
||||
}
|
||||
|
||||
private static DecodeContext expressions(Map<String, Object> values) {
|
||||
return new DecodeContext() {
|
||||
@Override
|
||||
public <V> V load(Type type, Object raw) throws DecodeException {
|
||||
return HANDLE.plainContext().load(type, raw instanceof String s && values.containsKey(s) ? values.get(s) : raw);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(Object raw) {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static final DecodeContext EXPRESSIONS = expressions(
|
||||
Map.of("20 * 60 * 20", 24000.0, "1 / 10", 0.1, "6000 * 2", 12000.0, "3000 * 2", 6000));
|
||||
|
||||
private static Map<String, Object> earlyGameSchedule() {
|
||||
return Map.of(
|
||||
"clock", "minecraft:overworld",
|
||||
"tracks", Map.of("minecraft:gameplay/can_pillager_patrol_spawn", Map.of(
|
||||
"modifier", "and",
|
||||
"keyframes", List.of(keyframe(0, false), keyframe(120000, true)))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> dayStyle() {
|
||||
Map<String, Object> raw = schedule(24000, Map.of("minecraft:visual/sun_angle",
|
||||
sunTrack(keyframe(0, 270.0), keyframe(6000, 360.0), keyframe(6000, 0.0), keyframe(18000, 180.0))));
|
||||
raw.put("time_markers", Map.of(
|
||||
"minecraft:noon", Map.of("ticks", 6000, "show_in_commands", true),
|
||||
"minecraft:wake_up_from_sleep", 0));
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static Map<String, Object> moonStyle() {
|
||||
return schedule(192000, Map.of("minecraft:visual/moon_phase",
|
||||
easedTrack("constant", keyframe(0, "full_moon"), keyframe(24000, "waning_gibbous"))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> cubicBezier() {
|
||||
return schedule(null, Map.of("minecraft:visual/sun_angle",
|
||||
easedTrack(Map.of("cubic_bezier", List.of(0.25, 0.1, 1, 1.0)), keyframe(0, 0.0), keyframe(10, 90.0))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> keyframeAtPeriod() {
|
||||
return schedule(100, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(100, 1.0))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> upperCaseClock() {
|
||||
return Map.of("clock", "minecraft:Overworld", "tracks", Map.of());
|
||||
}
|
||||
|
||||
private static Map<String, Object> ordered() {
|
||||
Map<String, Object> tracks = new LinkedHashMap<>();
|
||||
for(String id : ORDERED_TRACKS) tracks.put(id, sunTrack(keyframe(0, 10.0)));
|
||||
Map<String, Object> markers = new LinkedHashMap<>();
|
||||
for(int i = 0; i < ORDERED_MARKERS.size(); i++) markers.put(ORDERED_MARKERS.get(i), i * 100);
|
||||
Map<String, Object> raw = schedule(24000, tracks);
|
||||
raw.put("time_markers", markers);
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static Map<String, Object> expressionSchedule() {
|
||||
Map<String, Object> raw = schedule("20 * 60 * 20", Map.of("minecraft:visual/sun_angle",
|
||||
easedTrack(Map.of("cubic_bezier", List.of(0.25, "1 / 10", 0.25, 1)), keyframe(0, 270.0),
|
||||
Map.of("ticks", "6000 * 2", "value", 0.0))));
|
||||
raw.put("time_markers", Map.of("minecraft:noon", Map.of("ticks", "3000 * 2"), "minecraft:dusk", "6000 * 2"));
|
||||
return raw;
|
||||
}
|
||||
|
||||
@Test
|
||||
void numberExpressions() {
|
||||
ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, expressionSchedule(), LOOKUP, EXPRESSIONS);
|
||||
assertClean(r);
|
||||
AttributeSchedule def = r.schedule().orElseThrow();
|
||||
assertEquals(24000, def.periodTicks().orElseThrow());
|
||||
assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon")));
|
||||
assertEquals(new TimeMarker(12000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:dusk")));
|
||||
ScheduleTrack<?> track = def.tracks().get(SUN_ANGLE);
|
||||
assertEquals(12000, track.keyframes().get(1).ticks());
|
||||
assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f), track.ease());
|
||||
}
|
||||
|
||||
@Test
|
||||
void integralDouble() {
|
||||
ScheduleDecodeResult r = read(schedule(24000.0, Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0)))));
|
||||
assertClean(r);
|
||||
assertEquals(24000, r.schedule().orElseThrow().periodTicks().orElseThrow());
|
||||
Map<String, Object> raw = schedule(24000, Map.of("minecraft:visual/sun_angle", sunTrack(Map.of("ticks", 6000.0, "value", 0.0))));
|
||||
raw.put("time_markers", Map.of("minecraft:noon", 6000L));
|
||||
AttributeSchedule def = read(raw).schedule().orElseThrow();
|
||||
assertEquals(6000, def.tracks().get(SUN_ANGLE).keyframes().getFirst().ticks());
|
||||
assertEquals(new TimeMarker(6000, false), def.timeMarkers().get(RegistryKey.parse("minecraft:noon")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesVanillaStyleSchedules() {
|
||||
ScheduleDecodeResult early = read(earlyGameSchedule());
|
||||
assertClean(early);
|
||||
AttributeSchedule def = early.schedule().orElseThrow();
|
||||
assertEquals(RegistryKey.parse("minecraft:overworld"), def.clock());
|
||||
assertTrue(def.periodTicks().isEmpty());
|
||||
ScheduleTrack<?> patrol = def.tracks().get(PATROL);
|
||||
assertEquals(Operation.AND, patrol.operation());
|
||||
assertEquals(new Easing.Named("linear"), patrol.ease());
|
||||
assertEquals(List.of(new Keyframe(0, false), new Keyframe(120000, true)), patrol.keyframes());
|
||||
|
||||
ScheduleDecodeResult day = read(dayStyle());
|
||||
assertClean(day);
|
||||
def = day.schedule().orElseThrow();
|
||||
assertEquals(24000, def.periodTicks().orElseThrow());
|
||||
assertEquals(Operation.OVERRIDE, def.tracks().get(SUN_ANGLE).operation());
|
||||
assertEquals(4, def.tracks().get(SUN_ANGLE).keyframes().size());
|
||||
assertEquals(new TimeMarker(6000, true), def.timeMarkers().get(RegistryKey.parse("minecraft:noon")));
|
||||
assertEquals(new TimeMarker(0, false), def.timeMarkers().get(RegistryKey.parse("minecraft:wake_up_from_sleep")));
|
||||
|
||||
ScheduleDecodeResult moon = read(moonStyle());
|
||||
assertClean(moon);
|
||||
ScheduleTrack<?> phase = moon.schedule().orElseThrow().tracks().get(MOON_PHASE);
|
||||
assertEquals(new Keyframe(24000, MoonPhase.WANING_GIBBOUS), phase.keyframes().get(1));
|
||||
assertEquals(new Easing.Named("constant"), phase.ease());
|
||||
|
||||
assertEquals(new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f), read(cubicBezier()).schedule().orElseThrow().tracks().get(SUN_ANGLE).ease());
|
||||
assertEquals(RegistryKey.parse("minecraft:Overworld"), read(upperCaseClock()).schedule().orElseThrow().clock());
|
||||
}
|
||||
|
||||
private static Map<String, Object> withMarkers(Map<String, Object> raw, Map<String, Object> markers) {
|
||||
raw.put("time_markers", markers);
|
||||
return raw;
|
||||
}
|
||||
|
||||
static Stream<Arguments> rejected() {
|
||||
DecodeContext plain = HANDLE.plainContext();
|
||||
Map<String, Object> sun = Map.of("minecraft:visual/sun_angle", sunTrack(keyframe(0, 270.0)));
|
||||
return Stream.of(
|
||||
arguments(named("expression that is not an integer", schedule("5 / 2", sun)), expressions(Map.of("5 / 2", 2.5)),
|
||||
"period_ticks must be an integer"),
|
||||
arguments(named("fractional period", schedule(24000.5, sun)), plain, "period_ticks must be an integer"),
|
||||
arguments(named("expression in a plain context", schedule("20 * 60 * 20", sun)), plain, "period_ticks must be an integer"),
|
||||
arguments(named("non-positive period", schedule(0, Map.of())), plain, "period_ticks"),
|
||||
arguments(named("unsorted keyframes", schedule(null, Map.of("minecraft:visual/sun_angle",
|
||||
sunTrack(keyframe(10, 0.0), keyframe(5, 1.0))))), plain, "sorted"),
|
||||
arguments(named("three keyframes on one tick", schedule(null, Map.of("minecraft:visual/sun_angle",
|
||||
sunTrack(keyframe(5, 0.0), keyframe(5, 1.0), keyframe(5, 2.0))))), plain, "tick"),
|
||||
arguments(named("no keyframes", schedule(null, Map.of("minecraft:visual/sun_angle", sunTrack()))), plain, "keyframes"),
|
||||
arguments(named("keyframe beyond the period", schedule(100, Map.of("minecraft:visual/sun_angle",
|
||||
sunTrack(keyframe(0, 0.0), keyframe(101, 1.0))))), plain, "period"),
|
||||
arguments(named("marker equal to the period", withMarkers(schedule(100, Map.of()), Map.of("minecraft:noon", 100))), plain,
|
||||
"period"),
|
||||
arguments(named("bezier x out of range", schedule(null, Map.of("minecraft:visual/sun_angle",
|
||||
easedTrack(Map.of("cubic_bezier", List.of(1.5, 0, 0.5, 1)), keyframe(0, 0.0), keyframe(10, 1.0))))), plain,
|
||||
"cubic_bezier"),
|
||||
arguments(named("unknown easing", schedule(null, Map.of("minecraft:visual/sun_angle",
|
||||
easedTrack("wobbly", keyframe(0, 0.0), keyframe(10, 1.0))))), plain, "wobbly"),
|
||||
arguments(named("missing clock", Map.of("tracks", Map.of())), plain, "clock"),
|
||||
arguments(named("tag clock", Map.of("clock", "#minecraft:clocks", "tracks", Map.of())), plain, "clock must not be a tag"),
|
||||
arguments(named("bare clock", Map.of("clock", "overworld", "tracks", Map.of())), plain,
|
||||
"clock: a namespace is required, as in \"namespace:overworld\""),
|
||||
arguments(named("bare time marker", withMarkers(schedule(24000, Map.of()), Map.of("noon", 6000))), plain,
|
||||
"time marker key: a namespace is required, as in \"namespace:noon\""));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void rejected(Map<String, Object> raw, DecodeContext context, String reasonPart) {
|
||||
ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context);
|
||||
assertRejected(r, reasonPart);
|
||||
assertEquals("terra:test", r.skipped().orElseThrow().key());
|
||||
}
|
||||
|
||||
static Stream<Arguments> droppedTrack() {
|
||||
return Stream.of(
|
||||
arguments(named("unknown attribute", sunTrack(keyframe(0, 0.0))), "minecraft:visual/not_real", "unknown attribute"),
|
||||
arguments(named("bad keyframe value", sunTrack(keyframe(0, "not_a_phase"))), "minecraft:visual/moon_phase",
|
||||
"unknown moon phase \"not_a_phase\", expected one of [full_moon, waning_gibbous]"),
|
||||
arguments(named("modifier not valid for the type", Map.of("modifier", "add", "keyframes", List.of(keyframe(0, "full_moon")))),
|
||||
"minecraft:visual/moon_phase", "modifier add is not valid for minecraft:visual/moon_phase"),
|
||||
arguments(named("override out of range", sunTrack(keyframe(0, 5.0))), "minecraft:visual/star_brightness",
|
||||
"value 5.0 is outside [0, 1]"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource
|
||||
void droppedTrack(Map<String, Object> track, String key, String reason) {
|
||||
ScheduleDecodeResult r = read(schedule(null, Map.of(key, track, "minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0)))));
|
||||
assertEquals(List.of(new Problem(key, reason)), r.droppedTracks());
|
||||
assertTrue(r.skipped().isEmpty());
|
||||
assertEquals(Set.of(SUN_ANGLE), r.schedule().orElseThrow().tracks().keySet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppedTracksOnSkip() {
|
||||
Map<String, Object> tracks = new LinkedHashMap<>();
|
||||
tracks.put("minecraft:visual/not_real", sunTrack(keyframe(0, 0.0)));
|
||||
tracks.put("minecraft:visual/sun_angle", sunTrack(keyframe(0, 0.0), keyframe(200, 1.0)));
|
||||
ScheduleDecodeResult r = read(schedule(100, tracks));
|
||||
assertTrue(r.schedule().isEmpty());
|
||||
assertEquals(List.of(new Problem("minecraft:visual/not_real", "unknown attribute")), r.droppedTracks());
|
||||
assertEquals(new Problem("terra:test", "keyframe ticks 200 must be within period_ticks 100"), r.skipped().orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void configOrder() {
|
||||
ScheduleDecodeResult r = read(ordered());
|
||||
assertClean(r);
|
||||
AttributeSchedule def = r.schedule().orElseThrow();
|
||||
assertEquals(ORDERED_TRACKS, def.tracks().keySet().stream().map(attribute -> attribute.getRegistryKey().toString()).toList());
|
||||
assertEquals(ORDERED_MARKERS, def.timeMarkers().keySet().stream().map(RegistryKey::toString).toList());
|
||||
}
|
||||
|
||||
private static AttributeSchedule decode(Map<String, Object> raw, DecodeContext context) {
|
||||
ScheduleDecodeResult r = HANDLE.decodeSchedule(ID, raw, LOOKUP, context);
|
||||
assertClean(r);
|
||||
return r.schedule().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void roundTrip() {
|
||||
Map<String, Map<String, Object>> fixtures = new LinkedHashMap<>();
|
||||
fixtures.put("earlyGame", earlyGameSchedule());
|
||||
fixtures.put("dayStyle", dayStyle());
|
||||
fixtures.put("moonStyle", moonStyle());
|
||||
fixtures.put("cubicBezier", cubicBezier());
|
||||
fixtures.put("keyframeAtPeriod", keyframeAtPeriod());
|
||||
fixtures.put("upperCaseClock", upperCaseClock());
|
||||
fixtures.put("ordered", ordered());
|
||||
fixtures.forEach((name, raw) -> {
|
||||
AttributeSchedule schedule = decode(raw, HANDLE.plainContext());
|
||||
Map<String, Object> encoded = HANDLE.encodeSchedule(schedule);
|
||||
AttributeSchedule again = decode(encoded, HANDLE.plainContext());
|
||||
assertEquals(schedule, again, name + " via " + encoded);
|
||||
assertEquals(List.copyOf(schedule.tracks().keySet()), List.copyOf(again.tracks().keySet()), name + " track order");
|
||||
assertEquals(List.copyOf(schedule.timeMarkers().keySet()), List.copyOf(again.timeMarkers().keySet()),
|
||||
name + " marker order");
|
||||
});
|
||||
AttributeSchedule evaluated = decode(expressionSchedule(), EXPRESSIONS);
|
||||
assertEquals(evaluated, decode(HANDLE.encodeSchedule(evaluated), HANDLE.plainContext()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeOmitsDefaults() {
|
||||
AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(),
|
||||
Map.of(SUN_ANGLE, new ScheduleTrack<Float>(Operation.OVERRIDE, List.of(new Keyframe(0, 270f)), new Easing.Named("linear"))),
|
||||
Map.of(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, false)));
|
||||
assertEquals(Map.of(
|
||||
"clock", "minecraft:overworld",
|
||||
"tracks", Map.of("minecraft:visual/sun_angle", Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 270f)))),
|
||||
"time_markers", Map.of("minecraft:noon", Map.of("ticks", 6000))),
|
||||
HANDLE.encodeSchedule(schedule));
|
||||
AttributeSchedule empty = new AttributeSchedule(RegistryKey.parse("minecraft:overworld"), OptionalInt.empty(), Map.of(), Map.of());
|
||||
assertEquals(Map.of("clock", "minecraft:overworld"), HANDLE.encodeSchedule(empty));
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeNullKeyframe() {
|
||||
AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.empty(),
|
||||
Map.of(SUN_ANGLE, new ScheduleTrack<Float>(Operation.OVERRIDE, List.of(new Keyframe(0, null)), new Easing.Named("linear"))),
|
||||
Map.of());
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> HANDLE.encodeSchedule(schedule));
|
||||
assertEquals("keyframe 0 of minecraft:visual/sun_angle: a null value has no pack-format form", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodeNonDefaults() {
|
||||
AttributeSchedule schedule = new AttributeSchedule(RegistryKey.parse("mypack:day"), OptionalInt.of(24000),
|
||||
Map.of(SUN_ANGLE, new ScheduleTrack<Float>(Operation.ADD, List.of(new Keyframe(0, 1f), new Keyframe(10, 2f)),
|
||||
new Easing.CubicBezier(0.25f, 0.1f, 1f, 1f)),
|
||||
MOON_PHASE, new ScheduleTrack<MoonPhase>(Operation.OVERRIDE, List.of(new Keyframe(0, MoonPhase.WANING_GIBBOUS)),
|
||||
new Easing.Named("constant"))),
|
||||
Map.of(RegistryKey.parse("mypack:noon"), new TimeMarker(6000, true)));
|
||||
Map<String, Object> encoded = HANDLE.encodeSchedule(schedule);
|
||||
assertEquals("mypack:day", encoded.get("clock"));
|
||||
assertEquals(24000, encoded.get("period_ticks"));
|
||||
assertEquals(Map.of("mypack:noon", Map.of("ticks", 6000, "show_in_commands", true)), encoded.get("time_markers"));
|
||||
Map<?, ?> tracks = (Map<?, ?>) encoded.get("tracks");
|
||||
assertEquals(Map.of(
|
||||
"modifier", "add",
|
||||
"ease", Map.of("cubic_bezier", List.of(0.25f, 0.1f, 1f, 1f)),
|
||||
"keyframes", List.of(Map.of("ticks", 0, "value", 1f), Map.of("ticks", 10, "value", 2f))),
|
||||
tracks.get("minecraft:visual/sun_angle"));
|
||||
assertEquals(Map.of(
|
||||
"ease", "constant",
|
||||
"keyframes", List.of(Map.of("ticks", 0, "value", "waning_gibbous"))),
|
||||
tracks.get("minecraft:visual/moon_phase"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user