feat: add environment attribute system

This commit is contained in:
Zoe Gidiere committed 2026-11-09 16:34:50 -07:00
1 parent 8a940f7e1f
commit 4e37c361ea
127 files changed
+9022 -19

No files matched your search

+7 -1
View File
@@ -4,6 +4,12 @@ plugins {
}
repositories {
// TODO: remove once Tectonic 4.4.0 is published
mavenLocal {
content {
includeGroup("com.dfsek.tectonic")
}
}
mavenCentral()
gradlePluginPortal()
maven("https://maven.solo-studios.ca/releases") {
@@ -26,6 +32,6 @@ dependencies {
implementation("org.ow2.asm", "asm", "9.9")
implementation("org.ow2.asm", "asm-tree", "9.9")
implementation("com.dfsek.tectonic", "common", "4.3.1")
implementation("com.dfsek.tectonic", "common", "4.4.0")
implementation("org.yaml", "snakeyaml", "2.5")
}
+1 -1
View File
@@ -7,7 +7,7 @@ object Versions {
}
object Libraries {
const val tectonic = "4.3.1"
const val tectonic = "4.4.0"
const val paralithic = "2.0.1"
const val strata = "1.3.2"
const val seismic = "2.5.7"
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,10 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:minecraft-attributes"))
testImplementation(project(":common:addons:manifest-addon-loader"))
testImplementation("com.dfsek", "paralithic", Versions.Libraries.paralithic)
}
@@ -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();
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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> { }
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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();
}
}
@@ -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";
}
}
@@ -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());
}
}
@@ -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);
}
}
@@ -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());
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,8 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:manifest-addon-loader"))
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.world.attribute.RawValue;
public record AmbientParticle(RawValue particle, float probability) { }
@@ -0,0 +1,18 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import java.util.Optional;
public record AmbientSounds(Optional<SoundRef> loop, Optional<Mood> mood, List<Additions> additions) {
public static final AmbientSounds EMPTY = new AmbientSounds(Optional.empty(), Optional.empty(), List.of());
public AmbientSounds {
additions = List.copyOf(additions);
}
public record Mood(SoundRef sound, int tickDelay, int blockSearchExtent, double offset) { }
public record Additions(SoundRef sound, double tickChance) { }
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
public record BackgroundMusic(Optional<Music> defaultMusic, Optional<Music> creative, Optional<Music> underwater) {
public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty());
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.world.attribute.RawValue;
public record BedRule(Rule canSleep, Rule canSetSpawn, boolean destroyOnUse, boolean destroyOnLeave, Optional<RawValue> errorMessage) {
public enum Rule implements StringIdentifiable {
ALWAYS("always"),
WHEN_DARK("when_dark"),
NEVER("never");
private final String id;
Rule(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
}
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum CardinalLight implements StringIdentifiable {
DEFAULT("default"),
NETHER("nether");
private final String id;
CardinalLight(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum GrassColorModifier implements StringIdentifiable {
NONE("none"),
DARK_FOREST("dark_forest"),
SWAMP("swamp");
private final String id;
GrassColorModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,15 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.world.attribute.RawValue;
public record IntProviderValue(OptionalInt constant, Optional<RawValue> provider) {
public IntProviderValue {
if(constant.isPresent() == provider.isPresent()) {
throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider");
}
}
}
@@ -0,0 +1,159 @@
package com.dfsek.terra.addons.attribute.minecraft;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
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.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.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributeTable {
private static final RawValue NO_SLEEP_MESSAGE = new RawValue(Map.of("translate", "block.minecraft.bed.no_sleep"));
private static final BedRule CAN_SLEEP_WHEN_DARK = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.ALWAYS, false, false,
Optional.of(NO_SLEEP_MESSAGE));
private static final BedRule DESTROY_ON_LEAVE = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true,
Optional.of(NO_SLEEP_MESSAGE));
private static final IntProviderValue MONSTER_SPAWN_LIGHT_LEVEL = new IntProviderValue(OptionalInt.empty(), Optional.of(
new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))));
private MinecraftAttributeTable() { }
public static List<Attribute<?>> create(AttributeHandle handle) {
AttributeTypes t = handle.types();
MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle);
AttributeType<TemperatureModifier> temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class);
AttributeType<GrassColorModifier> grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class);
AttributeType<Skybox> skybox = t.enumType("skybox", Skybox.class);
AttributeType<CardinalLight> cardinalLight = t.enumType("cardinal_light", CardinalLight.class);
Table table = new Table(handle);
table.row(MinecraftAttributes.VISUAL_FOG_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_FOG_START_DISTANCE, t.floatType(), 0f);
table.row(MinecraftAttributes.VISUAL_FOG_END_DISTANCE, t.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE, t.floatType(), 512f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_CLOUD_FOG_END_DISTANCE, t.floatType(), 2048f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_COLOR, t.rgbColor(), Color.rgb(0x050533));
table.row(MinecraftAttributes.VISUAL_WATER_FOG_START_DISTANCE, t.floatType(), -8f);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, t.floatType(), 96f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_SUNRISE_SUNSET_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_HEIGHT, t.floatType(), 192.33f);
table.row(MinecraftAttributes.VISUAL_SUN_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_STAR_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_PHASE, m.moonPhase(), MoonPhase.FULL_MOON);
table.row(MinecraftAttributes.VISUAL_STAR_BRIGHTNESS, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_BLOCK_LIGHT_TINT, t.rgbColor(), Color.rgb(0xffd88c));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_COLOR, t.rgbColor(), Color.rgb(0xffffff));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_FACTOR, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_NIGHT_VISION_COLOR, t.rgbColor(), Color.rgb(0x999999));
table.row(MinecraftAttributes.VISUAL_AMBIENT_LIGHT_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_DEFAULT_DRIPSTONE_PARTICLE, m.particle(),
new RawValue(Map.of("type", "minecraft:dripping_dripstone_water")));
table.row(MinecraftAttributes.VISUAL_AMBIENT_PARTICLES, m.ambientParticles(), List.of());
table.row(MinecraftAttributes.AUDIO_BACKGROUND_MUSIC, m.backgroundMusic(), BackgroundMusic.EMPTY);
table.row(MinecraftAttributes.AUDIO_MUSIC_VOLUME, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.AUDIO_AMBIENT_SOUNDS, m.ambientSounds(), AmbientSounds.EMPTY);
table.row(MinecraftAttributes.AUDIO_FIREFLY_BUSH_SOUNDS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL, t.floatType(), 15f).range(0, 15).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_CAN_START_RAID, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_WATER_EVAPORATES, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_BED_RULE, m.bedRule(), CAN_SLEEP_WHEN_DARK);
table.row(MinecraftAttributes.GAMEPLAY_STRAW_BED_RULE, m.bedRule(), DESTROY_ON_LEAVE);
table.row(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_FAST_LAVA, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_INCREASED_FIRE_BURNOUT, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_EYEBLOSSOM_OPEN, t.triState(), TriState.DEFAULT);
table.row(MinecraftAttributes.GAMEPLAY_TURTLE_EGG_HATCH_CHANCE, t.floatType(), 0.002f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_PIGLINS_ZOMBIFY, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_SNOW_GOLEM_MELTS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CREAKING_ACTIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_BEES_STAY_IN_HIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_MONSTERS_BURN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_NATURAL_MOB_SPAWNS, m.mobSpawnSettings(), MobSpawnSettings.EMPTY);
table.row(MinecraftAttributes.GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY, t.floatType(), 0.1f).range(0, 0.9999999);
table.row(MinecraftAttributes.GAMEPLAY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.GAMEPLAY_BABY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.BIOME_HAS_PRECIPITATION, t.booleanType(), true);
table.row(MinecraftAttributes.BIOME_TEMPERATURE, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_TEMPERATURE_MODIFIER, temperatureModifier, TemperatureModifier.NONE);
table.row(MinecraftAttributes.BIOME_DOWNFALL, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_WATER_COLOR, t.rgbColor(), Color.rgb(0x3f76e4));
table.row(MinecraftAttributes.BIOME_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_DRY_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR_MODIFIER, grassColorModifier, GrassColorModifier.NONE);
table.row(MinecraftAttributes.BIOME_VILLAGER_TYPE, m.identifier(), RegistryKey.parse("minecraft:plains"));
table.row(MinecraftAttributes.DIMENSION_HAS_FIXED_TIME, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_SKYLIGHT, t.booleanType(), true).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_CEILING, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_ENDER_DRAGON_FIGHT, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_COORDINATE_SCALE, t.floatType(), 1f).packOnly().range(1e-5, 3e7);
table.row(MinecraftAttributes.DIMENSION_MIN_Y, t.integerOverrideOnly(), -64).packOnly().range(-2032, 2031).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(16, 4064).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_LOGICAL_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(0, 4064);
table.row(MinecraftAttributes.DIMENSION_INFINIBURN, m.identifierOrTag(),
Either.right(TagKey.parse("#minecraft:infiniburn_overworld"))).packOnly();
table.row(MinecraftAttributes.DIMENSION_AMBIENT_LIGHT, t.floatType(), 0f).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL, m.intProvider(), MONSTER_SPAWN_LIGHT_LEVEL).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT, t.integer(), 0).packOnly().range(0, 15);
table.row(MinecraftAttributes.DIMENSION_SKYBOX, skybox, Skybox.OVERWORLD).packOnly();
table.row(MinecraftAttributes.DIMENSION_CARDINAL_LIGHT, cardinalLight, CardinalLight.DEFAULT).packOnly();
table.row(MinecraftAttributes.DIMENSION_DEFAULT_CLOCK, m.identifier(), RegistryKey.parse("minecraft:overworld")).packOnly();
table.row(MinecraftAttributes.WORLD_SEA_LEVEL, t.integer(), 63).packOnly();
table.row(MinecraftAttributes.WORLD_SPAWN_HEIGHT, t.integer(), 64).packOnly();
table.row(MinecraftAttributes.WORLD_MOB_GENERATION, t.booleanType(), true).packOnly();
List<Attribute<?>> attributes = table.build();
if(!attributes.stream().map(Attribute::key).toList().equals(MinecraftAttributes.all())) {
throw new IllegalStateException("the Minecraft attribute table does not match MinecraftAttributes.all()");
}
return attributes;
}
private static final class Table {
private final AttributeHandle handle;
private final List<Attribute.Builder<?>> rows = new ArrayList<>();
private Table(AttributeHandle handle) {
this.handle = handle;
}
private <T> Attribute.Builder<T> row(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue) {
MinecraftIds.requireLowerCase(key.getRegistryKey());
Attribute.Builder<T> builder = handle.attributeBuilder(key, type, defaultValue);
rows.add(builder);
return builder;
}
private List<Attribute<?>> build() {
List<Attribute<?>> built = new ArrayList<>(rows.size());
for(Attribute.Builder<?> row : rows) built.add(row.build());
return List.copyOf(built);
}
}
}
@@ -0,0 +1,109 @@
package com.dfsek.terra.addons.attribute.minecraft;
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.TagKey;
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.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftAttributeTypes {
private final AttributeType<MoonPhase> moonPhase;
private final AttributeType<BedRule> bedRule;
private final AttributeType<RawValue> particle;
private final AttributeType<List<AmbientParticle>> ambientParticles;
private final AttributeType<BackgroundMusic> backgroundMusic;
private final AttributeType<AmbientSounds> ambientSounds;
private final AttributeType<MobSpawnSettings> mobSpawnSettings;
private final AttributeType<RegistryKey> identifier;
private final AttributeType<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeType<IntProviderValue> intProvider;
public MinecraftAttributeTypes(AttributeHandle handle) {
MinecraftCodecs codecs = new MinecraftCodecs(handle);
this.moonPhase = handle.typeBuilder("moon_phase", codecs.moonPhase()).build();
this.bedRule = handle.typeBuilder("bed_rule", codecs.bedRule()).build();
this.particle = handle.typeBuilder("particle", codecs.particle()).build();
this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles())
.op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append)
.build();
this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build();
this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build();
this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings())
.op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay)
.build();
this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build();
this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build();
this.intProvider = handle.typeBuilder("int_provider", codecs.intProvider()).build();
}
public AttributeType<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeType<BedRule> bedRule() {
return bedRule;
}
public AttributeType<RawValue> particle() {
return particle;
}
public AttributeType<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeType<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeType<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeType<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
public AttributeType<RegistryKey> identifier() {
return identifier;
}
public AttributeType<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeType<IntProviderValue> intProvider() {
return intProvider;
}
private static List<AmbientParticle> append(List<AmbientParticle> s, List<AmbientParticle> a) {
if(a.isEmpty()) return s;
if(s.isEmpty()) return a;
List<AmbientParticle> out = new ArrayList<>(s.size() + a.size());
out.addAll(s);
out.addAll(a);
return List.copyOf(out);
}
private static MobSpawnSettings overlay(MobSpawnSettings first, MobSpawnSettings second) {
if(first.spawnsByCategory().isEmpty() && first.spawnCosts().isEmpty()) return second;
if(second.spawnsByCategory().isEmpty() && second.spawnCosts().isEmpty()) return first;
if(second.spawnsByCategory().keySet().containsAll(first.spawnsByCategory().keySet())
&& second.spawnCosts().keySet().containsAll(first.spawnCosts().keySet())) {
return second;
}
Map<String, List<MobSpawnSettings.Spawner>> categories = new LinkedHashMap<>(first.spawnsByCategory());
categories.putAll(second.spawnsByCategory());
Map<RegistryKey, MobSpawnSettings.Cost> costs = new LinkedHashMap<>(first.spawnCosts());
costs.putAll(second.spawnCosts());
return new MobSpawnSettings(categories, costs);
}
}
@@ -0,0 +1,128 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.List;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributes {
private static List<AttributeKey<?>> building = new ArrayList<>();
public static final AttributeKey<Color> VISUAL_FOG_COLOR = vanilla("visual/fog_color");
public static final AttributeKey<Float> VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance");
public static final AttributeKey<Float> VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance");
public static final AttributeKey<Float> VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance");
public static final AttributeKey<Float> VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance");
public static final AttributeKey<Color> VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color");
public static final AttributeKey<Float> VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance");
public static final AttributeKey<Float> VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance");
public static final AttributeKey<Color> VISUAL_SKY_COLOR = vanilla("visual/sky_color");
public static final AttributeKey<Color> VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color");
public static final AttributeKey<Color> VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color");
public static final AttributeKey<Float> VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height");
public static final AttributeKey<Float> VISUAL_SUN_ANGLE = vanilla("visual/sun_angle");
public static final AttributeKey<Float> VISUAL_MOON_ANGLE = vanilla("visual/moon_angle");
public static final AttributeKey<Float> VISUAL_STAR_ANGLE = vanilla("visual/star_angle");
public static final AttributeKey<MoonPhase> VISUAL_MOON_PHASE = vanilla("visual/moon_phase");
public static final AttributeKey<Float> VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness");
public static final AttributeKey<Color> VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint");
public static final AttributeKey<Color> VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color");
public static final AttributeKey<Float> VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor");
public static final AttributeKey<Color> VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color");
public static final AttributeKey<Color> VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color");
public static final AttributeKey<RawValue> VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle");
public static final AttributeKey<List<AmbientParticle>> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles");
public static final AttributeKey<BackgroundMusic> AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music");
public static final AttributeKey<Float> AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume");
public static final AttributeKey<AmbientSounds> AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds");
public static final AttributeKey<Boolean> AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds");
public static final AttributeKey<Float> GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid");
public static final AttributeKey<Boolean> GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates");
public static final AttributeKey<BedRule> GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule");
public static final AttributeKey<BedRule> GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule");
public static final AttributeKey<Boolean> GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works");
public static final AttributeKey<Boolean> GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin");
public static final AttributeKey<Boolean> GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava");
public static final AttributeKey<Boolean> GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout");
public static final AttributeKey<TriState> GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open");
public static final AttributeKey<Float> GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance");
public static final AttributeKey<Boolean> GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify");
public static final AttributeKey<Boolean> GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts");
public static final AttributeKey<Boolean> GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active");
public static final AttributeKey<Float> GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance");
public static final AttributeKey<Float> GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance");
public static final AttributeKey<Boolean> GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive");
public static final AttributeKey<Boolean> GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn");
public static final AttributeKey<MobSpawnSettings> GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns");
public static final AttributeKey<Float> GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY =
vanilla("gameplay/creature_world_gen_spawn_probability");
public static final AttributeKey<RegistryKey> GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity");
public static final AttributeKey<RegistryKey> GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity");
public static final AttributeKey<Boolean> BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation");
public static final AttributeKey<Float> BIOME_TEMPERATURE = terra("biome/temperature");
public static final AttributeKey<TemperatureModifier> BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier");
public static final AttributeKey<Float> BIOME_DOWNFALL = terra("biome/downfall");
public static final AttributeKey<Color> BIOME_WATER_COLOR = terra("biome/water_color");
public static final AttributeKey<Color> BIOME_FOLIAGE_COLOR = terra("biome/foliage_color");
public static final AttributeKey<Color> BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color");
public static final AttributeKey<Color> BIOME_GRASS_COLOR = terra("biome/grass_color");
public static final AttributeKey<GrassColorModifier> BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier");
public static final AttributeKey<RegistryKey> BIOME_VILLAGER_TYPE = terra("biome/villager_type");
public static final AttributeKey<Boolean> DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time");
public static final AttributeKey<Boolean> DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight");
public static final AttributeKey<Boolean> DIMENSION_HAS_CEILING = terra("dimension/has_ceiling");
public static final AttributeKey<Boolean> DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight");
public static final AttributeKey<Float> DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale");
public static final AttributeKey<Integer> DIMENSION_MIN_Y = terra("dimension/min_y");
public static final AttributeKey<Integer> DIMENSION_HEIGHT = terra("dimension/height");
public static final AttributeKey<Integer> DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height");
public static final AttributeKey<Either<RegistryKey, TagKey>> DIMENSION_INFINIBURN = terra("dimension/infiniburn");
public static final AttributeKey<Float> DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light");
public static final AttributeKey<IntProviderValue> DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level");
public static final AttributeKey<Integer> DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT =
terra("dimension/monster_spawn_block_light_limit");
public static final AttributeKey<Skybox> DIMENSION_SKYBOX = terra("dimension/skybox");
public static final AttributeKey<CardinalLight> DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light");
public static final AttributeKey<RegistryKey> DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock");
public static final AttributeKey<Integer> WORLD_SEA_LEVEL = terra("world/sea_level");
public static final AttributeKey<Integer> WORLD_SPAWN_HEIGHT = terra("world/spawn_height");
public static final AttributeKey<Boolean> WORLD_MOB_GENERATION = terra("world/mob_generation");
private static final List<AttributeKey<?>> VIEW = seal();
private MinecraftAttributes() { }
public static List<AttributeKey<?>> all() {
return VIEW;
}
private static List<AttributeKey<?>> seal() {
List<AttributeKey<?>> view = List.copyOf(building);
building = null;
return view;
}
private static <T> AttributeKey<T> vanilla(String path) {
return add(RegistryKey.of("minecraft", path));
}
private static <T> AttributeKey<T> terra(String path) {
return add(RegistryKey.of("terra", path));
}
private static <T> AttributeKey<T> add(RegistryKey key) {
AttributeKey<T> attributeKey = AttributeKey.of(key);
building.add(attributeKey);
return attributeKey;
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
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.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.registry.CheckedRegistry;
import com.dfsek.terra.api.world.attribute.Attribute;
public class MinecraftAttributesAddon implements AddonInitializer {
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
List<Attribute<?>> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle());
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
CheckedRegistry<Attribute<?>> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
})
.failThrough();
}
}
@@ -0,0 +1,349 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeSet;
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.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 com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftCodecs {
public static final String NAMESPACE = "minecraft";
// Same wording as the core identifier codec.
private static final String EXPECTED_IDENTIFIER = "expected an identifier like \"" + NAMESPACE + ":id\"";
private static final Set<String> MOB_CATEGORIES = Set.of("monster", "creature", "ambient", "axolotls", "underground_water_creature",
"water_creature", "water_ambient", "misc");
private final AttributeCodecs codecs;
private final DecodeContext plain;
private final AttributeCodec<String> idString;
private final AttributeCodec<RegistryKey> identifier;
private final AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeCodec<MoonPhase> moonPhase;
private final AttributeCodec<RawValue> particle;
private final AttributeCodec<AmbientParticle> ambientParticle;
private final AttributeCodec<List<AmbientParticle>> ambientParticles;
private final AttributeCodec<IntProviderValue> intProvider;
private final AttributeCodec<SoundRef> soundRef;
private final AttributeCodec<Music> music;
private final AttributeCodec<BackgroundMusic> backgroundMusic;
private final AttributeCodec<AmbientSounds.Mood> mood;
private final AttributeCodec<List<AmbientSounds.Additions>> additions;
private final AttributeCodec<AmbientSounds> ambientSounds;
private final AttributeCodec<BedRule.Rule> bedRuleRule;
private final AttributeCodec<BedRule> bedRule;
private final AttributeCodec<List<MobSpawnSettings.Spawner>> spawners;
private final AttributeCodec<MobSpawnSettings.Cost> spawnCost;
private final AttributeCodec<Map<String, List<MobSpawnSettings.Spawner>>> spawnsByCategory;
private final AttributeCodec<Map<RegistryKey, MobSpawnSettings.Cost>> spawnCosts;
private final AttributeCodec<MobSpawnSettings> mobSpawnSettings;
public MinecraftCodecs(AttributeHandle handle) {
AttributeCodecs c = handle.codecs();
this.codecs = c;
this.plain = handle.plainContext();
this.idString = c.string(EXPECTED_IDENTIFIER);
AttributeCodec<RegistryKey> coreIdentifier = c.identifier(NAMESPACE);
this.identifier = c.of((raw, context) -> {
String s = idString.decode(raw, context);
return lowerCase(coreIdentifier.decode(s, plain), s);
}, coreIdentifier::encode);
AttributeCodec<Either<RegistryKey, TagKey>> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE);
this.identifierOrTag = c.of((raw, context) -> {
String s = idString.decode(raw, context);
Either<RegistryKey, TagKey> id = coreIdentifierOrTag.decode(s, plain);
lowerCase(id.hasLeft() ? id.getLeft().orElseThrow() : id.getRight().orElseThrow().key(), s);
return id;
}, coreIdentifierOrTag::encode);
this.moonPhase = c.enumCodec("moon phase", MoonPhase.class);
this.particle = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(!(value instanceof Map<?, ?> map) || !map.containsKey("type")) {
throw new DecodeException("expected a particle object with a \"type\" key, got " + c.describe(value));
}
if(map.get("type") instanceof String type) {
try {
identifier.decode(type, plain);
} catch(DecodeException e) {
throw new DecodeException("\"type\" of particle: " + e.getMessage(), e);
}
}
return c.raw().decode(value, context);
}, RawValue::value);
this.ambientParticle = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient particle", raw, context);
RawValue value = f.required("particle", this.particle);
float probability = f.required("probability", c.unitFloat());
f.finish();
return new AmbientParticle(value, probability);
}, value -> c.writer()
.put("particle", particle, value.particle())
.put("probability", c.unitFloat(), value.probability())
.map());
this.ambientParticles = c.list(ambientParticle);
this.intProvider = c.of((raw, context) -> {
String expected = "expected an integer or an int provider object";
Object value = context.resolve(raw);
if(value instanceof Map<?, ?> map) {
if(!map.containsKey("type")) throw new DecodeException("int provider object is missing \"type\"");
return new IntProviderValue(OptionalInt.empty(), Optional.of(c.raw().decode(value, context)));
}
if(value instanceof Number) return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
if(value instanceof String) {
try {
return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
} catch(DecodeException e) {
throw new DecodeException(expected + ", got " + c.describe(value), e);
}
}
throw new DecodeException(expected + ", got " + c.describe(value));
}, value -> value.constant().isPresent() ? (Object) value.constant().getAsInt() : value.provider().orElseThrow().value());
this.soundRef = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(value instanceof String) return new SoundRef(identifier.decode(value, context), OptionalDouble.empty());
if(value instanceof Map<?, ?>) {
ObjectReader f = c.reader("sound", value, context);
RegistryKey id = f.required("sound_id", identifier);
Optional<Double> range = f.optional("range", c.doubleCodec());
f.finish();
return new SoundRef(id, range.map(OptionalDouble::of).orElse(OptionalDouble.empty()));
}
throw new DecodeException("expected a sound ID or a {sound_id, range} object, got " + c.describe(value));
}, value -> {
if(value.range().isEmpty()) return identifier.encode(value.id());
return c.writer()
.put("sound_id", identifier, value.id())
.put("range", c.doubleCodec(), value.range().getAsDouble())
.map();
});
this.music = c.of((raw, context) -> {
ObjectReader f = c.reader("music", raw, context);
SoundRef sound = f.required("sound", soundRef);
int min = f.required("min_delay", c.nonNegativeInt());
int max = f.required("max_delay", c.nonNegativeInt());
boolean replace = f.orDefault("replace_current_music", c.booleanCodec(), false);
f.finish();
return new Music(sound, min, max, replace);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("min_delay", c.nonNegativeInt(), value.minDelay())
.put("max_delay", c.nonNegativeInt(), value.maxDelay())
.put("replace_current_music", c.booleanCodec(), value.replaceCurrentMusic())
.map());
this.backgroundMusic = c.of((raw, context) -> {
ObjectReader f = c.reader("background music", raw, context);
Optional<Music> def = f.optional("default", music);
Optional<Music> creative = f.optional("creative", music);
Optional<Music> underwater = f.optional("underwater", music);
f.finish();
return new BackgroundMusic(def, creative, underwater);
}, value -> c.writer()
.optional("default", music, value.defaultMusic())
.optional("creative", music, value.creative())
.optional("underwater", music, value.underwater())
.map());
this.mood = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient mood", raw, context);
SoundRef sound = f.required("sound", soundRef);
int tickDelay = f.required("tick_delay", c.intCodec());
int extent = f.required("block_search_extent", c.intCodec());
double offset = f.required("offset", c.doubleCodec());
f.finish();
return new AmbientSounds.Mood(sound, tickDelay, extent, offset);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_delay", c.intCodec(), value.tickDelay())
.put("block_search_extent", c.intCodec(), value.blockSearchExtent())
.put("offset", c.doubleCodec(), value.offset())
.map());
this.additions = c.compactList(c.of((raw, context) -> {
ObjectReader f = c.reader("ambient additions", raw, context);
SoundRef sound = f.required("sound", soundRef);
double chance = f.required("tick_chance", c.doubleCodec());
f.finish();
return new AmbientSounds.Additions(sound, chance);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_chance", c.doubleCodec(), value.tickChance())
.map()));
this.ambientSounds = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient sounds", raw, context);
Optional<SoundRef> loop = f.optional("loop", soundRef);
Optional<AmbientSounds.Mood> moodValue = f.optional("mood", mood);
List<AmbientSounds.Additions> additionsValue = f.orDefault("additions", additions, List.of());
f.finish();
return new AmbientSounds(loop, moodValue, additionsValue);
}, value -> c.writer()
.optional("loop", soundRef, value.loop())
.optional("mood", mood, value.mood())
.put("additions", additions, value.additions())
.map());
this.bedRuleRule = c.enumCodec("bed rule", BedRule.Rule.class);
this.bedRule = c.of((raw, context) -> {
ObjectReader f = c.reader("bed rule", raw, context);
BedRule.Rule canSleep = f.required("can_sleep", bedRuleRule);
BedRule.Rule canSetSpawn = f.required("can_set_spawn", bedRuleRule);
boolean onUse = f.orDefault("destroy_on_use", c.booleanCodec(), false);
boolean onLeave = f.orDefault("destroy_on_leave", c.booleanCodec(), false);
Optional<RawValue> message = f.optional("error_message", c.raw());
f.finish();
return new BedRule(canSleep, canSetSpawn, onUse, onLeave, message);
}, value -> c.writer()
.put("can_sleep", bedRuleRule, value.canSleep())
.put("can_set_spawn", bedRuleRule, value.canSetSpawn())
.put("destroy_on_use", c.booleanCodec(), value.destroyOnUse())
.put("destroy_on_leave", c.booleanCodec(), value.destroyOnLeave())
.optional("error_message", c.raw(), value.errorMessage())
.map());
this.spawners = c.list(c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawner", raw, context);
RegistryKey type = f.required("type", identifier);
int weight = f.required("weight", c.nonNegativeInt());
IntProviderValue count = f.required("count", intProvider);
f.finish();
return new MobSpawnSettings.Spawner(type, weight, count);
}, value -> c.writer()
.put("type", identifier, value.type())
.put("weight", c.nonNegativeInt(), value.weight())
.put("count", intProvider, value.count())
.map()));
this.spawnCost = c.of((raw, context) -> {
ObjectReader f = c.reader("spawn cost", raw, context);
double budget = f.required("energy_budget", c.doubleCodec());
double charge = f.required("charge", c.doubleCodec());
f.finish();
return new MobSpawnSettings.Cost(budget, charge);
}, value -> c.writer()
.put("energy_budget", c.doubleCodec(), value.energyBudget())
.put("charge", c.doubleCodec(), value.charge())
.map());
this.spawnsByCategory = c.of((raw, context) -> {
ObjectReader categories = c.reader("spawns_by_category", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> out = new LinkedHashMap<>();
for(String key : categories.keys()) {
if(!MOB_CATEGORIES.contains(key)) {
throw new DecodeException("unknown mob category \"" + key + "\", expected one of " + new TreeSet<>(MOB_CATEGORIES));
}
out.put(key, categories.required(key, spawners));
}
categories.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((category, list) -> out.put(category, spawners.encode(list)));
return out;
});
// Map keys are never preprocessed.
this.spawnCosts = c.of((raw, context) -> {
ObjectReader costs = c.reader("spawn_costs", raw, context);
Map<RegistryKey, MobSpawnSettings.Cost> out = new LinkedHashMap<>();
for(String key : costs.keys()) {
out.put(identifier.decode(key, plain), costs.required(key, spawnCost));
}
costs.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((entity, cost) -> out.put((String) identifier.encode(entity), spawnCost.encode(cost)));
return out;
});
this.mobSpawnSettings = c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawn settings", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> byCategory = f.required("spawns_by_category", spawnsByCategory);
Map<RegistryKey, MobSpawnSettings.Cost> costs = f.required("spawn_costs", spawnCosts);
f.finish();
return new MobSpawnSettings(byCategory, costs);
}, value -> c.writer()
.put("spawns_by_category", spawnsByCategory, value.spawnsByCategory())
.put("spawn_costs", spawnCosts, value.spawnCosts())
.map());
}
private RegistryKey lowerCase(RegistryKey key, String written) throws DecodeException {
try {
return MinecraftIds.requireLowerCase(key, written);
} catch(IllegalArgumentException e) {
throw new DecodeException(EXPECTED_IDENTIFIER + ", got " + codecs.describe(written), e);
}
}
public AttributeCodec<RegistryKey> identifier() {
return identifier;
}
public AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeCodec<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeCodec<RawValue> particle() {
return particle;
}
public AttributeCodec<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeCodec<IntProviderValue> intProvider() {
return intProvider;
}
public AttributeCodec<SoundRef> soundRef() {
return soundRef;
}
public AttributeCodec<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeCodec<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeCodec<BedRule> bedRule() {
return bedRule;
}
public AttributeCodec<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.regex.Pattern;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class MinecraftIds {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private MinecraftIds() { }
public static RegistryKey requireLowerCase(RegistryKey key) {
return requireLowerCase(key, key.toString());
}
public static RegistryKey requireLowerCase(RegistryKey key, String written) {
if(!NAMESPACE.matcher(key.getNamespace()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -");
}
if(!PATH.matcher(key.getID()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -");
}
return key;
}
}
@@ -0,0 +1,25 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record MobSpawnSettings(Map<String, List<Spawner>> spawnsByCategory, Map<RegistryKey, Cost> spawnCosts) {
public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of());
public MobSpawnSettings {
Map<String, List<Spawner>> copy = new LinkedHashMap<>();
spawnsByCategory.forEach((k, v) -> copy.put(k, List.copyOf(v)));
spawnsByCategory = Collections.unmodifiableMap(copy);
spawnCosts = Collections.unmodifiableMap(new LinkedHashMap<>(spawnCosts));
}
public record Spawner(RegistryKey type, int weight, IntProviderValue count) { }
public record Cost(double energyBudget, double charge) { }
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum MoonPhase implements StringIdentifiable {
FULL_MOON("full_moon"),
WANING_GIBBOUS("waning_gibbous"),
THIRD_QUARTER("third_quarter"),
WANING_CRESCENT("waning_crescent"),
NEW_MOON("new_moon"),
WAXING_CRESCENT("waxing_crescent"),
FIRST_QUARTER("first_quarter"),
WAXING_GIBBOUS("waxing_gibbous");
private final String id;
MoonPhase(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,3 @@
package com.dfsek.terra.addons.attribute.minecraft;
public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { }
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum Skybox implements StringIdentifiable {
NONE("none"),
OVERWORLD("overworld"),
END("end");
private final String id;
Skybox(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.OptionalDouble;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record SoundRef(RegistryKey id, OptionalDouble range) { }
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum TemperatureModifier implements StringIdentifiable {
NONE("none"),
FROZEN("frozen");
private final String id;
TemperatureModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,12 @@
schema-version: 1
contributors:
- Terra contributors
id: minecraft-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
@@ -0,0 +1,450 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
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.AttributeHandle;
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.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class MinecraftAttributeTypesTest {
private static final float EPS = 1e-6f;
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final MinecraftCodecs CODECS = new MinecraftCodecs(HANDLE);
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 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 everyTypeSupportsOverride() {
List<AttributeType<?>> all = List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.ambientParticles(),
TYPES.backgroundMusic(), TYPES.ambientSounds(), TYPES.mobSpawnSettings(), TYPES.identifier(), TYPES.identifierOrTag(),
TYPES.intProvider());
for(AttributeType<?> t : all) assertTrue(t.operations().contains(Operation.OVERRIDE), t.id());
}
@Test
void operationSets() {
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifier().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifierOrTag().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations());
}
@Test
void idsAreVanillaTypeIds() {
assertEquals("moon_phase", TYPES.moonPhase().id());
assertEquals("bed_rule", TYPES.bedRule().id());
assertEquals("particle", TYPES.particle().id());
assertEquals("ambient_particles", TYPES.ambientParticles().id());
assertEquals("background_music", TYPES.backgroundMusic().id());
assertEquals("ambient_sounds", TYPES.ambientSounds().id());
assertEquals("mob_spawn_settings", TYPES.mobSpawnSettings().id());
assertEquals("identifier", TYPES.identifier().id());
assertEquals("identifier_or_tag", TYPES.identifierOrTag().id());
assertEquals("int_provider", TYPES.intProvider().id());
}
@Test
void decodeFailuresReadTheSameEverywhere() {
String bedRule = assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage();
assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule);
String moonPhase = assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("x", PLAIN)).getMessage();
assertTrue(moonPhase.startsWith("unknown moon phase \"x\", expected one of [full_moon, "), moonPhase);
}
@Test
void enumsAreStringIdentifiable() {
assertEquals("waxing_gibbous", MoonPhase.WAXING_GIBBOUS.getID());
assertEquals("when_dark", BedRule.Rule.WHEN_DARK.getID());
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
}
@Test
void ambientParticlesAppend() throws DecodeException {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
List<AmbientParticle> one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN);
List<AmbientParticle> two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN);
assertEquals(1, one.size());
assertEquals(0.025f, one.get(0).probability(), EPS);
assertEquals(new RawValue(map("type", "minecraft:crimson_spore")), one.get(0).particle());
assertEquals(one, t.apply(Operation.APPEND, one, List.of()));
assertEquals(two, t.apply(Operation.APPEND, List.of(), two));
assertEquals(List.of(one.get(0), two.get(0)), t.apply(Operation.APPEND, one, two));
assertEquals(List.of(one.get(0), two.get(0)),
mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1))));
}
@Test
void ambientParticleValidation() {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 1.5)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"))), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", "x", "probability", 0.5)), PLAIN));
assertThrows(DecodeException.class,
() -> t.decode(List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(map("particle", map("type", "x"), "probability", 0.5), PLAIN));
}
private static MobSpawnSettings spawns(Map<String, Object> raw) throws DecodeException {
return TYPES.mobSpawnSettings().decode(raw, PLAIN);
}
private static Map<String, Object> spawner(String type, int weight, int count) {
return map("type", type, "weight", weight, "count", count);
}
@Test
void mobSpawnDecode() throws DecodeException {
MobSpawnSettings s = spawns(map(
"spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8))),
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15))));
MobSpawnSettings.Spawner sp = s.spawnsByCategory().get("ambient").get(0);
assertEquals(RegistryKey.parse("minecraft:bat"), sp.type());
assertEquals(10, sp.weight());
assertEquals(8, sp.count().constant().getAsInt());
assertEquals(0.7, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).energyBudget(), 1e-9);
assertEquals(0.15, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).charge(), 1e-9);
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map(), "spawn_costs", map(), "x", 1)));
}
@Test
void mobSpawnCountMapIsKeptRaw() throws DecodeException {
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(
map("type", "minecraft:zombie", "weight", 5,
"count", map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)))),
"spawn_costs", map()));
IntProviderValue c = s.spawnsByCategory().get("monster").get(0).count();
assertTrue(c.constant().isEmpty());
assertTrue(c.provider().isPresent());
}
@Test
void mobSpawnOverlayRules() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings empty = MobSpawnSettings.EMPTY;
MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))),
"spawn_costs", map()));
assertSame(a, t.apply(Operation.OVERLAY, empty, a));
assertSame(a, t.apply(Operation.OVERLAY, a, empty));
MobSpawnSettings sup = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:husk", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map()));
assertSame(sup, t.apply(Operation.OVERLAY, a, sup));
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))),
"spawn_costs", map("minecraft:a", map("energy_budget", 1, "charge", 1))));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))),
"spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2))));
MobSpawnSettings r = t.apply(Operation.OVERLAY, s, arg);
assertEquals(RegistryKey.parse("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type());
assertEquals(RegistryKey.parse("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type());
assertEquals(RegistryKey.parse("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type());
assertEquals(Set.of(RegistryKey.parse("minecraft:a"), RegistryKey.parse("minecraft:b")), r.spawnCosts().keySet());
}
@Test
void mobSpawnOverlayEmptyCategoryClears() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))), "spawn_costs", map()));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
assertTrue(r.spawnsByCategory().get("monster").isEmpty());
assertEquals(1, r.spawnsByCategory().get("creature").size());
assertEquals(r, t.apply(Operation.OVERLAY, s, arg));
}
@Test
void ambientSoundsDecode() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map(
"additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111),
"loop", "minecraft:ambient.crimson_forest.loop",
"mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood", "tick_delay", 6000)),
PLAIN);
assertEquals(1, a.additions().size());
assertEquals(0.0111, a.additions().get(0).tickChance(), 1e-9);
assertEquals(RegistryKey.parse("minecraft:ambient.crimson_forest.loop"), a.loop().orElseThrow().id());
assertEquals(6000, a.mood().orElseThrow().tickDelay());
assertEquals(8, a.mood().orElseThrow().blockSearchExtent());
assertEquals(2.0, a.mood().orElseThrow().offset(), 1e-9);
AmbientSounds list = TYPES.ambientSounds().decode(map(
"additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "a:c", "tick_chance", 0.2))), PLAIN);
assertEquals(2, list.additions().size());
assertTrue(list.loop().isEmpty());
assertEquals(AmbientSounds.EMPTY, TYPES.ambientSounds().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("looop", "a:b"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("mood", map("sound", "a:b")), PLAIN));
}
@Test
void soundRefForms() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b", "range", 16)), PLAIN);
assertEquals(RegistryKey.parse("a:b"), a.loop().orElseThrow().id());
assertEquals(16.0, a.loop().orElseThrow().range().getAsDouble(), 1e-9);
AmbientSounds b = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b")), PLAIN);
assertTrue(b.loop().orElseThrow().range().isEmpty());
assertEquals(RegistryKey.parse("minecraft:ambient.cave"),
TYPES.ambientSounds().decode(map("loop", "ambient.cave"), PLAIN).loop().orElseThrow().id());
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", 5), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", "Not Valid"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", map("range", 1)), PLAIN));
}
@Test
void upperCaseIdRejected() {
DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN));
assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage());
assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage());
assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN)));
}
private static String path(String written) {
return "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -";
}
private static String namespace(String written) {
return "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -";
}
private static String lowerCaseFailure(Executable decode) {
Throwable t = assertThrows(DecodeException.class, decode);
while(t != null && !(t instanceof IllegalArgumentException)) t = t.getCause();
assertNotNull(t, "no lower-case rule failure in the cause chain");
return t.getMessage();
}
@Test
void lowerCaseIds() {
assertEquals(path("minecraft:Music.Game"),
lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN)));
assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode(
map("default", map("sound", "Music.Game", "min_delay", 1, "max_delay", 2)), PLAIN)));
assertEquals(path("minecraft:Flame"), lowerCaseFailure(() -> TYPES.particle().decode(map("type", "minecraft:Flame"), PLAIN)));
assertEquals(path("Idle"), lowerCaseFailure(() -> TYPES.identifier().decode("Idle", PLAIN)));
assertEquals(path("#minecraft:Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#minecraft:Logs", PLAIN)));
assertEquals(path("#Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#Logs", PLAIN)));
assertEquals(namespace("Minecraft:stone"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("Minecraft:stone", PLAIN)));
assertEquals(path("minecraft:Zombie"), lowerCaseFailure(() -> spawns(map(
"spawns_by_category", map("monster", List.of(spawner("minecraft:Zombie", 1, 1))), "spawn_costs", map()))));
assertEquals(namespace("Minecraft:enderman"), lowerCaseFailure(() -> spawns(map("spawns_by_category", map(),
"spawn_costs", map("Minecraft:enderman", map("energy_budget", 1, "charge", 1))))));
}
@Test
void requireLowerCase() {
RegistryKey key = RegistryKey.parse("minecraft:visual/fog_color");
assertSame(key, MinecraftIds.requireLowerCase(key));
assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color"));
assertEquals(namespace("Mod:thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("Mod:thing"))).getMessage());
assertEquals(path("mod:Thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("mod:Thing"))).getMessage());
assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class,
() -> MinecraftIds.requireLowerCase(RegistryKey.parse("minecraft:Thing"), "Thing")).getMessage());
}
@Test
void integersFollowTheCoreRule() {
String weight = assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category",
map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))).getMessage();
assertTrue(weight.endsWith("\"weight\" of mob spawner: expected an integer, got 1.5"), weight);
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(99999999999L, PLAIN));
}
@Test
void backgroundMusicDecode() throws DecodeException {
BackgroundMusic m = TYPES.backgroundMusic().decode(map(
"default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game", "replace_current_music", true),
"underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")), PLAIN);
assertTrue(m.defaultMusic().orElseThrow().replaceCurrentMusic());
assertFalse(m.underwater().orElseThrow().replaceCurrentMusic());
assertEquals(12000, m.underwater().orElseThrow().minDelay());
assertEquals(24000, m.underwater().orElseThrow().maxDelay());
assertTrue(m.creative().isEmpty());
assertEquals(BackgroundMusic.EMPTY, TYPES.backgroundMusic().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("bogus", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", 1)), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1)), PLAIN));
}
@Test
void bedRuleDecode() throws DecodeException {
BedRule r = TYPES.bedRule().decode(map("can_set_spawn", "never", "can_sleep", "when_dark", "destroy_on_leave", true,
"error_message", map("translate", "block.minecraft.bed.no_sleep")), PLAIN);
assertEquals(BedRule.Rule.WHEN_DARK, r.canSleep());
assertEquals(BedRule.Rule.NEVER, r.canSetSpawn());
assertFalse(r.destroyOnUse());
assertTrue(r.destroyOnLeave());
assertTrue(r.errorMessage().isPresent());
BedRule plain = TYPES.bedRule().decode(map("can_set_spawn", "always", "can_sleep", "always"), PLAIN);
assertTrue(plain.errorMessage().isEmpty());
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "always"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "always", "can_set_spawn", "always", "nope", 1), PLAIN));
}
@Test
void simpleTypesDecode() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, TYPES.moonPhase().decode("new_moon", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("blue_moon", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("minecraft:idle", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("idle", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("Not Valid", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode(3, PLAIN));
assertEquals("expected an identifier, not a tag, got \"#minecraft:logs\"",
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("#minecraft:logs", PLAIN)).getMessage());
assertEquals(Either.left(RegistryKey.parse("minecraft:stone")), TYPES.identifierOrTag().decode("stone", PLAIN));
assertEquals(Either.right(TagKey.parse("#minecraft:logs")), TYPES.identifierOrTag().decode("#logs", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifierOrTag().decode("#", PLAIN));
}
@Test
void particleDecode() throws DecodeException {
RawValue p = TYPES.particle().decode(map("type", "minecraft:dripping_dripstone_lava"), PLAIN);
assertEquals(new RawValue(map("type", "minecraft:dripping_dripstone_lava")), p);
assertThrows(DecodeException.class, () -> TYPES.particle().decode(map("color", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.particle().decode("minecraft:flame", PLAIN));
}
@Test
void intProviderDecode() throws DecodeException {
IntProviderValue c = TYPES.intProvider().decode(7, PLAIN);
assertEquals(7, c.constant().getAsInt());
assertTrue(c.provider().isEmpty());
IntProviderValue p = TYPES.intProvider().decode(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3), PLAIN);
assertTrue(p.constant().isEmpty());
assertTrue(p.provider().isPresent());
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode("x", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(1.5, PLAIN));
}
@Test
void overrideArgumentDecodesWithValueDecoder() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, mod(TYPES.moonPhase(), Operation.OVERRIDE, MoonPhase.FULL_MOON, "new_moon"));
}
@Test
void nestedDecodeContext() 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 PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
return raw;
}
};
Map<String, Object> music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2);
TYPES.backgroundMusic().decode(map("default", music), recording);
assertTrue(seen.contains("minecraft:music.game"), seen.toString());
assertTrue(seen.contains(1), seen.toString());
assertTrue(seen.contains(2), seen.toString());
assertTrue(seen.contains(music), 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 PLAIN.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
void resolveBeforeShape() throws DecodeException {
DecodeContext context = referencing(map(
"@sound", map("sound_id", "minecraft:ambient.cave", "range", 4.0),
"@additions", List.of(map("sound", "minecraft:a", "tick_chance", 0.5), map("sound", "minecraft:b", "tick_chance", 0.25)),
"@provider", map("type", "minecraft:uniform", "min_inclusive", "@min", "max_inclusive", 4),
"@min", 1,
"@flame", "minecraft:flame",
"@message", map("translate", "@key"),
"@key", "block.minecraft.bed.no_sleep"));
AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context);
assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow());
assertEquals(2, sounds.additions().size());
IntProviderValue provider = TYPES.intProvider().decode("@provider", context);
assertEquals(new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 4)),
provider.provider().orElseThrow());
List<AmbientParticle> particles = TYPES.ambientParticles().decode(
List.of(map("particle", map("type", "@flame"), "probability", 0.5)), context);
assertEquals(new RawValue(map("type", "minecraft:flame")), particles.get(0).particle());
BedRule rule = TYPES.bedRule().decode(map("can_sleep", "never", "can_set_spawn", "never", "error_message", "@message"),
context);
assertEquals(new RawValue(map("translate", "block.minecraft.bed.no_sleep")), rule.errorMessage().orElseThrow());
}
@Test
void mapKeysInsideValuesAreNotPreprocessed() throws DecodeException {
DecodeContext context = referencing(map("minecraft:zombie", "minecraft:cow"));
MobSpawnSettings settings = TYPES.mobSpawnSettings().decode(map(
"spawns_by_category", map(),
"spawn_costs", map("minecraft:zombie", map("energy_budget", 1.0, "charge", 0.5))), context);
assertEquals(List.of(RegistryKey.parse("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet()));
}
}
@@ -0,0 +1,99 @@
package attribute.minecraft;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon;
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.EventManager;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.inject.Injector;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.event.EventManagerImpl;
import com.dfsek.terra.registry.CheckedRegistryImpl;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftAttributesAddonTest {
private static final BaseAddon ADDON = new BaseAddon() {
@Override
public String getID() {
return "minecraft-attributes";
}
@Override
public Version getVersion() {
return null;
}
};
private static final VersionRange ONE = Versions.getVersionRange(Versions.getVersion(1, 0, 0), true, Versions.getVersion(2, 0, 0),
false);
private static Platform platform(EventManager events, AttributeHandle handle) {
return (Platform) Proxy.newProxyInstance(Platform.class.getClassLoader(), new Class<?>[]{ Platform.class },
(proxy, method, args) -> switch(method.getName()) {
case "getEventManager" -> events;
case "getAttributeHandle" -> handle;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static ConfigPack pack(Map<BaseAddon, VersionRange> addons) {
Map<TypeKey<?>, CheckedRegistry<?>> registries = new HashMap<>();
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "addons" -> addons;
case "getOrCreateRegistry" -> registries.computeIfAbsent((TypeKey<?>) args[0],
type -> new CheckedRegistryImpl<>(new OpenRegistryImpl<>(type)));
default -> throw new UnsupportedOperationException(method.getName());
});
}
@Test
void dependentPacksOnly() {
EventManager events = new EventManagerImpl();
AttributeHandle handle = new AttributeHandleImpl();
MinecraftAttributesAddon initializer = new MinecraftAttributesAddon();
Injector<Platform> platformInjector = Injector.get(platform(events, handle));
platformInjector.addExplicitTarget(Platform.class);
platformInjector.inject(initializer);
Injector<BaseAddon> addonInjector = Injector.get(ADDON);
addonInjector.addExplicitTarget(BaseAddon.class);
addonInjector.inject(initializer);
initializer.initialize();
ConfigPack dependent = pack(Map.of(ADDON, ONE));
ConfigPack other = pack(Map.of());
events.callEvent(new ConfigPackPreLoadEvent(dependent, template -> { }));
events.callEvent(new ConfigPackPreLoadEvent(other, template -> { }));
CheckedRegistry<Attribute<?>> registered = dependent.getOrCreateRegistry(Attribute.REGISTRY_TYPE);
assertEquals(79, registered.entries().size());
assertTrue(other.getOrCreateRegistry(Attribute.REGISTRY_TYPE).entries().isEmpty());
Attribute<?> fog = MinecraftAttributes.VISUAL_FOG_COLOR.lookup(registered).orElseThrow();
assertSame(fog, registered.get(fog.getRegistryKey()).orElseThrow());
ConfigPack second = pack(Map.of(ADDON, ONE));
events.callEvent(new ConfigPackPreLoadEvent(second, template -> { }));
assertSame(fog, MinecraftAttributes.VISUAL_FOG_COLOR.lookup(second.getOrCreateRegistry(Attribute.REGISTRY_TYPE)).orElseThrow());
assertEquals(79, handle.attributeCount());
}
}
@@ -0,0 +1,194 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
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.CheckedRegistry;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.registry.CheckedRegistryImpl;
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;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftAttributesTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final List<Attribute<?>> ALL = MinecraftAttributeTable.create(HANDLE);
private static final CheckedRegistry<Attribute<?>> REGISTRY = registry();
private static CheckedRegistry<Attribute<?>> registry() {
CheckedRegistry<Attribute<?>> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE));
ALL.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute));
return registry;
}
private static Attribute<?> byId(String id) {
return REGISTRY.get(RegistryKey.parse(id)).orElseThrow();
}
@SuppressWarnings("unchecked")
private static <T> Attribute<T> typed(String id) {
return (Attribute<T>) byId(id);
}
@Test
void tableOrder() {
assertEquals(MinecraftAttributes.all(), ALL.stream().map(Attribute::key).toList());
int first = ALL.get(0).index();
for(int i = 0; i < ALL.size(); i++) {
assertEquals(first + i, ALL.get(i).index(), ALL.get(i).key().toString());
assertSame(ALL.get(i), REGISTRY.get(ALL.get(i).getRegistryKey()).orElseThrow());
}
assertTrue(HANDLE.attributeCount() >= first + ALL.size());
}
@Test
void scopes() {
Set<String> packOnly = ALL.stream().filter(a -> a.key().getNamespace().equals("minecraft"))
.filter(a -> a.scope() == AttributeScope.PACK_ONLY).map(a -> a.key().toString()).collect(Collectors.toSet());
assertEquals(Set.of("minecraft:gameplay/sky_light_level", "minecraft:gameplay/fast_lava"), packOnly);
for(Attribute<?> a : ALL) {
if(!a.key().getNamespace().equals("terra")) continue;
boolean packWide = a.key().getID().startsWith("dimension/") || a.key().getID().startsWith("world/");
assertEquals(packWide ? AttributeScope.PACK_ONLY : AttributeScope.ANYWHERE, a.scope(), a.key().toString());
}
}
@Test
void terraDefaults() {
assertNull(byId("terra:biome/foliage_color").defaultValue());
assertNull(byId("terra:biome/dry_foliage_color").defaultValue());
assertNull(byId("terra:biome/grass_color").defaultValue());
assertEquals(Color.rgb(0x3f76e4), byId("terra:biome/water_color").defaultValue());
assertEquals(-64, byId("terra:dimension/min_y").defaultValue());
assertEquals(384, byId("terra:dimension/height").defaultValue());
assertEquals(Either.right(TagKey.parse("#minecraft:infiniburn_overworld")),
byId("terra:dimension/infiniburn").defaultValue());
assertEquals(RegistryKey.parse("minecraft:plains"), byId("terra:biome/villager_type").defaultValue());
assertEquals(RegistryKey.parse("minecraft:overworld"), byId("terra:dimension/default_clock").defaultValue());
IntProviderValue light = (IntProviderValue) byId("terra:dimension/monster_spawn_light_level").defaultValue();
assertEquals(Optional.of(new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))),
light.provider());
}
@Test
void rangeValidation() throws Exception {
Attribute<Float> spawn = typed("minecraft:gameplay/creature_world_gen_spawn_probability");
assertEquals(0.5f, spawn.validate(0.5f));
assertThrows(DecodeException.class, () -> spawn.validate(1.0f));
assertThrows(DecodeException.class, () -> spawn.validate(-0.1f));
assertThrows(DecodeException.class, () -> spawn.validate(Float.NaN));
Attribute<Float> unit = typed("minecraft:audio/music_volume");
assertEquals("value 2.0 is outside [0, 1]", assertThrows(DecodeException.class, () -> unit.validate(2f)).getMessage());
Attribute<Float> fogEnd = typed("minecraft:visual/fog_end_distance");
assertThrows(DecodeException.class, () -> fogEnd.validate(-1f));
assertEquals(1e9f, fogEnd.validate(1e9f));
assertEquals(-5f, typed("minecraft:visual/fog_start_distance").validate(-5f));
Attribute<Float> scale = typed("terra:dimension/coordinate_scale");
assertEquals(1f, scale.validate(1f));
assertThrows(DecodeException.class, () -> scale.validate(0f));
Attribute<Integer> light = typed("terra:dimension/monster_spawn_block_light_limit");
assertThrows(DecodeException.class, () -> light.validate(16));
}
@Test
void dimensionGeometry() throws Exception {
for(String id : List.of("terra:dimension/min_y", "terra:dimension/height", "terra:dimension/logical_height")) {
assertEquals(EnumSet.of(Operation.OVERRIDE), byId(id).type().operations(), id);
}
Attribute<Integer> minY = typed("terra:dimension/min_y");
assertEquals(-2032, minY.validate(-2032));
assertThrows(DecodeException.class, () -> minY.validate(-2048));
assertThrows(DecodeException.class, () -> minY.validate(2032));
assertThrows(DecodeException.class, () -> minY.validate(-60));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(16, height.validate(16));
assertThrows(DecodeException.class, () -> height.validate(0));
assertEquals("value 100 is not a multiple of 16", assertThrows(DecodeException.class, () -> height.validate(100)).getMessage());
assertEquals(37, typed("terra:dimension/logical_height").validate(37));
}
@Test
void sanitizeClamps() {
Attribute<Float> sky = typed("minecraft:gameplay/sky_light_level");
assertEquals(15f, sky.sanitize(20f));
assertEquals(0f, sky.sanitize(-3f));
assertEquals(7f, sky.sanitize(7f));
Attribute<Boolean> flag = typed("minecraft:gameplay/can_start_raid");
assertEquals(true, flag.sanitize(true));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(4064, height.sanitize(9999));
}
@Test
void typedKeys() throws ReflectiveOperationException {
Set<AttributeKey<?>> constants = new HashSet<>();
for(Field field : MinecraftAttributes.class.getFields()) {
if(!Modifier.isStatic(field.getModifiers()) || field.getType() != AttributeKey.class) continue;
AttributeKey<?> key = (AttributeKey<?>) field.get(null);
Type argument = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
Class<?> valueClass = (Class<?>) (argument instanceof ParameterizedType p ? p.getRawType() : argument);
Attribute<?> attribute = key.lookup(REGISTRY).orElseThrow(() -> new AssertionError("Not registered: " + key));
assertSame(key, attribute.key(), field.getName());
Object defaultValue = attribute.defaultValue();
if(defaultValue != null) {
assertTrue(valueClass.isInstance(defaultValue),
field.getName() + ": " + defaultValue.getClass() + " is not a " + valueClass);
}
constants.add(key);
}
assertEquals(79, constants.size());
assertEquals(Set.copyOf(MinecraftAttributes.all()), constants);
assertEquals(79, ALL.size());
}
@Test
void typedLookup() {
AttributeKey<Float> lookalike = AttributeKey.parse("minecraft:visual/fog_color");
assertEquals(MinecraftAttributes.VISUAL_FOG_COLOR, lookalike);
assertTrue(lookalike.lookup(REGISTRY).isEmpty());
assertTrue(REGISTRY.get(lookalike.getRegistryKey()).isPresent());
}
@Test
void keyIds() {
for(AttributeKey<?> key : MinecraftAttributes.all()) {
String namespace = key.getRegistryKey().getNamespace();
String path = key.getRegistryKey().getID();
assertTrue(namespace.matches("[a-z0-9_.-]+") && path.matches("[a-z0-9_./-]+"), key.toString());
}
}
}
@@ -0,0 +1,177 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.CardinalLight;
import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
import com.dfsek.terra.addons.attribute.minecraft.Music;
import com.dfsek.terra.addons.attribute.minecraft.Skybox;
import com.dfsek.terra.addons.attribute.minecraft.SoundRef;
import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier;
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.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.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftCodecRoundTripTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final AttributeTypes CORE = HANDLE.types();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final RawValue FLAME = new RawValue(map("type", "minecraft:flame"));
private static final RawValue UNIFORM = new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3));
private static final SoundRef SOUND = new SoundRef(RegistryKey.parse("minecraft:music.game"), OptionalDouble.empty());
private static final SoundRef RANGED_SOUND = new SoundRef(RegistryKey.parse("minecraft:ambient.cave"), OptionalDouble.of(16));
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 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);
}
private static List<Case<?>> cases() {
MobSpawnSettings spawns = new MobSpawnSettings(
Map.of("monster", List.of(
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:zombie"), 95,
new IntProviderValue(OptionalInt.of(4), Optional.empty())),
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:husk"), 5,
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
"ambient", List.of()),
Map.of(RegistryKey.parse("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15)));
return List.of(
of(TYPES.moonPhase(), List.of(MoonPhase.values())),
of(TYPES.bedRule(), List.of(
new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, true, false,
Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep")))),
new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, true, Optional.empty()))),
of(TYPES.particle(), List.of(FLAME, new RawValue(map("type", "minecraft:dust", "color", List.of(1.0, 0.5, 0.0), "scale", 2)))),
of(TYPES.ambientParticles(), List.of(List.of(), List.of(new AmbientParticle(FLAME, 0.025f))),
Operation.APPEND, List.of(List.of(new AmbientParticle(FLAME, 0.5f), new AmbientParticle(FLAME, 1f)))),
of(TYPES.backgroundMusic(), List.of(BackgroundMusic.EMPTY,
new BackgroundMusic(Optional.of(new Music(SOUND, 12000, 24000, true)), Optional.empty(),
Optional.of(new Music(RANGED_SOUND, 0, 1, false))))),
of(TYPES.ambientSounds(), List.of(AmbientSounds.EMPTY,
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.of(new AmbientSounds.Mood(SOUND, 6000, 8, 2.0)),
List.of(new AmbientSounds.Additions(SOUND, 0.0111), new AmbientSounds.Additions(RANGED_SOUND, 0.5))))),
of(TYPES.mobSpawnSettings(), List.of(MobSpawnSettings.EMPTY, spawns),
Operation.OVERLAY, List.of(MobSpawnSettings.EMPTY, spawns)),
of(TYPES.identifier(), List.of(RegistryKey.parse("minecraft:stone"), RegistryKey.parse("my.pack:a/b"))),
of(TYPES.identifierOrTag(), List.<Either<RegistryKey, TagKey>>of(
Either.left(RegistryKey.parse("minecraft:stone")), Either.right(TagKey.parse("#my.pack:logs")))),
of(TYPES.intProvider(), List.of(new IntProviderValue(OptionalInt.of(-4), Optional.empty()),
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
of(CORE.enumType("skybox", Skybox.class), List.of(Skybox.values())),
of(CORE.enumType("cardinal_light", CardinalLight.class), List.of(CardinalLight.values())),
of(CORE.enumType("grass_color_modifier", GrassColorModifier.class), List.of(GrassColorModifier.values())),
of(CORE.enumType("temperature_modifier", TemperatureModifier.class), List.of(TemperatureModifier.values())));
}
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 everyMinecraftType() 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 canonicalForms() {
assertEquals("minecraft:stone", TYPES.identifier().encode(RegistryKey.parse("minecraft:stone")));
assertEquals("#minecraft:logs", TYPES.identifierOrTag().encode(Either.right(TagKey.parse("#minecraft:logs"))));
assertEquals("minecraft:stone", TYPES.identifierOrTag().encode(Either.left(RegistryKey.parse("minecraft:stone"))));
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
assertEquals("end", CORE.enumType("skybox", Skybox.class).encode(Skybox.END));
assertEquals(map("type", "minecraft:flame"), TYPES.particle().encode(FLAME));
assertEquals(7, TYPES.intProvider().encode(new IntProviderValue(OptionalInt.of(7), Optional.empty())));
Map<?, ?> plainLoop = (Map<?, ?>) TYPES.ambientSounds().encode(new AmbientSounds(Optional.of(SOUND), Optional.empty(), List.of()));
assertEquals("minecraft:music.game", plainLoop.get("loop"));
Map<?, ?> rangedLoop = (Map<?, ?>) TYPES.ambientSounds().encode(
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.empty(), List.of()));
assertEquals(map("sound_id", "minecraft:ambient.cave", "range", 16.0), rangedLoop.get("loop"));
Map<?, ?> bedRule = (Map<?, ?>) TYPES.bedRule().encode(
new BedRule(BedRule.Rule.NEVER, BedRule.Rule.NEVER, false, false, Optional.empty()));
assertFalse(bedRule.containsKey("error_message"));
}
}
@@ -23,6 +23,8 @@ import com.dfsek.terra.api.profiler.Profiler;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.tectonic.LoaderRegistrar;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeParents;
/**
@@ -89,4 +91,17 @@ public interface Platform extends LoaderRegistrar {
@Contract(pure = true)
int getGenerationThreads();
@NotNull
@Contract(pure = true)
AttributeHandle getAttributeHandle();
/**
* Each pack reads these once, when it loads.
*/
@NotNull
@Contract(pure = true)
default AttributeParents getAttributeParents() {
return AttributeParents.NONE;
}
}
@@ -52,6 +52,14 @@ public class Context {
return (T) list[key.key];
}
/**
* Unlike {@link #get(PropertyKey)}, safe for keys created after this context last stored a value.
*/
public boolean has(PropertyKey<?> key) {
Properties[] current = list;
return key.key < current.length && current[key.key] != null;
}
public <T extends Properties> boolean has(Class<T> test) {
return map.containsKey(test);
}
@@ -1,29 +1,31 @@
package com.dfsek.terra.api.registry.key;
import java.util.Objects;
import java.util.regex.Pattern;
public final class RegistryKey implements StringIdentifiable, Namespaced {
private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]*$");
private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^[a-zA-Z0-9_.-]*$");
private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_./-]*$");
private final String namespace;
private final String id;
private final int hash;
private RegistryKey(String namespace, String id) {
if(!ID_PATTERN.matcher(namespace).matches()) {
if(!NAMESPACE_PATTERN.matcher(namespace).matches()) {
throw new IllegalArgumentException(
"Namespace must only contain alphanumeric characters, hyphens, and underscores. \"" + namespace +
"Namespace must only contain alphanumeric characters, hyphens, underscores, and periods. \"" + namespace +
"\" is not a valid namespace.");
}
if(!ID_PATTERN.matcher(id).matches()) {
throw new IllegalArgumentException(
"ID must only contain alphanumeric characters, hyphens, and underscores. \"" + id +
"ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"" + id +
"\" is not a valid ID.");
}
this.namespace = namespace;
this.id = id;
this.hash = 31 * (31 + namespace.hashCode()) + id.hashCode();
}
public static RegistryKey parse(String key) {
@@ -36,6 +38,37 @@ public final class RegistryKey implements StringIdentifiable, Namespaced {
return new RegistryKey(namespace, id);
}
/**
* Parses {@code namespace:id}, or {@code id} in {@code defaultNamespace}.
*
* @throws IllegalArgumentException if a part is empty or invalid, or the key holds more than one {@code :}
*/
public static RegistryKey parse(String key, String defaultNamespace) {
// Shown to users in config warnings: no Java type names.
if(key == null) throw new IllegalArgumentException("malformed ID: none given");
int colon = key.indexOf(':');
if(colon != key.lastIndexOf(':')) throw new IllegalArgumentException(malformed(key, "more than one ':'"));
String namespace = colon < 0 ? defaultNamespace : key.substring(0, colon);
String id = key.substring(colon + 1);
if(namespace == null || namespace.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty namespace"));
if(id.isEmpty()) throw new IllegalArgumentException(malformed(key, "empty ID"));
return new RegistryKey(namespace, id);
}
private static String malformed(String key, String reason) {
return "malformed ID \"" + key + "\": " + reason;
}
/**
* @throws IllegalArgumentException if the key has no namespace or is otherwise invalid
*/
public static RegistryKey parseNamespaced(String key) {
if(key != null && key.indexOf(':') < 0) {
throw new IllegalArgumentException("a namespace is required, as in \"namespace:" + key + "\"");
}
return parse(key, "");
}
public static RegistryKey of(String namespace, String id) {
return new RegistryKey(namespace, id);
}
@@ -52,13 +85,14 @@ public final class RegistryKey implements StringIdentifiable, Namespaced {
@Override
public int hashCode() {
return Objects.hash(namespace, id);
return hash;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj instanceof RegistryKey that) {
return this.id.equals(that.id) && this.namespace.equals(that.namespace);
return this.hash == that.hash && this.id.equals(that.id) && this.namespace.equals(that.namespace);
}
return false;
}
@@ -0,0 +1,63 @@
package com.dfsek.terra.api.registry.key;
public final class TagKey {
private final RegistryKey key;
private TagKey(RegistryKey key) {
this.key = key;
}
public static TagKey of(RegistryKey key) {
return new TagKey(key);
}
/**
* @throws IllegalArgumentException if the string does not start with {@code #}, has no namespace, or is not a valid
* {@link RegistryKey}
*/
public static TagKey parse(String tag) {
String body = body(tag);
try {
return new TagKey(RegistryKey.parseNamespaced(body));
} catch(IllegalArgumentException e) {
if(body.indexOf(':') < 0) {
throw new IllegalArgumentException(
"invalid tag \"" + tag + "\": a namespace is required, as in \"#namespace:" + body + "\"", e);
}
throw e;
}
}
/**
* Parses {@code #namespace:id}, or {@code #id} in {@code defaultNamespace}.
*
* @throws IllegalArgumentException if the string does not start with {@code #} or is not a valid {@link RegistryKey}
*/
public static TagKey parse(String tag, String defaultNamespace) {
return new TagKey(RegistryKey.parse(body(tag), defaultNamespace));
}
private static String body(String tag) {
if(tag == null || !tag.startsWith("#")) throw new IllegalArgumentException("invalid tag (expected #namespace:id): \"" + tag + "\"");
return tag.substring(1);
}
public RegistryKey key() {
return key;
}
@Override
public boolean equals(Object obj) {
return obj instanceof TagKey that && key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return "#" + key;
}
}
@@ -0,0 +1,63 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import com.dfsek.terra.api.registry.key.Keyed;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.util.reflection.TypeKey;
/**
* Build each attribute once and register the same instance in every pack: every build takes a new {@link #index()}.
*/
public interface Attribute<T> extends Keyed<Attribute<T>> {
TypeKey<Attribute<?>> REGISTRY_TYPE = new TypeKey<>() { };
AttributeKey<T> key();
AttributeType<T> type();
/**
* {@code null} means no override.
*/
@Nullable
T defaultValue();
AttributeScope scope();
/**
* @throws DecodeException if the value is outside this attribute's range or not a required multiple
*/
T validate(T value) throws DecodeException;
/**
* Clamps numeric values to this attribute's range; returns other values unchanged.
*/
T sanitize(T value);
/**
* Dense, from 0, below {@link AttributeHandle#attributeCount()}.
*/
@ApiStatus.Internal
int index();
@Override
default RegistryKey getRegistryKey() {
return key().getRegistryKey();
}
interface Builder<T> {
/**
* Values must lie in {@code [min, max]}; resolved values are clamped to it.
*/
Builder<T> range(Number min, Number max);
Builder<T> multipleOf(int multipleOf);
Builder<T> packOnly();
Attribute<T> build();
}
}
@@ -0,0 +1,14 @@
package com.dfsek.terra.api.world.attribute;
public interface AttributeCodec<T> {
/**
* @param raw a number, string, boolean, list, string-keyed map, or {@code null}
*/
T decode(Object raw, DecodeContext context) throws DecodeException;
/**
* Returns a number, boolean, string, list or string-keyed map of those, or {@code null}. {@link #decode} must read it
* back to an equal value.
*/
Object encode(T value);
}
@@ -0,0 +1,127 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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;
public interface AttributeCodecs {
@FunctionalInterface
interface Decoder<T> {
T decode(Object raw, DecodeContext context) throws DecodeException;
}
@FunctionalInterface
interface Encoder<T> {
Object encode(T value);
}
/**
* Not thread safe.
*/
interface ObjectReader {
/**
* In config order.
*/
List<String> keys();
/**
* @throws DecodeException if the key is missing or its value does not decode
*/
<V> V required(String key, AttributeCodec<V> codec) throws DecodeException;
<V> Optional<V> optional(String key, AttributeCodec<V> codec) throws DecodeException;
<V> V orDefault(String key, AttributeCodec<V> codec, V fallback) throws DecodeException;
/**
* @throws DecodeException if the object has a key that was not read
*/
void finish() throws DecodeException;
}
/**
* Not thread safe. Keeps fields in the order written.
*/
interface ObjectWriter {
<V> ObjectWriter put(String key, AttributeCodec<V> codec, V value);
<V> ObjectWriter optional(String key, AttributeCodec<V> codec, Optional<V> value);
Map<String, Object> map();
}
<T> AttributeCodec<T> of(Decoder<T> decoder, Encoder<T> encoder);
/**
* Names {@code value} for messages, such as {@code "text"}, {@code an object} or {@code nothing}.
*/
String describe(@Nullable Object value);
AttributeCodec<Boolean> booleanCodec();
AttributeCodec<Float> floatCodec();
AttributeCodec<Double> doubleCodec();
/**
* Rejects fractions and values outside the {@code int} range.
*/
AttributeCodec<Integer> intCodec();
AttributeCodec<Integer> nonNegativeInt();
AttributeCodec<Float> unitFloat();
/**
* @param expected the start of the message when the value is not a string, as in {@code expected a sound ID}
*/
AttributeCodec<String> string(String expected);
AttributeCodec<RawValue> raw();
<V> AttributeCodec<List<V>> list(AttributeCodec<V> element);
/**
* Also reads a single element as a list of one. Always encodes a list.
*/
<V> AttributeCodec<List<V>> compactList(AttributeCodec<V> element);
/**
* Reads constants by {@link StringIdentifiable#getID() ID}.
*
* @param name names the enum in messages, such as {@code moon phase}
*
* @throws IllegalArgumentException if two constants share an ID
*/
<E extends Enum<E> & StringIdentifiable> AttributeCodec<E> enumCodec(String name, Class<E> type);
/**
* A bare ID takes {@code defaultNamespace}. Tags are rejected.
*/
AttributeCodec<RegistryKey> identifier(String defaultNamespace);
/**
* A bare ID takes {@code defaultNamespace}.
*/
AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag(String defaultNamespace);
/**
* @param what names the object in messages, such as {@code music}
*
* @throws DecodeException if {@code raw} is not an object, or has a key that is not a string
*/
ObjectReader reader(String what, Object raw, DecodeContext context) throws DecodeException;
ObjectWriter writer();
}
@@ -0,0 +1,43 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public record AttributeEntry<T>(@NotNull Operation operation, @Nullable Object argument) {
/**
* @throws IllegalArgumentException if {@code argument} is {@code null} and {@code operation} is not {@link Operation#OVERRIDE}
*/
public AttributeEntry {
Objects.requireNonNull(operation, "operation");
if(argument == null && operation != Operation.OVERRIDE) {
throw new IllegalArgumentException("modifier " + operation.getID() + " needs an argument");
}
}
@NotNull
@Contract("_ -> new")
public static <T> AttributeEntry<T> override(@Nullable T value) {
return new AttributeEntry<>(Operation.OVERRIDE, value);
}
/**
* @throws IllegalArgumentException if {@code argument} is {@code null} and {@code op} is not {@link Operation#OVERRIDE}
*/
@NotNull
@Contract("_, _ -> new")
public static <T> AttributeEntry<T> of(@NotNull Operation op, @Nullable Object argument) {
return new AttributeEntry<>(op, argument);
}
public T apply(@NotNull AttributeType<T> type, T subject) {
return type.apply(operation, subject, argument);
}
public boolean isOverride() {
return operation == Operation.OVERRIDE;
}
}
@@ -0,0 +1,110 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
public interface AttributeHandle {
@NotNull
@Contract(pure = true)
AttributeTypes types();
/**
* Applies no config preprocessing.
*/
@NotNull
@Contract(pure = true)
DecodeContext plainContext();
@NotNull
@Contract(pure = true)
AttributeCodecs codecs();
@NotNull
@Contract("_, _ -> new")
<T> AttributeType.Builder<T> typeBuilder(@NotNull String id, @NotNull AttributeCodec<T> codec);
@NotNull
@Contract("_, _, _ -> new")
<T> Attribute.Builder<T> attributeBuilder(@NotNull AttributeKey<T> key, @NotNull AttributeType<T> type, @Nullable T defaultValue);
/**
* Only grows. Every {@link Attribute#index()} is below it.
*/
@ApiStatus.Internal
int attributeCount();
/**
* Applies each non-null layer, bottom first, to the default, then sanitizes. A {@code null} value only changes on an override.
*/
@SuppressWarnings("unchecked")
@Contract(pure = true)
<T> @Nullable T resolve(@NotNull Attribute<T> attribute, AttributeEntry<T>... layersBottomToTop);
/**
* Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first.
*/
@Contract(pure = true)
<T> @Nullable T resolve(@NotNull Attribute<T> attribute, @Nullable AttributeEntry<T> first, @Nullable AttributeEntry<T> second,
@Nullable AttributeEntry<T> third);
/**
* Allocation-free {@link #resolve(Attribute, AttributeEntry[])}, bottom layer first.
*/
@Contract(pure = true)
<T> @Nullable T resolve(@NotNull Attribute<T> attribute, @Nullable AttributeEntry<T> first, @Nullable AttributeEntry<T> second,
@Nullable AttributeEntry<T> third, @Nullable AttributeEntry<T> fourth);
/**
* Composes two layers into one entry that applies like {@code lower} then {@code upper}. Empty when both are {@code null}
* or they don't compose; fall back to an override of the {@link #resolve resolved} value. Float results may differ by rounding.
*/
@NotNull
@Contract(pure = true)
<T> Optional<AttributeEntry<T>> compose(@NotNull Attribute<T> attribute, @Nullable AttributeEntry<T> lower,
@Nullable AttributeEntry<T> upper);
/**
* Reads a bare value as an override, or a {@code modifier} and {@code argument} map. Resolves {@code raw} first.
*/
@NotNull
<T> AttributeEntry<T> decodeEntry(@NotNull Attribute<T> attribute, @Nullable Object raw, @NotNull DecodeContext context)
throws DecodeException;
/**
* @throws IllegalArgumentException if {@code entry} is an override of {@code null}
*/
@NotNull
@Contract(pure = true)
<T> Object encodeEntry(@NotNull Attribute<T> attribute, @NotNull AttributeEntry<T> entry);
/**
* {@code raw} must already be {@link DecodeContext#resolve resolved}. A bad track is dropped; other problems skip the schedule.
*/
@NotNull
ScheduleDecodeResult decodeSchedule(@NotNull RegistryKey id, @NotNull Map<String, Object> raw, @NotNull AttributeLookup attributes,
@NotNull DecodeContext context);
/**
* @throws IllegalArgumentException if a keyframe's argument is {@code null}
*/
@NotNull
@Contract(pure = true)
Map<String, Object> encodeSchedule(@NotNull AttributeSchedule schedule);
/**
* Empty unless the {@code config-attributes} addon loaded {@code pack}.
*/
@NotNull
Optional<PackAttributes> pack(@NotNull ConfigPack pack);
}
@@ -0,0 +1,71 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.registry.key.Keyed;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class AttributeKey<T> implements Keyed<AttributeKey<T>> {
private final RegistryKey key;
private AttributeKey(RegistryKey key) {
this.key = key;
}
@NotNull
public static <T> AttributeKey<T> of(@NotNull RegistryKey key) {
return new AttributeKey<>(key);
}
/**
* {@code T} is unchecked: {@link #lookup} returns empty for a key made here.
*
* @throws IllegalArgumentException if the key has no namespace or is not a valid {@link RegistryKey}
*/
@NotNull
public static <T> AttributeKey<T> parse(@NotNull String key) {
if(key == null) throw new IllegalArgumentException("invalid attribute key: null");
try {
return new AttributeKey<>(RegistryKey.parseNamespaced(key));
} catch(IllegalArgumentException e) {
if(key.indexOf(':') < 0) throw new IllegalArgumentException("invalid attribute key \"" + key + "\": " + e.getMessage(), e);
throw new IllegalArgumentException("invalid attribute key: \"" + key + "\"", e);
}
}
/**
* Empty unless the registered attribute's {@link Attribute#key()} is this instance.
*/
@SuppressWarnings("unchecked")
@NotNull
public Optional<Attribute<T>> lookup(@NotNull Registry<Attribute<?>> registry) {
Optional<Attribute<?>> attribute = registry.get(key);
if(attribute.isEmpty() || attribute.get().key() != this) return Optional.empty();
return Optional.of((Attribute<T>) attribute.get());
}
@Override
public RegistryKey getRegistryKey() {
return key;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
return obj instanceof AttributeKey<?> that && key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return key.toString();
}
}
@@ -0,0 +1,9 @@
package com.dfsek.terra.api.world.attribute;
@FunctionalInterface
public interface AttributeLookup {
/**
* @throws DecodeException if {@code key} names no usable attribute; the message is reported as the reason
*/
Attribute<?> find(String key) throws DecodeException;
}
@@ -0,0 +1,103 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public final class AttributeMap {
private static final AttributeMap EMPTY = new AttributeMap(Map.of());
private final Map<AttributeKey<?>, AttributeEntry<?>> entries;
private AttributeMap(Map<AttributeKey<?>, AttributeEntry<?>> entries) {
this.entries = entries;
}
@NotNull
@Contract(pure = true)
public static AttributeMap empty() {
return EMPTY;
}
@NotNull
@Contract("-> new")
public static Builder builder() {
return new Builder();
}
@NotNull
@SuppressWarnings("unchecked")
public <T> Optional<AttributeEntry<T>> get(@NotNull AttributeKey<T> key) {
return Optional.ofNullable((AttributeEntry<T>) entries.get(key));
}
/**
* In insertion order. Unmodifiable.
*/
@NotNull
public Set<AttributeKey<?>> keys() {
return entries.keySet();
}
public boolean isEmpty() {
return entries.isEmpty();
}
/**
* {@code top}'s entries replace this map's per key.
*/
@NotNull
public AttributeMap overlay(@NotNull AttributeMap top) {
Objects.requireNonNull(top, "top");
if(top.entries.isEmpty()) return this;
if(entries.isEmpty()) return top;
Map<AttributeKey<?>, AttributeEntry<?>> merged = new LinkedHashMap<>(entries);
merged.putAll(top.entries);
return new AttributeMap(Collections.unmodifiableMap(merged));
}
@Override
public boolean equals(Object obj) {
return obj instanceof AttributeMap that && entries.equals(that.entries);
}
@Override
public int hashCode() {
return entries.hashCode();
}
@Override
public String toString() {
return "AttributeMap" + entries;
}
public static final class Builder {
private final Map<AttributeKey<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
private Builder() {
}
public <T> Builder put(AttributeKey<T> key, AttributeEntry<T> entry) {
entries.put(Objects.requireNonNull(key, "key"), Objects.requireNonNull(entry, "entry"));
return this;
}
public Builder remove(AttributeKey<?> key) {
entries.remove(key);
return this;
}
public AttributeMap build() {
if(entries.isEmpty()) return EMPTY;
return new AttributeMap(Collections.unmodifiableMap(new LinkedHashMap<>(entries)));
}
}
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.api.world.attribute;
@FunctionalInterface
public interface AttributeModifier<T, A> {
T apply(T subject, A argument);
}
@@ -0,0 +1,33 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.Nullable;
import com.dfsek.terra.api.world.biome.Biome;
/**
* Called on read paths: must not allocate.
*/
public interface AttributeParents {
AttributeParents NONE = new AttributeParents() {
@Override
public <T> @Nullable AttributeEntry<T> biomeOrNull(Biome biome, Attribute<T> attribute) {
return null;
}
@Override
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
return null;
}
};
/**
* Sits between the pack entry and the biome's own entry.
*/
<T> @Nullable AttributeEntry<T> biomeOrNull(Biome biome, Attribute<T> attribute);
/**
* Sits between the attribute's default and the pack entry.
*/
<T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute);
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.api.world.attribute;
public enum AttributeScope {
ANYWHERE,
PACK_ONLY
}
@@ -0,0 +1,61 @@
package com.dfsek.terra.api.world.attribute;
import java.util.Optional;
import java.util.Set;
import java.util.function.BinaryOperator;
public interface AttributeType<T> {
String id();
/**
* Always includes {@link Operation#OVERRIDE}. Unmodifiable.
*/
Set<Operation> operations();
T decode(Object raw, DecodeContext context) throws DecodeException;
Object encode(T value);
/**
* @throws DecodeException if {@code op} is not valid for this type, or the argument does not decode
*/
Object decodeArgument(Operation op, Object raw, DecodeContext context) throws DecodeException;
/**
* @throws IllegalArgumentException if {@code op} is not valid for this type
*/
Object encodeArgument(Operation op, Object argument);
/**
* @throws IllegalArgumentException if {@code op} is not valid for this type
*/
T apply(Operation op, T subject, Object argument);
/**
* @return empty when the type has no composer for {@code op}
*
* @throws NullPointerException if the composer returns {@code null}
*/
Optional<Object> compose(Operation op, Object lower, Object upper);
interface Builder<T> {
/**
* Replaces an earlier {@code op} and drops its composer.
*
* @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE}
*/
<A> Builder<T> op(Operation op, AttributeCodec<A> argumentCodec, AttributeModifier<T, A> modifier);
/**
* {@code combine(lower, upper)} must apply like {@code lower} then {@code upper}. {@code A} must be the argument type
* {@code op} was added with.
*
* @throws IllegalArgumentException if {@code op} is {@link Operation#OVERRIDE} or was not added first
*/
<A> Builder<T> composable(Operation op, BinaryOperator<A> combine);
AttributeType<T> build();
}
}
@@ -0,0 +1,68 @@
package com.dfsek.terra.api.world.attribute;
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.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public interface AttributeTypes {
/**
* {@code and}, {@code nand}, {@code or}, {@code nor}, {@code xor}, {@code xnor}.
*/
AttributeType<Boolean> booleanType();
/**
* Override only.
*/
AttributeType<TriState> triState();
/**
* {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}.
*/
AttributeType<Float> floatType();
/**
* The {@link #floatType()} library.
*/
AttributeType<Float> angleDegrees();
/**
* {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}.
*/
AttributeType<Color> rgbColor();
/**
* {@code alpha_blend}, {@code add}, {@code subtract}, {@code multiply}, {@code blend_to_gray}.
*/
AttributeType<Color> argbColor();
/**
* {@code add}, {@code subtract}, {@code multiply}, {@code minimum}, {@code maximum}.
*/
AttributeType<Integer> integer();
/**
* Override only.
*/
AttributeType<Integer> integerOverrideOnly();
/**
* Any ID; a bare ID takes {@code defaultNamespace}. Tags are rejected. Override only.
*/
AttributeType<RegistryKey> identifier(String defaultNamespace);
/**
* An ID or a {@code #tag}; a bare ID takes {@code defaultNamespace}. Override only.
*/
AttributeType<Either<RegistryKey, TagKey>> identifierOrTag(String defaultNamespace);
/**
* An enum identified by its {@link StringIdentifiable#getID() ID}. Override only.
*
* @param type its constants' IDs must be distinct
*/
<E extends Enum<E> & StringIdentifiable> AttributeType<E> enumType(String id, Class<E> type);
}
@@ -0,0 +1,17 @@
package com.dfsek.terra.api.world.attribute;
import java.lang.reflect.Type;
public interface DecodeContext {
/**
* {@code type} is {@code Float}, {@code Integer}, {@code Double}, {@code Boolean}, {@code String}, {@code List<Object>},
* {@code Map<String, Object>} or {@code Object}.
*/
<V> V load(Type type, Object raw) throws DecodeException;
/**
* Call before checking a value's shape. Numeric expressions stay strings; {@link #load} evaluates them.
*/
Object resolve(Object raw) throws DecodeException;
}
@@ -0,0 +1,14 @@
package com.dfsek.terra.api.world.attribute;
/**
* The message is shown to users in config warnings.
*/
public class DecodeException extends Exception {
public DecodeException(String message) {
super(message);
}
public DecodeException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,44 @@
package com.dfsek.terra.api.world.attribute;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum Operation implements StringIdentifiable {
OVERRIDE("override"),
ALPHA_BLEND("alpha_blend"),
ADD("add"),
SUBTRACT("subtract"),
MULTIPLY("multiply"),
BLEND_TO_GRAY("blend_to_gray"),
MINIMUM("minimum"),
MAXIMUM("maximum"),
AND("and"),
NAND("nand"),
OR("or"),
NOR("nor"),
XOR("xor"),
XNOR("xnor"),
APPEND("append"),
OVERLAY("overlay");
private final String id;
Operation(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
/**
* @throws IllegalArgumentException if no operation has this {@link #getID() ID}
*/
public static Operation parse(String name) {
for(Operation value : values()) {
if(value.id.equals(name)) return value;
}
throw new IllegalArgumentException("unknown modifier \"" + name + "\"");
}
}
@@ -0,0 +1,64 @@
package com.dfsek.terra.api.world.attribute;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.properties.Properties;
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.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.biome.Biome;
/**
* Reads resolve the static layers only; schedules are not applied.
*/
public interface PackAttributes extends Properties {
@NotNull
AttributeMap entries();
/**
* By config key, in config order. Unmodifiable.
*/
@NotNull
Map<String, RegistryKey> parents();
/**
* In config order.
*/
@NotNull
List<Either<RegistryKey, TagKey>> scheduleRefs();
/**
* By ID, in config order. Unmodifiable.
*/
@NotNull
Map<RegistryKey, AttributeSchedule> scheduleDefinitions();
/**
* {@code null} if the biome is not from this pack. Allocation-free.
*/
@Nullable
<T> AttributeEntry<T> biomeEntryOrNull(@NotNull Attribute<T> attribute, @NotNull Biome biome);
/**
* Merged across the biome's {@code extends} chain. Empty if the biome is not from this pack.
*/
@NotNull
AttributeMap biomeEntries(@NotNull Biome biome);
/**
* Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry,
* {@link AttributeParents#biomeOrNull biome parent}, biome entry.
*/
<T> @Nullable T resolve(@NotNull Attribute<T> attribute, @NotNull Biome biome);
/**
* Layers, bottom first: default, {@link AttributeParents#packOrNull pack parent}, pack entry.
*/
<T> @Nullable T resolvePack(@NotNull Attribute<T> attribute);
}
@@ -0,0 +1,34 @@
package com.dfsek.terra.api.world.attribute;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public record RawValue(Object value) {
public RawValue {
value = copy(value);
}
private static Object copy(Object o) {
if(o == null || o instanceof String || o instanceof Number || o instanceof Boolean) return o;
if(o instanceof List<?> list) {
List<Object> out = new ArrayList<>(list.size());
for(Object e : list) out.add(copy(e));
return Collections.unmodifiableList(out);
}
if(o instanceof Map<?, ?> map) {
Map<String, Object> out = new LinkedHashMap<>();
for(Map.Entry<?, ?> e : map.entrySet()) {
if(!(e.getKey() instanceof String key)) {
throw new IllegalArgumentException("unsupported value: map keys must be strings");
}
out.put(key, copy(e.getValue()));
}
return Collections.unmodifiableMap(out);
}
throw new IllegalArgumentException("unsupported value");
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.api.world.attribute.schedule;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.OptionalInt;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.Attribute;
/**
* Both maps are unmodifiable copies in the given order.
*/
public record AttributeSchedule(RegistryKey clock, OptionalInt periodTicks, Map<Attribute<?>, ScheduleTrack<?>> tracks,
Map<RegistryKey, TimeMarker> timeMarkers) {
public AttributeSchedule {
tracks = Collections.unmodifiableMap(new LinkedHashMap<>(tracks));
timeMarkers = Collections.unmodifiableMap(new LinkedHashMap<>(timeMarkers));
}
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.api.world.attribute.schedule;
import java.util.Set;
public sealed interface Easing {
Set<String> NAMES = Set.of(
"constant", "linear",
"in_back", "in_bounce", "in_circ", "in_cubic", "in_elastic", "in_expo", "in_quad", "in_quart", "in_quint", "in_sine",
"in_out_back", "in_out_bounce", "in_out_circ", "in_out_cubic", "in_out_elastic", "in_out_expo", "in_out_quad",
"in_out_quart", "in_out_quint", "in_out_sine",
"out_back", "out_bounce", "out_circ", "out_cubic", "out_elastic", "out_expo", "out_quad", "out_quart", "out_quint",
"out_sine");
record Named(String name) implements Easing {
public Named {
if(!NAMES.contains(name)) throw new IllegalArgumentException("unknown easing \"" + name + "\"");
}
}
record CubicBezier(float x1, float y1, float x2, float y2) implements Easing {
public CubicBezier {
if(!(x1 >= 0f && x1 <= 1f)) throw new IllegalArgumentException("cubic_bezier x1 is outside [0, 1]");
if(!(x2 >= 0f && x2 <= 1f)) throw new IllegalArgumentException("cubic_bezier x2 is outside [0, 1]");
}
}
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.api.world.attribute.schedule;
/**
* {@code argument} comes from {@link com.dfsek.terra.api.world.attribute.AttributeType#decodeArgument}.
*/
public record Keyframe(int ticks, Object argument) { }
@@ -0,0 +1,20 @@
package com.dfsek.terra.api.world.attribute.schedule;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public record ScheduleDecodeResult(Optional<AttributeSchedule> schedule, List<Problem> droppedTracks, Optional<Problem> skipped) {
public ScheduleDecodeResult {
Objects.requireNonNull(schedule, "schedule");
droppedTracks = List.copyOf(droppedTracks);
Objects.requireNonNull(skipped, "skipped");
if(schedule.isPresent() == skipped.isPresent()) {
throw new IllegalArgumentException("exactly one of schedule and skipped must be present");
}
}
public record Problem(String key, String reason) { }
}
@@ -0,0 +1,12 @@
package com.dfsek.terra.api.world.attribute.schedule;
import java.util.List;
import com.dfsek.terra.api.world.attribute.Operation;
public record ScheduleTrack<T>(Operation operation, List<Keyframe> keyframes, Easing ease) {
public ScheduleTrack {
keyframes = List.copyOf(keyframes);
}
}
@@ -0,0 +1,3 @@
package com.dfsek.terra.api.world.attribute.schedule;
public record TimeMarker(int ticks, boolean showInCommands) { }
@@ -0,0 +1,6 @@
package com.dfsek.terra.api.world.attribute.value;
/**
* Both in [0, 1].
*/
public record BlendToGray(float brightness, float factor) { }
@@ -0,0 +1,97 @@
package com.dfsek.terra.api.world.attribute.value;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.regex.Pattern;
/**
* Channels are in [0, 1].
*/
public record Color(float r, float g, float b, float a) {
private static final Pattern HEX6 = Pattern.compile("#[0-9a-fA-F]{6}");
private static final Pattern HEX8 = Pattern.compile("#[0-9a-fA-F]{8}");
public static Color rgb(int rgb) {
return new Color(((rgb >> 16) & 0xFF) / 255f, ((rgb >> 8) & 0xFF) / 255f, (rgb & 0xFF) / 255f, 1f);
}
public static Color argb(int argb) {
return new Color(((argb >> 16) & 0xFF) / 255f, ((argb >> 8) & 0xFF) / 255f, (argb & 0xFF) / 255f, ((argb >>> 24) & 0xFF) / 255f);
}
/**
* Accepts {@code "#rrggbb"}, a list of 3 floats, or an integer {@code 0xRRGGBB} (alpha bits ignored).
*/
public static Color parseRgb(Object o) {
if(o instanceof String s) {
if(!HEX6.matcher(s).matches()) throw new IllegalArgumentException("invalid RGB color (expected #rrggbb): \"" + s + "\"");
return rgb(Integer.parseInt(s.substring(1), 16));
}
if(o instanceof List<?> l) {
if(l.size() != 3) throw new IllegalArgumentException("color list must have 3 elements, got " + l);
return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), 1f);
}
if(o instanceof Number n) return rgb(integral(n, Integer.MAX_VALUE));
throw new IllegalArgumentException("invalid RGB color: " + o);
}
/**
* Accepts {@code "#aarrggbb"}, a list of 4 floats (r, g, b, a), or an integer {@code 0xAARRGGBB}, signed or unsigned.
*/
public static Color parseArgb(Object o) {
if(o instanceof String s) {
if(!HEX8.matcher(s).matches()) throw new IllegalArgumentException("invalid ARGB color (expected #aarrggbb): \"" + s + "\"");
return argb((int) Long.parseLong(s.substring(1), 16));
}
if(o instanceof List<?> l) {
if(l.size() != 4) throw new IllegalArgumentException("color list must have 4 elements, got " + l);
return new Color(channel(l.get(0)), channel(l.get(1)), channel(l.get(2)), channel(l.get(3)));
}
if(o instanceof Number n) return argb(integral(n, 0xFFFFFFFFL));
throw new IllegalArgumentException("invalid ARGB color: " + o);
}
private static int integral(Number n, long max) {
BigInteger value;
try {
value = exact(n).toBigIntegerExact();
} catch(ArithmeticException | NumberFormatException e) {
throw new IllegalArgumentException("color integer must be integral: " + n);
}
if(value.compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || value.compareTo(BigInteger.valueOf(max)) > 0) {
throw new IllegalArgumentException("value " + n + " is outside [" + Integer.MIN_VALUE + ", " + max + "]");
}
return value.intValue();
}
private static BigDecimal exact(Number n) {
if(n instanceof Integer || n instanceof Long || n instanceof Short || n instanceof Byte) return BigDecimal.valueOf(n.longValue());
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 float channel(Object o) {
if(o instanceof Number n) return n.floatValue();
throw new IllegalArgumentException("color channel must be a number: " + o);
}
private static int to255(float c) {
return Math.max(0, Math.min(255, Math.round(c * 255)));
}
public int toRgbInt() {
return (to255(r) << 16) | (to255(g) << 8) | to255(b);
}
public int toArgbInt() {
return (to255(a) << 24) | toRgbInt();
}
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.api.world.attribute.value;
/**
* {@code alpha} is in [0, 1].
*/
public record FloatWithAlpha(float value, float alpha) { }
@@ -0,0 +1,21 @@
package com.dfsek.terra.api.world.attribute.value;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum TriState implements StringIdentifiable {
TRUE("true"),
FALSE("false"),
DEFAULT("default");
private final String id;
TriState(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,113 @@
package com.dfsek.terra.api.registry.key;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class RegistryKeyTest {
@ParameterizedTest
@CsvSource({
"mypack:visual/fog_color, mypack, visual/fog_color",
"mypack:ambient.cave, mypack, ambient.cave",
"my.pack:thing, my.pack, thing",
"terra:overworld_biome-1, terra, overworld_biome-1",
"MyPack:Seasons, MyPack, Seasons",
})
void validKeysParse(String key, String namespace, String id) {
RegistryKey parsed = RegistryKey.parse(key);
assertEquals(RegistryKey.of(namespace, id), parsed);
assertEquals(namespace, parsed.getNamespace());
assertEquals(id, parsed.getID());
assertEquals(key, parsed.toString());
assertEquals(parsed, RegistryKey.parse(key, "other"));
assertEquals(parsed, RegistryKey.parseNamespaced(key));
}
@ParameterizedTest
@ValueSource(strings = { "a/b:thing", "bad key", "a:b:c", "a:b c", "a b:c" })
void invalidKeysAreRejected(String key) {
assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key));
}
@Test
void invalidCharacterMessage() {
String id = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a", "b c")).getMessage();
assertTrue(id.contains("slashes") && id.contains("periods") && id.contains("\"b c\""), id);
String ns = assertThrows(IllegalArgumentException.class, () -> RegistryKey.of("a b", "c")).getMessage();
assertTrue(ns.contains("periods") && !ns.contains("slashes") && ns.contains("\"a b\""), ns);
}
@Test
void hashAndEquals() {
RegistryKey key = RegistryKey.parse("mypack:visual/fog_color");
RegistryKey same = RegistryKey.of("mypack", "visual/fog_color");
assertEquals(Objects.hash("mypack", "visual/fog_color"), key.hashCode());
assertEquals(key, same);
assertEquals(key.hashCode(), same.hashCode());
assertNotEquals(key, RegistryKey.of("mypack", "visual/sky_color"));
assertNotEquals(key, RegistryKey.of("terra", "visual/fog_color"));
assertNotEquals(RegistryKey.of("a", "bc"), RegistryKey.of("ab", "c"));
assertNotEquals(key, "mypack:visual/fog_color");
}
@Test
void parseWithDefaultNamespace() {
assertEquals(RegistryKey.of("mypack", "fog"), RegistryKey.parse("fog", "mypack"));
assertEquals(RegistryKey.of("my.pack", "a/b"), RegistryKey.parse("my.pack:a/b", "mypack"));
}
@ParameterizedTest
@CsvSource(nullValues = "NULL", value = {
":x, mypack, 'malformed ID \":x\": empty namespace'",
"x:, mypack, 'malformed ID \"x:\": empty ID'",
"'', mypack, 'malformed ID \"\": empty ID'",
"NULL, mypack, 'malformed ID: none given'",
"x, NULL, 'malformed ID \"x\": empty namespace'",
"a:b:c, mypack, 'malformed ID \"a:b:c\": more than one '':'''",
})
void parseWithDefaultNamespaceRejects(String key, String defaultNamespace, String message) {
assertEquals(message, assertThrows(IllegalArgumentException.class, () -> RegistryKey.parse(key, defaultNamespace)).getMessage());
}
@Test
void parseNamespacedWithoutNamespace() {
assertEquals("a namespace is required, as in \"namespace:overworld\"",
assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced("overworld")).getMessage());
}
@ParameterizedTest
@NullSource
@ValueSource(strings = { "mypack:Bad Id", "#mypack:tag", "mypack:", ":overworld", "a:b:c" })
void parseNamespacedRejects(String key) {
assertThrows(IllegalArgumentException.class, () -> RegistryKey.parseNamespaced(key));
}
@Test
void tagKey() {
TagKey tag = TagKey.parse("#mypack:infiniburn");
assertEquals(RegistryKey.parse("mypack:infiniburn"), tag.key());
assertEquals("#mypack:infiniburn", tag.toString());
assertEquals(tag, TagKey.parse("#infiniburn", "mypack"));
assertEquals(tag, TagKey.of(RegistryKey.parse("mypack:infiniburn")));
assertEquals(RegistryKey.of("mypack", "Music.Game"), TagKey.parse("#mypack:Music.Game").key());
assertEquals(RegistryKey.of("MyPack", "Logs"), TagKey.parse("#Logs", "MyPack").key());
assertEquals("invalid tag \"#stone\": a namespace is required, as in \"#namespace:stone\"",
assertThrows(IllegalArgumentException.class, () -> TagKey.parse("#stone")).getMessage());
}
@ParameterizedTest
@ValueSource(strings = { "mypack:stone", "#mypack:", "#mypack:bad id" })
void tagKeyRejects(String tag) {
assertThrows(IllegalArgumentException.class, () -> TagKey.parse(tag));
}
}
@@ -0,0 +1,72 @@
package com.dfsek.terra.api.world.attribute;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
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 AttributeMapTest {
private static final AttributeKey<Integer> A = AttributeKey.parse("test:a");
private static final AttributeKey<Integer> B = AttributeKey.parse("test:b");
@Test
void emptyIsShared() {
assertSame(AttributeMap.empty(), AttributeMap.builder().build());
assertSame(AttributeMap.empty(), AttributeMap.builder().put(A, AttributeEntry.override(1)).remove(A).build());
assertTrue(AttributeMap.empty().get(A).isEmpty());
}
@Test
void overlayReplacesPerKey() {
AttributeEntry<Integer> bottomA = AttributeEntry.override(1);
AttributeMap bottom = AttributeMap.builder().put(A, bottomA).put(B, AttributeEntry.override(2)).build();
AttributeMap top = AttributeMap.builder().put(B, AttributeEntry.override(3)).build();
AttributeMap merged = bottom.overlay(top);
assertEquals(List.of(A, B), List.copyOf(merged.keys()));
assertSame(bottomA, merged.get(A).orElseThrow());
assertEquals(AttributeEntry.override(3), merged.get(B).orElseThrow());
assertEquals(AttributeEntry.override(2), bottom.get(B).orElseThrow());
}
@Test
void builderRemove() {
AttributeMap map = AttributeMap.builder().put(A, AttributeEntry.override(1)).put(B, AttributeEntry.override(2)).remove(A).build();
assertEquals(Set.of(B), map.keys());
assertTrue(map.get(AttributeKey.<Integer>parse("test:b")).isPresent());
assertThrows(UnsupportedOperationException.class, () -> map.keys().clear());
}
@Test
void nullsThrow() {
AttributeMap.Builder builder = AttributeMap.builder();
assertThrows(NullPointerException.class, () -> builder.put(null, AttributeEntry.override(1)));
assertThrows(NullPointerException.class, () -> builder.put(A, null));
assertEquals("top", assertThrows(NullPointerException.class, () -> AttributeMap.empty().overlay(null)).getMessage());
}
@Test
void nullArgument() {
assertNull(AttributeEntry.override(null).argument());
assertNull(AttributeEntry.of(Operation.OVERRIDE, null).argument());
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> AttributeEntry.of(Operation.ADD, null));
assertEquals("modifier add needs an argument", e.getMessage());
assertThrows(IllegalArgumentException.class, () -> new AttributeEntry<Integer>(Operation.MULTIPLY, null));
}
@Test
void equalByContent() {
AttributeMap one = AttributeMap.builder().put(A, AttributeEntry.override(1)).build();
AttributeMap two = AttributeMap.builder().put(A, AttributeEntry.override(1)).build();
assertEquals(one, two);
assertEquals(one.hashCode(), two.hashCode());
assertNotEquals(one, AttributeMap.builder().put(A, AttributeEntry.override(2)).build());
}
}
@@ -0,0 +1,132 @@
package com.dfsek.terra.api.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 org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.schedule.Easing;
import com.dfsek.terra.api.world.attribute.value.Color;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.params.provider.Arguments.arguments;
public class ValueTypesTest {
@Test
public void attributeKey() {
RegistryKey registryKey = RegistryKey.parse("my.pack:visual/Fog_Color");
AttributeKey<Float> key = AttributeKey.parse("my.pack:visual/Fog_Color");
assertEquals(registryKey, key.getRegistryKey());
assertEquals("my.pack:visual/Fog_Color", key.toString());
AttributeKey<Float> wrapped = AttributeKey.of(registryKey);
assertSame(registryKey, wrapped.getRegistryKey());
assertEquals(wrapped, key);
assertEquals(registryKey.hashCode(), key.hashCode());
assertNotEquals(key, AttributeKey.parse("my.pack:visual/other"));
assertEquals("invalid attribute key \"visual/fog_color\": a namespace is required, as in \"namespace:visual/fog_color\"",
assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse("visual/fog_color")).getMessage());
}
@ParameterizedTest
@NullSource
@ValueSource(strings = { "Bad Key", "mypack:", ":visual/fog_color", "a:b:c" })
public void attributeKeyRejects(String key) {
assertThrows(IllegalArgumentException.class, () -> AttributeKey.parse(key));
}
@Test
public void parseFailureMessages() {
assertEquals("unknown modifier \"frobnicate\"",
assertThrows(IllegalArgumentException.class, () -> Operation.parse("frobnicate")).getMessage());
assertEquals("unknown easing \"x\"",
assertThrows(IllegalArgumentException.class, () -> new Easing.Named("x")).getMessage());
for(Operation op : Operation.values()) assertSame(op, Operation.parse(op.getID()));
}
private static Arguments rgb(Object raw, int expected) {
return arguments(raw, (Function<Object, Color>) Color::parseRgb, Color.rgb(expected));
}
private static Arguments argb(Object raw, int expected) {
return arguments(raw, (Function<Object, Color>) Color::parseArgb, Color.argb(expected));
}
static Stream<Arguments> colors() {
return Stream.of(
rgb("#050533", 0x050533),
arguments(List.of(1.0, 0.5, 0.0), (Function<Object, Color>) Color::parseRgb, new Color(1f, 0.5f, 0f, 1f)),
rgb(16777215, 0xFFFFFF),
rgb(16777215L, 0xFFFFFF),
rgb(1.6777215E7, 0xFFFFFF),
rgb(BigInteger.valueOf(0x102030), 0x102030),
rgb(new BigDecimal("1056816.0"), 0x102030),
rgb(0xFF102030, 0x102030),
argb("#80ff0000", 0x80FF0000),
argb(0xFF102030L, 0xFF102030),
argb(0xFF102030, 0xFF102030),
argb(BigInteger.valueOf(0xFFFFFFFFL), 0xFFFFFFFF));
}
@ParameterizedTest
@MethodSource
public void colors(Object raw, Function<Object, Color> parser, Color expected) {
assertEquals(expected, parser.apply(raw));
}
private static Arguments rejectRgb(Object raw, String message) {
return arguments(raw, (Function<Object, Color>) Color::parseRgb, message);
}
private static Arguments rejectArgb(Object raw, String message) {
return arguments(raw, (Function<Object, Color>) Color::parseArgb, message);
}
static Stream<Arguments> colorsRejected() {
return Stream.of(
rejectRgb("#12345", null),
rejectRgb(0.5, null),
rejectArgb(0.5, null),
rejectRgb(new BigDecimal("1.5"), "color integer must be integral: 1.5"),
rejectArgb(new BigDecimal("1.5"), null),
rejectRgb(Double.NaN, null),
rejectRgb(Double.POSITIVE_INFINITY, null),
rejectRgb(0xFFFFFFFFL, "value 4294967295 is outside [-2147483648, 2147483647]"),
rejectRgb(new BigInteger("100000000000"), null),
rejectArgb(0x100000000L, "value 4294967296 is outside [-2147483648, 4294967295]"),
rejectArgb(-2147483649L, null));
}
@ParameterizedTest
@MethodSource
public void colorsRejected(Object raw, Function<Object, Color> parser, String message) {
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> parser.apply(raw));
if(message != null) assertEquals(message, e.getMessage());
}
@Test
public void rawValueDeepCopy() {
Map<String, Object> inner = new HashMap<>();
inner.put("a", 1);
Map<String, Object> map = new HashMap<>();
map.put("inner", inner);
RawValue raw = new RawValue(map);
map.put("b", 2);
inner.put("c", 3);
@SuppressWarnings("unchecked")
Map<String, Object> copy = (Map<String, Object>) raw.value();
assertEquals(1, copy.size());
assertEquals(Map.of("a", 1), copy.get("inner"));
}
}
@@ -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;
@@ -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);
}
@@ -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);
@@ -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));
}
}
@@ -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();
});
@@ -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();
}
}
@@ -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);
}
}
@@ -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());
}
}
}
@@ -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());
}
}
@@ -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);
}
}
}
@@ -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());
}
}
@@ -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));
}
}
@@ -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());
}
@@ -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);
}
}
@@ -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()));
};
}
}
@@ -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));
}
}
@@ -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));
}
}
@@ -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());
}
}
@@ -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());
}
}
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more