mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-11-29 17:34:52 +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
+194
@@ -0,0 +1,194 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.helpers.MessageFormatter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
|
||||
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
|
||||
import com.dfsek.terra.api.Platform;
|
||||
import com.dfsek.terra.api.addon.BaseAddon;
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
|
||||
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent;
|
||||
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
|
||||
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
|
||||
import com.dfsek.terra.api.inject.annotations.Inject;
|
||||
import com.dfsek.terra.api.properties.Context;
|
||||
import com.dfsek.terra.api.properties.PropertyKey;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
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.api.world.biome.Biome;
|
||||
|
||||
|
||||
/**
|
||||
* Biome configs load in parallel: the biome handler may only read shared immutable state and write to its own biome.
|
||||
*/
|
||||
public class AttributeAddon implements AddonInitializer {
|
||||
private static final String ATTRIBUTE_WARNING = "Pack \"{}\", config \"{}\": attribute \"{}\" skipped: {}";
|
||||
private static final String SCHEDULE_SKIPPED = "Pack \"{}\": schedule \"{}\" skipped: {}";
|
||||
private static final String TRACK_DROPPED = "Pack \"{}\": schedule \"{}\" track \"{}\" dropped: {}";
|
||||
private static final String PARENT_WARNING = "Pack \"{}\", config \"{}\": \"{}\" ignored: {}";
|
||||
private static final String PACK_CONFIG = "pack.yml";
|
||||
private static final String VANILLA = "vanilla";
|
||||
private static final String VANILLA_GENERATION = "vanilla-generation";
|
||||
|
||||
@Inject
|
||||
private Platform platform;
|
||||
|
||||
@Inject
|
||||
private BaseAddon addon;
|
||||
|
||||
@Inject
|
||||
private Logger logger;
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
AttributeHandle handle = platform.getAttributeHandle();
|
||||
// Before any parallel load: Context.create is not thread safe.
|
||||
PropertyKey<BiomeAttributeEntries> biomeKey = Context.create(BiomeAttributeEntries.class);
|
||||
PropertyKey<PackAttributes> packKey = Context.create(PackAttributes.class);
|
||||
|
||||
platform.getEventManager()
|
||||
.getHandler(FunctionalEventHandler.class)
|
||||
.register(addon, ConfigPackPreLoadEvent.class)
|
||||
.then(event -> {
|
||||
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) event.getPack().applyLoader(type, LazyConfigValue.LOADER);
|
||||
})
|
||||
.failThrough();
|
||||
|
||||
platform.getEventManager()
|
||||
.getHandler(FunctionalEventHandler.class)
|
||||
.register(addon, ConfigurationLoadEvent.class)
|
||||
.then(event -> {
|
||||
if(!event.is(Biome.class)) return;
|
||||
Map<String, LazyConfigValue> raw = event.load(new BiomeAttributesTemplate()).getAttributes();
|
||||
AttributeReader reader = new AttributeReader(event.getPack().getRegistry(Attribute.REGISTRY_TYPE), handle);
|
||||
Result result = reader.readConfig(raw, Scope.BIOME);
|
||||
List<String> warnings = new ArrayList<>();
|
||||
for(Problem problem : result.problems()) {
|
||||
warnings.add(warn(ATTRIBUTE_WARNING, event.getPack(), event.getConfiguration().getID(), problem.key(),
|
||||
problem.reason()));
|
||||
}
|
||||
event.getLoadedObject(Biome.class).getContext().put(biomeKey, new BiomeAttributeEntries(result.map(), warnings));
|
||||
})
|
||||
.failThrough();
|
||||
|
||||
platform.getEventManager()
|
||||
.getHandler(FunctionalEventHandler.class)
|
||||
.register(addon, ConfigPackPostLoadEvent.class)
|
||||
.then(event -> {
|
||||
ConfigPack pack = event.getPack();
|
||||
Registry<Attribute<?>> attributes = pack.getRegistry(Attribute.REGISTRY_TYPE);
|
||||
PackAttributesTemplate template = event.loadTemplate(new PackAttributesTemplate());
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
Result result = new AttributeReader(attributes, handle).readConfig(template.getAttributes(), Scope.PACK);
|
||||
for(Problem problem : result.problems()) {
|
||||
warnings.add(warn(ATTRIBUTE_WARNING, pack, PACK_CONFIG, problem.key(), problem.reason()));
|
||||
}
|
||||
|
||||
Map<String, RegistryKey> parents = new LinkedHashMap<>();
|
||||
parent(parents, VANILLA, template.getVanilla(), pack, warnings);
|
||||
parent(parents, VANILLA_GENERATION, template.getVanillaGeneration(), pack, warnings);
|
||||
|
||||
List<Either<RegistryKey, TagKey>> schedules = new ArrayList<>();
|
||||
for(String schedule : template.getSchedules()) {
|
||||
try {
|
||||
schedules.add(ScheduleIds.reference(schedule));
|
||||
} catch(IllegalArgumentException e) {
|
||||
warnings.add(warn(SCHEDULE_SKIPPED, pack, schedule, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
|
||||
Set<RegistryKey> claimed = new HashSet<>();
|
||||
RegistryAttributeLookup lookup = new RegistryAttributeLookup(attributes);
|
||||
template.getScheduleDefinitions().forEach((idString, lazy) -> {
|
||||
RegistryKey id;
|
||||
try {
|
||||
id = ScheduleIds.claim(idString, claimed);
|
||||
} catch(IllegalArgumentException e) {
|
||||
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
|
||||
return;
|
||||
}
|
||||
DecodeContext context;
|
||||
Object value;
|
||||
try {
|
||||
context = lazy == null ? handle.plainContext() : lazy.context(handle.plainContext());
|
||||
value = lazy == null ? null : context.resolve(lazy.raw());
|
||||
} catch(DecodeException e) {
|
||||
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
|
||||
return;
|
||||
}
|
||||
if(!(value instanceof Map<?, ?> map) || !map.keySet().stream().allMatch(String.class::isInstance)) {
|
||||
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, "a schedule must be a map"));
|
||||
return;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> raw = (Map<String, Object>) map;
|
||||
ScheduleDecodeResult schedule = handle.decodeSchedule(id, raw, lookup, context);
|
||||
for(ScheduleDecodeResult.Problem problem : schedule.droppedTracks()) {
|
||||
warnings.add(warn(TRACK_DROPPED, pack, idString, problem.key(), problem.reason()));
|
||||
}
|
||||
schedule.skipped().ifPresent(problem -> warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, problem.reason())));
|
||||
schedule.schedule().ifPresent(definition -> definitions.put(id, definition));
|
||||
});
|
||||
|
||||
pack.getContext().put(packKey, new PackAttributesImpl(handle, platform.getAttributeParents(), attributes,
|
||||
result.map(),
|
||||
parents,
|
||||
schedules,
|
||||
definitions,
|
||||
biomeEntries(pack, biomeKey),
|
||||
warnings));
|
||||
})
|
||||
.failThrough();
|
||||
}
|
||||
|
||||
private static AttributeMap[] biomeEntries(ConfigPack pack, PropertyKey<BiomeAttributeEntries> biomeKey) {
|
||||
Registry<Biome> biomes = pack.getRegistry(Biome.class);
|
||||
if(biomes == null) return new AttributeMap[0];
|
||||
AttributeMap[] entries = new AttributeMap[pack.getBiomeTagIndex().size()];
|
||||
biomes.forEach(biome -> {
|
||||
if(biome.getContext().has(biomeKey)) entries[biome.getIntID()] = biome.getContext().get(biomeKey).entries();
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
private void parent(Map<String, RegistryKey> parents, String key, Optional<String> value, ConfigPack pack, List<String> warnings) {
|
||||
if(value.isEmpty()) return;
|
||||
try {
|
||||
parents.put(key, RegistryKey.parseNamespaced(value.get()));
|
||||
} catch(IllegalArgumentException e) {
|
||||
warnings.add(warn(PARENT_WARNING, pack, PACK_CONFIG, key, e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
private String warn(String format, ConfigPack pack, Object... args) {
|
||||
Object[] all = new Object[args.length + 1];
|
||||
all[0] = pack.getID();
|
||||
System.arraycopy(args, 0, all, 1, args.length);
|
||||
logger.warn(format, all);
|
||||
return MessageFormatter.arrayFormat(format, all).getMessage();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeScope;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
public final class AttributeReader {
|
||||
private final RegistryAttributeLookup lookup;
|
||||
private final AttributeHandle handle;
|
||||
|
||||
public AttributeReader(@Nullable Registry<Attribute<?>> registry, AttributeHandle handle) {
|
||||
this.lookup = new RegistryAttributeLookup(registry);
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
public enum Scope { BIOME, PACK }
|
||||
|
||||
|
||||
public record Result(AttributeMap map, List<Problem> problems) { }
|
||||
|
||||
|
||||
public record Problem(String key, String reason) { }
|
||||
|
||||
|
||||
private record Value(Object raw, DecodeContext context) { }
|
||||
|
||||
public Result read(Map<String, Object> raw, Scope scope) {
|
||||
DecodeContext plain = handle.plainContext();
|
||||
Map<String, Value> values = new LinkedHashMap<>();
|
||||
raw.forEach((key, value) -> values.put(key, new Value(value, plain)));
|
||||
return readValues(values, scope);
|
||||
}
|
||||
|
||||
Result readConfig(Map<String, LazyConfigValue> config, Scope scope) {
|
||||
DecodeContext plain = handle.plainContext();
|
||||
Map<String, Value> values = new LinkedHashMap<>();
|
||||
config.forEach((key, value) -> values.put(key, value == null
|
||||
? new Value(null, plain)
|
||||
: new Value(value.raw(), value.context(plain))));
|
||||
return readValues(values, scope);
|
||||
}
|
||||
|
||||
private Result readValues(Map<String, Value> raw, Scope scope) {
|
||||
AttributeMap.Builder builder = AttributeMap.builder();
|
||||
List<Problem> problems = new ArrayList<>();
|
||||
for(Map.Entry<String, Value> entry : raw.entrySet()) {
|
||||
String keyString = entry.getKey();
|
||||
Attribute<?> attribute;
|
||||
try {
|
||||
attribute = lookup.find(keyString);
|
||||
} catch(DecodeException e) {
|
||||
problems.add(new Problem(keyString, e.getMessage()));
|
||||
continue;
|
||||
}
|
||||
if(scope == Scope.BIOME && attribute.scope() == AttributeScope.PACK_ONLY) {
|
||||
problems.add(new Problem(keyString, "not allowed in a biome"));
|
||||
continue;
|
||||
}
|
||||
// Explicit null un-sets an inherited value.
|
||||
if(entry.getValue().raw() == null) continue;
|
||||
try {
|
||||
put(builder, attribute, entry.getValue().raw(), entry.getValue().context());
|
||||
} catch(DecodeException | RuntimeException e) {
|
||||
problems.add(new Problem(keyString, e.getMessage() == null ? "unexpected error" : e.getMessage()));
|
||||
}
|
||||
}
|
||||
return new Result(builder.build(), problems);
|
||||
}
|
||||
|
||||
private <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, Object value, DecodeContext context)
|
||||
throws DecodeException {
|
||||
builder.put(attribute.key(), handle.decodeEntry(attribute, value, context));
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dfsek.terra.api.properties.Properties;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
|
||||
|
||||
record BiomeAttributeEntries(AttributeMap entries, List<String> warnings) implements Properties {
|
||||
BiomeAttributeEntries {
|
||||
warnings = List.copyOf(warnings);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
|
||||
import com.dfsek.tectonic.api.config.template.annotations.Default;
|
||||
import com.dfsek.tectonic.api.config.template.annotations.Merge;
|
||||
import com.dfsek.tectonic.api.config.template.annotations.Value;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.config.meta.Meta;
|
||||
|
||||
|
||||
public class BiomeAttributesTemplate implements ConfigTemplate {
|
||||
@Value("attributes")
|
||||
@Merge
|
||||
@Default
|
||||
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
|
||||
|
||||
Map<String, LazyConfigValue> getAttributes() {
|
||||
return Collections.unmodifiableMap(attributes);
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import com.dfsek.tectonic.api.depth.DepthTracker;
|
||||
import com.dfsek.tectonic.api.exception.ConfigException;
|
||||
import com.dfsek.tectonic.api.exception.LoadException;
|
||||
import com.dfsek.tectonic.api.loader.ConfigLoader;
|
||||
|
||||
import java.lang.reflect.AnnotatedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.AbstractList;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.config.meta.Meta;
|
||||
import com.dfsek.terra.api.util.reflection.TypeKey;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
/**
|
||||
* Tectonic picks preprocessors by declared type.
|
||||
* <p>
|
||||
* Not thread safe: include preprocessors mutate the {@link DepthTracker}.
|
||||
*/
|
||||
final class ConfigDecodeContext implements DecodeContext {
|
||||
static final List<Class<?>> CAPTURED_TYPES = List.of(LazyConfigValue.class, MapShape.class, ListShape.class);
|
||||
|
||||
private static final AnnotatedType WHOLE_VALUE = new TypeKey<@Meta LazyConfigValue>() { }.getAnnotatedType();
|
||||
private static final AnnotatedType MAP = new TypeKey<@Meta MapShape<String, LazyConfigValue>>() { }.getAnnotatedType();
|
||||
private static final AnnotatedType LIST = new TypeKey<@Meta ListShape<LazyConfigValue>>() { }.getAnnotatedType();
|
||||
private static final AnnotatedType STRING = new TypeKey<@Meta String>() { }.getAnnotatedType();
|
||||
private static final AnnotatedType NUMBER = new TypeKey<@Meta Double>() { }.getAnnotatedType();
|
||||
|
||||
private final ConfigLoader loader;
|
||||
private final DepthTracker tracker;
|
||||
private final DecodeContext plain;
|
||||
private final Set<Object> resolved = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
|
||||
ConfigDecodeContext(ConfigLoader loader, DepthTracker tracker, DecodeContext plain) {
|
||||
this.loader = loader;
|
||||
this.tracker = tracker;
|
||||
this.plain = plain;
|
||||
}
|
||||
|
||||
private static boolean numeric(Type type) {
|
||||
return type instanceof Class<?> c && Number.class.isAssignableFrom(c);
|
||||
}
|
||||
|
||||
private static DecodeException failure(RuntimeException e) {
|
||||
String message = e instanceof ConfigException && e.getMessage() != null ? e.getMessage().strip() : "config preprocessing failed";
|
||||
// Tectonic leaves some details only in the cause.
|
||||
Throwable cause = e.getCause();
|
||||
boolean readable = cause instanceof ConfigException
|
||||
|| cause != null && !(cause instanceof RuntimeException || cause instanceof Error);
|
||||
if(readable && cause.getMessage() != null && !message.contains(cause.getMessage().strip())) {
|
||||
message += "\n\tCaused by: " + cause.getMessage().strip();
|
||||
}
|
||||
return new DecodeException(message, e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <V> V load(Type type, Object raw) throws DecodeException {
|
||||
Object value = resolve(raw);
|
||||
if(value instanceof String expression && numeric(type)) {
|
||||
try {
|
||||
value = loadType(NUMBER, expression, tracker);
|
||||
} catch(RuntimeException e) {
|
||||
throw failure(e);
|
||||
}
|
||||
}
|
||||
return plain.load(type, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolve(Object raw) throws DecodeException {
|
||||
try {
|
||||
return resolve(raw, tracker);
|
||||
} catch(RuntimeException e) {
|
||||
throw failure(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Object resolve(Object raw, DepthTracker at) {
|
||||
if(raw == null || raw instanceof Number || raw instanceof Boolean || resolved.contains(raw)) return raw;
|
||||
LazyConfigValue whole = capture(WHOLE_VALUE, raw, at);
|
||||
Object value = whole.raw();
|
||||
Object out;
|
||||
if(value instanceof String) {
|
||||
out = loadType(STRING, raw, at);
|
||||
} else if(value instanceof Map<?, ?>) {
|
||||
LazyConfigValue included = capture(MAP, value, whole.tracker());
|
||||
Map<Object, Object> map = new LinkedHashMap<>();
|
||||
for(Map.Entry<?, ?> entry : ((Map<?, ?>) included.raw()).entrySet()) {
|
||||
map.put(entry.getKey(), resolve(entry.getValue(), included.tracker().entry(String.valueOf(entry.getKey()))));
|
||||
}
|
||||
out = Collections.unmodifiableMap(map);
|
||||
} else if(value instanceof List<?>) {
|
||||
LazyConfigValue included = capture(LIST, value, whole.tracker());
|
||||
List<?> elements = (List<?>) included.raw();
|
||||
List<Object> list = new ArrayList<>(elements.size());
|
||||
for(int i = 0; i < elements.size(); i++) list.add(resolve(elements.get(i), included.tracker().index(i)));
|
||||
out = Collections.unmodifiableList(list);
|
||||
} else {
|
||||
out = value;
|
||||
}
|
||||
if(out != null) resolved.add(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
private LazyConfigValue capture(AnnotatedType type, Object raw, DepthTracker at) {
|
||||
return (LazyConfigValue) loadType(type, raw, at);
|
||||
}
|
||||
|
||||
private Object loadType(AnnotatedType type, Object raw, DepthTracker at) {
|
||||
try {
|
||||
return loader.loadType(type, raw, at);
|
||||
} catch(ConfigException e) {
|
||||
throw e;
|
||||
} catch(RuntimeException e) {
|
||||
throw new LoadException("config preprocessing failed", e, at);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private abstract static class MapShape<K, V> extends AbstractMap<K, V> { }
|
||||
|
||||
|
||||
private abstract static class ListShape<E> extends AbstractList<E> { }
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import com.dfsek.tectonic.api.depth.DepthTracker;
|
||||
import com.dfsek.tectonic.api.loader.ConfigLoader;
|
||||
import com.dfsek.tectonic.api.loader.type.TypeLoader;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
|
||||
|
||||
/**
|
||||
* Use only on the thread that loaded it: the {@link DepthTracker} is mutable.
|
||||
*/
|
||||
record LazyConfigValue(Object raw, ConfigLoader loader, DepthTracker tracker) {
|
||||
static final TypeLoader<LazyConfigValue> LOADER = (type, o, loader, depthTracker) -> new LazyConfigValue(o, loader, depthTracker);
|
||||
|
||||
DecodeContext context(DecodeContext plain) {
|
||||
return new ConfigDecodeContext(loader, tracker, plain);
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
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.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeParents;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.biome.Biome;
|
||||
|
||||
|
||||
/**
|
||||
* {@link #biomeEntryOrNull}, {@link #resolve} and {@link #resolvePack} must not allocate.
|
||||
*/
|
||||
public final class PackAttributesImpl implements PackAttributes {
|
||||
private final AttributeHandle handle;
|
||||
private final AttributeParents attributeParents;
|
||||
private final AttributeMap entries;
|
||||
private final AttributeEntry<?>[] packEntries;
|
||||
private final AttributeEntry<?>[][] columns;
|
||||
private final AttributeMap[] biomeEntries;
|
||||
private final Map<String, RegistryKey> parents;
|
||||
private final List<Either<RegistryKey, TagKey>> scheduleRefs;
|
||||
private final Map<RegistryKey, AttributeSchedule> scheduleDefinitions;
|
||||
private final List<String> warnings;
|
||||
|
||||
public PackAttributesImpl(AttributeHandle handle, AttributeParents attributeParents, @Nullable Registry<Attribute<?>> attributes,
|
||||
AttributeMap entries, Map<String, RegistryKey> parents,
|
||||
List<Either<RegistryKey, TagKey>> scheduleRefs, Map<RegistryKey, AttributeSchedule> scheduleDefinitions,
|
||||
AttributeMap[] biomeEntries, List<String> warnings) {
|
||||
this.handle = handle;
|
||||
this.attributeParents = attributeParents;
|
||||
this.entries = entries;
|
||||
this.packEntries = new AttributeEntry<?>[handle.attributeCount()];
|
||||
for(AttributeKey<?> key : entries.keys()) {
|
||||
packEntries[attribute(attributes, key).index()] = entries.get(key).orElseThrow();
|
||||
}
|
||||
this.columns = new AttributeEntry<?>[handle.attributeCount()][];
|
||||
for(int id = 0; id < biomeEntries.length; id++) {
|
||||
AttributeMap declared = biomeEntries[id];
|
||||
if(declared == null) continue;
|
||||
for(AttributeKey<?> key : declared.keys()) {
|
||||
int index = attribute(attributes, key).index();
|
||||
if(columns[index] == null) columns[index] = new AttributeEntry<?>[biomeEntries.length];
|
||||
columns[index][id] = declared.get(key).orElseThrow();
|
||||
}
|
||||
}
|
||||
this.biomeEntries = biomeEntries;
|
||||
this.parents = Collections.unmodifiableMap(new LinkedHashMap<>(parents));
|
||||
this.scheduleRefs = List.copyOf(scheduleRefs);
|
||||
this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions));
|
||||
this.warnings = List.copyOf(warnings);
|
||||
}
|
||||
|
||||
private static Attribute<?> attribute(@Nullable Registry<Attribute<?>> attributes, AttributeKey<?> key) {
|
||||
if(attributes == null) throw new IllegalArgumentException("entry " + key + " given for a pack without attributes");
|
||||
return attributes.get(key.getRegistryKey())
|
||||
.orElseThrow(() -> new IllegalArgumentException("entry " + key + " names no attribute of the pack"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeMap entries() {
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, RegistryKey> parents() {
|
||||
return parents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Either<RegistryKey, TagKey>> scheduleRefs() {
|
||||
return scheduleRefs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<RegistryKey, AttributeSchedule> scheduleDefinitions() {
|
||||
return scheduleDefinitions;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> @Nullable AttributeEntry<T> biomeEntryOrNull(Attribute<T> attribute, Biome biome) {
|
||||
int index = attribute.index();
|
||||
if(index >= columns.length) return null;
|
||||
AttributeEntry<?>[] column = columns[index];
|
||||
if(column == null) return null;
|
||||
int id = biome.getIntID();
|
||||
if(id < 0 || id >= column.length) return null;
|
||||
return (AttributeEntry<T>) column[id];
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeMap biomeEntries(Biome biome) {
|
||||
int id = biome.getIntID();
|
||||
if(id < 0 || id >= biomeEntries.length || biomeEntries[id] == null) return AttributeMap.empty();
|
||||
return biomeEntries[id];
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> @Nullable AttributeEntry<T> packEntryOrNull(Attribute<T> attribute) {
|
||||
int index = attribute.index();
|
||||
return index < packEntries.length ? (AttributeEntry<T>) packEntries[index] : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolve(Attribute<T> attribute, Biome biome) {
|
||||
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute),
|
||||
attributeParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolvePack(Attribute<T> attribute) {
|
||||
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), null);
|
||||
}
|
||||
|
||||
public List<String> warnings() {
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
|
||||
import com.dfsek.tectonic.api.config.template.annotations.Default;
|
||||
import com.dfsek.tectonic.api.config.template.annotations.Value;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.dfsek.terra.api.config.meta.Meta;
|
||||
|
||||
|
||||
public class PackAttributesTemplate implements ConfigTemplate {
|
||||
@Value("attributes")
|
||||
@Default
|
||||
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
|
||||
|
||||
@Value("schedules")
|
||||
@Default
|
||||
private @Meta List<@Meta String> schedules = List.of();
|
||||
|
||||
@Value("schedule-definitions")
|
||||
@Default
|
||||
private @Meta Map<@Meta String, LazyConfigValue> scheduleDefinitions = Map.of();
|
||||
|
||||
// May be a map (vanilla.mobs); only a string names a parent.
|
||||
@Value("vanilla")
|
||||
@Default
|
||||
private @Meta LazyConfigValue vanilla = null;
|
||||
|
||||
@Value("vanilla-generation")
|
||||
@Default
|
||||
private @Meta LazyConfigValue vanillaGeneration = null;
|
||||
|
||||
Map<String, LazyConfigValue> getAttributes() {
|
||||
return Collections.unmodifiableMap(attributes);
|
||||
}
|
||||
|
||||
public List<String> getSchedules() {
|
||||
return schedules;
|
||||
}
|
||||
|
||||
Map<String, LazyConfigValue> getScheduleDefinitions() {
|
||||
return Collections.unmodifiableMap(scheduleDefinitions);
|
||||
}
|
||||
|
||||
public Optional<String> getVanilla() {
|
||||
return string(vanilla);
|
||||
}
|
||||
|
||||
public Optional<String> getVanillaGeneration() {
|
||||
return string(vanillaGeneration);
|
||||
}
|
||||
|
||||
private static Optional<String> string(LazyConfigValue value) {
|
||||
return value != null && value.raw() instanceof String s ? Optional.of(s) : Optional.empty();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeLookup;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
/**
|
||||
* Keys must be fully namespaced: inheritance merges config maps by raw key text.
|
||||
*/
|
||||
public final class RegistryAttributeLookup implements AttributeLookup {
|
||||
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
|
||||
private static final String UNKNOWN = "unknown attribute";
|
||||
private static final Map<String, String> NAMESPACE_ADDONS = Map.of(
|
||||
"minecraft", "minecraft-attributes",
|
||||
"terra", "minecraft-attributes");
|
||||
|
||||
private final @Nullable Registry<Attribute<?>> registry;
|
||||
|
||||
public RegistryAttributeLookup(@Nullable Registry<Attribute<?>> registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Attribute<?> find(String key) throws DecodeException {
|
||||
AttributeKey<?> parsed;
|
||||
try {
|
||||
parsed = AttributeKey.parse(key);
|
||||
} catch(IllegalArgumentException e) {
|
||||
if(key.indexOf(':') < 0) throw new DecodeException(NAMESPACE_REQUIRED, e);
|
||||
throw new DecodeException(invalidKey(e), e);
|
||||
}
|
||||
Attribute<?> attribute = registry == null ? null : registry.get(parsed.getRegistryKey()).orElse(null);
|
||||
if(attribute == null) throw new DecodeException(unknownAttribute(parsed.getRegistryKey()));
|
||||
return attribute;
|
||||
}
|
||||
|
||||
private static String invalidKey(IllegalArgumentException e) {
|
||||
Throwable cause = e.getCause() == null ? e : e.getCause();
|
||||
String message = cause.getMessage();
|
||||
return message == null ? "invalid attribute key" : "invalid attribute key: " + message;
|
||||
}
|
||||
|
||||
private String unknownAttribute(RegistryKey key) {
|
||||
String namespace = key.getNamespace();
|
||||
String addon = NAMESPACE_ADDONS.get(namespace);
|
||||
if(addon == null) return UNKNOWN;
|
||||
if(registry != null && registry.keys().stream().anyMatch(registered -> registered.getNamespace().equals(namespace))) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
return UNKNOWN + ": no \"" + namespace + "\" attributes are registered; add the \"" + addon + "\" addon to the pack's addons";
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
|
||||
|
||||
final class ScheduleIds {
|
||||
private ScheduleIds() { }
|
||||
|
||||
static RegistryKey claim(String id, Set<RegistryKey> claimed) {
|
||||
if(id.startsWith("#")) throw new IllegalArgumentException("schedule IDs must not be tags");
|
||||
RegistryKey key;
|
||||
try {
|
||||
key = RegistryKey.parseNamespaced(id);
|
||||
} catch(IllegalArgumentException e) {
|
||||
if(id.indexOf(':') < 0) throw new IllegalArgumentException("schedule IDs must include a namespace, e.g. \"mypack:seasons\"", e);
|
||||
throw e;
|
||||
}
|
||||
if(!claimed.add(key)) throw new IllegalArgumentException("duplicate schedule ID");
|
||||
return key;
|
||||
}
|
||||
|
||||
static Either<RegistryKey, TagKey> reference(String value) {
|
||||
if(value.startsWith("#")) return Either.right(TagKey.parse(value));
|
||||
return Either.left(RegistryKey.parseNamespaced(value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
{
|
||||
"id": "config-attributes",
|
||||
"docVersion": 1,
|
||||
"description": "Environment attributes for biomes and packs. Contributes the attributes key to biome configurations, and attributes, schedules, schedule-definitions and vanilla-generation to pack.yml, and reads pack.yml's vanilla key when it is a string. The pack must list this addon under addons: in pack.yml, along with the addon that registers the attributes it uses (minecraft-attributes for the minecraft: and terra: ones); an unknown key's warning names that addon when none of its attributes are registered. Attribute keys must be fully namespaced (minecraft:visual/fog_color); a bad entry logs a warning and is skipped without affecting the rest of the pack.",
|
||||
"types": {
|
||||
"terra:AttributeEntry": {
|
||||
"kind": "oneOf",
|
||||
"options": [
|
||||
{
|
||||
"kind": "object",
|
||||
"fields": {
|
||||
"modifier": {
|
||||
"schema": {
|
||||
"kind": "string"
|
||||
},
|
||||
"required": true,
|
||||
"summary": "Modifier name. The modifier form is exactly the two keys modifier and argument. Examples: override, add, subtract, multiply, minimum, maximum, overlay, alpha_blend or blend_to_gray. Which modifiers are valid depends on the attribute's value type."
|
||||
},
|
||||
"argument": {
|
||||
"schema": {
|
||||
"kind": "any"
|
||||
},
|
||||
"required": true,
|
||||
"summary": "Modifier argument, in the attribute's value format or the modifier's own argument format. Range validation applies to plain values and override arguments; other modifier arguments are clamped when the value is resolved."
|
||||
}
|
||||
},
|
||||
"description": "Modifier form. Any map containing a modifier key is read as this form, never as a plain value."
|
||||
},
|
||||
{
|
||||
"kind": "any"
|
||||
}
|
||||
],
|
||||
"description": "A plain value in the attribute's vanilla format (for example \"#c0d8ff\", 0.5, true, or a list or map for complex types), or a modifier object. Particle options and text components are kept as opaque raw values for platforms to decode, with meta resolved."
|
||||
},
|
||||
"terra:Biome": {
|
||||
"kind": "object",
|
||||
"fields": {
|
||||
"attributes": {
|
||||
"schema": {
|
||||
"kind": "keyMap",
|
||||
"keys": {
|
||||
"kind": "string"
|
||||
},
|
||||
"values": {
|
||||
"kind": "type",
|
||||
"target": "terra:AttributeEntry"
|
||||
},
|
||||
"nullable": true
|
||||
},
|
||||
"required": false,
|
||||
"default": {},
|
||||
"summary": "Maps namespaced attribute IDs (for example minecraft:visual/fog_color) to a value or a {modifier, argument} object. Merged per key through extends, nearest config winning, and << meta includes work at every layer. A key without a namespace, an unknown key, a value that does not decode, or a non-biome attribute logs a warning and is skipped. Attributes not set here are inherited, not defaulted. An explicit null value for a known attribute that is allowed in biomes clears the inherited entry without a warning, so the attribute falls back to the lower layers (the platform's biome parent, the pack, the platform's pack parent, the default). Setting attributes: null on a child does not clear what it inherits, because inheritance merges per key and skips a null layer; clear entries one key at a time instead. Meta features work inside values at any depth: $file:key references, ${file:key} interpolation, << includes in maps and lists, and number expressions wherever a number is expected. A meta error inside a value logs a warning and skips that entry."
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"BIOME": {
|
||||
"kind": "object",
|
||||
"fields": {},
|
||||
"extends": [
|
||||
"terra:Biome"
|
||||
]
|
||||
},
|
||||
"pack.yml": {
|
||||
"kind": "object",
|
||||
"fields": {
|
||||
"attributes": {
|
||||
"schema": {
|
||||
"kind": "keyMap",
|
||||
"keys": {
|
||||
"kind": "string"
|
||||
},
|
||||
"values": {
|
||||
"kind": "type",
|
||||
"target": "terra:AttributeEntry"
|
||||
},
|
||||
"nullable": true
|
||||
},
|
||||
"required": false,
|
||||
"default": {},
|
||||
"summary": "Pack-level (dimension) attribute values, keyed by namespaced attribute ID. They layer over the platform's pack parent, which it may take from the IDs in vanilla: and vanilla-generation:, and biome values layer on top of them. Bad entries warn and are skipped. An explicit null value for a known attribute sets no entry, without a warning."
|
||||
},
|
||||
"schedules": {
|
||||
"schema": {
|
||||
"kind": "list",
|
||||
"element": {
|
||||
"kind": "string"
|
||||
},
|
||||
"nullable": true
|
||||
},
|
||||
"required": false,
|
||||
"default": [],
|
||||
"summary": "Schedule IDs or #tags to attach to the pack's dimension, each with a namespace (mypack:seasons, #mypack:in_overworld); an entry without one logs a warning and is skipped. Entries are resolved by the platform; they may also name schedules declared in schedule-definitions. A single string is accepted as a one-entry list. Platforms map schedules to Minecraft timelines."
|
||||
},
|
||||
"schedule-definitions": {
|
||||
"schema": {
|
||||
"kind": "keyMap",
|
||||
"keys": {
|
||||
"kind": "string"
|
||||
},
|
||||
"values": {
|
||||
"kind": "any"
|
||||
},
|
||||
"nullable": true
|
||||
},
|
||||
"required": false,
|
||||
"default": {},
|
||||
"summary": "Maps schedule IDs to schedule objects in vanilla's format (clock, period_ticks, time_markers, tracks of keyframes). IDs must include a namespace (mypack:seasons), must not be tags, and must be unique; the first definition with an ID wins. Clock and time-marker IDs must include a namespace too; one without skips the whole definition. A shape error skips the whole definition; an unknown attribute, a modifier invalid for the attribute's type, or a bad keyframe value drops only that track. An unknown modifier name skips the whole definition."
|
||||
},
|
||||
"vanilla-generation": {
|
||||
"schema": {
|
||||
"kind": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"required": false,
|
||||
"summary": "Parent ID for the platform's generation settings (for example minecraft:overworld). Like pack.yml's vanilla: key, which this addon reads only when it is a string ID (a map there is for other settings and is ignored here), it must include a namespace. An ID without one, or an invalid ID, in either key logs a warning and is ignored. The platform decides what each parent supplies and to which attributes; without platform support these layers are empty."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
schema-version: 1
|
||||
contributors:
|
||||
- Terra contributors
|
||||
id: config-attributes
|
||||
version: @VERSION@
|
||||
entrypoints:
|
||||
- "com.dfsek.terra.addons.attribute.AttributeAddon"
|
||||
website:
|
||||
issues: https://github.com/PolyhedralDev/Terra/issues
|
||||
source: https://github.com/PolyhedralDev/Terra
|
||||
docs: https://terra.polydev.org
|
||||
license: MIT License
|
||||
depends:
|
||||
config-biome: "1.+"
|
||||
@@ -0,0 +1,193 @@
|
||||
package 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.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader;
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
|
||||
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
|
||||
import com.dfsek.terra.addons.attribute.RegistryAttributeLookup;
|
||||
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
|
||||
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
|
||||
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
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.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
class AttributeReaderTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final Registry<Attribute<?>> REGISTRY = registry();
|
||||
private static final AttributeReader READER = new AttributeReader(REGISTRY, HANDLE);
|
||||
private static final String LIGHT = "terra:dimension/monster_spawn_light_level";
|
||||
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
|
||||
|
||||
private static Registry<Attribute<?>> registry() {
|
||||
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
for(Attribute<?> attribute : MinecraftAttributeTable.create(HANDLE)) registry.register(attribute.getRegistryKey(), attribute);
|
||||
return registry;
|
||||
}
|
||||
|
||||
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 void assertExactProblem(Result result, String key, String reason) {
|
||||
assertEquals(List.of(new Problem(key, reason)), result.problems());
|
||||
}
|
||||
|
||||
static Stream<Arguments> accepted() {
|
||||
return Stream.of(
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/fog_color", "#c0d8ff", Operation.OVERRIDE),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/water_fog_end_distance", map("modifier", "multiply", "argument", 0.85),
|
||||
Operation.MULTIPLY),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "multiply", "argument", 5), Operation.MULTIPLY),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", map("modifier", "append",
|
||||
"argument", List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025))), Operation.APPEND),
|
||||
Arguments.of(Scope.BIOME, "minecraft:gameplay/natural_mob_spawns", map("modifier", "overlay", "argument", map(
|
||||
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)),
|
||||
"spawns_by_category", map("creature", List.of(
|
||||
map("type", "minecraft:sheep", "count", 4, "weight", 12),
|
||||
map("type", "minecraft:horse", "weight", 5,
|
||||
"count", map("type", "minecraft:uniform", "max_inclusive", 6, "min_inclusive", 2)))))), Operation.OVERLAY),
|
||||
Arguments.of(Scope.PACK, "minecraft:gameplay/fast_lava", true, Operation.OVERRIDE),
|
||||
Arguments.of(Scope.PACK, LIGHT, map("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7), Operation.OVERRIDE));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{1}")
|
||||
@MethodSource("accepted")
|
||||
void accepts(Scope scope, String key, Object value, Operation operation) {
|
||||
Result r = READER.read(Map.of(key, value), scope);
|
||||
assertTrue(r.problems().isEmpty(), r.problems().toString());
|
||||
assertEquals(operation, r.map().get(AttributeKey.parse(key)).orElseThrow().operation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void intProviderModifierForm() {
|
||||
Result r = READER.read(Map.of(LIGHT, Map.of("modifier", "override", "argument", 7)), Scope.PACK);
|
||||
assertTrue(r.problems().isEmpty(), r.problems().toString());
|
||||
AttributeEntry<?> e = r.map().get(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL).orElseThrow();
|
||||
assertEquals(Operation.OVERRIDE, e.operation());
|
||||
assertEquals(new IntProviderValue(OptionalInt.of(7), Optional.empty()), e.argument());
|
||||
}
|
||||
|
||||
static Stream<Arguments> problems() {
|
||||
return Stream.of(
|
||||
Arguments.of(Scope.BIOME, "minecraft:nope", 1, "unknown attribute"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:Visual/Sky_Color", "#123456", "unknown attribute"),
|
||||
Arguments.of(Scope.BIOME, "visual/sky_color", "#123456", NAMESPACE_REQUIRED),
|
||||
Arguments.of(Scope.BIOME, "minecraft:Bad Key!", 1, "invalid attribute key..."),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/sky_color", true, "expected..."),
|
||||
Arguments.of(Scope.BIOME, "minecraft:audio/ambient_sounds", map("loop", "minecraft:Music.Game"),
|
||||
"\"loop\" of ambient sounds: expected an identifier like \"minecraft:id\", got \"minecraft:Music.Game\""),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", 2, "value 2.0 is outside [0, 1]"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "override", "argument", 2),
|
||||
"value 2.0 is outside [0, 1]"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "and", "argument", true),
|
||||
"modifier and is not valid for minecraft:visual/star_brightness"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "frobnicate", "argument", 1),
|
||||
"unknown modifier \"frobnicate\""),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "add", "argument", null),
|
||||
"expected a number, got nothing"),
|
||||
Arguments.of(Scope.PACK, LIGHT, map("modifier", "frobnicate", "argument", 7), "unknown modifier \"frobnicate\""),
|
||||
Arguments.of(Scope.PACK, LIGHT, map("min_inclusive", 0, "max_inclusive", 7), "int provider object is missing \"type\""),
|
||||
Arguments.of(Scope.PACK, "terra:dimension/height", 100, "value 100 is not a multiple of 16"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:gameplay/fast_lava", true, "not allowed in a biome"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", Arrays.asList((Object) null),
|
||||
"element 0: expected an object for ambient particle, got nothing"),
|
||||
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", List.of(map("particle", null, "probability", 0.1)),
|
||||
"element 0: \"particle\" of ambient particle: expected a particle object with a \"type\" key, got nothing"));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{1}: {3}")
|
||||
@MethodSource("problems")
|
||||
void badEntryIsolated(Scope scope, String key, Object value, String reason) {
|
||||
Result r = READER.read(map(key, value, "minecraft:visual/fog_color", "#c0d8ff"), scope);
|
||||
assertEquals(1, r.problems().size(), r.problems().toString());
|
||||
assertEquals(key, r.problems().get(0).key());
|
||||
if(reason.endsWith("...")) {
|
||||
String prefix = reason.substring(0, reason.length() - 3);
|
||||
assertTrue(r.problems().get(0).reason().startsWith(prefix), r.problems().get(0).reason());
|
||||
} else {
|
||||
assertEquals(reason, r.problems().get(0).reason());
|
||||
}
|
||||
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isPresent());
|
||||
assertEquals(1, r.map().keys().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullUnsetsKnownKeys() {
|
||||
for(Scope scope : Scope.values()) {
|
||||
Result r = READER.read(map("minecraft:visual/fog_color", null, "minecraft:visual/sky_color", "#405060"), scope);
|
||||
assertTrue(r.problems().isEmpty(), r.problems().toString());
|
||||
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isEmpty());
|
||||
assertEquals(1, r.map().keys().size());
|
||||
}
|
||||
Map<String, Object> raw = map("minecraft:nope", null, "minecraft:Bad Key!", null, "visual/sky_color", null,
|
||||
"terra:world/sea_level", null, "minecraft:visual/fog_color", null);
|
||||
Result r = READER.read(raw, Scope.BIOME);
|
||||
assertEquals(List.of(
|
||||
new Problem("minecraft:nope", "unknown attribute"),
|
||||
new Problem("minecraft:Bad Key!", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"Bad Key!\" is not a valid ID."),
|
||||
new Problem("visual/sky_color", NAMESPACE_REQUIRED),
|
||||
new Problem("terra:world/sea_level", "not allowed in a biome")),
|
||||
r.problems());
|
||||
assertTrue(r.map().isEmpty());
|
||||
assertTrue(READER.read(map("terra:world/sea_level", null), Scope.PACK).problems().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeyHint() {
|
||||
AttributeReader empty = new AttributeReader(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE), HANDLE);
|
||||
for(String key : List.of("minecraft:visual/fog_color", "terra:biome/temperature")) {
|
||||
String namespace = key.substring(0, key.indexOf(':'));
|
||||
assertExactProblem(empty.read(Map.of(key, "#ffffff"), Scope.BIOME), key,
|
||||
"unknown attribute: no \"" + namespace + "\" attributes are registered; add the \"minecraft-attributes\" addon "
|
||||
+ "to the pack's addons");
|
||||
}
|
||||
Result none = new AttributeReader(null, HANDLE).read(Map.of("minecraft:visual/fog_color", "#ffffff"), Scope.PACK);
|
||||
assertExactProblem(none, "minecraft:visual/fog_color", "unknown attribute: no \"minecraft\" attributes are registered; add the "
|
||||
+ "\"minecraft-attributes\" addon to the pack's addons");
|
||||
assertExactProblem(empty.read(Map.of("mypack:thing", 1), Scope.BIOME), "mypack:thing", "unknown attribute");
|
||||
assertExactProblem(READER.read(Map.of("minecraft:visual/fog_colour", "#ffffff"), Scope.BIOME), "minecraft:visual/fog_colour",
|
||||
"unknown attribute");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scheduleTrackKeys() {
|
||||
Map<String, Object> track = Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 10.0)));
|
||||
Map<String, Object> raw = map("clock", "minecraft:overworld", "tracks", map(
|
||||
"visual/sun_angle", track,
|
||||
"minecraft:visual/sun angle", track,
|
||||
"minecraft:visual/moon_angle", track));
|
||||
ScheduleDecodeResult r = HANDLE.decodeSchedule(RegistryKey.parse("terra:test"), raw, new RegistryAttributeLookup(REGISTRY),
|
||||
HANDLE.plainContext());
|
||||
assertEquals(List.of(
|
||||
new ScheduleDecodeResult.Problem("visual/sun_angle", NAMESPACE_REQUIRED),
|
||||
new ScheduleDecodeResult.Problem("minecraft:visual/sun angle", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"visual/sun angle\" is not a valid ID.")),
|
||||
r.droppedTracks());
|
||||
assertEquals(1, r.schedule().orElseThrow().tracks().size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.PackAttributesImpl;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
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.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeParents;
|
||||
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.biome.Biome;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
|
||||
|
||||
class PackAttributesImplTest {
|
||||
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
private static final Attribute<Integer> COUNT = HANDLE.attributeBuilder(AttributeKey.parse("test:count"), HANDLE.types().integer(),
|
||||
10).build();
|
||||
private static final Attribute<Integer> OTHER = HANDLE.attributeBuilder(AttributeKey.parse("test:other"), HANDLE.types().integer(),
|
||||
0).build();
|
||||
private static final Registry<Attribute<?>> REGISTRY = registry(COUNT, OTHER);
|
||||
|
||||
private static Registry<Attribute<?>> registry(Attribute<?>... attributes) {
|
||||
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
|
||||
return registry;
|
||||
}
|
||||
|
||||
private static Biome withId(int id) {
|
||||
return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class<?>[]{ Biome.class }, (proxy, method, args) ->
|
||||
switch(method.getName()) {
|
||||
case "getIntID" -> id;
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
private static PackAttributesImpl pack(AttributeParents parents, AttributeMap entries, AttributeMap... biomeEntries) {
|
||||
return new PackAttributesImpl(HANDLE, parents, REGISTRY, entries, Map.of(), List.of(), Map.of(), biomeEntries, List.of());
|
||||
}
|
||||
|
||||
private static AttributeMap map(Attribute<Integer> attribute, AttributeEntry<Integer> entry) {
|
||||
return AttributeMap.builder().put(attribute.key(), entry).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveUsesParents() {
|
||||
AttributeParents parents = new AttributeParents() {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> @Nullable AttributeEntry<T> biomeOrNull(Biome biome, Attribute<T> attribute) {
|
||||
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.override(5) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
|
||||
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.of(Operation.ADD, 1) : null;
|
||||
}
|
||||
};
|
||||
PackAttributesImpl pack = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), new AttributeMap[2]);
|
||||
|
||||
assertEquals(5, pack.resolve(COUNT, withId(1)));
|
||||
assertEquals(COUNT.defaultValue() + 3, pack.resolvePack(COUNT));
|
||||
PackAttributesImpl withBiome = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
|
||||
map(COUNT, AttributeEntry.of(Operation.ADD, 100)));
|
||||
assertEquals(105, withBiome.resolve(COUNT, withId(1)));
|
||||
assertEquals(0, pack.resolve(OTHER, withId(1)));
|
||||
assertEquals(0, pack.resolvePack(OTHER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentsNone() {
|
||||
PackAttributesImpl pack = pack(AttributeParents.NONE, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
|
||||
map(COUNT, AttributeEntry.of(Operation.MULTIPLY, 3)));
|
||||
assertEquals(36, pack.resolve(COUNT, withId(1)));
|
||||
assertEquals(12, pack.resolve(COUNT, withId(0)));
|
||||
assertEquals(12, pack.resolvePack(COUNT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoPacksIndependentColumns() {
|
||||
AttributeEntry<Integer> small1 = AttributeEntry.override(1);
|
||||
AttributeEntry<Integer> large1 = AttributeEntry.override(2);
|
||||
AttributeEntry<Integer> large2 = AttributeEntry.override(3);
|
||||
PackAttributesImpl small = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, small1));
|
||||
PackAttributesImpl large = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, large1), map(COUNT, large2));
|
||||
|
||||
assertSame(small1, small.biomeEntryOrNull(COUNT, withId(1)));
|
||||
assertSame(large1, large.biomeEntryOrNull(COUNT, withId(1)));
|
||||
assertSame(large2, large.biomeEntryOrNull(COUNT, withId(2)));
|
||||
assertNull(small.biomeEntryOrNull(COUNT, withId(2)));
|
||||
assertEquals(10, small.resolve(COUNT, withId(2)));
|
||||
assertEquals(3, large.resolve(COUNT, withId(2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedBiomeEntry() {
|
||||
AttributeEntry<Integer> stored = AttributeEntry.override(7);
|
||||
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, stored), null);
|
||||
|
||||
assertSame(stored, pack.biomeEntryOrNull(COUNT, withId(1)));
|
||||
assertNull(pack.biomeEntryOrNull(COUNT, withId(0)));
|
||||
assertNull(pack.biomeEntryOrNull(COUNT, withId(-1)));
|
||||
assertNull(pack.biomeEntryOrNull(COUNT, withId(3)));
|
||||
assertNull(pack.biomeEntryOrNull(OTHER, withId(1)));
|
||||
Attribute<Integer> later = HANDLE.attributeBuilder(AttributeKey.parse("test:later"), HANDLE.types().integer(), 4).build();
|
||||
assertNull(pack.biomeEntryOrNull(later, withId(1)));
|
||||
assertEquals(4, pack.resolve(later, withId(1)));
|
||||
assertEquals(4, pack.resolvePack(later));
|
||||
}
|
||||
|
||||
@Test
|
||||
void biomeEntriesCold() {
|
||||
AttributeMap declared = AttributeMap.builder()
|
||||
.put(COUNT.key(), AttributeEntry.override(1))
|
||||
.put(OTHER.key(), AttributeEntry.of(Operation.ADD, 2))
|
||||
.build();
|
||||
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, declared);
|
||||
|
||||
assertSame(declared, pack.biomeEntries(withId(1)));
|
||||
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(0)));
|
||||
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(2)));
|
||||
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(-1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configOrder() {
|
||||
Map<String, RegistryKey> parents = new LinkedHashMap<>();
|
||||
parents.put("vanilla-generation", RegistryKey.parse("test:generation"));
|
||||
parents.put("vanilla", RegistryKey.parse("test:dimension"));
|
||||
List<String> ids = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", "terra:x", "terra:d");
|
||||
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
|
||||
for(String id : ids) {
|
||||
definitions.put(RegistryKey.parse(id), new AttributeSchedule(RegistryKey.parse("test:clock"), OptionalInt.empty(),
|
||||
Map.of(), Map.of()));
|
||||
}
|
||||
PackAttributesImpl pack = new PackAttributesImpl(HANDLE, AttributeParents.NONE, REGISTRY, AttributeMap.empty(), parents,
|
||||
List.of(), definitions, new AttributeMap[0], List.of());
|
||||
assertEquals(List.of("vanilla-generation", "vanilla"), List.copyOf(pack.parents().keySet()));
|
||||
assertEquals(ids, pack.scheduleDefinitions().keySet().stream().map(RegistryKey::toString).toList());
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import com.dfsek.paralithic.eval.parser.Parser.ParseOptions;
|
||||
import com.dfsek.tectonic.api.config.Configuration;
|
||||
import com.dfsek.tectonic.api.depth.DepthTracker;
|
||||
import com.dfsek.tectonic.api.loader.ConfigLoader;
|
||||
import com.dfsek.tectonic.api.preprocessor.Result;
|
||||
import com.dfsek.tectonic.api.preprocessor.ValuePreprocessor;
|
||||
import com.dfsek.tectonic.impl.MapConfiguration;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.AnnotatedType;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.config.meta.Meta;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor;
|
||||
import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor;
|
||||
import com.dfsek.terra.config.preprocessor.MetaNumberPreprocessor;
|
||||
import com.dfsek.terra.config.preprocessor.MetaStringPreprocessor;
|
||||
import com.dfsek.terra.config.preprocessor.MetaValuePreprocessor;
|
||||
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
class ConfigDecodeContextTest {
|
||||
private static final Map<String, Object> META = map(
|
||||
"n", 3,
|
||||
"s", "two",
|
||||
"chain", "$meta.yml:s",
|
||||
"obj", map("x", 1, "y", "$meta.yml:s"),
|
||||
"list", List.of("a", "b"));
|
||||
|
||||
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 DecodeContext context() {
|
||||
return context(Map.of("meta.yml", new MapConfiguration(META, "meta.yml")));
|
||||
}
|
||||
|
||||
private static DecodeContext context(Map<String, Configuration> configs) {
|
||||
ConfigLoader loader = new ConfigLoader();
|
||||
loader.registerPreprocessor(Meta.class, new MetaStringPreprocessor(configs));
|
||||
loader.registerPreprocessor(Meta.class, new MetaListLikePreprocessor(configs));
|
||||
loader.registerPreprocessor(Meta.class, new MetaMapPreprocessor(configs));
|
||||
loader.registerPreprocessor(Meta.class, new MetaValuePreprocessor(configs));
|
||||
loader.registerPreprocessor(Meta.class, new MetaNumberPreprocessor(configs, new ParseOptions()));
|
||||
return context(loader);
|
||||
}
|
||||
|
||||
private static DecodeContext context(ConfigLoader loader) {
|
||||
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) loader.registerLoader(type, LazyConfigValue.LOADER);
|
||||
DepthTracker tracker = new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml"));
|
||||
return new LazyConfigValue(null, loader, tracker).context(new AttributeHandleImpl().plainContext());
|
||||
}
|
||||
|
||||
@Test
|
||||
void numberExpressions() throws DecodeException {
|
||||
DecodeContext context = context();
|
||||
assertEquals("2 * 6000", context.resolve("2 * 6000"));
|
||||
assertEquals(12000, context.<Integer>load(Integer.class, "2 * 6000"));
|
||||
assertEquals(1.5f, context.<Float>load(Float.class, "${meta.yml:n} / 2"));
|
||||
assertEquals(3.0, context.<Double>load(Double.class, "$meta.yml:n"));
|
||||
assertEquals(0.5f, context.<Float>load(Float.class, 0.5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainConversion() {
|
||||
DecodeContext context = context();
|
||||
assertTrue(assertThrows(DecodeException.class, () -> context.load(Integer.class, "5 / 2")).getMessage()
|
||||
.startsWith("expected an integer"));
|
||||
assertEquals("expected a string, got 3",
|
||||
assertThrows(DecodeException.class, () -> context.load(String.class, "$meta.yml:n")).getMessage());
|
||||
assertEquals("expected a boolean (true or false), got \"two\"",
|
||||
assertThrows(DecodeException.class, () -> context.load(Boolean.class, "$meta.yml:s")).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedResolve() throws DecodeException {
|
||||
Map<String, Object> raw = map(
|
||||
"null", null,
|
||||
"ref", "$meta.yml:obj",
|
||||
"list", List.of("<< meta.yml:list", "c", "${meta.yml:s}"),
|
||||
"include", map("<<", List.of("meta.yml:obj"), "x", 2),
|
||||
"string", "one-${meta.yml:s}",
|
||||
"deep", map("a", List.of(map("b", "$meta.yml:n"))));
|
||||
Map<?, ?> resolved = (Map<?, ?>) context().resolve(raw);
|
||||
assertEquals(map(
|
||||
"null", null,
|
||||
"ref", map("x", 1, "y", "two"),
|
||||
"list", List.of("a", "b", "c", "two"),
|
||||
"include", map("x", 2, "y", "two"),
|
||||
"string", "one-two",
|
||||
"deep", map("a", List.of(map("b", 3)))), resolved);
|
||||
assertEquals(List.copyOf(raw.keySet()), List.copyOf(resolved.keySet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveTwice() throws DecodeException {
|
||||
DecodeContext context = context();
|
||||
Object once = context.resolve(map("a", "$meta.yml:chain"));
|
||||
assertEquals(map("a", "$meta.yml:s"), once);
|
||||
assertSame(once, context.resolve(once));
|
||||
Object chained = ((Map<?, ?>) once).get("a");
|
||||
assertSame(chained, context.resolve(chained));
|
||||
assertEquals("$meta.yml:s", context.load(String.class, chained));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preprocessingErrors() {
|
||||
DecodeContext context = context();
|
||||
String missing = assertThrows(DecodeException.class, () -> context.resolve(map("a", "${meta.yml:missing}"))).getMessage();
|
||||
assertTrue(missing.contains("No such key missing"), missing);
|
||||
assertTrue(missing.contains("Path: a"), missing);
|
||||
|
||||
String malformed = assertThrows(DecodeException.class, () -> context.resolve(List.of("${2 * 6000}"))).getMessage();
|
||||
assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed);
|
||||
assertTrue(malformed.contains("Path: [0]"), malformed);
|
||||
assertReadable(malformed);
|
||||
|
||||
String escape = assertThrows(DecodeException.class, () -> context.resolve(map("a", "$meta.yml:bad\\q"))).getMessage();
|
||||
assertTrue(escape.contains("meta reference \"meta.yml:bad\\q\" has an invalid key path"), escape);
|
||||
assertReadable(escape);
|
||||
|
||||
String expression = assertThrows(DecodeException.class, () -> context.load(Float.class, "1 +")).getMessage();
|
||||
assertTrue(expression.contains("Invalid expression"), expression);
|
||||
|
||||
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("meta.yml:list")))).getMessage();
|
||||
assertTrue(include.contains("MetaMap injection candidate must be map, is type java.util."), include);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullMetaTargets() {
|
||||
Configuration nulls = new Configuration() {
|
||||
@Override
|
||||
public Object get(@NotNull String key) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(@NotNull String key) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "null.yml";
|
||||
}
|
||||
};
|
||||
DecodeContext context = context(Map.of("null.yml", nulls));
|
||||
String string = assertThrows(DecodeException.class, () -> context.resolve("${null.yml:x}")).getMessage();
|
||||
assertTrue(string.contains("must be string or primitive, is null"), string);
|
||||
String list = assertThrows(DecodeException.class, () -> context.resolve(List.of("<< null.yml:x"))).getMessage();
|
||||
assertTrue(list.contains("'null.yml:x' points to null"), list);
|
||||
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("null.yml:x")))).getMessage();
|
||||
assertTrue(include.contains("must be map, is null"), include);
|
||||
}
|
||||
|
||||
@Test
|
||||
void preprocessorRuntimeExceptions() {
|
||||
ConfigLoader loader = new ConfigLoader();
|
||||
loader.registerPreprocessor(Meta.class, new ValuePreprocessor<Meta>() {
|
||||
@Override
|
||||
public @NotNull <T> Result<T> process(AnnotatedType t, T c, ConfigLoader l, Meta annotation, DepthTracker depthTracker) {
|
||||
throw new IllegalStateException("java.lang.Boom");
|
||||
}
|
||||
});
|
||||
DecodeContext context = context(loader);
|
||||
String message = assertThrows(DecodeException.class, () -> context.resolve("x")).getMessage();
|
||||
assertTrue(message.contains("config preprocessing failed"), message);
|
||||
assertReadable(message);
|
||||
}
|
||||
|
||||
private static void assertReadable(String message) {
|
||||
assertFalse(message.contains("java."), message);
|
||||
assertFalse(message.contains("Exception"), message);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.dfsek.terra.addons.attribute;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
|
||||
class ScheduleIdsTest {
|
||||
@Test
|
||||
void referenceNamespace() {
|
||||
assertEquals(Either.left(RegistryKey.parse("mypack:seasons")), ScheduleIds.reference("mypack:seasons"));
|
||||
assertEquals(Either.right(TagKey.parse("#mypack:in_overworld")), ScheduleIds.reference("#mypack:in_overworld"));
|
||||
assertEquals("a namespace is required, as in \"namespace:seasons\"",
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("seasons")).getMessage());
|
||||
assertEquals("invalid tag \"#in_overworld\": a namespace is required, as in \"#namespace:in_overworld\"",
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("#in_overworld")).getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void claim() {
|
||||
Set<RegistryKey> claimed = new HashSet<>();
|
||||
assertEquals(RegistryKey.parse("mypack:seasons"), ScheduleIds.claim("mypack:seasons", claimed));
|
||||
assertEquals("duplicate schedule ID",
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:seasons", claimed)).getMessage());
|
||||
assertEquals(RegistryKey.parse("MyPack:Seasons"), ScheduleIds.claim("MyPack:Seasons", claimed));
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:", claimed));
|
||||
assertEquals("schedule IDs must include a namespace, e.g. \"mypack:seasons\"",
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("seasons", claimed)).getMessage());
|
||||
assertEquals("schedule IDs must not be tags",
|
||||
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("#mypack:seasons", claimed)).getMessage());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user