feat: build Fabric biomes, dimensions and timelines from environment attributes

This commit is contained in:
Zoe Gidiere committed 2026-11-09 16:34:50 -07:00
1 parent 4e37c361ea
commit bebcb775fc
59 files changed
+4773 -1264

No files matched your search

+3
View File
@@ -13,6 +13,9 @@ dependencies {
compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}")
minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}")
// Tests only: the addon ships as its own jar.
testImplementation(project(":common:addons:minecraft-attributes"))
}
architectury {
@@ -23,15 +23,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dfsek.terra.api.addon.BaseAddon;
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.world.biome.Biome;
import com.dfsek.terra.mod.config.PostLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.config.VanillaWorldProperties;
public abstract class MinecraftAddon implements BaseAddon {
@@ -45,12 +41,6 @@ public abstract class MinecraftAddon implements BaseAddon {
@Override
public void initialize() {
modPlatform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigPackPostLoadEvent.class)
.then(event -> event.getPack().getContext().put(event.loadTemplate(new VanillaWorldProperties())))
.priority(100)
.global();
modPlatform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigPackPreLoadEvent.class)
@@ -63,16 +53,6 @@ public abstract class MinecraftAddon implements BaseAddon {
.then(event -> event.getPack().getContext().put(event.loadTemplate(new PostLoadCompatibilityOptions())))
.priority(100)
.global();
modPlatform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
}
@Override
@@ -6,20 +6,8 @@ import com.dfsek.tectonic.api.exception.LoadException;
import net.minecraft.core.Registry;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import net.minecraft.world.attribute.AmbientMoodSettings;
import net.minecraft.world.attribute.AmbientParticle;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biome.Precipitation;
import net.minecraft.world.level.biome.Biome.TemperatureModifier;
import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
@@ -34,19 +22,10 @@ import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.handle.ItemHandle;
import com.dfsek.terra.api.handle.WorldHandle;
import com.dfsek.terra.api.world.attribute.AttributeParents;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.mod.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.mod.config.BiomeMoodSoundTemplate;
import com.dfsek.terra.mod.config.BiomeParticleConfigTemplate;
import com.dfsek.terra.mod.config.EntityTypeTemplate;
import com.dfsek.terra.mod.config.MusicSoundTemplate;
import com.dfsek.terra.mod.attribute.MinecraftAttributeParents;
import com.dfsek.terra.mod.config.ProtoPlatformBiome;
import com.dfsek.terra.mod.config.SoundEventTemplate;
import com.dfsek.terra.mod.config.SpawnCostConfig;
import com.dfsek.terra.mod.config.SpawnEntryConfig;
import com.dfsek.terra.mod.config.SpawnSettingsTemplate;
import com.dfsek.terra.mod.config.SpawnTypeConfig;
import com.dfsek.terra.mod.config.VillagerTypeTemplate;
import com.dfsek.terra.mod.handle.MinecraftItemHandle;
import com.dfsek.terra.mod.handle.MinecraftWorldHandle;
import com.dfsek.terra.mod.util.PresetUtil;
@@ -55,6 +34,7 @@ import com.dfsek.terra.mod.util.PresetUtil;
public abstract class ModPlatform extends AbstractPlatform {
private final ItemHandle itemHandle = new MinecraftItemHandle();
private final WorldHandle worldHandle = new MinecraftWorldHandle();
private final MinecraftAttributeParents attributeParents = new MinecraftAttributeParents(getAttributeHandle());
public abstract MinecraftServer getServer();
@@ -80,24 +60,7 @@ public abstract class ModPlatform extends AbstractPlatform {
if(identifier == null)
throw new LoadException("Invalid identifier: " + o, depthTracker);
return identifier;
})
.registerLoader(Precipitation.class, (type, o, loader, depthTracker) -> Precipitation.valueOf(((String) o).toUpperCase()))
.registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase()))
.registerLoader(TemperatureModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase()))
.registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o))
.registerLoader(AmbientParticle.class, BiomeParticleConfigTemplate::new)
.registerLoader(SoundEvent.class, SoundEventTemplate::new)
.registerLoader(AmbientMoodSettings.class, BiomeMoodSoundTemplate::new)
.registerLoader(AmbientAdditionsSettings.class, BiomeAdditionsSoundTemplate::new)
.registerLoader(Music.class, MusicSoundTemplate::new)
.registerLoader(EntityType.class, EntityTypeTemplate::new)
.registerLoader(SpawnCostConfig.class, SpawnCostConfig::new)
.registerLoader(SpawnEntryConfig.class, SpawnEntryConfig::new)
.registerLoader(SpawnTypeConfig.class, SpawnTypeConfig::new)
.registerLoader(MobSpawnSettings.class, SpawnSettingsTemplate::new)
.registerLoader(VillagerType.class, VillagerTypeTemplate::new);
});
}
private ProtoPlatformBiome parseBiome(String id, DepthTracker tracker) throws LoadException {
@@ -133,5 +96,14 @@ public abstract class ModPlatform extends AbstractPlatform {
return itemHandle;
}
@Override
public @NotNull AttributeParents getAttributeParents() {
return attributeParents;
}
public MinecraftAttributeParents attributeParents() {
return attributeParents;
}
}
@@ -0,0 +1,68 @@
package com.dfsek.terra.mod.attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import com.dfsek.terra.api.config.ConfigPack;
/**
* Thread safe.
*/
public final class AttributeReport {
private static final Logger LOGGER = LoggerFactory.getLogger(AttributeReport.class);
private static final String NOT_A_MINECRAFT_TAG = "no such tag in the minecraft namespace";
private final String pack;
private final Consumer<String> warn;
private final Consumer<String> debug;
private final Set<String> notApplied = ConcurrentHashMap.newKeySet();
public AttributeReport(String pack, Consumer<String> warn, Consumer<String> debug) {
this.pack = Objects.requireNonNull(pack, "pack");
this.warn = Objects.requireNonNull(warn, "warn");
this.debug = Objects.requireNonNull(debug, "debug");
}
public static AttributeReport logging(ConfigPack pack) {
return logging(pack, LOGGER);
}
public static AttributeReport logging(ConfigPack pack, Logger logger) {
return new AttributeReport(pack.getID(), logger::warn, logger::debug);
}
public void attributeSkipped(String config, String key, String reason) {
warn.accept("Pack \"" + pack + "\", config \"" + config + "\": attribute \"" + key + "\" skipped: " + reason);
}
public void scheduleSkipped(String schedule, String reason) {
warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" skipped: " + reason);
}
public void trackDropped(String schedule, String key, String reason) {
warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" track \"" + key + "\" dropped: " + reason);
}
public void timeMarkerDropped(String schedule, String marker, String clock) {
warn.accept("Pack \"" + pack + "\": schedule \"" + schedule + "\" time marker \"" + marker + "\" dropped: already defined for "
+ "clock \"" + clock + "\"");
}
public void ignored(String config, String key, String reason) {
warn.accept("Pack \"" + pack + "\", config \"" + config + "\": \"" + key + "\" ignored: " + reason);
}
public void tagCreated(String config, String tag) {
warn.accept("Pack \"" + pack + "\", config \"" + config + "\": tag \"" + tag + "\" created: " + NOT_A_MINECRAFT_TAG);
}
public void notApplied(String key) {
if(notApplied.add(key)) debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied on this platform");
}
}
@@ -0,0 +1,36 @@
package com.dfsek.terra.mod.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
/**
* An attribute built after the slots were sized reads as absent.
*/
public final class AttributeSlots {
public static final AttributeSlots EMPTY = new AttributeSlots(new AttributeEntry<?>[0]);
private final AttributeEntry<?>[] entries;
private AttributeSlots(AttributeEntry<?>[] entries) {
this.entries = entries;
}
/**
* Keeps {@code entries} without copying: the caller must not change the array afterwards.
*/
public static AttributeSlots of(AttributeEntry<?>[] entries) {
return new AttributeSlots(Objects.requireNonNull(entries, "entries"));
}
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> get(Attribute<T> attribute) {
int index = attribute.index();
AttributeEntry<?>[] entries = this.entries;
return index < entries.length ? (AttributeEntry<T>) entries[index] : null;
}
}
@@ -0,0 +1,171 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import com.dfsek.terra.api.config.ConfigPack;
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.AttributeParents;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.mod.config.ProtoPlatformBiome;
public final class MinecraftAttributeParents implements AttributeParents {
private static final String PACK_CONFIG = "pack.yml";
private static final String VANILLA = "vanilla";
private static final String VANILLA_GENERATION = "vanilla-generation";
private static final PackParents[] NO_PACKS = new PackParents[0];
private final AttributeHandle handle;
// Replaced, never mutated: a read sees one load's context and packs together.
private volatile State state = new State(null, NO_PACKS, 0);
public MinecraftAttributeParents(AttributeHandle handle) {
this.handle = Objects.requireNonNull(handle, "handle");
}
public synchronized void beginLoad(VanillaContext context) {
state = new State(Objects.requireNonNull(context, "context"), NO_PACKS, 0);
MinecraftTimelines.clear();
}
public synchronized void clearPacks() {
state = new State(state.context(), NO_PACKS, 0);
}
/**
* Old packs keep their parents until {@link #endPackReload}; worlds may still be generating with them.
*/
public synchronized void beginPackReload() {
State current = state;
state = new State(current.context(), current.packs(), current.packs().length);
}
public synchronized void endPackReload() {
State current = state;
state = new State(current.context(), Arrays.copyOfRange(current.packs(), current.reloadedFrom(), current.packs().length), 0);
}
public @Nullable VanillaContext context() {
return state.context();
}
public synchronized PackParents prepare(ConfigPack pack, Optional<PackAttributes> attributes, AttributeReport report) {
State current = state;
VanillaContext context = current.context();
if(context == null) throw new IllegalStateException("no registry load has begun");
PackAttributes packAttributes = attributes.orElse(null);
PackParents[] prepared = current.packs();
for(int i = current.reloadedFrom(); i < prepared.length; i++) {
if(prepared[i].pack() == pack && prepared[i].attributes() == packAttributes) return prepared[i];
}
ResourceKey<DimensionType> dimensionKey = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(),
BuiltinDimensionTypes.OVERWORLD, "dimension type", report);
ResourceKey<NoiseGeneratorSettings> generationKey = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS,
context.noiseSettings(), NoiseGeneratorSettings.OVERWORLD, "noise settings", report);
DimensionType dimension = context.dimensionTypes().getOrThrow(dimensionKey).value();
NoiseGeneratorSettings generation = context.noiseSettings().getOrThrow(generationKey).value();
PackAttributeTable table = PackAttributeTable.of(pack.getRegistry(Attribute.REGISTRY_TYPE));
VanillaParentReader reader = new VanillaParentReader(handle, context);
AttributeSlots dimensionSlots = reader.dimension(dimension, table, parentSkipped(report, dimensionKey.identifier().toString()));
AttributeSlots generationSlots = reader.generation(generation, table);
PackParents parents = new PackParents(pack, dimensionKey, dimension, generationKey, generation, table,
fold(table, dimensionSlots, generationSlots), packAttributes, report, reader);
PackParents[] packs = Arrays.copyOf(prepared, prepared.length + 1);
packs[packs.length - 1] = parents;
state = new State(context, packs, current.reloadedFrom());
return parents;
}
public AttributeSlots biomeEntries(PackParents pack, ResourceKey<Biome> key, Biome biome) {
AttributeSlots cached = pack.biomeEntries().get(key);
if(cached != null) return cached;
// Warn outside the map's bin lock, and only for the read that gets cached.
record Skipped(Attribute<?> attribute, String reason) { }
List<Skipped> skipped = new ArrayList<>(0);
AttributeSlots read = pack.reader().biome(key, biome, pack.table(),
(attribute, reason) -> skipped.add(new Skipped(attribute, reason)));
AttributeSlots raced = pack.biomeEntries().putIfAbsent(key, read);
if(raced != null) return raced;
BiConsumer<Attribute<?>, String> report = parentSkipped(pack.report(), key.identifier().toString());
for(Skipped s : skipped) report.accept(s.attribute(), s.reason());
return read;
}
@Override
public <T> @Nullable AttributeEntry<T> biomeOrNull(com.dfsek.terra.api.world.biome.Biome biome, Attribute<T> attribute) {
return biome.getPlatformBiome() instanceof ProtoPlatformBiome proto ? proto.parentEntries().get(attribute) : null;
}
@Override
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
PackParents[] packs = state.packs();
for(PackParents prepared : packs) {
if(prepared.attributes() == pack) return prepared.packEntries().get(attribute);
}
return null;
}
private static <T> ResourceKey<T> parent(@Nullable PackAttributes attributes, String configKey,
ResourceKey<? extends Registry<T>> registry, HolderGetter<T> getter,
ResourceKey<T> fallback, String what, AttributeReport report) {
RegistryKey id = attributes == null ? null : attributes.parents().get(configKey);
if(id == null) return fallback;
ResourceKey<T> key;
try {
key = ResourceKey.create(registry, VanillaIds.identifier(id));
} catch(IllegalArgumentException e) {
report.ignored(PACK_CONFIG, configKey, e.getMessage());
return fallback;
}
if(getter.get(key).isPresent()) return key;
report.ignored(PACK_CONFIG, configKey, "no such " + what + " \"" + key.identifier() + "\"");
return fallback;
}
private AttributeSlots fold(PackAttributeTable table, AttributeSlots dimension, AttributeSlots generation) {
AttributeEntry<?>[] slots = new AttributeEntry<?>[handle.attributeCount()];
for(PackAttributeTable.Bound bound : table.environment()) fold(bound.attribute(), dimension, generation, slots);
for(PackAttributeTable.Field field : table.dimension()) fold(field.attribute(), dimension, generation, slots);
if(table.seaLevel() != null) fold(table.seaLevel(), dimension, generation, slots);
if(table.mobGeneration() != null) fold(table.mobGeneration(), dimension, generation, slots);
return AttributeSlots.of(slots);
}
private <T> void fold(Attribute<T> attribute, AttributeSlots dimension, AttributeSlots generation, AttributeEntry<?>[] slots) {
AttributeEntry<T> lower = dimension.get(attribute);
AttributeEntry<T> upper = generation.get(attribute);
if(lower == null && upper == null) return;
slots[attribute.index()] = handle.compose(attribute, lower, upper)
.orElseGet(() -> AttributeEntry.override(handle.resolve(attribute, lower, upper, null)));
}
static BiConsumer<Attribute<?>, String> parentSkipped(AttributeReport report, String parent) {
return (attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(),
"vanilla parent \"" + parent + "\": " + reason);
}
// reloadedFrom: the first pack prepared since a pack reload began, or 0 outside one.
private record State(@Nullable VanillaContext context, PackParents[] packs, int reloadedFrom) { }
}
@@ -0,0 +1,164 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import org.jetbrains.annotations.Nullable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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.DecodeException;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.mod.config.ProtoPlatformBiome;
public final class MinecraftBiomeFactory {
private final AttributeHandle handle;
private final VanillaContext context;
private final VanillaAttributeMaps maps;
public MinecraftBiomeFactory(AttributeHandle handle, VanillaContext context) {
this.handle = Objects.requireNonNull(handle, "handle");
this.context = Objects.requireNonNull(context, "context");
this.maps = new VanillaAttributeMaps(handle, context);
}
/**
* {@code terraBiome}'s parent entries must already be set from {@link MinecraftAttributeParents#biomeEntries}.
*/
public Built create(ResourceKey<Biome> parentKey, Biome parent, com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack,
AttributeReport report) {
String config = terraBiome.getID();
PackAttributes attributes = pack.attributes();
PackAttributeTable table = pack.table();
Biome.ClimateSettings climate = parent.climateSettings;
BiomeSpecialEffects effects = parent.getSpecialEffects();
EnvironmentAttributeMap environment = parent.getAttributes();
ResourceKey<VillagerType> villagerType = null;
if(attributes != null) {
climate = fields(Biome.ClimateSettings.CODEC.codec(), climate, table.climate(), attributes, terraBiome, config, report);
effects = fields(BiomeSpecialEffects.CODEC, effects, table.effects(), attributes, terraBiome, config, report);
environment = environment(environment, table, attributes, terraBiome, config, report);
if(table.villagerType() != null) villagerType = villagerType(table.villagerType(), attributes, terraBiome, config, report);
for(Attribute<?> unapplied : table.unapplied()) {
if(attributes.biomeEntryOrNull(unapplied, terraBiome) != null) report.notApplied(unapplied.getRegistryKey().toString());
}
}
if(villagerType == null) villagerType = Objects.requireNonNullElse(context.villagerTypes().apply(parentKey), VillagerType.PLAINS);
Biome biome = new Biome.BiomeBuilder()
.hasPrecipitation(climate.hasPrecipitation())
.temperature(climate.temperature())
.temperatureAdjustment(climate.temperatureModifier())
.downfall(climate.downfall())
.specialEffects(effects)
.putAttributes(environment)
.generationSettings(parent.getGenerationSettings())
.build();
return new Built(biome, villagerType);
}
private <V> V fields(Codec<V> codec, V parent, List<PackAttributeTable.Field> fields, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome terraBiome, String config, AttributeReport report) {
if(fields.isEmpty()) return parent;
Map<?, ?> original = (Map<?, ?>) VanillaCodecs.encode(codec, parent, context.ops());
Map<Object, Object> all = new LinkedHashMap<>(original);
for(PackAttributeTable.Field field : fields) set(all, field, attributes, terraBiome);
// Parsing it again would give colours an opaque alpha.
if(all.equals(original)) return parent;
try {
return VanillaCodecs.parse(codec, all, context.ops());
} catch(DecodeException whole) {
V value = parent;
Map<Object, Object> accepted = new LinkedHashMap<>(original);
for(PackAttributeTable.Field field : fields) {
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
set(trial, field, attributes, terraBiome);
if(trial.equals(accepted)) continue;
try {
value = VanillaCodecs.parse(codec, trial, context.ops());
accepted = trial;
} catch(DecodeException e) {
report.attributeSkipped(config, field.attribute().getRegistryKey().toString(), e.getMessage());
}
}
return value;
}
}
private static void set(Map<Object, Object> fields, PackAttributeTable.Field field, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome terraBiome) {
Object value = resolveEncoded(field.attribute(), attributes, terraBiome);
if(value == null) {
fields.remove(field.name());
} else {
fields.put(field.name(), value);
}
}
private static <T> @Nullable Object resolveEncoded(Attribute<T> attribute, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome biome) {
T value = attributes.resolve(attribute, biome);
return value == null ? null : attribute.type().encode(value);
}
private EnvironmentAttributeMap environment(EnvironmentAttributeMap parent, PackAttributeTable table, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome terraBiome, String config,
AttributeReport report) {
AttributeSlots parentSlots = terraBiome.getPlatformBiome() instanceof ProtoPlatformBiome proto
? proto.parentEntries()
: AttributeSlots.EMPTY;
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
for(PackAttributeTable.Bound bound : table.environment()) {
AttributeEntry<?> entry = entry(bound.attribute(), parentSlots, attributes, terraBiome);
if(entry != null) entries.put(bound.attribute(), entry);
}
if(entries.isEmpty()) return parent;
return maps.toVanilla(parent, entries, true,
(attribute, reason) -> report.attributeSkipped(config, attribute.getRegistryKey().toString(), reason));
}
private <T> @Nullable AttributeEntry<T> entry(Attribute<T> attribute, AttributeSlots parentSlots, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome terraBiome) {
AttributeEntry<T> entry = attributes.biomeEntryOrNull(attribute, terraBiome);
if(entry == null) return null;
return handle.compose(attribute, parentSlots.get(attribute), entry)
.orElseGet(() -> AttributeEntry.override(attributes.resolve(attribute, terraBiome)));
}
private static @Nullable ResourceKey<VillagerType> villagerType(Attribute<?> attribute, PackAttributes attributes,
com.dfsek.terra.api.world.biome.Biome terraBiome, String config,
AttributeReport report) {
Object encoded = resolveEncoded(attribute, attributes, terraBiome);
if(encoded == null) return null;
String key = attribute.getRegistryKey().toString();
Identifier id;
try {
id = VanillaIds.identifier(RegistryKey.parseNamespaced(String.valueOf(encoded)));
} catch(IllegalArgumentException e) {
report.attributeSkipped(config, key, e.getMessage());
return null;
}
ResourceKey<VillagerType> type = ResourceKey.create(Registries.VILLAGER_TYPE, id);
if(BuiltInRegistries.VILLAGER_TYPE.containsKey(type)) return type;
report.attributeSkipped(config, key, "no such villager type \"" + id + "\"");
return null;
}
public record Built(Biome biome, ResourceKey<VillagerType> villagerType) { }
}
@@ -0,0 +1,173 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.tags.TagKey;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.timeline.Timeline;
import org.jetbrains.annotations.Nullable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import com.dfsek.terra.api.util.range.ConstantRange;
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.DecodeException;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.mod.generation.GenerationSettings;
public final class MinecraftDimensionFactory {
private static final String PACK_CONFIG = "pack.yml";
private static final String ATTRIBUTES = "attributes";
private static final String TIMELINES = "timelines";
private static final String SCHEDULES = "schedules";
private static final int DEFAULT_SPAWN_HEIGHT = 64;
private final AttributeHandle handle;
private final VanillaContext context;
private final VanillaAttributeMaps maps;
public MinecraftDimensionFactory(AttributeHandle handle, VanillaContext context) {
this.handle = Objects.requireNonNull(handle, "handle");
this.context = Objects.requireNonNull(context, "context");
this.maps = new VanillaAttributeMaps(handle, context);
}
public DimensionType create(PackParents pack, @Nullable TagKey<Timeline> timelines) {
DimensionType parent = pack.dimension();
PackAttributes attributes = pack.attributes();
PackAttributeTable table = pack.table();
AttributeReport report = pack.report();
Map<?, ?> original = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, parent, context.ops());
Map<Object, Object> all = new LinkedHashMap<>(original);
if(attributes != null) {
for(PackAttributeTable.Field field : table.dimension()) set(all, field, attributes);
all.put(ATTRIBUTES, environment(parent.attributes(), pack, attributes, report));
for(Attribute<?> unapplied : table.unapplied()) {
if(attributes.entries().get(unapplied.key()).isPresent()) report.notApplied(unapplied.getRegistryKey().toString());
}
}
if(timelines != null) all.put(TIMELINES, "#" + timelines.location());
if(all.equals(original)) return copy(parent);
DimensionType built;
try {
built = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, all, context.ops());
} catch(DecodeException whole) {
built = fieldByField(parent, original, all, table.dimension(), attributes, timelines, report);
}
// Terra may encode a field in another number type, e.g. coordinate_scale as a float.
return original.equals(VanillaCodecs.encode(DimensionType.DIRECT_CODEC, built, context.ops())) ? copy(parent) : built;
}
// A registry refuses the same value under a second key.
private static DimensionType copy(DimensionType parent) {
return new DimensionType(parent.hasFixedTime(), parent.hasSkyLight(), parent.hasCeiling(), parent.hasEnderDragonFight(),
parent.coordinateScale(), parent.minY(), parent.height(), parent.logicalHeight(), parent.infiniburn(), parent.ambientLight(),
parent.monsterSettings(), parent.skybox(), parent.cardinalLightType(), parent.attributes(), parent.timelines(),
parent.defaultClock());
}
private DimensionType fieldByField(DimensionType parent, Map<?, ?> original, Map<Object, Object> all,
List<PackAttributeTable.Field> fields, @Nullable PackAttributes attributes,
@Nullable TagKey<Timeline> timelines, AttributeReport report) {
DimensionType value = parent;
Map<Object, Object> accepted = new LinkedHashMap<>(original);
if(all.containsKey(ATTRIBUTES)) {
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
trial.put(ATTRIBUTES, all.get(ATTRIBUTES));
try {
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
accepted = trial;
} catch(DecodeException e) {
report.ignored(PACK_CONFIG, ATTRIBUTES, e.getMessage());
}
}
if(attributes != null) {
for(PackAttributeTable.Field field : fields) {
if(attributes.entries().get(field.attribute().key()).isEmpty()) continue;
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
set(trial, field, attributes);
if(trial.equals(accepted)) continue;
try {
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
accepted = trial;
} catch(DecodeException e) {
report.attributeSkipped(PACK_CONFIG, field.attribute().getRegistryKey().toString(), e.getMessage());
}
}
}
if(timelines != null) {
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
trial.put(TIMELINES, all.get(TIMELINES));
try {
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
} catch(DecodeException e) {
report.ignored(PACK_CONFIG, SCHEDULES, e.getMessage());
}
}
return value;
}
private static void set(Map<Object, Object> fields, PackAttributeTable.Field field, PackAttributes attributes) {
Object value = resolveEncoded(field.attribute(), attributes);
if(value == null) {
fields.remove(field.name());
} else {
fields.put(field.name(), value);
}
}
private static <T> @Nullable Object resolveEncoded(Attribute<T> attribute, PackAttributes attributes) {
T value = attributes.resolvePack(attribute);
return value == null ? null : attribute.type().encode(value);
}
private Object environment(EnvironmentAttributeMap parent, PackParents pack, PackAttributes attributes, AttributeReport report) {
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
for(PackAttributeTable.Bound bound : pack.table().environment()) {
AttributeEntry<?> entry = entry(bound.attribute(), pack.packEntries(), attributes);
if(entry != null) entries.put(bound.attribute(), entry);
}
EnvironmentAttributeMap map = entries.isEmpty() ? parent : maps.toVanilla(parent, entries, false,
(attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(), reason));
return VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops());
}
private <T> @Nullable AttributeEntry<T> entry(Attribute<T> attribute, AttributeSlots packEntries, PackAttributes attributes) {
Optional<AttributeEntry<T>> entry = attributes.entries().get(attribute.key());
if(entry.isEmpty()) return null;
return handle.compose(attribute, packEntries.get(attribute), entry.get())
.orElseGet(() -> AttributeEntry.override(attributes.resolvePack(attribute)));
}
@SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry
public GenerationSettings generationSettings(PackParents pack, DimensionType dimension) {
PackAttributes attributes = pack.attributes();
PackAttributeTable table = pack.table();
int minY = dimension.minY();
int height = dimension.height();
int seaLevel = pack.generation().seaLevel();
boolean mobGeneration = !pack.generation().disableMobGeneration();
int spawnHeight = DEFAULT_SPAWN_HEIGHT;
if(attributes != null) {
seaLevel = intValue(table.seaLevel(), attributes, seaLevel);
spawnHeight = intValue(table.spawnHeight(), attributes, spawnHeight);
if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), attributes) instanceof Boolean value) {
mobGeneration = value;
}
}
return new GenerationSettings(new ConstantRange(minY, minY + height), seaLevel, mobGeneration, spawnHeight);
}
private static int intValue(@Nullable Attribute<?> attribute, PackAttributes attributes, int fallback) {
if(attribute == null) return fallback;
return resolveEncoded(attribute, attributes) instanceof Number value ? value.intValue() : fallback;
}
}
@@ -0,0 +1,270 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.datafixers.util.Either;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.world.clock.WorldClock;
import net.minecraft.world.timeline.Timeline;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
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.config.ConfigPack;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
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.ScheduleTrack;
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
public final class MinecraftTimelines {
private static final Logger LOGGER = LoggerFactory.getLogger(MinecraftTimelines.class);
private static final String TERRA = "terra";
private static final String EXISTS = "a timeline with this ID already exists";
private static final String NO_TIMELINE = "no such timeline";
private static final String NO_TAG = "no such timeline tag";
private static final String PACK_CONFIG = "pack.yml";
private static final String SCHEDULES = "schedules";
private static final String NO_VALID_SCHEDULE = "no valid schedule; the parent's timelines are kept";
private static final Map<TagKey<Timeline>, Pending> PENDING = new LinkedHashMap<>();
// Holders stay unbound until the registry freezes.
private static final Map<Holder.Reference<Timeline>, Timeline> REGISTERED = new IdentityHashMap<>();
private MinecraftTimelines() { }
public static @Nullable Timeline create(RegistryKey id, AttributeSchedule schedule, PackAttributeTable table, AttributeHandle handle,
VanillaContext context, AttributeReport report) {
String name = id.toString();
ResourceKey<WorldClock> clock;
try {
VanillaIds.identifier(id);
clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock()));
for(RegistryKey marker : schedule.timeMarkers().keySet()) VanillaIds.identifier(marker);
} catch(IllegalArgumentException e) {
report.scheduleSkipped(name, e.getMessage());
return null;
}
Optional<HolderGetter<WorldClock>> clocks = context.ops().getter(Registries.WORLD_CLOCK);
if(clocks.isEmpty() || clocks.get().get(clock).isEmpty()) {
report.scheduleSkipped(name, "no such clock \"" + clock.identifier() + "\"");
return null;
}
try {
return VanillaCodecs.parse(Timeline.DIRECT_CODEC, handle.encodeSchedule(vanillaTracks(schedule, table, report)),
context.ops());
} catch(DecodeException | IllegalArgumentException e) {
report.scheduleSkipped(name, e.getMessage());
return null;
}
}
private static AttributeSchedule vanillaTracks(AttributeSchedule schedule, PackAttributeTable table, AttributeReport report) {
Set<Attribute<?>> vanilla = new HashSet<>();
for(PackAttributeTable.Bound bound : table.environment()) vanilla.add(bound.attribute());
Map<Attribute<?>, ScheduleTrack<?>> tracks = new LinkedHashMap<>();
schedule.tracks().forEach((attribute, track) -> {
if(vanilla.contains(attribute)) {
tracks.put(attribute, track);
} else {
report.notApplied(attribute.getRegistryKey().toString());
}
});
if(tracks.size() == schedule.tracks().size()) return schedule;
return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), tracks, schedule.timeMarkers());
}
public static void register(ConfigPack pack, PackParents parents, WritableRegistry<Timeline> timelines, AttributeHandle handle,
VanillaContext context) {
PackAttributes attributes = parents.attributes();
if(attributes == null) return;
AttributeReport report = parents.report();
for(Map.Entry<RegistryKey, AttributeSchedule> entry : attributes.scheduleDefinitions().entrySet()) {
RegistryKey id = entry.getKey();
Identifier location;
try {
location = VanillaIds.identifier(id);
} catch(IllegalArgumentException e) {
report.scheduleSkipped(id.toString(), e.getMessage());
continue;
}
if(timelines.containsKey(location)) {
report.scheduleSkipped(id.toString(), EXISTS);
continue;
}
AttributeSchedule schedule = withoutClashingMarkers(id.toString(), entry.getValue(), timelines, report);
Timeline timeline = create(id, schedule, parents.table(), handle, context, report);
if(timeline == null) continue;
Holder.Reference<Timeline> holder = timelines.register(ResourceKey.create(Registries.TIMELINE, location), timeline,
RegistrationInfo.BUILT_IN);
synchronized(REGISTERED) {
REGISTERED.put(holder, timeline);
}
LOGGER.debug("Registered timeline {} from pack {}", location, pack.getID());
}
}
// Vanilla fails the whole load on a time marker its clock already has.
private static AttributeSchedule withoutClashingMarkers(String name, AttributeSchedule schedule, Registry<Timeline> timelines,
AttributeReport report) {
if(schedule.timeMarkers().isEmpty()) return schedule;
ResourceKey<WorldClock> clock;
try {
clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock()));
} catch(IllegalArgumentException e) {
return schedule;
}
Set<Identifier> defined = markersOn(clock, timelines);
Map<RegistryKey, TimeMarker> kept = new LinkedHashMap<>();
schedule.timeMarkers().forEach((id, marker) -> {
Identifier location;
try {
location = VanillaIds.identifier(id);
} catch(IllegalArgumentException e) {
kept.put(id, marker);
return;
}
if(defined.contains(location)) {
report.timeMarkerDropped(name, id.toString(), clock.identifier().toString());
} else {
kept.put(id, marker);
}
});
if(kept.size() == schedule.timeMarkers().size()) return schedule;
return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), schedule.tracks(), kept);
}
private static Set<Identifier> markersOn(ResourceKey<WorldClock> clock, Registry<Timeline> timelines) {
Set<Identifier> markers = new HashSet<>();
Optional<ResourceKey<WorldClock>> wanted = Optional.of(clock);
for(Holder.Reference<Timeline> holder : timelines.listElements().toList()) {
Timeline other;
if(holder.isBound()) {
other = holder.value();
} else {
synchronized(REGISTERED) {
other = REGISTERED.get(holder);
}
}
if(other != null && other.clock().unwrapKey().equals(wanted)) {
other.registerTimeMarkers((key, marker) -> markers.add(key.identifier()));
}
}
return markers;
}
public static @Nullable TagKey<Timeline> tagFor(ConfigPack pack, PackParents parents) {
PackAttributes attributes = parents.attributes();
if(attributes == null || attributes.scheduleRefs().isEmpty()) return null;
AttributeReport report = parents.report();
List<Either<Identifier, TagKey<Timeline>>> refs = new ArrayList<>();
for(com.dfsek.terra.api.util.generic.either.Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> ref
: attributes.scheduleRefs()) {
Optional<RegistryKey> id = ref.getLeft();
Optional<com.dfsek.terra.api.registry.key.TagKey> tag = ref.getRight();
try {
if(id.isPresent()) {
refs.add(Either.left(VanillaIds.identifier(id.get())));
} else if(tag.isPresent()) {
refs.add(Either.right(TagKey.create(Registries.TIMELINE, VanillaIds.identifier(tag.get().key()))));
}
} catch(IllegalArgumentException e) {
report.scheduleSkipped(id.map(Object::toString).orElseGet(() -> String.valueOf(tag.orElse(null))), e.getMessage());
}
}
TagKey<Timeline> key = TagKey.create(Registries.TIMELINE,
Identifier.fromNamespaceAndPath(TERRA, pack.getID().toLowerCase(Locale.ROOT)));
synchronized(PENDING) {
PENDING.put(key, new Pending(report, refs, parents.dimension().timelines()));
}
return key;
}
/**
* Vanilla won't freeze a registry with an unbound tag.
*/
public static void bindPendingTags(WritableRegistry<Timeline> timelines) {
HolderGetter<Timeline> registration = timelines.createRegistrationLookup();
Map<TagKey<Timeline>, List<Holder<Timeline>>> unbound = new HashMap<>();
synchronized(PENDING) {
for(TagKey<Timeline> key : PENDING.keySet()) {
if(!registration.getOrThrow(key).isBound()) unbound.put(key, List.of());
}
}
timelines.bindTags(unbound);
}
public static void fillTags(Map<TagKey<Timeline>, List<Holder<Timeline>>> collect, Registry<Timeline> registry) {
synchronized(PENDING) {
PENDING.forEach((key, pending) -> {
Set<Holder<Timeline>> contents = new LinkedHashSet<>();
for(Either<Identifier, TagKey<Timeline>> ref : pending.refs()) {
ref.ifLeft(id -> registry.get(id).ifPresentOrElse(contents::add,
() -> pending.report().scheduleSkipped(id.toString(), NO_TIMELINE)))
.ifRight(tag -> {
List<Holder<Timeline>> members = collect.get(tag);
if(members == null) {
pending.report().scheduleSkipped("#" + tag.location(), NO_TAG);
} else {
contents.addAll(members);
}
});
}
if(contents.isEmpty()) {
pending.report().ignored(PACK_CONFIG, SCHEDULES, NO_VALID_SCHEDULE);
parentTimelines(pending.parent(), collect, registry, contents);
}
collect.put(key, List.copyOf(contents));
});
}
}
private static void parentTimelines(HolderSet<Timeline> parent, Map<TagKey<Timeline>, List<Holder<Timeline>>> collect,
Registry<Timeline> registry, Set<Holder<Timeline>> contents) {
parent.unwrap()
.ifLeft(tag -> contents.addAll(collect.getOrDefault(tag, List.of())))
.ifRight(direct -> {
for(Holder<Timeline> holder : direct) holder.unwrapKey().flatMap(registry::get).ifPresent(contents::add);
});
}
static void clear() {
synchronized(PENDING) {
PENDING.clear();
}
synchronized(REGISTERED) {
REGISTERED.clear();
}
}
public record Pending(AttributeReport report, List<Either<Identifier, TagKey<Timeline>>> refs, HolderSet<Timeline> parent) {
public Pending {
refs = List.copyOf(refs);
}
}
}
@@ -0,0 +1,165 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.world.attribute.EnvironmentAttribute;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
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;
public final class PackAttributeTable {
public static final PackAttributeTable EMPTY = new PackAttributeTable(List.of(), List.of(), List.of(), List.of(), null, null, null,
null, List.of());
private static final String MINECRAFT = "minecraft";
private static final String TERRA = "terra";
private static final String BIOME = "biome/";
private static final String DIMENSION = "dimension/";
private static final Set<String> CLIMATE_FIELDS = Set.of("has_precipitation", "temperature", "temperature_modifier", "downfall");
private static final Set<String> EFFECTS_FIELDS = Set.of("water_color", "foliage_color", "dry_foliage_color", "grass_color",
"grass_color_modifier");
private static final RegistryKey VILLAGER_TYPE = AttributeKey.parse("terra:biome/villager_type").getRegistryKey();
private static final RegistryKey SEA_LEVEL = AttributeKey.parse("terra:world/sea_level").getRegistryKey();
private static final RegistryKey SPAWN_HEIGHT = AttributeKey.parse("terra:world/spawn_height").getRegistryKey();
private static final RegistryKey MOB_GENERATION = AttributeKey.parse("terra:world/mob_generation").getRegistryKey();
private final List<Bound> environment;
private final List<Field> climate;
private final List<Field> effects;
private final List<Field> dimension;
private final @Nullable Attribute<?> villagerType;
private final @Nullable Attribute<?> seaLevel;
private final @Nullable Attribute<?> spawnHeight;
private final @Nullable Attribute<?> mobGeneration;
private final List<Attribute<?>> unapplied;
private PackAttributeTable(List<Bound> environment, List<Field> climate, List<Field> effects, List<Field> dimension,
@Nullable Attribute<?> villagerType, @Nullable Attribute<?> seaLevel, @Nullable Attribute<?> spawnHeight,
@Nullable Attribute<?> mobGeneration, List<Attribute<?>> unapplied) {
this.environment = environment;
this.climate = climate;
this.effects = effects;
this.dimension = dimension;
this.villagerType = villagerType;
this.seaLevel = seaLevel;
this.spawnHeight = spawnHeight;
this.mobGeneration = mobGeneration;
this.unapplied = unapplied;
}
public static PackAttributeTable of(@Nullable Registry<Attribute<?>> registry) {
if(registry == null) return EMPTY;
Builder builder = new Builder();
registry.forEach(builder::add);
return builder.build();
}
public List<Bound> environment() {
return environment;
}
public List<Field> climate() {
return climate;
}
public List<Field> effects() {
return effects;
}
public List<Field> dimension() {
return dimension;
}
public @Nullable Attribute<?> villagerType() {
return villagerType;
}
public @Nullable Attribute<?> seaLevel() {
return seaLevel;
}
public @Nullable Attribute<?> spawnHeight() {
return spawnHeight;
}
public @Nullable Attribute<?> mobGeneration() {
return mobGeneration;
}
public List<Attribute<?>> unapplied() {
return unapplied;
}
public record Bound(Attribute<?> attribute, EnvironmentAttribute<?> vanilla) { }
public record Field(Attribute<?> attribute, String name) { }
private static final class Builder {
private final List<Bound> environment = new ArrayList<>();
private final List<Field> climate = new ArrayList<>();
private final List<Field> effects = new ArrayList<>();
private final List<Field> dimension = new ArrayList<>();
private final List<Attribute<?>> unapplied = new ArrayList<>();
private @Nullable Attribute<?> villagerType;
private @Nullable Attribute<?> seaLevel;
private @Nullable Attribute<?> spawnHeight;
private @Nullable Attribute<?> mobGeneration;
private void add(RegistryKey key, Attribute<?> attribute) {
String namespace = key.getNamespace();
String path = key.getID();
if(namespace.equals(MINECRAFT)) {
// tryBuild returns null for the upper case Terra allows.
Identifier id = Identifier.tryBuild(namespace, path);
EnvironmentAttribute<?> vanilla = id == null ? null : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getValue(id);
if(vanilla != null) {
environment.add(new Bound(attribute, vanilla));
return;
}
} else if(namespace.equals(TERRA)) {
if(key.equals(VILLAGER_TYPE)) {
villagerType = attribute;
return;
} else if(key.equals(SEA_LEVEL)) {
seaLevel = attribute;
return;
} else if(key.equals(SPAWN_HEIGHT)) {
spawnHeight = attribute;
return;
} else if(key.equals(MOB_GENERATION)) {
mobGeneration = attribute;
return;
} else if(path.startsWith(BIOME)) {
String name = path.substring(BIOME.length());
if(CLIMATE_FIELDS.contains(name)) {
climate.add(new Field(attribute, name));
return;
} else if(EFFECTS_FIELDS.contains(name)) {
effects.add(new Field(attribute, name));
return;
}
} else if(path.startsWith(DIMENSION) && path.length() > DIMENSION.length()) {
dimension.add(new Field(attribute, path.substring(DIMENSION.length())));
return;
}
}
unapplied.add(attribute);
}
private PackAttributeTable build() {
return new PackAttributeTable(List.copyOf(environment), List.copyOf(climate), List.copyOf(effects), List.copyOf(dimension),
villagerType, seaLevel, spawnHeight, mobGeneration, List.copyOf(unapplied));
}
}
}
@@ -0,0 +1,87 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.attribute.PackAttributes;
public final class PackParents {
private final ConfigPack pack;
private final ResourceKey<DimensionType> dimensionKey;
private final DimensionType dimension;
private final ResourceKey<NoiseGeneratorSettings> generationKey;
private final NoiseGeneratorSettings generation;
private final PackAttributeTable table;
private final AttributeSlots packEntries;
private final @Nullable PackAttributes attributes;
private final AttributeReport report;
private final VanillaParentReader reader;
private final Map<ResourceKey<Biome>, AttributeSlots> biomeEntries = new ConcurrentHashMap<>();
PackParents(ConfigPack pack, ResourceKey<DimensionType> dimensionKey, DimensionType dimension,
ResourceKey<NoiseGeneratorSettings> generationKey, NoiseGeneratorSettings generation, PackAttributeTable table,
AttributeSlots packEntries, @Nullable PackAttributes attributes, AttributeReport report, VanillaParentReader reader) {
this.pack = pack;
this.dimensionKey = dimensionKey;
this.dimension = dimension;
this.generationKey = generationKey;
this.generation = generation;
this.table = table;
this.packEntries = packEntries;
this.attributes = attributes;
this.report = report;
this.reader = reader;
}
public ResourceKey<DimensionType> dimensionKey() {
return dimensionKey;
}
public DimensionType dimension() {
return dimension;
}
public ResourceKey<NoiseGeneratorSettings> generationKey() {
return generationKey;
}
public NoiseGeneratorSettings generation() {
return generation;
}
public PackAttributeTable table() {
return table;
}
public AttributeSlots packEntries() {
return packEntries;
}
public @Nullable PackAttributes attributes() {
return attributes;
}
public AttributeReport report() {
return report;
}
ConfigPack pack() {
return pack;
}
VanillaParentReader reader() {
return reader;
}
Map<ResourceKey<Biome>, AttributeSlots> biomeEntries() {
return biomeEntries;
}
}
@@ -0,0 +1,65 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import java.util.Map;
import java.util.function.BiConsumer;
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.DecodeException;
final class VanillaAttributeMaps {
private final AttributeHandle handle;
private final VanillaContext context;
VanillaAttributeMaps(AttributeHandle handle, VanillaContext context) {
this.handle = handle;
this.context = context;
}
void toTerra(EnvironmentAttributeMap map, PackAttributeTable table, AttributeEntry<?>[] into,
BiConsumer<Attribute<?>, String> unreadable) {
if(map.keySet().isEmpty() || table.environment().isEmpty()) return;
Map<?, ?> encoded = (Map<?, ?>) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops());
for(PackAttributeTable.Bound bound : table.environment()) {
if(!map.contains(bound.vanilla())) continue;
Object raw = encoded.get(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(bound.vanilla())));
Attribute<?> attribute = bound.attribute();
try {
into[attribute.index()] = handle.decodeEntry(attribute, raw, handle.plainContext());
} catch(DecodeException e) {
unreadable.accept(attribute, e.getMessage());
}
}
}
EnvironmentAttributeMap toVanilla(EnvironmentAttributeMap base, Map<Attribute<?>, AttributeEntry<?>> entries, boolean positionalOnly,
BiConsumer<Attribute<?>, String> skipped) {
Codec<EnvironmentAttributeMap> codec = positionalOnly
? EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL
: EnvironmentAttributeMap.CODEC;
EnvironmentAttributeMap.Builder builder = EnvironmentAttributeMap.builder().putAll(base);
for(Map.Entry<Attribute<?>, AttributeEntry<?>> entry : entries.entrySet()) {
Attribute<?> attribute = entry.getKey();
AttributeEntry<?> value = entry.getValue();
if(value == null || (value.isOverride() && value.argument() == null)) continue;
Map<String, Object> single = Map.of(attribute.getRegistryKey().toString(), encode(attribute, value));
try {
builder.putAll(VanillaCodecs.parse(codec, single, context.ops()));
} catch(DecodeException e) {
skipped.accept(attribute, e.getMessage());
}
}
return builder.build();
}
@SuppressWarnings("unchecked")
private <T> Object encode(Attribute<T> attribute, AttributeEntry<?> entry) {
return handle.encodeEntry(attribute, (AttributeEntry<T>) entry);
}
}
@@ -0,0 +1,37 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
import net.minecraft.resources.RegistryOps;
import java.util.Optional;
import com.dfsek.terra.api.world.attribute.DecodeException;
public final class VanillaCodecs {
private static final String CAUGHT = "Caught exception decoding ";
private VanillaCodecs() { }
public static <V> Object encode(Codec<V> codec, V value, RegistryOps<Object> ops) {
return codec.encodeStart(ops, value).getOrThrow(IllegalStateException::new);
}
public static <V> V parse(Codec<V> codec, Object raw, RegistryOps<Object> ops) throws DecodeException {
DataResult<V> result = codec.parse(ops, raw);
Optional<DataResult.Error<V>> error = result.error();
if(error.isPresent()) {
String message = error.get().message();
// ExtraCodecs.catchDecoderException's form; only the outermost one names raw itself.
String caught = CAUGHT + raw + ": ";
throw new DecodeException(lowerFirst(message.startsWith(caught) ? message.substring(caught.length()) : message));
}
return result.getOrThrow();
}
private static String lowerFirst(String reason) {
if(reason.isEmpty()) return reason;
return Character.toLowerCase(reason.charAt(0)) + reason.substring(1);
}
}
@@ -0,0 +1,88 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.JavaOps;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderGetter;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderOwner;
import net.minecraft.core.HolderSet;
import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
public record VanillaContext(RegistryOps<Object> ops, HolderGetter<DimensionType> dimensionTypes,
HolderGetter<NoiseGeneratorSettings> noiseSettings, HolderGetter<Biome> biomes,
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
public static VanillaContext of(HolderLookup.Provider registries,
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
return new VanillaContext(registries.createSerializationContext(JavaOps.INSTANCE),
registries.lookupOrThrow(Registries.DIMENSION_TYPE),
registries.lookupOrThrow(Registries.NOISE_SETTINGS),
registries.lookupOrThrow(Registries.BIOME),
villagerTypes);
}
/**
* {@code context} must be the list vanilla's loader received: until the load finishes, only it has the static registries'
* new tags.
*/
public static VanillaContext ofLoad(List<? extends WritableRegistry<?>> loaded, List<? extends HolderLookup.RegistryLookup<?>> context,
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
Map<ResourceKey<?>, HolderGetter<?>> getters = new HashMap<>();
// Vanilla's order: the context first, then the registries being loaded over it.
for(HolderLookup.RegistryLookup<?> lookup : context) getters.put(lookup.key(), lookup);
for(WritableRegistry<?> registry : loaded) getters.put(registry.key(), loadGetter(registry));
RegistryOps.RegistryInfoLookup lookup = new RegistryOps.RegistryInfoLookup() {
@Override
@SuppressWarnings("unchecked")
public <T> Optional<HolderGetter<T>> lookup(ResourceKey<? extends Registry<? extends T>> key) {
return Optional.ofNullable((HolderGetter<T>) getters.get(key));
}
};
return new VanillaContext(RegistryOps.create(JavaOps.INSTANCE, lookup),
loadedGetter(lookup, Registries.DIMENSION_TYPE),
loadedGetter(lookup, Registries.NOISE_SETTINGS),
loadedGetter(lookup, Registries.BIOME),
villagerTypes);
}
// The registration lookup makes a holder for any key, and an unbound one fails Registry.freeze() for the whole load.
private static <T> HolderGetter<T> loadGetter(WritableRegistry<T> registry) {
HolderGetter<T> registration = registry.createRegistrationLookup();
return new HolderGetter<>() {
@Override
public Optional<Holder.Reference<T>> get(ResourceKey<T> key) {
return registry.get(key.identifier());
}
@Override
public Optional<HolderSet.Named<T>> get(TagKey<T> key) {
return registration.get(key);
}
@Override
public boolean canSerialize(HolderOwner<T> owner) {
return registration.canSerialize(owner);
}
};
}
private static <T> HolderGetter<T> loadedGetter(RegistryOps.RegistryInfoLookup lookup, ResourceKey<? extends Registry<T>> key) {
return lookup.<T>lookup(key).orElseThrow(() -> new IllegalArgumentException("registry " + key.identifier() + " is not loaded"));
}
}
@@ -0,0 +1,19 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.resources.Identifier;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class VanillaIds {
private VanillaIds() { }
public static Identifier identifier(RegistryKey key) {
Identifier identifier = Identifier.tryBuild(key.getNamespace(), key.getID());
if(identifier == null) {
throw new IllegalArgumentException(
"invalid ID \"" + key + "\": Minecraft IDs use only lower-case a-z, 0-9, _, . and -, and / in the path");
}
return identifier;
}
}
@@ -0,0 +1,101 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
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.DecodeException;
final class VanillaParentReader {
private static final String DEFAULT_CLOCK = "default_clock";
private final AttributeHandle handle;
private final VanillaContext context;
private final VanillaAttributeMaps maps;
VanillaParentReader(AttributeHandle handle, VanillaContext context) {
this.handle = handle;
this.context = context;
this.maps = new VanillaAttributeMaps(handle, context);
}
AttributeSlots biome(ResourceKey<Biome> key, Biome biome, PackAttributeTable table, BiConsumer<Attribute<?>, String> unreadable) {
AttributeEntry<?>[] slots = slots();
maps.toTerra(biome.getAttributes(), table, slots, unreadable);
if(!table.climate().isEmpty()) {
readFields(encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings), table.climate(), slots, unreadable);
}
if(!table.effects().isEmpty()) {
readFields(encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects()), table.effects(), slots, unreadable);
}
Attribute<?> villagerType = table.villagerType();
if(villagerType != null) {
ResourceKey<VillagerType> type = context.villagerTypes().apply(key);
if(type != null) read(villagerType, type.identifier().toString(), slots, unreadable);
}
return AttributeSlots.of(slots);
}
AttributeSlots dimension(DimensionType type, PackAttributeTable table, BiConsumer<Attribute<?>, String> unreadable) {
AttributeEntry<?>[] slots = slots();
maps.toTerra(type.attributes(), table, slots, unreadable);
if(!table.dimension().isEmpty()) {
Map<?, ?> fields = encode(DimensionType.DIRECT_CODEC, type);
for(PackAttributeTable.Field field : table.dimension()) {
Object raw = fields.get(field.name());
if(raw != null) {
read(field.attribute(), raw, slots, unreadable);
} else if(field.name().equals(DEFAULT_CLOCK)) {
slots[field.attribute().index()] = AttributeEntry.override(null);
}
}
}
return AttributeSlots.of(slots);
}
@SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry
AttributeSlots generation(NoiseGeneratorSettings settings, PackAttributeTable table) {
AttributeEntry<?>[] slots = slots();
Attribute<?> seaLevel = table.seaLevel();
if(seaLevel != null) read(seaLevel, settings.seaLevel(), slots, (attribute, reason) -> { });
Attribute<?> mobGeneration = table.mobGeneration();
if(mobGeneration != null) read(mobGeneration, !settings.disableMobGeneration(), slots, (attribute, reason) -> { });
return AttributeSlots.of(slots);
}
private AttributeEntry<?>[] slots() {
return new AttributeEntry<?>[handle.attributeCount()];
}
private void readFields(Map<?, ?> fields, List<PackAttributeTable.Field> table, AttributeEntry<?>[] slots,
BiConsumer<Attribute<?>, String> unreadable) {
for(PackAttributeTable.Field field : table) {
Object raw = fields.get(field.name());
if(raw != null) read(field.attribute(), raw, slots, unreadable);
}
}
private void read(Attribute<?> attribute, Object raw, AttributeEntry<?>[] slots, BiConsumer<Attribute<?>, String> unreadable) {
try {
slots[attribute.index()] = AttributeEntry.override(attribute.type().decode(raw, handle.plainContext()));
} catch(DecodeException e) {
unreadable.accept(attribute, e.getMessage());
}
}
private <V> Map<?, ?> encode(Codec<V> codec, V value) {
return (Map<?, ?>) VanillaCodecs.encode(codec, value, context.ops());
}
}
@@ -1,28 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
public class BiomeAdditionsSoundTemplate implements ObjectTemplate<AmbientAdditionsSettings> {
@Value("sound")
@Default
private SoundEvent sound = null;
@Value("sound-chance")
@Default
private Double soundChance = null;
@Override
public AmbientAdditionsSettings get() {
if(sound == null || soundChance == null) {
return null;
} else {
return new AmbientAdditionsSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundChance);
}
}
}
@@ -1,36 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientMoodSettings;
public class BiomeMoodSoundTemplate implements ObjectTemplate<AmbientMoodSettings> {
@Value("sound")
@Default
private SoundEvent sound = null;
@Value("cultivation-ticks")
@Default
private Integer soundCultivationTicks = null;
@Value("spawn-range")
@Default
private Integer soundSpawnRange = null;
@Value("extra-distance")
@Default
private Double soundExtraDistance = null;
@Override
public AmbientMoodSettings get() {
if(sound == null || soundCultivationTicks == null || soundSpawnRange == null || soundExtraDistance == null) {
return null;
} else {
return new AmbientMoodSettings(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), soundCultivationTicks, soundSpawnRange, soundExtraDistance);
}
}
}
@@ -1,40 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.ParticleArgument;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.world.attribute.AmbientParticle;
import java.util.stream.Stream;
public class BiomeParticleConfigTemplate implements ObjectTemplate<AmbientParticle> {
@Value("particle")
@Default
private String particle = null;
@Value("probability")
@Default
private Float probability = 0.1f;
@Override
public AmbientParticle get() {
if(particle == null) {
return null;
}
try {
return new AmbientParticle(
ParticleArgument.readParticle(new StringReader(particle),
HolderLookup.Provider.create(Stream.of(BuiltInRegistries.PARTICLE_TYPE))),
probability);
} catch(CommandSyntaxException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EntityType;
public class EntityTypeTemplate implements ObjectTemplate<EntityType<?>> {
@Value("id")
@Default
private Identifier id = null;
@Override
public EntityType<?> get() {
return BuiltInRegistries.ENTITY_TYPE.get(id).orElseThrow().value();
}
}
@@ -1,48 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.api.util.range.Range;
public class MonsterSettingsConfig implements ObjectTemplate<MonsterSettingsConfig> {
@Value("piglin-safe")
@Default
private Boolean piglinSafe = null;
@Value("has-raids")
@Default
private Boolean hasRaids = null;
@Value("monster-spawn-light")
@Default
private Range monsterSpawnLight = null;
@Value("monster-spawn-block-light-limit")
@Default
private Integer monsterSpawnBlockLightLimit = null;
public Boolean getPiglinSafe() {
return piglinSafe;
}
public Boolean getHasRaids() {
return hasRaids;
}
public Range getMonsterSpawnLight() {
return monsterSpawnLight;
}
public Integer getMonsterSpawnBlockLightLimit() {
return monsterSpawnBlockLightLimit;
}
@Override
public MonsterSettingsConfig get() {
return this;
}
}
@@ -1,34 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import com.dfsek.terra.api.util.range.Range;
public class MusicSoundTemplate implements ObjectTemplate<Music> {
@Value("sound")
@Default
private SoundEvent sound = null;
@Value("delay")
@Default
private Range delay = null;
@Value("replace-current-music")
@Default
private Boolean replaceCurrentMusic = null;
@Override
public Music get() {
if(sound == null || delay == null || replaceCurrentMusic == null) {
return null;
} else {
return new Music(BuiltInRegistries.SOUND_EVENT.wrapAsHolder(sound), delay.getMin(), delay.getMax(), replaceCurrentMusic);
}
}
}
@@ -26,6 +26,7 @@ import net.minecraft.world.level.biome.Biome;
import java.util.Objects;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.mod.attribute.AttributeSlots;
import com.dfsek.terra.mod.util.MinecraftUtil;
@@ -34,6 +35,9 @@ public class ProtoPlatformBiome implements PlatformBiome {
private Holder<Biome> delegate;
// Volatile for generation threads; AttributeSlots is immutable.
private volatile AttributeSlots parentEntries = AttributeSlots.EMPTY;
public ProtoPlatformBiome(Identifier identifier) {
this.identifier = identifier;
}
@@ -54,4 +58,12 @@ public class ProtoPlatformBiome implements PlatformBiome {
public void setDelegate(Holder<Biome> delegate) {
this.delegate = Objects.requireNonNull(delegate);
}
public AttributeSlots parentEntries() {
return parentEntries;
}
public void setParentEntries(AttributeSlots parentEntries) {
this.parentEntries = Objects.requireNonNull(parentEntries);
}
}
@@ -1,29 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.SoundEvent;
public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
@Value("id")
@Default
private Identifier id = null;
@Value("distance-to-travel")
@Default
private Float distanceToTravel = null;
@Override
public SoundEvent get() {
if(id == null) {
return null;
} else if(distanceToTravel == null) {
return SoundEvent.createVariableRangeEvent(id);
} else {
return SoundEvent.createFixedRangeEvent(id, distanceToTravel);
}
}
}
@@ -1,38 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.world.entity.EntityType;
public class SpawnCostConfig implements ObjectTemplate<SpawnCostConfig> {
@Value("type")
@Default
private EntityType<?> type = null;
@Value("mass")
@Default
private Double mass = null;
@Value("gravity")
@Default
private Double gravity = null;
public EntityType<?> getType() {
return type;
}
public Double getMass() {
return mass;
}
public Double getGravity() {
return gravity;
}
@Override
public SpawnCostConfig get() {
return this;
}
}
@@ -1,38 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.util.valueproviders.UniformInt;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData;
import com.dfsek.terra.api.util.range.Range;
public class SpawnEntryConfig implements ObjectTemplate<SpawnEntryConfig> {
@Value("type")
@Default
private EntityType<?> type = null;
@Value("weight")
@Default
private Integer weight = null;
@Value("group-size")
@Default
private Range groupSize = null;
public Integer getWeight() {
return weight;
}
public SpawnerData getSpawnEntry() {
return new SpawnerData(type, UniformInt.of(groupSize.getMin(), groupSize.getMax()));
}
@Override
public SpawnEntryConfig get() {
return this;
}
}
@@ -1,43 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.MobSpawnSettings;
import java.util.List;
public class SpawnSettingsTemplate implements ObjectTemplate<MobSpawnSettings> {
@Value("spawns")
@Default
private List<SpawnTypeConfig> spawns = null;
@Value("costs")
@Default
private List<SpawnCostConfig> costs = null;
@Value("probability")
@Default
private Float probability = null;
@Override
public MobSpawnSettings get() {
MobSpawnSettings.Builder builder = new MobSpawnSettings.Builder();
for(SpawnTypeConfig spawn : spawns) {
MobCategory group = spawn.getGroup();
for(SpawnEntryConfig entry : spawn.getEntries()) {
MobSpawnSettings.SpawnerData spawnEntry = entry.getSpawnEntry();
builder.addSpawn(spawnEntry.type(), group, entry.getWeight(), spawnEntry.count());
}
}
for(SpawnCostConfig cost : costs) {
builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity());
}
// TODO: environment attributes. Creature generation probability is now the
// gameplay/creature_world_gen_spawn_probability biome attribute, so it is ignored here.
return builder.build();
}
}
@@ -1,32 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.world.entity.MobCategory;
import java.util.List;
public class SpawnTypeConfig implements ObjectTemplate<SpawnTypeConfig> {
@Value("group")
@Default
private MobCategory group = null;
@Value("entries")
@Default
private List<SpawnEntryConfig> entries = null;
public MobCategory getGroup() {
return group;
}
public List<SpawnEntryConfig> getEntries() {
return entries;
}
@Override
public SpawnTypeConfig get() {
return this;
}
}
@@ -1,181 +0,0 @@
package com.dfsek.terra.mod.config;
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 net.minecraft.resources.ResourceKey;
import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.attribute.AmbientAdditionsSettings;
import net.minecraft.world.attribute.AmbientMoodSettings;
import net.minecraft.world.attribute.AmbientParticle;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome.TemperatureModifier;
import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier;
import net.minecraft.world.level.biome.MobSpawnSettings;
import com.dfsek.terra.api.properties.Properties;
public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("colors.grass")
@Default
private Integer grassColor = null;
@Value("colors.fog")
@Default
private Integer fogColor = null;
@Value("colors.water")
@Default
private Integer waterColor = null;
@Value("colors.water-fog")
@Default
private Integer waterFogColor = null;
@Value("colors.foliage")
@Default
private Integer foliageColor = null;
@Value("colors.dry-foliage")
@Default
private Integer dryFoliageColor = null;
@Value("colors.sky")
@Default
private Integer skyColor = null;
@Value("colors.modifier")
@Default
private GrassColorModifier grassColorModifier = null;
@Value("particles")
@Default
private AmbientParticle particleConfig = null;
@Value("climate.precipitation")
@Default
private Boolean precipitation = null;
@Value("climate.temperature")
@Default
private Float temperature = null;
@Value("climate.temperature-modifier")
@Default
private TemperatureModifier temperatureModifier = null;
@Value("climate.downfall")
@Default
private Float downfall = null;
@Value("sound.loop-sound.sound")
@Default
private SoundEvent loopSound = null;
@Value("sound.mood-sound")
@Default
private AmbientMoodSettings moodSound = null;
@Value("sound.additions-sound")
@Default
private AmbientAdditionsSettings additionsSound = null;
@Value("sound.music")
@Default
private Music music = null;
@Value("sound.music-volume")
@Default
private Float musicVolume = null;
@Value("spawning")
@Default
private MobSpawnSettings spawnSettings = null;
@Value("villager-type")
@Default
private
ResourceKey<VillagerType> villagerType = null;
public Integer getGrassColor() {
return grassColor;
}
public Integer getFogColor() {
return fogColor;
}
public Integer getWaterColor() {
return waterColor;
}
public Integer getWaterFogColor() {
return waterFogColor;
}
public Integer getFoliageColor() {
return foliageColor;
}
public Integer getDryFoliageColor() {
return dryFoliageColor;
}
public Integer getSkyColor() {
return skyColor;
}
public GrassColorModifier getGrassColorModifier() {
return grassColorModifier;
}
public AmbientParticle getParticleConfig() {
return particleConfig;
}
public Boolean getPrecipitation() {
return precipitation;
}
public Float getTemperature() {
return temperature;
}
public TemperatureModifier getTemperatureModifier() {
return temperatureModifier;
}
public Float getDownfall() {
return downfall;
}
public SoundEvent getLoopSound() {
return loopSound;
}
public AmbientMoodSettings getMoodSound() {
return moodSound;
}
public AmbientAdditionsSettings getAdditionsSound() {
return additionsSound;
}
public Music getMusic() {
return music;
}
public Float getMusicVolume() {
return musicVolume;
}
public MobSpawnSettings getSpawnSettings() {
return spawnSettings;
}
public ResourceKey<VillagerType> getVillagerType() {
return villagerType;
}
}
@@ -1,179 +0,0 @@
package com.dfsek.terra.mod.config;
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 net.minecraft.resources.Identifier;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.util.range.ConstantRange;
import com.dfsek.terra.api.util.range.Range;
public class VanillaWorldProperties implements ConfigTemplate, Properties {
@Value("vanilla")
@Default
private String vanillaDimension = "minecraft:overworld";
@Value("vanilla-generation")
@Default
private String vanillaGeneration = vanillaDimension;
@Value("minecraft.fixed-time")
@Default
private Long fixedTime = null;
@Value("minecraft.has-sky-light")
@Default
private Boolean hasSkyLight = null;
@Value("minecraft.has-ceiling")
@Default
private Boolean hasCeiling = null;
@Value("minecraft.ultra-warm")
@Default
private Boolean ultraWarm = null;
@Value("minecraft.natural")
@Default
private Boolean natural = null;
@Value("minecraft.coordinate-scale")
@Default
private Double coordinateScale = null;
@Value("minecraft.bed-works")
@Default
private Boolean bedWorks = null;
@Value("minecraft.respawn-anchor-works")
@Default
private Boolean respawnAnchorWorks = null;
@Value("minecraft.height")
@Default
private Range height = null;
@Value("minecraft.height.logical")
@Default
private Integer logicalHeight = null;
@Value("minecraft.infiniburn")
@Default
private Identifier infiniburn = null;
@Value("minecraft.effects")
@Default
private Identifier effects = null;
@Value("minecraft.ambient-light")
@Default
private Float ambientLight = null;
@Value("minecraft.cloud-height")
@Default
private Integer cloudHeight = null;
@Value("minecraft.monster-settings")
@Default
private MonsterSettingsConfig monsterSettings = null;
@Value("minecraft.mob-generation")
@Default
private Boolean mobGeneration = null;
@Value("minecraft.sealevel")
@Default
private Integer sealevel = null;
@Value("minecraft.spawn-height")
@Default
private Integer spawnHeight = 64;
public String getVanillaDimension() {
return vanillaDimension;
}
public String getVanillaGeneration() {
return vanillaGeneration;
}
public Long getFixedTime() {
return fixedTime;
}
public Boolean getHasSkyLight() {
return hasSkyLight;
}
public Boolean getHasCeiling() {
return hasCeiling;
}
public Boolean getUltraWarm() {
return ultraWarm;
}
public Boolean getNatural() {
return natural;
}
public Double getCoordinateScale() {
return coordinateScale;
}
public Boolean getBedWorks() {
return bedWorks;
}
public Boolean getRespawnAnchorWorks() {
return respawnAnchorWorks;
}
public ConstantRange getHeight() {
//TODO THIS IS BAD
if(height != null) {
return new ConstantRange(height.getMin(), height.getMax());
} else {
return null;
}
}
public Integer getLogicalHeight() {
return logicalHeight;
}
public Identifier getInfiniburn() {
return infiniburn;
}
public Identifier getEffects() {
return effects;
}
public Float getAmbientLight() {
return ambientLight;
}
public Integer getCloudHeight() {
return cloudHeight;
}
public MonsterSettingsConfig getMonsterSettings() {
return monsterSettings;
}
public Boolean getMobGeneration() {
return mobGeneration;
}
public Integer getSealevel() {
return sealevel;
}
public Integer getSpawnHeight() {
return spawnHeight;
}
}
@@ -1,21 +0,0 @@
package com.dfsek.terra.mod.config;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
public class VillagerTypeTemplate implements ObjectTemplate<ResourceKey<VillagerType>> {
@Value("id")
@Default
private Identifier id = null;
@Override
public ResourceKey<VillagerType> get() {
return ResourceKey.create(Registries.VILLAGER_TYPE, id);
}
}
@@ -1,12 +0,0 @@
package com.dfsek.terra.mod.mixin.access;
import net.minecraft.world.level.biome.Biome;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(Biome.class)
public interface BiomeAccessor {
@Accessor("climateSettings")
Biome.ClimateSettings getWeather();
}
@@ -48,6 +48,8 @@ public class ReloadableServerResourcesMixin {
RegistryAccess.Frozen dynamicRegistryManager = dynamicRegistries.compositeAccess();
TagUtil.registerWorldPresetTags(dynamicRegistryManager.lookupOrThrow(Registries.WORLD_PRESET));
TagUtil.registerTimelineTags(dynamicRegistryManager.lookupOrThrow(Registries.TIMELINE));
Registry<Biome> biomeRegistry = dynamicRegistryManager.lookupOrThrow(Registries.BIOME);
TagUtil.registerBiomeTags(biomeRegistry);
MinecraftUtil.registerFlora(biomeRegistry);
@@ -1,7 +1,6 @@
package com.dfsek.terra.mod.util;
import net.minecraft.resources.Identifier;
import net.minecraft.world.level.biome.Biome;
import java.util.HashMap;
import java.util.List;
@@ -9,16 +8,14 @@ import java.util.Locale;
import java.util.Map;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
public class BiomeUtil {
public static final Map<Identifier, List<Identifier>>
TERRA_BIOME_MAP = new HashMap<>();
public static Biome createBiome(Biome vanilla, VanillaBiomeProperties vanillaBiomeProperties) {
throw new UnsupportedOperationException("TODO: environment attributes");
}
public static final Map<Identifier, TagUtil.PlatformTagSource>
TERRA_BIOME_PLATFORM_TAGS = new HashMap<>();
public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) {
return pack.getID()
@@ -28,4 +25,8 @@ public class BiomeUtil {
public static Map<Identifier, List<Identifier>> getTerraBiomeMap() {
return Map.copyOf(TERRA_BIOME_MAP);
}
public static Map<Identifier, TagUtil.PlatformTagSource> getTerraBiomePlatformTags() {
return Map.copyOf(TERRA_BIOME_PLATFORM_TAGS);
}
}
@@ -1,22 +0,0 @@
package com.dfsek.terra.mod.util;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.DimensionType.MonsterSettings;
import org.jetbrains.annotations.NotNull;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.config.MonsterSettingsConfig;
import com.dfsek.terra.mod.config.VanillaWorldProperties;
public class DimensionUtil {
public static DimensionType createDimension(VanillaWorldProperties vanillaWorldProperties, DimensionType defaultDimension,
ModPlatform platform) {
throw new UnsupportedOperationException("TODO: environment attributes");
}
@NotNull
private static MonsterSettings getMonsterSettings(DimensionType defaultDimension, MonsterSettingsConfig monsterSettingsConfig) {
throw new UnsupportedOperationException("TODO: environment attributes");
}
}
@@ -28,9 +28,13 @@ import java.util.Locale;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.config.MetaPack;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.api.util.range.ConstantRange;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.config.VanillaWorldProperties;
import com.dfsek.terra.mod.attribute.AttributeReport;
import com.dfsek.terra.mod.attribute.MinecraftAttributeParents;
import com.dfsek.terra.mod.attribute.MinecraftDimensionFactory;
import com.dfsek.terra.mod.attribute.MinecraftTimelines;
import com.dfsek.terra.mod.attribute.PackParents;
import com.dfsek.terra.mod.attribute.VanillaContext;
import com.dfsek.terra.mod.generation.GenerationSettings;
import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
import com.dfsek.terra.mod.generation.TerraBiomeSource;
@@ -56,8 +60,7 @@ public class PresetUtil {
HashMap<ResourceKey<LevelStem>, LevelStem> dimensionMap = new HashMap<>();
insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap,
packInMetapack);
insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap, packInMetapack);
insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(),
dimensionMap);
@@ -82,7 +85,7 @@ public class PresetUtil {
HashMap<ResourceKey<LevelStem>, LevelStem> dimensionMap = new HashMap<>();
metaPack.packs().forEach((key, pack) -> {
insertCustom(platform, key, pack, dimensionTypeRegistry, chunkGeneratorSettingsRegistry, dimensionMap, false);
insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap, false);
});
insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(),
@@ -94,27 +97,20 @@ public class PresetUtil {
}
private static void insertCustom(ModPlatform platform, String key, ConfigPack pack, Registry<DimensionType> dimensionTypeRegistry,
Registry<NoiseGeneratorSettings> chunkGeneratorSettingsRegistry,
HashMap<ResourceKey<LevelStem>, LevelStem> dimensionMap, boolean packInMetapack) {
Identifier demensionIdentifier = Identifier.parse(key);
VanillaWorldProperties vanillaWorldProperties;
if(pack.getContext().has(VanillaWorldProperties.class)) {
vanillaWorldProperties = pack.getContext().get(VanillaWorldProperties.class);
} else {
vanillaWorldProperties = new VanillaWorldProperties();
}
DimensionType defaultDimension = dimensionTypeRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaDimension()));
assert defaultDimension != null;
MinecraftAttributeParents parents = platform.attributeParents();
VanillaContext context = parents.context();
if(context == null) throw new IllegalStateException("no registry load has begun");
PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack));
MinecraftDimensionFactory factory = new MinecraftDimensionFactory(platform.getAttributeHandle(), context);
Identifier dimensionTypeID = Identifier.fromNamespaceAndPath("terra", pack.getID().toLowerCase(Locale.ROOT));
DimensionType dimensionType;
if(!packInMetapack) {
dimensionType = DimensionUtil.createDimension(vanillaWorldProperties, defaultDimension, platform);
dimensionType = factory.create(packParents, MinecraftTimelines.tagFor(pack, packParents));
ResourceKey<DimensionType> dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey(
dimensionTypeID);
@@ -127,20 +123,7 @@ public class PresetUtil {
TerraBiomeSource biomeSource = new TerraBiomeSource(pack);
Holder<NoiseGeneratorSettings> defaultGeneratorSettings = chunkGeneratorSettingsRegistry.wrapAsHolder(
chunkGeneratorSettingsRegistry.getValue(Identifier.parse(vanillaWorldProperties.getVanillaGeneration())));
GenerationSettings generatorSettings = new GenerationSettings(
vanillaWorldProperties.getHeight() == null ? new ConstantRange(
defaultGeneratorSettings.value().noiseSettings().minY(),
defaultGeneratorSettings.value().noiseSettings().height()) : vanillaWorldProperties.getHeight(),
vanillaWorldProperties.getSealevel() == null
? defaultGeneratorSettings.value().seaLevel()
: vanillaWorldProperties.getSealevel(),
vanillaWorldProperties.getMobGeneration() == null
? !defaultGeneratorSettings.value().disableMobGeneration()
: vanillaWorldProperties.getMobGeneration(),
vanillaWorldProperties.getSpawnHeight());
GenerationSettings generatorSettings = factory.generationSettings(packParents, dimensionType);
ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, generatorSettings);
@@ -2,20 +2,32 @@ package com.dfsek.terra.mod.util;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TagLoader.LoadResult;
import net.minecraft.tags.WorldPresetTags;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraft.world.timeline.Timeline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.mod.attribute.AttributeReport;
import com.dfsek.terra.mod.attribute.MinecraftTimelines;
import com.dfsek.terra.mod.attribute.VanillaIds;
public final class TagUtil {
private static final Logger logger = LoggerFactory.getLogger(TagUtil.class);
@@ -58,45 +70,21 @@ public final class TagUtil {
}
}
public static void registerTimelineTags(Registry<Timeline> registry) {
logger.info("Registering timeline tags.");
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = tagsToMutableMap(registry);
MinecraftTimelines.fillTags(collect, registry);
registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply();
}
public record PlatformTagSource(AttributeReport report, String config, Set<RegistryKey> tags) { }
public static void registerBiomeTags(Registry<Biome> registry) {
logger.info("Doing biome tag garbage....");
Map<TagKey<Biome>, List<Holder<Biome>>> collect = tagsToMutableMap(registry);
BiomeUtil
.getTerraBiomeMap()
.forEach((vb, terraBiomes) ->
MinecraftUtil
.getEntry(registry, vb)
.ifPresentOrElse(
vanilla -> terraBiomes
.forEach(tb -> MinecraftUtil
.getEntry(registry, tb)
.ifPresentOrElse(
terra -> {
logger.debug(
vanilla.unwrapKey()
.orElseThrow()
.identifier() +
" (vanilla for " +
terra.unwrapKey()
.orElseThrow()
.identifier() +
": " +
vanilla.tags()
.toList());
vanilla.tags()
.forEach(
tag -> collect
.computeIfAbsent(
tag,
t -> new ArrayList<>())
.add(terra));
},
() -> logger.error(
"No such biome: {}",
tb))),
() -> logger.error("No vanilla biome: {}", vb)));
addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(),
BiomeUtil.getTerraBiomePlatformTags());
registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply();
@@ -107,4 +95,44 @@ public final class TagUtil {
.forEach(logger::debug);
}
}
public static void addTerraBiomes(Map<TagKey<Biome>, List<Holder<Biome>>> collect,
Function<Identifier, Optional<Holder<Biome>>> lookup,
Map<Identifier, List<Identifier>> byParent, Map<Identifier, PlatformTagSource> platformTags) {
byParent.forEach((vb, terraBiomes) ->
lookup.apply(vb).ifPresentOrElse(
vanilla -> terraBiomes.forEach(tb -> lookup.apply(tb).ifPresentOrElse(
terra -> {
logger.debug(vanilla.unwrapKey().orElseThrow().identifier() + " (vanilla for " +
terra.unwrapKey().orElseThrow().identifier() + ": " + vanilla.tags().toList());
vanilla.tags().forEach(tag -> collect.computeIfAbsent(tag, t -> new ArrayList<>()).add(terra));
},
() -> logger.error("No such biome: {}", tb))),
() -> logger.error("No vanilla biome: {}", vb)));
Set<TagKey<Biome>> existing = new HashSet<>(collect.keySet());
platformTags.forEach((tb, source) -> {
if(source.tags().isEmpty()) return;
Optional<Holder<Biome>> terra = lookup.apply(tb);
if(terra.isEmpty()) {
logger.error("No such biome: {}", tb);
return;
}
for(RegistryKey key : source.tags()) {
Identifier id;
try {
id = VanillaIds.identifier(key);
} catch(IllegalArgumentException e) {
source.report().ignored(source.config(), key.toString(), e.getMessage());
continue;
}
TagKey<Biome> tag = TagKey.create(Registries.BIOME, id);
if(!existing.contains(tag) && id.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) {
source.report().tagCreated(source.config(), key.toString());
}
List<Holder<Biome>> biomes = collect.computeIfAbsent(tag, t -> new ArrayList<>());
if(!biomes.contains(terra.get())) biomes.add(terra.get());
}
});
}
}
@@ -4,3 +4,4 @@ accessible class net/minecraft/world/level/levelgen/presets/WorldPresets$Bootstr
accessible field net/minecraft/world/level/levelgen/WorldDimensions BUILTIN_ORDER Ljava/util/Set;
extendable class net/minecraft/nbt/Tag
accessible field net/minecraft/world/level/block/entity/BlockEntity TYPE_CODEC Lcom/mojang/serialization/Codec;
accessible field net/minecraft/world/level/biome/Biome climateSettings Lnet/minecraft/world/level/biome/Biome$ClimateSettings;
@@ -4,7 +4,6 @@
"package": "com.dfsek.terra.mod.mixin",
"compatibilityLevel": "JAVA_25",
"mixins": [
"access.BiomeAccessor",
"access.BaseSpawnerAccessor",
"access.StructureManagerAccessor",
"access.VillagerTypeAccessor",
@@ -0,0 +1,120 @@
package com.dfsek.terra.mod.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.IdentityHashMap;
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.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
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;
final class FakePackAttributes implements PackAttributes {
private static final AttributeEntry<?> UNREAD = AttributeEntry.override(new Object());
private final AttributeHandle handle;
private final AttributeParents platformParents;
private final AttributeMap pack;
private final Map<String, RegistryKey> parents;
private final Map<Biome, AttributeMap> biomes;
private final List<Either<RegistryKey, TagKey>> scheduleRefs;
private final Map<RegistryKey, AttributeSchedule> scheduleDefinitions;
private final AttributeEntry<?>[] packSlots;
private final IdentityHashMap<Biome, AttributeEntry<?>[]> biomeSlots = new IdentityHashMap<>();
FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map<String, RegistryKey> parents,
Map<Biome, AttributeMap> biomes) {
this(handle, platformParents, pack, parents, biomes, List.of(), Map.of());
}
FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map<String, RegistryKey> parents,
Map<Biome, AttributeMap> biomes, List<Either<RegistryKey, TagKey>> scheduleRefs,
Map<RegistryKey, AttributeSchedule> scheduleDefinitions) {
this.handle = handle;
this.platformParents = platformParents;
this.pack = pack;
this.parents = Map.copyOf(parents);
this.biomes = Map.copyOf(biomes);
this.scheduleRefs = List.copyOf(scheduleRefs);
this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions));
this.packSlots = unread();
for(Biome biome : biomes.keySet()) biomeSlots.put(biome, unread());
}
private AttributeEntry<?>[] unread() {
AttributeEntry<?>[] slots = new AttributeEntry<?>[handle.attributeCount()];
Arrays.fill(slots, UNREAD);
return slots;
}
@SuppressWarnings("unchecked")
private static <T> @Nullable AttributeEntry<T> slot(AttributeEntry<?>[] slots, AttributeMap map, Attribute<T> attribute) {
int index = attribute.index();
if(index >= slots.length) return map.get(attribute.key()).orElse(null);
AttributeEntry<?> entry = slots[index];
if(entry == UNREAD) {
entry = map.get(attribute.key()).orElse(null);
slots[index] = entry;
}
return (AttributeEntry<T>) entry;
}
private <T> @Nullable AttributeEntry<T> packEntryOrNull(Attribute<T> attribute) {
return slot(packSlots, pack, attribute);
}
@Override
public AttributeMap entries() {
return pack;
}
@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
public <T> @Nullable AttributeEntry<T> biomeEntryOrNull(Attribute<T> attribute, Biome biome) {
AttributeEntry<?>[] slots = biomeSlots.get(biome);
return slots == null ? null : slot(slots, biomes.get(biome), attribute);
}
@Override
public AttributeMap biomeEntries(Biome biome) {
return biomes.getOrDefault(biome, AttributeMap.empty());
}
@Override
public <T> @Nullable T resolve(Attribute<T> attribute, Biome biome) {
return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute),
platformParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome));
}
@Override
public <T> @Nullable T resolvePack(Attribute<T> attribute) {
return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute), null);
}
}
@@ -0,0 +1,400 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.api.config.ConfigPack;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
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;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftAttributeParentsTest {
private static final com.dfsek.terra.api.registry.Registry<Attribute<?>> REGISTRY = registry();
private static final ConfigPack PACK = pack("test", REGISTRY);
private static final Attribute<Boolean> RESPAWN_ANCHOR = attr(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS);
private static final Attribute<Float> SKY_LIGHT = attr(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL);
private static final Attribute<Boolean> HAS_CEILING = attr(MinecraftAttributes.DIMENSION_HAS_CEILING);
private static final Attribute<Integer> SEA_LEVEL = attr(MinecraftAttributes.WORLD_SEA_LEVEL);
private static final Attribute<Boolean> PRECIPITATION = attr(MinecraftAttributes.BIOME_HAS_PRECIPITATION);
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private static <T> Attribute<T> attr(AttributeKey<T> key) {
return attribute(key.getRegistryKey().toString());
}
static ConfigPack pack(String id, com.dfsek.terra.api.registry.Registry<Attribute<?>> attributes) {
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "getID" -> id;
case "getRegistry" -> attributes;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "ConfigPack[" + id + "]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private FakePackAttributes fake(Map<String, RegistryKey> parentIds) {
return new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), parentIds, Map.of());
}
private static <T> T value(ResourceKey<? extends Registry<T>> registry, ResourceKey<T> key) {
return REGISTRIES.lookupOrThrow(registry).getOrThrow(key).value();
}
private static PackAttributeTable table() {
return PackAttributeTable.of(REGISTRY);
}
@Test
void reportFormats() {
report.attributeSkipped("BIOME", "minecraft:visual/fog_color", "not a colour");
report.scheduleSkipped("mypack:seasons", "no clock");
report.trackDropped("mypack:seasons", "minecraft:visual/fog_color", "bad keyframe");
report.timeMarkerDropped("mypack:seasons", "minecraft:noon", "minecraft:overworld");
report.ignored("pack.yml", "vanilla", "no such dimension type \"minecraft:nope\"");
report.tagCreated("BIOME", "minecraft:is_custom");
report.notApplied("test:custom");
report.notApplied("test:custom");
report.notApplied("test:other");
assertEquals(List.of(
"Pack \"test\", config \"BIOME\": attribute \"minecraft:visual/fog_color\" skipped: not a colour",
"Pack \"test\": schedule \"mypack:seasons\" skipped: no clock",
"Pack \"test\": schedule \"mypack:seasons\" track \"minecraft:visual/fog_color\" dropped: bad keyframe",
"Pack \"test\": schedule \"mypack:seasons\" time marker \"minecraft:noon\" dropped: already defined for clock "
+ "\"minecraft:overworld\"",
"Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"",
"Pack \"test\", config \"BIOME\": tag \"minecraft:is_custom\" created: no such tag in the minecraft namespace"), warnings);
assertEquals(List.of(
"Pack \"test\": attribute \"test:custom\" is not applied on this platform",
"Pack \"test\": attribute \"test:other\" is not applied on this platform"), debugs);
}
@Test
void unreadableParentValueNamesTheParent() {
MinecraftAttributeParents.parentSkipped(report, "minecraft:plains").accept(HAS_CEILING, "not a boolean");
assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"" + HAS_CEILING.getRegistryKey()
+ "\" skipped: vanilla parent \"minecraft:plains\": not a boolean"), warnings);
}
@Test
void overworldByDefault() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of());
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
DimensionType overworld = value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.OVERWORLD);
AttributeSlots expected = new VanillaParentReader(HANDLE, CONTEXT).dimension(overworld, table(), FAIL);
assertEquals(expected.get(RESPAWN_ANCHOR), parents.packOrNull(fake, RESPAWN_ANCHOR));
assertFalse(fake.resolvePack(RESPAWN_ANCHOR));
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING));
assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL));
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
assertSame(overworld, pack.dimension());
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
assertSame(value(Registries.NOISE_SETTINGS, NoiseGeneratorSettings.OVERWORLD), pack.generation());
assertSame(fake, pack.attributes());
assertSame(report, pack.report());
assertEquals(List.of(), warnings);
PackParents bare = parents.prepare(pack("bare", REGISTRY), Optional.empty(), report);
assertNull(bare.attributes());
assertEquals(BuiltinDimensionTypes.OVERWORLD, bare.dimensionKey());
assertEquals(NoiseGeneratorSettings.OVERWORLD, bare.generationKey());
assertEquals(AttributeEntry.override(63), bare.packEntries().get(SEA_LEVEL));
}
@Test
void vanillaParentIsUsed() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
assertEquals(BuiltinDimensionTypes.NETHER, pack.dimensionKey());
assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), pack.dimension());
assertEquals(AttributeEntry.override(true), parents.packOrNull(fake, HAS_CEILING));
assertEquals(AttributeEntry.override(4f), parents.packOrNull(fake, SKY_LIGHT));
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL));
assertEquals(List.of(), warnings);
}
@Test
void generationParentSuppliesWorld() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether")));
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
assertEquals(NoiseGeneratorSettings.NETHER, pack.generationKey());
assertEquals(AttributeEntry.override(32), parents.packOrNull(fake, SEA_LEVEL));
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
assertEquals(List.of(), warnings);
}
@Test
void badParentWarnsAndFallsBack() {
parents.beginLoad(CONTEXT);
PackParents upper = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:The_Nether")))),
report);
PackParents unknown = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"),
"vanilla-generation", RegistryKey.parse("minecraft:nope")))),
report);
assertEquals(List.of(
"Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: invalid ID \"minecraft:The_Nether\": Minecraft IDs use only "
+ "lower-case a-z, 0-9, _, . and -, and / in the path",
"Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"",
"Pack \"test\", config \"pack.yml\": \"vanilla-generation\" ignored: no such noise settings \"minecraft:nope\""),
warnings);
for(PackParents pack : List.of(upper, unknown)) {
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
assertEquals(AttributeEntry.override(false), pack.packEntries().get(HAS_CEILING));
}
}
@Test
void unknownParentCreatesNoHolder() {
MappedRegistry<DimensionType> dimensionTypes = VanillaContextTest.copy(Registries.DIMENSION_TYPE);
MappedRegistry<NoiseGeneratorSettings> noiseSettings = VanillaContextTest.copy(Registries.NOISE_SETTINGS);
MappedRegistry<Biome> biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
VanillaContext load = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(),
key -> null);
parents.beginLoad(new VanillaContext(CONTEXT.ops(), load.dimensionTypes(), load.noiseSettings(), load.biomes(), key -> null));
dimensionTypes.freeze();
noiseSettings.freeze();
PackParents pack = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"),
"vanilla-generation", RegistryKey.parse("minecraft:nope")))),
report);
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
assertEquals(2, warnings.size(), warnings.toString());
assertFalse(dimensionTypes.containsKey(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope"))));
assertFalse(noiseSettings.containsKey(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope"))));
}
@Test
void biomeOrNullReadsProtoBiome() {
parents.beginLoad(CONTEXT);
PackParents pack = parents.prepare(PACK, Optional.empty(), report);
TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier());
assertSame(AttributeSlots.EMPTY, biome.proto().parentEntries());
assertNull(parents.biomeOrNull(biome, PRECIPITATION));
AttributeSlots desert = parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
assertSame(desert, parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)), "cached per parent key");
biome.proto().setParentEntries(desert);
assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION));
PlatformBiome other = () -> "other";
assertNull(parents.biomeOrNull(new TestBiome("OTHER", 1, other), PRECIPITATION));
assertEquals(List.of(), warnings);
}
@Test
void unreadableBiomeParentIsReportedOnce() {
Attribute<RegistryKey> downfall = HANDLE.attributeBuilder(AttributeKey.<RegistryKey>parse("terra:biome/downfall"),
HANDLE.types().identifier("minecraft"),
RegistryKey.parse("minecraft:none")).build();
parents.beginLoad(CONTEXT);
PackParents pack = parents.prepare(pack("test", registry(downfall)), Optional.empty(), report);
Biome plains = value(Registries.BIOME, Biomes.PLAINS);
AttributeSlots first = parents.biomeEntries(pack, Biomes.PLAINS, plains);
assertSame(first, parents.biomeEntries(pack, Biomes.PLAINS, plains));
assertEquals(1, warnings.size(), warnings.toString());
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" skipped: "
+ "vanilla parent \"minecraft:plains\": "), warnings.getFirst());
assertNull(first.get(downfall));
}
@Test
void readsAllocateNothing() {
parents.beginLoad(CONTEXT);
parents.prepare(PACK, Optional.of(fake(Map.of())), report);
parents.prepare(pack("other", REGISTRY), Optional.empty(), report);
TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier());
TestBiome plain = new TestBiome("PLAIN", 1, (PlatformBiome) () -> "plain");
FakePackAttributes fake = new FakePackAttributes(HANDLE, parents,
AttributeMap.builder().put(RESPAWN_ANCHOR.key(), AttributeEntry.override(true)).build(),
Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")),
Map.of(biome, AttributeMap.builder().put(HAS_CEILING.key(), AttributeEntry.override(true)).build()));
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
biome.proto().setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)));
FakePackAttributes unprepared = fake(Map.of());
assertEquals(List.of(), warnings);
assertEquals(1023, reads(fake, unprepared, biome, plain), "every read sees the expected entry or value");
com.sun.management.ThreadMXBean threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long thread = Thread.currentThread().threadId();
int sink = 0;
for(int i = 0; i < 100_000; i++) sink += reads(fake, unprepared, biome, plain);
long before = threads.getThreadAllocatedBytes(thread);
for(int i = 0; i < 10_000; i++) sink += reads(fake, unprepared, biome, plain);
long allocated = threads.getThreadAllocatedBytes(thread) - before;
assertEquals(110_000 * 1023, sink);
assertTrue(allocated < 1024, allocated + " bytes allocated");
System.out.println("readsAllocateNothing: " + allocated + " bytes over 10000 measured iterations");
}
private int reads(FakePackAttributes fake, FakePackAttributes unprepared, TestBiome biome, TestBiome plain) {
int hash = 0;
hash += parents.biomeOrNull(biome, PRECIPITATION) == null ? 0 : 1;
hash += parents.biomeOrNull(plain, PRECIPITATION) == null ? 2 : 0;
hash += parents.packOrNull(fake, HAS_CEILING) == null ? 0 : 4;
hash += parents.packOrNull(fake, SKY_LIGHT) == null ? 0 : 8;
hash += parents.packOrNull(unprepared, SKY_LIGHT) == null ? 16 : 0;
hash += fake.resolve(PRECIPITATION, biome) ? 0 : 32;
hash += fake.resolve(HAS_CEILING, plain) ? 64 : 0;
hash += fake.resolve(HAS_CEILING, biome) ? 128 : 0;
hash += fake.resolvePack(RESPAWN_ANCHOR) ? 256 : 0;
hash += fake.resolvePack(HAS_CEILING) ? 512 : 0;
return hash;
}
@Test
void beginLoadDropsOldPacks() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of());
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
assertNotNull(parents.packOrNull(fake, HAS_CEILING));
parents.beginLoad(CONTEXT);
assertNull(parents.packOrNull(fake, HAS_CEILING));
PackParents second = parents.prepare(PACK, Optional.of(fake), report);
assertNotSame(first, second);
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING));
parents.clearPacks();
assertSame(CONTEXT, parents.context());
assertNull(parents.packOrNull(fake, HAS_CEILING));
}
@Test
void packReloadKeepsOldPacks() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of());
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
parents.beginPackReload();
assertSame(CONTEXT, parents.context());
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING), "the old pack keeps its parents");
FakePackAttributes reloaded = fake(Map.of());
PackParents second = parents.prepare(PACK, Optional.of(reloaded), report);
assertNotSame(first, second);
assertNotSame(first, parents.prepare(PACK, Optional.of(fake), report), "prepared fresh during the reload");
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
assertNotNull(parents.packOrNull(fake, HAS_CEILING));
parents.endPackReload();
assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report));
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
assertNotNull(parents.packOrNull(fake, HAS_CEILING), "re-prepared during the reload, so kept");
assertEquals(List.of(), warnings);
parents.beginPackReload();
parents.endPackReload();
assertNull(parents.packOrNull(reloaded, HAS_CEILING), "not prepared again, so dropped");
}
@Test
void prepareAfterClearPacksIsFresh() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of());
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
AttributeSlots desert = parents.biomeEntries(first, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
parents.clearPacks();
FakePackAttributes reloaded = fake(Map.of());
assertNull(parents.packOrNull(reloaded, HAS_CEILING));
PackParents second = parents.prepare(PACK, Optional.of(reloaded), report);
assertNotSame(first, second);
assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report));
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
assertNull(parents.packOrNull(fake, HAS_CEILING), "the old pack's attributes get no parents");
AttributeSlots again = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
assertNotSame(desert, again, "biome entries are read again for the new pack");
assertEquals(AttributeEntry.override(false), again.get(PRECIPITATION));
assertEquals(List.of(), warnings);
}
@Test
void unpreparedPackHasNoParents() {
FakePackAttributes fake = fake(Map.of());
assertNull(parents.context());
assertNull(parents.packOrNull(fake, HAS_CEILING));
assertThrows(IllegalStateException.class, () -> parents.prepare(PACK, Optional.of(fake), report));
parents.beginLoad(CONTEXT);
assertSame(CONTEXT, parents.context());
assertNull(parents.packOrNull(fake, HAS_CEILING));
}
@Test
void prepareIsIdempotent() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope")));
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
assertEquals(1, warnings.size());
assertSame(first, parents.prepare(PACK, Optional.of(fake), report));
assertEquals(1, warnings.size());
PackParents bare = parents.prepare(PACK, Optional.empty(), report);
assertNotSame(first, bare);
assertSame(bare, parents.prepare(PACK, Optional.empty(), report));
}
}
@@ -0,0 +1,466 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.attribute.EnvironmentAttribute;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import net.minecraft.world.level.biome.Biomes;
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.function.BiConsumer;
import com.dfsek.terra.api.config.ConfigPack;
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.AttributeKey;
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.value.Color;
import com.dfsek.terra.registry.OpenRegistryImpl;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
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;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftBiomeFactoryTest {
private static final Registry<Attribute<?>> REGISTRY = registry();
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
private static final RegistryOps<Object> OPS = CONTEXT.ops();
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT);
private static final String CONFIG = "BIOME";
private static final String FOG_COLOR = "minecraft:visual/fog_color";
private static final String SKY_COLOR = "minecraft:visual/sky_color";
private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles";
private static final String SPAWN_PROBABILITY = "minecraft:gameplay/creature_world_gen_spawn_probability";
private static final String VILLAGER_TYPE = "terra:biome/villager_type";
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private static Biome biome(ResourceKey<Biome> key) {
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value();
}
@SuppressWarnings("unchecked")
private static <V> Object encode(Codec<V> codec, Object value) {
return VanillaCodecs.encode(codec, (V) value, OPS);
}
private static Object climate(Biome biome) {
return encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings);
}
private static Object effects(Biome biome) {
return encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects());
}
private static Map<?, ?> environment(Biome biome) {
return (Map<?, ?>) encode(EnvironmentAttributeMap.CODEC, biome.getAttributes());
}
private static AttributeEntry<?> decoded(String id, Object raw) {
try {
return HANDLE.decodeEntry(attribute(id), raw, PLAIN);
} catch(DecodeException e) {
throw new AssertionError(id + ": " + e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
private static <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, AttributeEntry<?> entry) {
builder.put(attribute.key(), (AttributeEntry<T>) entry);
}
private record Fixture(TestBiome biome, FakePackAttributes attributes, PackParents pack, MinecraftBiomeFactory factory,
ResourceKey<Biome> parentKey, Biome parent) {
MinecraftBiomeFactory.Built create(AttributeReport report) {
return factory.create(parentKey, parent, biome, pack, report);
}
}
private Fixture fixture(ResourceKey<Biome> parentKey, Biome parent, Map<Attribute<?>, AttributeEntry<?>> entries) {
return fixture(CONTEXT, PACK, parentKey, parent, entries);
}
private Fixture fixture(VanillaContext context, ConfigPack pack, ResourceKey<Biome> parentKey, Biome parent,
Map<Attribute<?>, AttributeEntry<?>> entries) {
TestBiome biome = new TestBiome(CONFIG, 0, parentKey.identifier());
AttributeMap.Builder builder = AttributeMap.builder();
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(),
Map.of(biome, builder.build()));
parents.beginLoad(context);
PackParents prepared = parents.prepare(pack, Optional.of(attributes), report);
biome.proto().setParentEntries(parents.biomeEntries(prepared, parentKey, parent));
return new Fixture(biome, attributes, prepared, new MinecraftBiomeFactory(HANDLE, context), parentKey, parent);
}
private static Map<Attribute<?>, AttributeEntry<?>> entries(Object... idsAndRaw) {
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
for(int i = 0; i < idsAndRaw.length; i += 2) {
String id = (String) idsAndRaw[i];
entries.put(attribute(id), decoded(id, idsAndRaw[i + 1]));
}
return entries;
}
private static void assertMatches(Biome expected, Biome actual) {
assertEquals(expected.hasPrecipitation(), actual.hasPrecipitation());
assertEquals(expected.getBaseTemperature(), actual.getBaseTemperature());
assertEquals(expected.climateSettings, actual.climateSettings);
assertEquals(climate(expected), climate(actual));
assertEquals(effects(expected), effects(actual));
assertEquals(expected.getAttributes().keySet(), actual.getAttributes().keySet());
assertEquals(environment(expected), environment(actual));
assertSame(expected.getGenerationSettings(), actual.getGenerationSettings());
}
@Test
void noEntriesMatchesParent() {
Biome plains = biome(Biomes.PLAINS);
MinecraftBiomeFactory.Built built = fixture(Biomes.PLAINS, plains, Map.of()).create(report);
assertMatches(plains, built.biome());
assertNotSame(plains, built.biome());
assertEquals(VillagerType.PLAINS, built.villagerType());
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void createdBiomeRegistersBesideItsParent() {
Biome plains = biome(Biomes.PLAINS);
Biome built = fixture(Biomes.PLAINS, plains, Map.of()).create(report).biome();
MappedRegistry<Biome> registry = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
registry.register(Biomes.PLAINS, plains, RegistrationInfo.BUILT_IN);
ResourceKey<Biome> key = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test"));
assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN));
}
@Test
void noAttributesMatchesTheParent() {
Biome plains = biome(Biomes.PLAINS);
parents.beginLoad(CONTEXT);
PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
assertNull(bare.attributes());
assertSame(PackAttributeTable.EMPTY, bare.table());
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier());
biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains));
MinecraftBiomeFactory.Built built = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, bare, report);
assertMatches(plains, built.biome());
assertNotSame(plains, built.biome());
assertEquals(VillagerType.PLAINS, built.villagerType());
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void equivalentInputMatchesVanilla() {
Biome plains = biome(Biomes.PLAINS);
Biome desert = biome(Biomes.DESERT);
PackAttributeTable table = PackAttributeTable.of(REGISTRY);
AttributeSlots desertSlots = new VanillaParentReader(HANDLE, CONTEXT).biome(Biomes.DESERT, desert, table, FAIL);
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
List<Attribute<?>> attributes = new ArrayList<>();
table.environment().forEach(bound -> attributes.add(bound.attribute()));
table.climate().forEach(field -> attributes.add(field.attribute()));
table.effects().forEach(field -> attributes.add(field.attribute()));
for(Attribute<?> attribute : attributes) {
AttributeEntry<?> entry = desertSlots.get(attribute);
if(entry != null) entries.put(attribute, entry);
}
assertTrue(entries.size() > 5, "desert has few entries: " + entries.size());
Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome();
assertEquals(desert.climateSettings, built.climateSettings);
assertEquals(climate(desert), climate(built));
assertEquals(effects(desert), effects(built));
Map<?, ?> expected = environment(desert);
Map<?, ?> parent = environment(plains);
Map<?, ?> actual = environment(built);
for(PackAttributeTable.Bound bound : table.environment()) {
String id = bound.attribute().getRegistryKey().toString();
if(desert.getAttributes().contains(bound.vanilla())) {
assertEquals(expected.get(id), actual.get(id), id);
} else {
assertEquals(parent.get(id), actual.get(id), id + ": a key desert lacks keeps the plains parent's value");
}
}
assertEquals(List.of(), warnings);
}
@Test
void desertParentKeepsNoPrecipitation() {
Biome desert = biome(Biomes.DESERT);
assertFalse(desert.hasPrecipitation());
Biome built = fixture(Biomes.DESERT, desert, entries(FOG_COLOR, "#123456")).create(report).biome();
assertFalse(built.hasPrecipitation());
assertEquals(desert.climateSettings, built.climateSettings);
assertEquals(List.of(), warnings);
}
@Test
void spawnProbabilityIsApplied() {
Biome plains = biome(Biomes.PLAINS);
Biome built = fixture(Biomes.PLAINS, plains, entries(SPAWN_PROBABILITY, 0.2)).create(report).biome();
assertTrue(built.getAttributes().contains(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY));
assertEquals(0.2f, built.getAttributes().applyModifier(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY, 0.5f));
assertEquals(List.of(), warnings);
}
@Test
void nonComposableFallsBackToResolved() throws DecodeException {
Attribute<Color> fog = attribute(FOG_COLOR);
Biome plains = biome(Biomes.PLAINS);
AttributeEntry<Color> blend = HANDLE.decodeEntry(fog, Map.of("modifier", "alpha_blend", "argument", "#80ff0000"), PLAIN);
Biome parent = new Biome.BiomeBuilder()
.hasPrecipitation(true)
.temperature(0.8f)
.downfall(0.4f)
.putAttributes(MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, blend), true, FAIL))
.specialEffects(plains.getSpecialEffects())
.generationSettings(plains.getGenerationSettings())
.build();
ResourceKey<Biome> parentKey = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("test", "blended"));
AttributeEntry<?> multiply = decoded(FOG_COLOR, Map.of("modifier", "multiply", "argument", "#808080"));
Fixture fixture = fixture(parentKey, parent, Map.of(fog, multiply));
assertEquals(blend, fixture.biome().proto().parentEntries().get(fog), "the parent's modifier is read");
assertTrue(composed(fog, blend, multiply).isEmpty(), "alpha_blend then multiply has no single entry");
Biome built = fixture.create(report).biome();
Color resolved = fixture.attributes().resolve(fog, fixture.biome());
assertNotNull(resolved);
EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, AttributeEntry.override(resolved)),
true, FAIL);
assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR));
assertEquals(List.of(), warnings);
}
@SuppressWarnings("unchecked")
private static <T> Optional<AttributeEntry<T>> composed(Attribute<T> attribute, AttributeEntry<?> lower, AttributeEntry<?> upper) {
return HANDLE.compose(attribute, (AttributeEntry<T>) lower, (AttributeEntry<T>) upper);
}
@Test
void badEntryIsSkippedAlone() {
Biome plains = biome(Biomes.PLAINS);
Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand"));
Map<Attribute<?>, AttributeEntry<?>> entries = entries(
AMBIENT_PARTICLES, List.of(Map.of("particle", oldParticle, "probability", 0.01)),
FOG_COLOR, "#123456");
Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome();
String reason = rejection(AMBIENT_PARTICLES, entries.get(attribute(AMBIENT_PARTICLES)));
assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + AMBIENT_PARTICLES + "\" skipped: " + reason), warnings);
assertEquals(plains.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES),
built.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES));
assertFogApplied(entries.get(attribute(FOG_COLOR)), built);
}
private static void assertFogApplied(AttributeEntry<?> fog, Biome built) {
EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(attribute(FOG_COLOR), fog), true, FAIL);
assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR));
}
@SuppressWarnings("unchecked")
private static String rejection(String id, AttributeEntry<?> entry) {
Attribute<Object> attribute = attribute(id);
Object raw = HANDLE.encodeEntry(attribute, (AttributeEntry<Object>) entry);
DecodeException e = assertThrows(DecodeException.class,
() -> VanillaCodecs.parse(EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL, Map.of(id, raw), OPS));
assertFalse(e.getMessage().isBlank());
return e.getMessage();
}
@Test
void badFieldIsSkippedAlone() {
Attribute<RegistryKey> downfall = HANDLE.attributeBuilder(AttributeKey.<RegistryKey>parse("terra:biome/downfall"),
HANDLE.types().identifier("minecraft"),
RegistryKey.parse("minecraft:none")).build();
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : ATTRIBUTES) {
if(!attribute.getRegistryKey().equals(downfall.getRegistryKey())) registry.register(attribute.getRegistryKey(), attribute);
}
registry.register(downfall.getRegistryKey(), downfall);
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>(entries("terra:biome/temperature", 0.3));
entries.put(downfall, AttributeEntry.override(RegistryKey.parse("minecraft:wet")));
Biome plains = biome(Biomes.PLAINS);
Biome built = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("test", registry), Biomes.PLAINS, plains, entries)
.create(report).biome();
assertEquals(2, warnings.size(), warnings.toString());
assertTrue(warnings.get(0).startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" "
+ "skipped: vanilla parent \"minecraft:plains\": "), warnings.get(0));
assertTrue(warnings.get(1).startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/downfall\" skipped: "),
warnings.get(1));
assertEquals(0.3f, built.getBaseTemperature());
assertEquals(plains.climateSettings.downfall(), built.climateSettings.downfall());
assertEquals(plains.hasPrecipitation(), built.hasPrecipitation());
}
@Test
void nonPositionalOnBiomeIsSkipped() {
PackAttributeTable.Bound bound = PackAttributeTable.of(REGISTRY).environment().stream()
.filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null)
.findFirst().orElseThrow();
String id = bound.attribute().getRegistryKey().toString();
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(bound.attribute(), AttributeEntry.override(bound.attribute().defaultValue()));
entries.putAll(entries(FOG_COLOR, "#123456"));
Biome plains = biome(Biomes.PLAINS);
Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome();
assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: "
+ rejection(id, entries.get(bound.attribute()))), warnings);
assertFalse(built.getAttributes().contains(bound.vanilla()));
assertFogApplied(entries.get(attribute(FOG_COLOR)), built);
}
@Test
void unknownParentAttributeIsKept() {
OpenRegistryImpl<Attribute<?>> withoutSky = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : ATTRIBUTES) {
if(!attribute.getRegistryKey().toString().equals(SKY_COLOR)) withoutSky.register(attribute.getRegistryKey(), attribute);
}
Biome plains = biome(Biomes.PLAINS);
EnvironmentAttribute<?> sky = vanilla(SKY_COLOR);
assertTrue(plains.getAttributes().contains(sky));
Map<Attribute<?>, AttributeEntry<?>> entries = entries(FOG_COLOR, "#123456");
Fixture fixture = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("nosky", withoutSky), Biomes.PLAINS, plains, entries);
assertNull(fixture.biome().proto().parentEntries().get(attribute(SKY_COLOR)), "the pack does not know sky colour");
Biome built = fixture.create(report).biome();
assertSame(plains.getAttributes().get(sky), built.getAttributes().get(sky));
assertFogApplied(entries.get(attribute(FOG_COLOR)), built);
assertEquals(List.of(), warnings);
}
@Test
void addonAttributeIsDebugLogged() {
Attribute<Float> custom = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:custom"), HANDLE.types().floatType(), 0f)
.build();
Attribute<Float> unset = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:unset"), HANDLE.types().floatType(), 0f)
.build();
ConfigPack pack = MinecraftAttributeParentsTest.pack("test", registry(custom, unset));
Biome plains = biome(Biomes.PLAINS);
Biome built = fixture(CONTEXT, pack, Biomes.PLAINS, plains, Map.of(custom, AttributeEntry.override(1f))).create(report).biome();
assertEquals(List.of("Pack \"test\": attribute \"test:custom\" is not applied on this platform"), debugs);
assertEquals(List.of(), warnings);
assertMatches(plains, built);
}
@Test
void villagerTypeFallsBackToParent() {
VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null);
Biome desert = biome(Biomes.DESERT);
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, Map.of()).create(report).villagerType());
assertEquals(VillagerType.SNOW, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:snow"))
.create(report).villagerType());
assertEquals(List.of(), warnings);
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:nope"))
.create(report).villagerType());
assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: "
+ "no such villager type \"minecraft:nope\""), warnings);
assertEquals(VillagerType.PLAINS, fixture(villagers, PACK, Biomes.PLAINS, biome(Biomes.PLAINS), Map.of())
.create(report).villagerType());
parents.beginLoad(villagers);
PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.DESERT.identifier());
biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.DESERT, desert));
assertEquals(VillagerType.DESERT,
new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report).villagerType());
}
@Test
void upperCaseVillagerTypeWarns() {
VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null);
Map<Attribute<?>, AttributeEntry<?>> entries = Map.of(attribute(VILLAGER_TYPE),
AttributeEntry.override(RegistryKey.of("minecraft", "Snow")));
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, biome(Biomes.DESERT), entries).create(report)
.villagerType());
assertEquals(1, warnings.size(), warnings.toString());
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: "
+ "invalid ID \"minecraft:Snow\""), warnings.getFirst());
}
@Test
void reloadBuildsEqualBiome() {
Biome plains = biome(Biomes.PLAINS);
Map<Attribute<?>, AttributeEntry<?>> entries = entries(FOG_COLOR, "#123456", "terra:biome/temperature", 0.3);
Fixture before = fixture(Biomes.PLAINS, plains, entries);
Biome first = before.create(report).biome();
parents.clearPacks();
assertNull(parents.packOrNull(before.attributes(), attribute(FOG_COLOR)));
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier());
AttributeMap.Builder builder = AttributeMap.builder();
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
FakePackAttributes reloaded = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(),
Map.of(biome, builder.build()));
PackParents again = parents.prepare(PACK, Optional.of(reloaded), report);
assertNotSame(before.pack(), again);
biome.proto().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains));
Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report).biome();
assertEquals(0.3f, second.getBaseTemperature());
assertEquals(climate(first), climate(second));
assertEquals(effects(first), effects(second));
assertEquals(environment(first), environment(second));
assertEquals(List.of(), warnings);
}
}
@@ -0,0 +1,358 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.HolderSet;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.timeline.Timeline;
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.function.BiConsumer;
import com.dfsek.terra.api.config.ConfigPack;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.mod.generation.GenerationSettings;
import com.dfsek.terra.registry.OpenRegistryImpl;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftDimensionFactoryTest {
private static final Registry<Attribute<?>> REGISTRY = registry();
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
private static final RegistryOps<Object> OPS = CONTEXT.ops();
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private final MinecraftDimensionFactory factory = new MinecraftDimensionFactory(HANDLE, CONTEXT);
private static DimensionType dimensionType(ResourceKey<DimensionType> key) {
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value();
}
private static Map<?, ?> environment(EnvironmentAttributeMap map) {
return (Map<?, ?>) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS);
}
@SuppressWarnings("unchecked")
private static <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, AttributeEntry<?> entry) {
builder.put(attribute.key(), (AttributeEntry<T>) entry);
}
private static AttributeEntry<?> decoded(String id, Object raw) {
try {
return HANDLE.decodeEntry(attribute(id), raw, HANDLE.plainContext());
} catch(DecodeException e) {
throw new AssertionError(id + ": " + e.getMessage(), e);
}
}
private PackParents prepare(ConfigPack pack, Map<Attribute<?>, AttributeEntry<?>> entries, Map<String, RegistryKey> parentIds) {
AttributeMap.Builder builder = AttributeMap.builder();
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, builder.build(), parentIds, Map.of());
parents.beginLoad(CONTEXT);
return parents.prepare(pack, Optional.of(attributes), report);
}
private PackParents prepare(Map<Attribute<?>, AttributeEntry<?>> entries) {
return prepare(PACK, entries, Map.of());
}
private PackParents bare() {
parents.beginLoad(CONTEXT);
return parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
}
@Test
void noEntriesMatchesParent() {
DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD);
DimensionType built = factory.create(prepare(Map.of()), null);
assertEquals(overworld, built);
assertNotSame(overworld, built);
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void noAttributesMatchesTheParent() {
DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD);
DimensionType built = factory.create(bare(), null);
assertEquals(overworld, built);
assertNotSame(overworld, built);
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void createdTypeRegistersBesideItsParent() {
assertRegistersBesideOverworld(factory.create(prepare(Map.of()), null));
assertRegistersBesideOverworld(factory.create(bare(), null));
}
private static void assertRegistersBesideOverworld(DimensionType built) {
MappedRegistry<DimensionType> registry = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable());
registry.register(BuiltinDimensionTypes.OVERWORLD, dimensionType(BuiltinDimensionTypes.OVERWORLD), RegistrationInfo.BUILT_IN);
ResourceKey<DimensionType> key = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("terra", "test"));
assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN));
}
@Test
void equivalentInputMatchesVanilla() {
DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER);
PackAttributeTable table = PackAttributeTable.of(REGISTRY);
AttributeSlots netherSlots = new VanillaParentReader(HANDLE, CONTEXT).dimension(nether, table, FAIL);
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
List<Attribute<?>> attributes = new ArrayList<>();
table.environment().forEach(bound -> attributes.add(bound.attribute()));
table.dimension().forEach(field -> attributes.add(field.attribute()));
for(Attribute<?> attribute : attributes) {
AttributeEntry<?> entry = netherSlots.get(attribute);
if(entry != null) entries.put(attribute, entry);
}
assertTrue(entries.size() > 5, "the nether has few entries: " + entries.size());
DimensionType built = factory.create(prepare(entries), null);
assertEquals(nether.hasFixedTime(), built.hasFixedTime());
assertEquals(nether.hasSkyLight(), built.hasSkyLight());
assertEquals(nether.hasCeiling(), built.hasCeiling());
assertEquals(nether.hasEnderDragonFight(), built.hasEnderDragonFight());
assertEquals(nether.coordinateScale(), built.coordinateScale());
assertEquals(nether.minY(), built.minY());
assertEquals(nether.height(), built.height());
assertEquals(nether.logicalHeight(), built.logicalHeight());
assertEquals(nether.infiniburn().unwrapKey(), built.infiniburn().unwrapKey());
assertEquals(nether.ambientLight(), built.ambientLight());
assertEquals(nether.monsterSettings(), built.monsterSettings());
assertEquals(nether.skybox(), built.skybox());
assertEquals(nether.cardinalLightType(), built.cardinalLightType());
assertEquals(Optional.empty(), built.defaultClock());
assertEquals(nether.defaultClock(), built.defaultClock());
Map<?, ?> expected = environment(nether.attributes());
Map<?, ?> actual = environment(built.attributes());
for(Object key : expected.keySet()) assertEquals(expected.get(key), actual.get(key), String.valueOf(key));
assertEquals(List.of(), warnings);
}
@Test
void netherParentHasNoClock() {
PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
DimensionType built = factory.create(pack, null);
assertEquals(Optional.empty(), built.defaultClock());
assertEquals(dimensionType(BuiltinDimensionTypes.NETHER), built);
assertEquals(List.of(), warnings);
}
@Test
void packEntriesGoOnTheDimension() {
String fastLava = "minecraft:gameplay/fast_lava";
DimensionType built = factory.create(prepare(Map.of(attribute(fastLava), decoded(fastLava, true))), null);
assertTrue(built.attributes().contains(vanilla(fastLava)));
assertEquals(true, environment(built.attributes()).get(fastLava));
assertEquals(List.of(), warnings);
}
@Test
void invalidHeightIsSkippedAlone() {
String ambientLight = "terra:dimension/ambient_light";
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(attribute("terra:dimension/height"), AttributeEntry.override(100));
entries.put(attribute(ambientLight), decoded(ambientLight, 0.5));
PackParents pack = prepare(entries);
DimensionType built = factory.create(pack, null);
assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: "
+ "logical_height cannot be higher than height"), warnings);
assertEquals(384, built.height());
assertEquals(0.5f, built.ambientLight());
assertEquals(384, factory.generationSettings(pack, built).height().getRange());
}
@Test
void invalidHeightKeepsThePacksAttributes() {
String fastLava = "minecraft:gameplay/fast_lava";
String height = "terra:dimension/height";
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(attribute(height), AttributeEntry.override(100));
entries.put(attribute(fastLava), decoded(fastLava, true));
assertInvalidHeightKeepsFastLava(prepare(entries), fastLava);
warnings.clear();
OpenRegistryImpl<Attribute<?>> narrow = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
narrow.register(attribute(height).getRegistryKey(), attribute(height));
narrow.register(attribute(fastLava).getRegistryKey(), attribute(fastLava));
assertInvalidHeightKeepsFastLava(prepare(MinecraftAttributeParentsTest.pack("test", narrow), entries, Map.of()), fastLava);
}
private void assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) {
DimensionType built = factory.create(pack, null);
assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: "
+ "logical_height cannot be higher than height"), warnings);
assertEquals(384, built.height());
assertTrue(built.attributes().contains(vanilla(fastLava)));
assertEquals(true, environment(built.attributes()).get(fastLava));
}
@Test
void validHeightOverrideReachesBoth() {
String minY = "terra:dimension/min_y";
String height = "terra:dimension/height";
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(attribute(minY), decoded(minY, -128));
entries.put(attribute(height), decoded(height, 512));
PackParents pack = prepare(entries);
DimensionType built = factory.create(pack, null);
GenerationSettings settings = factory.generationSettings(pack, built);
assertEquals(-128, built.minY());
assertEquals(512, built.height());
assertEquals(-128, settings.height().getMin());
assertEquals(512, settings.height().getRange());
assertEquals(List.of(), warnings);
}
@Test
void timelineTagIsUsed() {
TagKey<Timeline> tag = TagKey.create(Registries.TIMELINE, Identifier.parse("minecraft:in_overworld"));
DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER);
assertNotEquals(Optional.of(tag), nether.timelines().unwrapKey());
PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
DimensionType built = factory.create(pack, tag);
assertTrue(built.timelines() instanceof HolderSet.Named<?>, String.valueOf(built.timelines()));
assertEquals(Optional.of(tag), built.timelines().unwrapKey());
assertEquals(List.of(), warnings);
}
@Test
void rejectedTimelineTag() {
TagKey<Timeline> tag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:nope"));
HolderLookup.RegistryLookup<Timeline> timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE);
HolderLookup.RegistryLookup<Timeline> withoutTag = new HolderLookup.RegistryLookup.Delegate<>() {
@Override
public HolderLookup.RegistryLookup<Timeline> parent() {
return timelines;
}
@Override
public Optional<HolderSet.Named<Timeline>> get(TagKey<Timeline> key) {
return key.equals(tag) ? Optional.empty() : timelines.get(key);
}
};
HolderLookup.Provider registries = HolderLookup.Provider.create(REGISTRIES.listRegistries()
.map(lookup -> lookup.key().equals(Registries.TIMELINE) ? withoutTag : lookup));
MinecraftDimensionFactory strict = new MinecraftDimensionFactory(HANDLE, VanillaContext.of(registries, key -> null));
DimensionType built = strict.create(prepare(Map.of()), tag);
assertEquals(1, warnings.size(), String.valueOf(warnings));
String prefix = "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: ";
assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst());
assertTrue(Character.isLowerCase(warnings.getFirst().charAt(prefix.length())), warnings.getFirst());
assertEquals(dimensionType(BuiltinDimensionTypes.OVERWORLD).timelines().unwrapKey(), built.timelines().unwrapKey());
}
@Test
void unappliedPackEntriesAreDebugLogged() {
Attribute<Integer> own = HANDLE.attributeBuilder(AttributeKey.<Integer>parse("addon:own"),
HANDLE.types().integer(), 0).build();
Registry<Attribute<?>> registry = registry(own);
PackParents pack = prepare(MinecraftAttributeParentsTest.pack("test", registry), Map.of(own, AttributeEntry.override(3)),
Map.of());
factory.create(pack, null);
assertEquals(List.of("Pack \"test\": attribute \"addon:own\" is not applied on this platform"), debugs);
}
private static void assertOverworldGeneration(GenerationSettings settings) {
assertEquals(-64, settings.height().getMin());
assertEquals(384, settings.height().getRange());
assertEquals(63, settings.sealevel());
assertEquals(true, settings.mobGeneration());
assertEquals(64, settings.spawnHeight());
}
private GenerationSettings generation(PackParents pack) {
return factory.generationSettings(pack, factory.create(pack, null));
}
@Test
void generationSettingsFromAttributes() {
assertOverworldGeneration(generation(prepare(Map.of())));
String seaLevel = "terra:world/sea_level";
String spawnHeight = "terra:world/spawn_height";
String mobGeneration = "terra:world/mob_generation";
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(attribute(seaLevel), decoded(seaLevel, 40));
entries.put(attribute(spawnHeight), decoded(spawnHeight, 90));
entries.put(attribute(mobGeneration), decoded(mobGeneration, false));
GenerationSettings settings = generation(prepare(entries));
assertEquals(40, settings.sealevel());
assertEquals(90, settings.spawnHeight());
assertEquals(false, settings.mobGeneration());
assertEquals(-64, settings.height().getMin());
assertEquals(384, settings.height().getRange());
assertEquals(List.of(), warnings);
}
@Test
void generationWithoutAttributes() {
assertOverworldGeneration(generation(bare()));
OpenRegistryImpl<Attribute<?>> noWorld = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
ATTRIBUTES.stream()
.filter(attribute -> !attribute.getRegistryKey().toString().startsWith("terra:world/"))
.forEach(attribute -> noWorld.register(attribute.getRegistryKey(), attribute));
PackParents pack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of());
assertNull(pack.table().seaLevel());
assertOverworldGeneration(generation(pack));
assertEquals(List.of(), warnings);
}
}
@@ -0,0 +1,73 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.SharedConstants;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.data.registries.VanillaRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.Bootstrap;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.attribute.EnvironmentAttribute;
import java.util.List;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeLookup;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
final class MinecraftTestSupport {
static {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
}
static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup();
static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null);
static final AttributeHandle HANDLE = new AttributeHandleImpl();
static final List<Attribute<?>> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE);
private static final Registry<Attribute<?>> TABLE = registry();
static final AttributeLookup LOOKUP = key -> {
RegistryKey id;
try {
id = RegistryKey.parseNamespaced(key);
} catch(IllegalArgumentException e) {
throw new DecodeException("unknown attribute", e);
}
return TABLE.get(id).orElseThrow(() -> new DecodeException("unknown attribute"));
};
private MinecraftTestSupport() { }
static List<HolderLookup.RegistryLookup<?>> loadContext(net.minecraft.core.Registry.PendingTags<?>... pending) {
return TagLoader.buildUpdatedLookups(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), List.of(pending));
}
static Registry<Attribute<?>> registry(Attribute<?>... extra) {
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
ATTRIBUTES.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute));
for(Attribute<?> attribute : extra) registry.register(attribute.getRegistryKey(), attribute);
return registry;
}
@SuppressWarnings("unchecked")
static <T> Attribute<T> attribute(String id) {
AttributeKey<T> key = AttributeKey.parse(id);
return (Attribute<T>) TABLE.get(key.getRegistryKey()).orElseThrow(() -> new IllegalArgumentException("no attribute " + id));
}
static EnvironmentAttribute<?> vanilla(String id) {
return BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getOptional(Identifier.parse(id))
.orElseThrow(() -> new IllegalArgumentException("no vanilla attribute " + id));
}
}
@@ -0,0 +1,416 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TimelineTags;
import net.minecraft.world.clock.WorldClock;
import net.minecraft.world.timeline.Timeline;
import net.minecraft.world.timeline.Timelines;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeMap;
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.ScheduleTrack;
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
import com.dfsek.terra.mod.util.TagUtil;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla;
import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftTimelinesTest {
private static final com.dfsek.terra.api.registry.Registry<Attribute<?>> REGISTRY = registry();
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
private static final PackAttributeTable TABLE = PackAttributeTable.of(REGISTRY);
private static final RegistryKey SEASONS = RegistryKey.parse("mypack:seasons");
private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld");
private static final String SKY_COLOR = "minecraft:visual/sky_color";
private static final TagKey<Timeline> TERRA_TEST = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test"));
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private static Object argument(Attribute<?> attribute, Object raw) {
try {
return attribute.type().decodeArgument(Operation.OVERRIDE, raw, HANDLE.plainContext());
} catch(DecodeException e) {
throw new AssertionError(attribute.getRegistryKey() + ": " + e.getMessage(), e);
}
}
private static ScheduleTrack<?> track(Attribute<?> attribute, Object first, Object second) {
return new ScheduleTrack<>(Operation.OVERRIDE, List.of(new Keyframe(0, argument(attribute, first)),
new Keyframe(12000, argument(attribute, second))),
new Easing.Named("linear"));
}
private static AttributeSchedule schedule(RegistryKey clock, Map<RegistryKey, TimeMarker> markers) {
Attribute<?> sky = attribute(SKY_COLOR);
return new AttributeSchedule(clock, OptionalInt.of(24000), Map.of(sky, track(sky, "#78a7ff", "#000000")), markers);
}
private static AttributeSchedule skySchedule() {
return schedule(OVERWORLD, Map.of());
}
private record Load(MappedRegistry<Timeline> timelines, MappedRegistry<WorldClock> clocks, VanillaContext context) {
static Load create() {
MappedRegistry<WorldClock> clocks = bound(copy(Registries.WORLD_CLOCK));
MappedRegistry<Timeline> timelines = bound(copy(Registries.TIMELINE));
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
copy(Registries.BIOME), clocks, timelines),
MinecraftTestSupport.loadContext(), key -> null);
timelines.bindTags(Map.of(TimelineTags.IN_OVERWORLD, List.of(timelines.get(Timelines.OVERWORLD_DAY).orElseThrow(),
timelines.get(Timelines.MOON).orElseThrow()),
TimelineTags.UNIVERSAL, List.of()));
return new Load(timelines, clocks, context);
}
private static <T> MappedRegistry<T> bound(MappedRegistry<T> registry) {
try {
Method bind = Holder.Reference.class.getDeclaredMethod("bindValue", Object.class);
bind.setAccessible(true);
for(Map.Entry<ResourceKey<T>, T> entry : registered(registry).entrySet()) {
bind.invoke(registry.get(entry.getKey()).orElseThrow(), entry.getValue());
}
} catch(ReflectiveOperationException e) {
throw new AssertionError(e);
}
return registry;
}
@SuppressWarnings("unchecked")
private static <T> Map<ResourceKey<T>, T> registered(MappedRegistry<T> registry) throws ReflectiveOperationException {
java.lang.reflect.Field byValue = MappedRegistry.class.getDeclaredField("byValue");
byValue.setAccessible(true);
Map<ResourceKey<T>, T> values = new LinkedHashMap<>();
((Map<T, Holder.Reference<T>>) byValue.get(registry)).forEach((value, holder) -> values.put(holder.key(), value));
return values;
}
Holder.Reference<Timeline> timeline(ResourceKey<Timeline> key) {
return timelines.get(key).orElseThrow();
}
}
private PackParents prepare(List<Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey>> refs,
Map<RegistryKey, AttributeSchedule> definitions) {
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(), refs,
definitions);
parents.beginLoad(CONTEXT);
return parents.prepare(PACK, Optional.of(attributes), report);
}
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> id(String id) {
return Either.left(RegistryKey.parse(id));
}
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> tag(String namespace, String id) {
return Either.right(com.dfsek.terra.api.registry.key.TagKey.of(RegistryKey.of(namespace, id)));
}
private static String skipped(String schedule, String reason) {
return "Pack \"test\": schedule \"" + schedule + "\" skipped: " + reason;
}
private void assertOneWarningStartingWith(String prefix) {
assertEquals(1, warnings.size(), String.valueOf(warnings));
assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst());
}
@Test
void definitionParses() {
Timeline timeline = MinecraftTimelines.create(SEASONS, skySchedule(), TABLE, HANDLE, CONTEXT, report);
assertNotNull(timeline, String.valueOf(warnings));
assertEquals(Optional.of(24000), timeline.periodTicks());
assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes());
assertEquals(Optional.of(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.parse("minecraft:overworld"))),
timeline.clock().unwrapKey());
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void upperCaseIdsWarn() {
assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE,
CONTEXT, report)));
assertOneWarningStartingWith(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\""));
warnings.clear();
assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"),
Map.of()), TABLE, HANDLE, CONTEXT, report)));
assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\""));
warnings.clear();
AttributeSchedule upperMarker = schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"), new TimeMarker(6000, false)));
assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, upperMarker, TABLE, HANDLE, CONTEXT, report)));
assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"mypack:Noon\""));
}
@Test
void unknownClockIsSkipped() {
assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE, CONTEXT, report));
assertEquals(List.of(skipped("mypack:seasons", "no such clock \"test:nope\"")), warnings);
}
@Test
void terraTracksAreDropped() {
Attribute<?> sky = attribute(SKY_COLOR);
Attribute<?> temperature = attribute("terra:biome/temperature");
Map<Attribute<?>, ScheduleTrack<?>> tracks = new LinkedHashMap<>();
tracks.put(sky, track(sky, "#78a7ff", "#000000"));
tracks.put(temperature, track(temperature, 0.5, 1.0));
AttributeSchedule schedule = new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, Map.of());
Timeline timeline = MinecraftTimelines.create(SEASONS, schedule, TABLE, HANDLE, CONTEXT, report);
assertNotNull(timeline, String.valueOf(warnings));
assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes());
assertEquals(List.of(), warnings);
assertEquals(List.of("Pack \"test\": attribute \"terra:biome/temperature\" is not applied on this platform"), debugs);
}
@Test
void definitionsAreRegistered() {
Load load = Load.create();
int before = load.timelines().size();
PackParents pack = prepare(List.of(), Map.of(SEASONS, skySchedule()));
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
assertEquals(List.of(), warnings);
assertEquals(before + 1, load.timelines().size());
assertDoesNotThrow(load.timelines()::freeze);
Timeline seasons = load.timelines().getValue(Identifier.parse("mypack:seasons"));
assertNotNull(seasons);
assertEquals(Set.of(vanilla(SKY_COLOR)), seasons.attributes());
assertSame(load.clocks().get(Identifier.parse("minecraft:overworld")).orElseThrow(), seasons.clock());
}
@Test
void existingIdIsNotReplaced() {
Load load = Load.create();
int before = load.timelines().size();
PackParents pack = prepare(List.of(), Map.of(RegistryKey.parse("minecraft:day"), skySchedule()));
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
assertEquals(List.of(skipped("minecraft:day", "a timeline with this ID already exists")), warnings);
assertEquals(before, load.timelines().size());
load.timelines().freeze();
assertSame(REGISTRIES.lookupOrThrow(Registries.TIMELINE).getOrThrow(Timelines.OVERWORLD_DAY).value(),
load.timelines().getValue(Timelines.OVERWORLD_DAY));
}
@Test
void duplicateTimeMarkerIsDropped() {
Load load = Load.create();
int before = load.timelines().size();
Map<RegistryKey, TimeMarker> seasonsMarkers = new LinkedHashMap<>();
seasonsMarkers.put(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, true));
seasonsMarkers.put(RegistryKey.parse("mypack:dawn"), new TimeMarker(0, false));
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
definitions.put(SEASONS, schedule(OVERWORLD, seasonsMarkers));
definitions.put(RegistryKey.parse("mypack:first"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"),
new TimeMarker(13000, false))));
definitions.put(RegistryKey.parse("mypack:second"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"),
new TimeMarker(14000, false))));
PackParents pack = prepare(List.of(), definitions);
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
assertEquals(List.of(markerDropped("mypack:seasons", "minecraft:noon"), markerDropped("mypack:second", "mypack:dusk")),
warnings);
assertEquals(before + 3, load.timelines().size());
load.timelines().freeze();
Map<ResourceKey<?>, Exception> errors = new HashMap<>();
Timeline.validateRegistry(load.timelines(), errors);
assertEquals(Map.of(), errors);
assertEquals(Set.of("mypack:dawn"), markers(load.timelines().getValue(Identifier.parse("mypack:seasons"))));
assertEquals(Set.of("mypack:dusk"), markers(load.timelines().getValue(Identifier.parse("mypack:first"))));
Timeline second = load.timelines().getValue(Identifier.parse("mypack:second"));
assertEquals(Set.of(), markers(second));
assertEquals(Set.of(vanilla(SKY_COLOR)), second.attributes(), "the tracks stay");
}
private static String markerDropped(String schedule, String marker) {
return "Pack \"test\": schedule \"" + schedule + "\" time marker \"" + marker
+ "\" dropped: already defined for clock \"minecraft:overworld\"";
}
private static Set<String> markers(Timeline timeline) {
Set<String> markers = new HashSet<>();
timeline.registerTimeMarkers((key, marker) -> markers.add(key.identifier().toString()));
return markers;
}
@Test
void noRefsMeansNoTag() {
assertNull(MinecraftTimelines.tagFor(PACK, prepare(List.of(), Map.of())));
parents.beginLoad(CONTEXT);
assertNull(MinecraftTimelines.tagFor(PACK, parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(),
report)));
assertEquals(List.of(), warnings);
}
@Test
void upperCaseRefIsSkipped() {
Load load = Load.create();
PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of());
TagKey<Timeline> tag = assertDoesNotThrow(() -> MinecraftTimelines.tagFor(PACK, pack));
assertEquals(TERRA_TEST, tag);
assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\""));
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
MinecraftTimelines.fillTags(collect, load.timelines());
assertEquals(List.of(load.timeline(Timelines.OVERWORLD_DAY)), collect.get(TERRA_TEST));
assertEquals(1, warnings.size());
}
@Test
void tagsAreFilled() {
Load load = Load.create();
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
Holder.Reference<Timeline> villagers = load.timeline(Timelines.VILLAGER_SCHEDULE);
PackParents pack = prepare(List.of(id("minecraft:day"), tag("minecraft", "in_overworld"), id("minecraft:nope"),
tag("minecraft", "nope")), Map.of());
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack));
assertEquals(List.of(), warnings);
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon, villagers));
MinecraftTimelines.fillTags(collect, load.timelines());
assertEquals(List.of(day, moon, villagers), collect.get(TERRA_TEST));
assertEquals(List.of(day, moon, villagers), collect.get(TimelineTags.IN_OVERWORLD));
assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag")),
warnings);
}
@Test
void invalidRefsKeepParentTimelines() {
Load load = Load.create();
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:nope"), tag("minecraft", "nope")), Map.of());
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack));
assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\""));
warnings.clear();
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon));
MinecraftTimelines.fillTags(collect, load.timelines());
assertEquals(List.of(day, moon), collect.get(TERRA_TEST));
assertTrue(collect.get(TERRA_TEST).contains(day), "the day cycle");
assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag"),
"Pack \"test\", config \"pack.yml\": \"schedules\" ignored: no valid schedule; "
+ "the parent's timelines are kept"),
warnings);
}
@Test
void tagRefillsOnReload() {
Load load = Load.create();
Registry<Timeline> timelines = load.timelines();
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
PackParents pack = prepare(List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")),
Map.of(SEASONS, skySchedule()));
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
TagKey<Timeline> tag = MinecraftTimelines.tagFor(PACK, pack);
assertEquals(TERRA_TEST, tag);
HolderSet.Named<Timeline> dimensionTimelines = load.context().ops().getter(Registries.TIMELINE).orElseThrow().get(tag)
.orElseThrow();
assertFalse(dimensionTimelines.isBound());
MinecraftTimelines.bindPendingTags(load.timelines());
assertDoesNotThrow(load.timelines()::freeze);
Map<ResourceKey<?>, Exception> errors = new HashMap<>();
Timeline.validateRegistry(timelines, errors);
assertEquals(Map.of(), errors);
TagUtil.registerTimelineTags(timelines);
Holder.Reference<Timeline> seasons = timelines.get(Identifier.parse("mypack:seasons")).orElseThrow();
assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList());
assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow());
assertEquals(List.of(day, moon), timelines.get(TimelineTags.IN_OVERWORLD).orElseThrow().stream().toList());
assertTrue(seasons.is(TERRA_TEST));
int tagsBefore = frozenTags(load.timelines()).size();
parents.beginPackReload();
parents.prepare(PACK, Optional.of(new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(),
List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")),
Map.of(SEASONS, skySchedule()))), report);
TagUtil.registerTimelineTags(timelines);
parents.endPackReload();
assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow());
assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList());
assertEquals(tagsBefore, frozenTags(load.timelines()).size(), "the reload created no tag");
assertEquals(List.of(), warnings);
}
private static Map<?, ?> frozenTags(MappedRegistry<Timeline> registry) {
try {
java.lang.reflect.Field field = MappedRegistry.class.getDeclaredField("frozenTags");
field.setAccessible(true);
return (Map<?, ?>) field.get(registry);
} catch(ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
@Test
void beginLoadDropsPendingTags() {
Load load = Load.create();
PackParents pack = prepare(List.of(id("minecraft:day")), Map.of());
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack));
parents.beginLoad(CONTEXT);
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
MinecraftTimelines.fillTags(collect, load.timelines());
assertFalse(collect.containsKey(TERRA_TEST));
}
}
@@ -0,0 +1,106 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.BiomeTags;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.mod.util.TagUtil;
import com.dfsek.terra.mod.util.TagUtil.PlatformTagSource;
import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TagUtilTest {
private static final Identifier TERRA_ID = Identifier.parse("terra:test/biome");
private static final TagKey<Biome> HAS_SNOW = tag("mypack:has_snow");
private final List<String> warnings = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, m -> { });
private final MappedRegistry<Biome> registry = copy(Registries.BIOME);
private final Holder<Biome> terra = registry.get(Biomes.DESERT).orElseThrow();
private final Map<TagKey<Biome>, List<Holder<Biome>>> collect = new HashMap<>();
private static TagKey<Biome> tag(String id) {
return TagKey.create(Registries.BIOME, Identifier.parse(id));
}
private Optional<Holder<Biome>> lookup(Identifier id) {
return id.equals(TERRA_ID) ? Optional.of(terra) : registry.get(ResourceKey.create(Registries.BIOME, id))
.map(h -> h);
}
private void add(Map<Identifier, List<Identifier>> byParent, String... tags) {
Set<RegistryKey> keys = new LinkedHashSet<>();
for(String t : tags) keys.add(RegistryKey.parse(t));
TagUtil.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys)));
}
private static void bindTags(Holder<Biome> holder, TagKey<Biome> tag) throws ReflectiveOperationException {
Method bind = Holder.Reference.class.getDeclaredMethod("bindTags", Collection.class);
bind.setAccessible(true);
bind.invoke(holder, List.of(tag));
}
@Test
void platformTagsAreAdded() {
Holder<Biome> forest = registry.get(Biomes.FOREST).orElseThrow();
collect.put(BiomeTags.IS_FOREST, new ArrayList<>(List.of(forest)));
add(Map.of(), "mypack:has_snow", "minecraft:is_forest");
assertEquals(List.of(terra), collect.get(HAS_SNOW));
assertEquals(List.of(forest, terra), collect.get(BiomeTags.IS_FOREST));
assertEquals(List.of(), warnings);
}
@Test
void inheritedTagsStillApply() throws ReflectiveOperationException {
Holder<Biome> forest = registry.get(Biomes.FOREST).orElseThrow();
bindTags(forest, BiomeTags.IS_FOREST);
Identifier forestId = Biomes.FOREST.identifier();
add(Map.of(forestId, List.of(TERRA_ID)));
assertEquals(List.of(terra), collect.get(BiomeTags.IS_FOREST));
assertEquals(List.of(), warnings);
}
@Test
void upperCaseTagIsIgnored() {
add(Map.of(), "mypack:Has_Snow");
assertTrue(collect.isEmpty(), collect.toString());
assertEquals(1, warnings.size(), warnings.toString());
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": \"mypack:Has_Snow\" ignored: invalid ID "),
warnings.getFirst());
}
@Test
void missingMinecraftTagWarnsAndIsCreated() {
add(Map.of(), "minecraft:is_forrest");
assertEquals(List.of("Pack \"test\", config \"BIOME\": tag \"minecraft:is_forrest\" created: no such tag in the minecraft namespace"),
warnings);
assertEquals(List.of(terra), collect.get(tag("minecraft:is_forrest")));
}
}
@@ -0,0 +1,67 @@
package com.dfsek.terra.mod.attribute;
import net.minecraft.resources.Identifier;
import java.util.Set;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.mod.config.ProtoPlatformBiome;
final class TestBiome implements Biome {
private final String id;
private final int intId;
private final PlatformBiome platformBiome;
private final Context context = new Context();
TestBiome(String id, int intId, Identifier parent) {
this(id, intId, new ProtoPlatformBiome(parent));
}
TestBiome(String id, int intId, PlatformBiome platformBiome) {
this.id = id;
this.intId = intId;
this.platformBiome = platformBiome;
}
ProtoPlatformBiome proto() {
return (ProtoPlatformBiome) platformBiome;
}
@Override
public PlatformBiome getPlatformBiome() {
return platformBiome;
}
@Override
public int getColor() {
return 0;
}
@Override
public Set<String> getTags() {
return Set.of();
}
@Override
public int getIntID() {
return intId;
}
@Override
public String getID() {
return id;
}
@Override
public Context getContext() {
return context;
}
@Override
public String toString() {
return "TestBiome[" + id + "]";
}
}
@@ -0,0 +1,308 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.ARGB;
import net.minecraft.world.attribute.EnvironmentAttribute;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.timeline.Timeline;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import org.joml.Vector4f;
import org.joml.Vector4fc;
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.OptionalInt;
import java.util.Set;
import java.util.TreeSet;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
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.AttributeKey;
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.ScheduleTrack;
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.LOOKUP;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class VanillaCodecHarnessTest {
private static final RegistryOps<Object> OPS = CONTEXT.ops();
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final String FOG_COLOR = "minecraft:visual/fog_color";
private static final String CLOUD_COLOR = "minecraft:visual/cloud_color";
private static final String SKY_COLOR = "minecraft:visual/sky_color";
private static final String STAR_BRIGHTNESS = "minecraft:visual/star_brightness";
private static final String WATER_FOG_END = "minecraft:visual/water_fog_end_distance";
private static final String EYEBLOSSOM_OPEN = "minecraft:gameplay/eyeblossom_open";
private static final String SURFACE_SLIME_SPAWN_CHANCE = "minecraft:gameplay/surface_slime_spawn_chance";
private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld");
private static final RegistryKey NOON = RegistryKey.parse("mypack:noon");
private static final RegistryKey DUSK = RegistryKey.parse("mypack:dusk");
@SuppressWarnings("unchecked")
private static <V> Codec<V> codec(String id) {
return (Codec<V>) vanilla(id).valueCodec();
}
@SuppressWarnings("unchecked")
private static Map<String, Object> asMap(Object raw) {
return (Map<String, Object>) assertInstanceOf(Map.class, raw);
}
private static float c(int n) {
return (n + 0.25f) / 255f;
}
private static <T> Object argument(Attribute<T> attribute, Operation operation, Object raw) throws DecodeException {
return attribute.type().decodeArgument(operation, raw, PLAIN);
}
@Test
void bootstrapsVanilla() {
assertTrue(REGISTRIES.lookupOrThrow(Registries.BIOME).get(Biomes.PLAINS).isPresent());
assertTrue(REGISTRIES.lookupOrThrow(Registries.WORLD_CLOCK)
.get(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.withDefaultNamespace("overworld"))).isPresent());
assertTrue(REGISTRIES.lookupOrThrow(Registries.TIMELINE)
.get(ResourceKey.create(Registries.TIMELINE, Identifier.withDefaultNamespace("day"))).isPresent());
}
@Test
void hexColorsMatchVanilla() throws DecodeException {
Attribute<Color> fog = attribute(FOG_COLOR);
Object fogForm = fog.type().encode(fog.type().decode("#c0d8ff", PLAIN));
assertEquals("#c0d8ff", fogForm);
Codec<Vector3fc> fogCodec = codec(FOG_COLOR);
assertEquals(ARGB.vector3fFromRGB24(0xc0d8ff), VanillaCodecs.parse(fogCodec, fogForm, OPS));
Attribute<Color> cloud = attribute(CLOUD_COLOR);
Object cloudForm = cloud.type().encode(cloud.type().decode("#80ff0000", PLAIN));
assertEquals("#80ff0000", cloudForm);
Codec<Vector4fc> cloudCodec = codec(CLOUD_COLOR);
assertEquals(ARGB.vector4fFromARGB32(0x80ff0000), VanillaCodecs.parse(cloudCodec, cloudForm, OPS));
assertEquals(Color.rgb(0xc0d8ff), fog.type().decode(VanillaCodecs.encode(fogCodec, ARGB.vector3fFromRGB24(0xc0d8ff), OPS), PLAIN));
assertEquals(Color.argb(0x80ff0000),
cloud.type().decode(VanillaCodecs.encode(cloudCodec, ARGB.vector4fFromARGB32(0x80ff0000), OPS), PLAIN));
}
@Test
void floatListColorsMatchVanilla() throws DecodeException {
Attribute<Color> fog = attribute(FOG_COLOR);
Object fogForm = fog.type().encode(new Color(c(51), c(102), c(153), 1f));
assertEquals(3, assertInstanceOf(List.class, fogForm).size());
Vector3fc fogValue = VanillaCodecs.parse(VanillaCodecHarnessTest.<Vector3fc>codec(FOG_COLOR), fogForm, OPS);
assertEquals(0x336699, ARGB.colorFromVector3f(fogValue) & 0xFFFFFF);
assertEquals(new Vector3f(c(51), c(102), c(153)), fogValue, "vanilla keeps the float channels exactly");
Attribute<Color> cloud = attribute(CLOUD_COLOR);
Object cloudForm = cloud.type().encode(new Color(c(51), c(102), c(153), c(204)));
List<?> cloudList = assertInstanceOf(List.class, cloudForm);
assertEquals(4, cloudList.size());
assertEquals(c(204), cloudList.get(3), "alpha is last");
Vector4fc cloudValue = VanillaCodecs.parse(VanillaCodecHarnessTest.<Vector4fc>codec(CLOUD_COLOR), cloudForm, OPS);
assertEquals(0xcc336699, ARGB.colorFromVector4f(cloudValue));
assertEquals(new Vector4f(c(51), c(102), c(153), c(204)), cloudValue, "vanilla keeps the float channels exactly");
}
@Test
void triStateMatchesVanilla() throws DecodeException {
Attribute<TriState> eyeblossom = attribute(EYEBLOSSOM_OPEN);
Codec<net.minecraft.util.TriState> codec = codec(EYEBLOSSOM_OPEN);
Map<TriState, Object> forms = Map.of(TriState.TRUE, true, TriState.FALSE, false, TriState.DEFAULT, "default");
Map<TriState, net.minecraft.util.TriState> vanillaValues = Map.of(
TriState.TRUE, net.minecraft.util.TriState.TRUE,
TriState.FALSE, net.minecraft.util.TriState.FALSE,
TriState.DEFAULT, net.minecraft.util.TriState.DEFAULT);
for(TriState value : TriState.values()) {
Object form = eyeblossom.type().encode(value);
assertEquals(forms.get(value), form, value.name());
assertEquals(vanillaValues.get(value), VanillaCodecs.parse(codec, form, OPS), value.name());
assertEquals(value, eyeblossom.type().decode(VanillaCodecs.encode(codec, vanillaValues.get(value), OPS), PLAIN),
value.name());
}
}
@Test
void everyDefaultMatchesVanilla() {
List<String> mismatches = new ArrayList<>();
Set<String> checked = new TreeSet<>();
for(AttributeKey<?> key : MinecraftAttributes.all()) {
if(!key.getRegistryKey().getNamespace().equals("minecraft")) continue;
String id = key.toString();
String mismatch = defaultMismatch(attribute(id), vanilla(id));
if(mismatch != null) mismatches.add(id + ": " + mismatch);
checked.add(id);
}
assertEquals(List.of(), mismatches);
Set<String> vanillaIds = new TreeSet<>();
BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.keySet().forEach(id -> vanillaIds.add(id.toString()));
assertEquals(vanillaIds, checked, "every vanilla attribute has a Terra key in the minecraft namespace");
}
private static <T, V> String defaultMismatch(Attribute<T> attribute, EnvironmentAttribute<V> vanilla) {
if(attribute.defaultValue() == null) return "Terra has no default";
Object terraForm = attribute.type().encode(attribute.defaultValue());
Codec<V> codec = vanilla.valueCodec();
Object expected = VanillaCodecs.encode(codec, vanilla.defaultValue(), OPS);
Object actual;
try {
actual = VanillaCodecs.encode(codec, VanillaCodecs.parse(codec, terraForm, OPS), OPS);
} catch(DecodeException e) {
return "vanilla rejects " + terraForm + ": " + e.getMessage();
}
return expected.equals(actual) ? null : "Terra " + terraForm + " reads as " + actual + ", vanilla default is " + expected;
}
@Test
void modifierEntriesParse() throws DecodeException {
Attribute<Float> water = attribute(WATER_FOG_END);
Object multiply = HANDLE.encodeEntry(water, AttributeEntry.of(Operation.MULTIPLY, argument(water, Operation.MULTIPLY, 0.85)));
EnvironmentAttributeMap waterMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(WATER_FOG_END, multiply), OPS);
@SuppressWarnings("unchecked")
EnvironmentAttribute<Float> vanillaWater = (EnvironmentAttribute<Float>) vanilla(WATER_FOG_END);
assertTrue(waterMap.contains(vanillaWater));
assertEquals(85f, waterMap.applyModifier(vanillaWater, 100f), 1e-4f);
Attribute<Color> fog = attribute(FOG_COLOR);
Object blend = HANDLE.encodeEntry(fog, AttributeEntry.of(Operation.ALPHA_BLEND, argument(fog, Operation.ALPHA_BLEND, "#80ff0000")));
EnvironmentAttributeMap fogMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(FOG_COLOR, blend), OPS);
@SuppressWarnings("unchecked")
EnvironmentAttribute<Vector3fc> vanillaFog = (EnvironmentAttribute<Vector3fc>) vanilla(FOG_COLOR);
assertTrue(fogMap.contains(vanillaFog));
float alpha = 128 / 255f;
Vector3fc blended = fogMap.applyModifier(vanillaFog, new Vector3f(0, 0, 1));
assertEquals(alpha, blended.x(), 1e-3f, blended.toString());
assertEquals(0, blended.y(), 1e-3f, blended.toString());
assertEquals(1 - alpha, blended.z(), 1e-3f, blended.toString());
}
private static AttributeSchedule clockOnly() {
return new AttributeSchedule(OVERWORLD, OptionalInt.empty(), Map.of(), Map.of());
}
private static AttributeSchedule periodic(Map<Attribute<?>, ScheduleTrack<?>> tracks, Map<RegistryKey, TimeMarker> markers) {
return new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, markers);
}
private static AttributeSchedule withMarkers() {
Map<RegistryKey, TimeMarker> markers = new LinkedHashMap<>();
markers.put(NOON, new TimeMarker(12000, false));
markers.put(DUSK, new TimeMarker(13000, true));
return periodic(Map.of(), markers);
}
private static AttributeSchedule withTrack(String id, Operation operation, Easing ease, Object first, Object second)
throws DecodeException {
Attribute<?> attribute = attribute(id);
List<Keyframe> keyframes = List.of(new Keyframe(0, argument(attribute, operation, first)),
new Keyframe(12000, argument(attribute, operation, second)));
return periodic(Map.of(attribute, new ScheduleTrack<>(operation, keyframes, ease)), Map.of());
}
private static AttributeSchedule skyColorTrack() throws DecodeException {
return withTrack(SKY_COLOR, Operation.OVERRIDE, new Easing.Named("linear"), "#78a7ff", "#000000");
}
private static Map<String, AttributeSchedule> schedules() throws DecodeException {
Map<String, AttributeSchedule> schedules = new LinkedHashMap<>();
schedules.put("a: clock only", clockOnly());
schedules.put("b: period", periodic(Map.of(), Map.of()));
schedules.put("c: time markers", withMarkers());
schedules.put("d: override, linear", skyColorTrack());
schedules.put("e: maximum, constant", withTrack(SURFACE_SLIME_SPAWN_CHANCE, Operation.MAXIMUM, new Easing.Named("constant"),
0.25, 0.75));
schedules.put("f: cubic bezier", withTrack(STAR_BRIGHTNESS, Operation.OVERRIDE, new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f),
1.0, 0.0));
return schedules;
}
@Test
void schedulesParseAsTimelines() throws DecodeException {
for(Map.Entry<String, AttributeSchedule> entry : schedules().entrySet()) {
String name = entry.getKey();
AttributeSchedule schedule = entry.getValue();
Timeline timeline = VanillaCodecs.parse(Timeline.DIRECT_CODEC, HANDLE.encodeSchedule(schedule), OPS);
Object vanillaForm = VanillaCodecs.encode(Timeline.DIRECT_CODEC, timeline, OPS);
ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse("mypack:schedule"), asMap(vanillaForm), LOOKUP,
PLAIN);
assertEquals(List.of(), result.droppedTracks(), name);
assertEquals(Optional.empty(), result.skipped(), name);
assertEquals(Optional.of(schedule), result.schedule(), name);
}
}
@Test
void encodedSchedulesOmitDefaults() throws DecodeException {
Map<String, Object> clockOnly = HANDLE.encodeSchedule(clockOnly());
assertEquals(Map.of("clock", "minecraft:overworld"), clockOnly);
VanillaCodecs.parse(Timeline.DIRECT_CODEC, clockOnly, OPS);
Map<String, Object> markers = HANDLE.encodeSchedule(withMarkers());
Map<String, Object> encodedMarkers = asMap(markers.get("time_markers"));
assertFalse(asMap(encodedMarkers.get("mypack:noon")).containsKey("show_in_commands"));
assertEquals(true, asMap(encodedMarkers.get("mypack:dusk")).get("show_in_commands"));
VanillaCodecs.parse(Timeline.DIRECT_CODEC, markers, OPS);
Map<String, Object> track = HANDLE.encodeSchedule(skyColorTrack());
Map<String, Object> encodedTrack = asMap(asMap(track.get("tracks")).get(SKY_COLOR));
assertFalse(encodedTrack.containsKey("modifier"));
assertFalse(encodedTrack.containsKey("ease"));
VanillaCodecs.parse(Timeline.DIRECT_CODEC, track, OPS);
}
@Test
void vanillaTimelinesRoundTrip() throws DecodeException {
List<Holder.Reference<Timeline>> timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements().toList();
assertFalse(timelines.isEmpty());
for(Holder.Reference<Timeline> holder : timelines) {
String name = holder.key().identifier().toString();
Object first = VanillaCodecs.encode(Timeline.DIRECT_CODEC, holder.value(), OPS);
ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse(name), asMap(first), LOOKUP, PLAIN);
assertEquals(List.of(), result.droppedTracks(), name);
assertEquals(Optional.empty(), result.skipped(), name);
Map<String, Object> terraForm = HANDLE.encodeSchedule(result.schedule().orElseThrow());
Timeline reparsed = VanillaCodecs.parse(Timeline.DIRECT_CODEC, terraForm, OPS);
assertEquals(first, VanillaCodecs.encode(Timeline.DIRECT_CODEC, reparsed, OPS), name);
}
}
@Test
void reasonsStartLowerCase() {
DecodeException e = assertThrows(DecodeException.class, () -> VanillaCodecs.parse(Codec.INT, "x", OPS));
assertEquals("not a number: x", e.getMessage());
}
}
@@ -0,0 +1,97 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class VanillaContextTest {
static <T> MappedRegistry<T> copy(ResourceKey<? extends Registry<T>> key) {
MappedRegistry<T> registry = new MappedRegistry<>(key, Lifecycle.stable());
REGISTRIES.lookupOrThrow(key).listElements()
.forEach(holder -> registry.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN));
return registry;
}
@Test
void unknownIdsKeepLoadFreezable() {
MappedRegistry<DimensionType> dimensionTypes = copy(Registries.DIMENSION_TYPE);
MappedRegistry<NoiseGeneratorSettings> noiseSettings = copy(Registries.NOISE_SETTINGS);
MappedRegistry<Biome> biomes = copy(Registries.BIOME);
VanillaContext context = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(),
key -> null);
ResourceKey<DimensionType> nope = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope"));
assertFalse(context.dimensionTypes().get(nope).isPresent());
assertFalse(context.noiseSettings().get(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope")))
.isPresent());
assertFalse(context.biomes().get(ResourceKey.create(Registries.BIOME, Identifier.parse("minecraft:nope"))).isPresent());
assertFalse(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow().get(nope).isPresent());
Holder.Reference<DimensionType> overworld = context.dimensionTypes().getOrThrow(BuiltinDimensionTypes.OVERWORLD);
assertSame(dimensionTypes.get(BuiltinDimensionTypes.OVERWORLD).orElseThrow(), overworld);
assertTrue(overworld.canSerializeIn(context.dimensionTypes()));
assertTrue(overworld.canSerializeIn(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow()));
assertDoesNotThrow(dimensionTypes::freeze);
assertDoesNotThrow(noiseSettings::freeze);
assertDoesNotThrow(biomes::freeze);
assertEquals(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElementIds().count(), dimensionTypes.size());
assertSame(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value(),
overworld.value());
}
@Test
void tagsAreCreatedOnDemand() {
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
copy(Registries.BIOME)), MinecraftTestSupport.loadContext(),
key -> null);
TagKey<Biome> tag = TagKey.create(Registries.BIOME, Identifier.parse("terra:pack"));
assertTrue(context.ops().getter(Registries.BIOME).orElseThrow().get(tag).isPresent());
}
@Test
void staticTagsResolveThroughLoadContext() {
DimensionType overworld = REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value();
TagKey<Block> infiniburn = BlockTags.INFINIBURN_OVERWORLD;
assertTrue(BuiltInRegistries.BLOCK.get(infiniburn).isEmpty(), "the built-in registry already has the tag");
Registry.PendingTags<Block> pending = BuiltInRegistries.BLOCK.prepareTagReload(
new TagLoader.LoadResult<>(Registries.BLOCK, Map.of(infiniburn, List.of(Blocks.NETHERRACK.builtInRegistryHolder()))));
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
copy(Registries.BIOME), copy(Registries.WORLD_CLOCK),
copy(Registries.TIMELINE)),
MinecraftTestSupport.loadContext(pending), key -> null);
Map<?, ?> encoded = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, overworld, CONTEXT.ops());
assertEquals("#minecraft:infiniburn_overworld", encoded.get("infiniburn"));
DimensionType parsed = assertDoesNotThrow(() -> VanillaCodecs.parse(DimensionType.DIRECT_CODEC, encoded, context.ops()));
assertEquals(infiniburn, parsed.infiniburn().unwrapKey().orElseThrow());
}
}
@@ -0,0 +1,374 @@
package com.dfsek.terra.mod.attribute;
import com.mojang.serialization.Codec;
import net.minecraft.core.Holder;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ParticleOptions;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.attribute.EnvironmentAttribute;
import net.minecraft.world.attribute.EnvironmentAttributeMap;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSpecialEffects;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.value.Color;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry;
import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class VanillaParentReaderTest {
private static final RegistryOps<Object> OPS = CONTEXT.ops();
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final PackAttributeTable TABLE = PackAttributeTable.of(registry());
private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT);
private static final VanillaParentReader READER = new VanillaParentReader(HANDLE, CONTEXT);
private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles";
private static final String FOG_COLOR = "minecraft:visual/fog_color";
private static final String DEFAULT_CLOCK = "default_clock";
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
private static Biome biome(ResourceKey<Biome> key) {
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value();
}
private static DimensionType dimensionType(ResourceKey<DimensionType> key) {
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value();
}
private static List<Holder.Reference<Biome>> biomes() {
return REGISTRIES.lookupOrThrow(Registries.BIOME).listElements().toList();
}
private static List<Holder.Reference<DimensionType>> dimensionTypes() {
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements().toList();
}
@SuppressWarnings("unchecked")
private static Map<String, Object> encodeMap(Codec<?> codec, Object value) {
Object raw = VanillaCodecs.encode((Codec<Object>) codec, value, OPS);
return new LinkedHashMap<>((Map<String, Object>) assertInstanceOf(Map.class, raw));
}
private static Map<String, Object> climate(Biome biome) {
return encodeMap(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings);
}
private static Map<String, Object> effects(Biome biome) {
return encodeMap(BiomeSpecialEffects.CODEC, biome.getSpecialEffects());
}
private static void assertNoEntries(AttributeSlots slots, String what) {
for(Attribute<?> attribute : ATTRIBUTES) assertNull(slots.get(attribute), what + ": " + attribute.getRegistryKey());
}
@Test
void everyVanillaAttributeInTable() {
Set<EnvironmentAttribute<?>> bound = new HashSet<>();
for(PackAttributeTable.Bound b : TABLE.environment()) {
assertEquals(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(b.vanilla())),
b.attribute().getRegistryKey().toString());
bound.add(b.vanilla());
}
assertEquals(Set.copyOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.stream().toList()), bound);
assertEquals(51, bound.size());
assertEquals(51, TABLE.environment().size());
assertEquals(List.of(), TABLE.unapplied());
assertEquals(4, TABLE.climate().size());
assertEquals(5, TABLE.effects().size());
assertEquals(15, TABLE.dimension().size());
assertEquals(attribute("terra:biome/villager_type"), TABLE.villagerType());
assertEquals(attribute("terra:world/sea_level"), TABLE.seaLevel());
assertEquals(attribute("terra:world/spawn_height"), TABLE.spawnHeight());
assertEquals(attribute("terra:world/mob_generation"), TABLE.mobGeneration());
}
@Test
void terraScopeMatchesVanillaPositional() {
List<String> mismatches = new ArrayList<>();
for(PackAttributeTable.Bound b : TABLE.environment()) {
boolean anywhere = b.attribute().scope() == AttributeScope.ANYWHERE;
if(anywhere != b.vanilla().isPositional()) {
mismatches.add(b.attribute().getRegistryKey() + ": Terra " + b.attribute().scope() + ", vanilla positional "
+ b.vanilla().isPositional());
}
}
assertEquals(List.of(), mismatches);
}
@Test
void noRegistryMeansEmptyTable() {
PackAttributeTable table = PackAttributeTable.of(null);
assertEquals(List.of(), table.environment());
assertEquals(List.of(), table.climate());
assertEquals(List.of(), table.effects());
assertEquals(List.of(), table.dimension());
assertEquals(List.of(), table.unapplied());
assertNull(table.villagerType());
assertNull(table.seaLevel());
assertNull(table.spawnHeight());
assertNull(table.mobGeneration());
VanillaParentReader reader = new VanillaParentReader(HANDLE, VanillaContext.of(REGISTRIES, key -> VillagerType.DESERT));
assertNoEntries(reader.biome(Biomes.PLAINS, biome(Biomes.PLAINS), table, FAIL), "biome");
assertNoEntries(reader.dimension(dimensionType(BuiltinDimensionTypes.NETHER), table, FAIL), "dimension");
assertNoEntries(reader.generation(REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.OVERWORLD).value(), table), "generation");
assertNoEntries(AttributeSlots.EMPTY, "empty");
}
@Test
void addonAttributeIsUnapplied() {
Attribute<Float> custom = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:custom"), HANDLE.types().floatType(), 0f)
.build();
PackAttributeTable table = PackAttributeTable.of(registry(custom));
assertEquals(List.of(custom), table.unapplied());
assertEquals(51, table.environment().size());
assertNull(READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(custom));
}
@Test
void vanillaMapsRoundTrip() {
int nonEmpty = 0;
for(Holder.Reference<Biome> holder : biomes()) {
if(roundTrip(holder.key().identifier().toString(), holder.value().getAttributes(), true)) nonEmpty++;
}
for(Holder.Reference<DimensionType> holder : dimensionTypes()) {
if(roundTrip(holder.key().identifier().toString(), holder.value().attributes(), false)) nonEmpty++;
}
assertTrue(nonEmpty > 10, "few vanilla maps had entries: " + nonEmpty);
}
private static boolean roundTrip(String name, EnvironmentAttributeMap map, boolean positional) {
AttributeEntry<?>[] into = new AttributeEntry<?>[HANDLE.attributeCount()];
MAPS.toTerra(map, TABLE, into, (attribute, reason) -> fail(name + ": " + attribute.getRegistryKey() + " unreadable: " + reason));
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
for(Attribute<?> attribute : ATTRIBUTES) {
if(into[attribute.index()] != null) entries.put(attribute, into[attribute.index()]);
}
assertEquals(map.keySet().size(), entries.size(), name);
EnvironmentAttributeMap back = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, positional,
(attribute, reason) -> fail(name + ": " + attribute.getRegistryKey()
+ " skipped: " + reason));
assertEquals(map.keySet(), back.keySet(), name);
assertEquals(VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS),
VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, back, OPS), name);
return !entries.isEmpty();
}
@Test
void oldParticleFormIsRejected() throws DecodeException {
Attribute<Object> particles = attribute(AMBIENT_PARTICLES);
Attribute<Color> fog = attribute(FOG_COLOR);
Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand"));
Object newParticle = VanillaCodecs.encode(ParticleTypes.CODEC,
new BlockParticleOption(ParticleTypes.FALLING_DUST, Blocks.SAND.defaultBlockState()),
OPS);
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
entries.put(particles, HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN));
entries.put(fog, HANDLE.decodeEntry(fog, "#123456", PLAIN));
List<String> skipped = new ArrayList<>();
EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, true,
(attribute, reason) -> {
assertEquals(particles, attribute);
skipped.add(reason);
});
assertEquals(1, skipped.size());
assertFalse(skipped.getFirst().isBlank());
assertFalse(rejected.contains(EnvironmentAttributes.AMBIENT_PARTICLES));
assertTrue(rejected.contains(vanilla(FOG_COLOR)), "the other entry still applies");
AttributeEntry<Object> accepted = HANDLE.decodeEntry(particles, List.of(Map.of("particle", newParticle, "probability", 0.01)),
PLAIN);
EnvironmentAttributeMap map = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, accepted), true, FAIL);
List<net.minecraft.world.attribute.AmbientParticle> value = map.applyModifier(EnvironmentAttributes.AMBIENT_PARTICLES,
List.of());
assertEquals(1, value.size());
ParticleOptions particle = value.getFirst().particle();
BlockParticleOption block = assertInstanceOf(BlockParticleOption.class, particle);
assertEquals(Blocks.SAND.defaultBlockState(), block.getState());
}
@Test
void nullOverrideKeepsBase() {
Attribute<Color> fog = attribute(FOG_COLOR);
EnvironmentAttributeMap base = biome(Biomes.PLAINS).getAttributes();
EnvironmentAttributeMap result = MAPS.toVanilla(base, Map.of(fog, AttributeEntry.override(null)), true, FAIL);
assertEquals(base, result);
}
@Test
void readsBiomeFields() {
Attribute<?> temperature = attribute("terra:biome/temperature");
Attribute<?> precipitation = attribute("terra:biome/has_precipitation");
Attribute<?> villager = attribute("terra:biome/villager_type");
AttributeSlots plains = READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL);
assertEquals(AttributeEntry.override(0.8f), plains.get(temperature));
assertEquals(AttributeEntry.override(true), plains.get(precipitation));
assertNull(plains.get(villager), "the test context has no villager types");
AttributeSlots desert = READER.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL);
assertEquals(AttributeEntry.override(false), desert.get(precipitation));
assertEquals(AttributeEntry.override(Color.rgb(0x3f76e4)), plains.get(attribute("terra:biome/water_color")));
assertNull(plains.get(attribute("terra:biome/grass_color")));
VanillaParentReader withVillagers = new VanillaParentReader(HANDLE, VanillaContext.of(
REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null));
assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:desert")),
withVillagers.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL).get(villager));
assertNull(withVillagers.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(villager));
}
@Test
void readsBiomeEnvironment() {
Biome plains = biome(Biomes.PLAINS);
AttributeSlots slots = READER.biome(Biomes.PLAINS, plains, TABLE, FAIL);
int present = 0;
for(PackAttributeTable.Bound b : TABLE.environment()) {
if(plains.getAttributes().contains(b.vanilla())) {
assertNotNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString());
present++;
} else {
assertNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString());
}
}
assertTrue(present > 0);
}
@Test
void everyTerraPathIsVanillaField() {
Set<String> dimensionKeys = new HashSet<>();
List<Holder.Reference<DimensionType>> types = dimensionTypes();
assertEquals(4, types.size());
for(Holder.Reference<DimensionType> holder : types) {
dimensionKeys.addAll(encodeMap(DimensionType.DIRECT_CODEC, holder.value()).keySet());
}
for(PackAttributeTable.Field field : TABLE.dimension()) {
assertTrue(dimensionKeys.contains(field.name()), field.name() + " is not a dimension type field: " + dimensionKeys);
}
Set<String> biomeKeys = new HashSet<>();
for(Holder.Reference<Biome> holder : biomes()) {
biomeKeys.addAll(climate(holder.value()).keySet());
biomeKeys.addAll(effects(holder.value()).keySet());
}
for(PackAttributeTable.Field field : TABLE.climate()) {
assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys);
}
for(PackAttributeTable.Field field : TABLE.effects()) {
assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys);
}
}
@Test
void absentFieldsMatchTerraDefaults() {
List<String> mismatches = new ArrayList<>();
for(Holder.Reference<DimensionType> holder : dimensionTypes()) {
absentFields(holder.key().identifier().toString(), DimensionType.DIRECT_CODEC, holder.value(), TABLE.dimension(), mismatches);
}
for(ResourceKey<Biome> key : List.of(Biomes.PLAINS, Biomes.SWAMP, Biomes.PALE_GARDEN)) {
Biome biome = biome(key);
absentFields(key.identifier().toString(), Biome.ClimateSettings.CODEC.codec(), biome.climateSettings, TABLE.climate(),
mismatches);
absentFields(key.identifier().toString(), BiomeSpecialEffects.CODEC, biome.getSpecialEffects(), TABLE.effects(), mismatches);
}
assertEquals(List.of(), mismatches);
}
private static <V> void absentFields(String name, Codec<V> codec, V original, List<PackAttributeTable.Field> fields,
List<String> mismatches) {
Map<String, Object> json = encodeMap(codec, original);
for(PackAttributeTable.Field field : fields) {
if(field.name().equals(DEFAULT_CLOCK) || json.containsKey(field.name())) continue;
Map<String, Object> withDefault = new LinkedHashMap<>(json);
Object terraDefault = encodedDefault(field.attribute());
if(terraDefault != null) withDefault.put(field.name(), terraDefault);
try {
Map<String, Object> parsed = encodeMap(codec, VanillaCodecs.parse(codec, withDefault, OPS));
if(!json.equals(parsed)) {
mismatches.add(name + " " + field.name() + ": Terra default " + terraDefault + " reads as " + parsed.get(field.name()));
}
} catch(DecodeException e) {
mismatches.add(name + " " + field.name() + ": vanilla rejects Terra default " + terraDefault + ": " + e.getMessage());
}
}
}
private static <T> Object encodedDefault(Attribute<T> attribute) {
T value = attribute.defaultValue();
return value == null ? null : attribute.type().encode(value);
}
@Test
void readsDimensionFields() {
AttributeSlots overworld = READER.dimension(dimensionType(BuiltinDimensionTypes.OVERWORLD), TABLE, FAIL);
assertEquals(AttributeEntry.override(-64), overworld.get(attribute("terra:dimension/min_y")));
assertEquals(AttributeEntry.override(384), overworld.get(attribute("terra:dimension/height")));
assertEquals(AttributeEntry.override(true), overworld.get(attribute("terra:dimension/has_skylight")));
assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:overworld")),
overworld.get(attribute("terra:dimension/default_clock")));
AttributeSlots nether = READER.dimension(dimensionType(BuiltinDimensionTypes.NETHER), TABLE, FAIL);
assertEquals(AttributeEntry.override(null), nether.get(attribute("terra:dimension/default_clock")));
assertEquals(AttributeEntry.override(true), nether.get(attribute("terra:dimension/has_ceiling")));
assertEquals(AttributeEntry.override(4f), nether.get(attribute("minecraft:gameplay/sky_light_level")));
}
@Test
void readsGeneration() {
NoiseGeneratorSettings overworld = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.OVERWORLD).value();
AttributeSlots slots = READER.generation(overworld, TABLE);
assertEquals(AttributeEntry.override(63), slots.get(attribute("terra:world/sea_level")));
assertEquals(AttributeEntry.override(true), slots.get(attribute("terra:world/mob_generation")));
assertNull(slots.get(attribute("terra:world/spawn_height")));
NoiseGeneratorSettings nether = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
.getOrThrow(NoiseGeneratorSettings.NETHER).value();
assertEquals(AttributeEntry.override(32), READER.generation(nether, TABLE).get(attribute("terra:world/sea_level")));
}
}
@@ -25,6 +25,7 @@ import java.util.stream.Stream;
import com.dfsek.terra.addon.EphemeralAddon;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.lifecycle.util.LifecycleBiomeUtil;
import com.dfsek.terra.lifecycle.util.LifecycleUtil;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper;
@@ -82,22 +83,32 @@ public abstract class LifecyclePlatform extends ModPlatform {
@Override
public boolean reload() {
getTerraConfig().load(this);
boolean succeed = loadConfigPacks();
// Old packs keep their parents until the reloaded packs are prepared and in the chunk generators.
attributeParents().beginPackReload();
boolean succeed;
try {
succeed = loadConfigPacks();
if(server != null) {
LifecycleBiomeUtil.registerBiomes(server.registryAccess().lookupOrThrow(Registries.BIOME));
server.reloadResources(server.getPackRepository().getSelectedIds()).exceptionally(throwable -> {
LOGGER.warn("Failed to execute reload", throwable);
return null;
}).join();
server.getAllLevels().forEach(world -> {
if(world.getChunkSource().getGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) {
getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> {
chunkGeneratorWrapper.setPack(pack);
LOGGER.info("Replaced pack in chunk generator for world {}", world);
});
}
});
if(server != null) {
LifecycleBiomeUtil.registerBiomes(server.registryAccess().lookupOrThrow(Registries.BIOME),
LifecycleUtil.biomeFactory(this));
server.reloadResources(server.getPackRepository().getSelectedIds()).exceptionally(throwable -> {
LOGGER.warn("Failed to execute reload", throwable);
return null;
}).join();
server.getAllLevels().forEach(world -> {
if(world.getChunkSource().getGenerator() instanceof MinecraftChunkGeneratorWrapper chunkGeneratorWrapper) {
getConfigRegistry().get(chunkGeneratorWrapper.getPack().getRegistryKey()).ifPresent(pack -> {
chunkGeneratorWrapper.setPack(pack);
LOGGER.info("Replaced pack in chunk generator for world {}", world);
});
}
});
LOGGER.info("Packs reloaded; dimension types, generation settings, timelines and existing biomes need a restart " +
"or new world.");
}
} finally {
attributeParents().endPackReload();
}
return succeed;
}
@@ -0,0 +1,28 @@
package com.dfsek.terra.lifecycle.mixin;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.RegistryLoadTask;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import java.util.List;
import com.dfsek.terra.lifecycle.util.LoadContextHolder;
@Mixin(RegistryLoadTask.class)
public abstract class RegistryLoadTaskMixin implements LoadContextHolder {
@Unique
private @Nullable List<HolderLookup.RegistryLookup<?>> terra$contextRegistries;
@Override
public @Nullable List<HolderLookup.RegistryLookup<?>> terra_contextRegistries() {
return terra$contextRegistries;
}
@Override
public void terra_setContextRegistries(List<HolderLookup.RegistryLookup<?>> contextRegistries) {
this.terra$contextRegistries = contextRegistries;
}
}
@@ -1,11 +1,13 @@
package com.dfsek.terra.lifecycle.mixin.lifecycle;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.RegistryLoadTask;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceManagerRegistryLoadTask;
import net.minecraft.world.item.enchantment.Enchantment;
@@ -14,6 +16,7 @@ import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraft.world.timeline.Timeline;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
@@ -22,18 +25,29 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import com.dfsek.terra.lifecycle.LifecyclePlatform;
import com.dfsek.terra.lifecycle.mixin.RegistryLoadTaskAccessor;
import com.dfsek.terra.lifecycle.util.LifecycleUtil;
import com.dfsek.terra.lifecycle.util.LoadContextHolder;
import com.dfsek.terra.lifecycle.util.RegistryHack;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.attribute.VanillaContext;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
@Mixin(RegistryDataLoader.class)
public class RegistryDataLoaderMixin {
// Until the load finishes, the static registries' tags are only in these lookups.
@Inject(method = "createContext", at = @At("HEAD"))
private static void captureContext(List<HolderLookup.RegistryLookup<?>> contextRegistries, List<RegistryLoadTask<?>> loadTasks,
CallbackInfoReturnable<RegistryOps.RegistryInfoLookup> cir) {
for(RegistryLoadTask<?> task : loadTasks) ((LoadContextHolder) task).terra_setContextRegistries(contextRegistries);
}
// The thenApplyAsync callback in load(LoaderFactory, List, List, Executor): every registry populated, none frozen.
@Inject(
method = "lambda$load$2(Ljava/util/List;Ljava/util/Map;Ljava/lang/Void;)Lnet/minecraft/core/RegistryAccess$Frozen;",
@@ -54,10 +68,18 @@ public class RegistryDataLoaderMixin {
WritableRegistry<MultiNoiseBiomeSourceParameterList> multiNoiseBiomeSourceParameterLists = extractRegistry(loadTasks,
Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST).orElseThrow();
WritableRegistry<Enchantment> enchantments = extractRegistry(loadTasks, Registries.ENCHANTMENT).orElseThrow();
// Binds the datapack's timelines before the freeze, for the time-marker check.
WritableRegistry<Timeline> timelines = extractRegistry(loadTasks, Registries.TIMELINE).orElseThrow();
LifecyclePlatform.setRegistries(biomes, dimensionTypes, chunkGeneratorSettings, multiNoiseBiomeSourceParameterLists,
enchantments);
LifecycleUtil.initialize(biomes, worldPresets);
// After extractRegistry: its terra_bind gives the parents' holders their values before the freeze.
List<? extends WritableRegistry<?>> loaded = loadTasks.stream().map(RegistryDataLoaderMixin::getRegistry).toList();
List<HolderLookup.RegistryLookup<?>> context = Objects.requireNonNull(
((LoadContextHolder) loadTasks.getFirst()).terra_contextRegistries(), "the load built no context");
platform.attributeParents().beginLoad(
VanillaContext.ofLoad(loaded, context, VillagerTypeAccessor.getBiomeTypeToIdMap()::get));
LifecycleUtil.initialize(biomes, timelines, worldPresets);
}
}
@@ -4,23 +4,25 @@ import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.attribute.AttributeReport;
import com.dfsek.terra.mod.attribute.MinecraftAttributeParents;
import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory;
import com.dfsek.terra.mod.attribute.PackParents;
import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.mod.config.ProtoPlatformBiome;
import com.dfsek.terra.mod.config.VanillaBiomeProperties;
import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor;
import com.dfsek.terra.mod.util.BiomeUtil;
import com.dfsek.terra.mod.util.MinecraftUtil;
import com.dfsek.terra.mod.util.TagUtil;
public final class LifecycleBiomeUtil {
@@ -30,78 +32,63 @@ public final class LifecycleBiomeUtil {
}
public static void registerBiomes(Registry<net.minecraft.world.level.biome.Biome> biomeRegistry) {
public static void registerBiomes(Registry<net.minecraft.world.level.biome.Biome> biomeRegistry, MinecraftBiomeFactory factory) {
logger.info("Registering biomes...");
CommonPlatform.get().getConfigRegistry().forEach(pack -> { // Register all Terra biomes.
BiomeUtil.TERRA_BIOME_MAP.clear();
BiomeUtil.TERRA_BIOME_PLATFORM_TAGS.clear();
ModPlatform platform = CommonPlatform.get();
MinecraftAttributeParents parents = platform.attributeParents();
platform.getConfigRegistry().forEach(pack -> { // Register all Terra biomes.
PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack),
AttributeReport.logging(pack));
pack.getCheckedRegistry(Biome.class)
.forEach((id, biome) -> registerBiome(biome, pack, id, biomeRegistry));
.forEach((id, biome) -> registerBiome(biome, pack, packParents, id, biomeRegistry, parents, factory));
});
logger.info("Terra biomes registered.");
}
/**
* Clones a Vanilla biome and injects Terra data to create a Terra-vanilla biome delegate.
* Builds a Terra biome's vanilla biome from its vanilla parent and its attribute entries, and registers it.
*
* @param biome The Terra BiomeBuilder.
* @param pack The ConfigPack this biome belongs to.
*/
private static void registerBiome(Biome biome, ConfigPack pack,
private static void registerBiome(Biome biome, ConfigPack pack, PackParents packParents,
com.dfsek.terra.api.registry.key.RegistryKey id,
Registry<net.minecraft.world.level.biome.Biome> registry) {
ResourceKey<net.minecraft.world.level.biome.Biome> vanilla = ((ProtoPlatformBiome) biome.getPlatformBiome()).get(registry);
if(vanilla == null) {
Registry<net.minecraft.world.level.biome.Biome> registry, MinecraftAttributeParents parents,
MinecraftBiomeFactory factory) {
ProtoPlatformBiome proto = (ProtoPlatformBiome) biome.getPlatformBiome();
ResourceKey<net.minecraft.world.level.biome.Biome> vanilla = proto.get(registry);
net.minecraft.world.level.biome.Biome vanillaBiome = vanilla == null ? null : registry.getValue(vanilla);
if(vanillaBiome == null) {
logger.error("""
Failed to get Vanilla Biome Regiestry key!
Failed to get Vanilla Biome!
Terra Biome ID: {}
Vanilla Biome: {}""", biome.getID(), biome.getPlatformBiome());
Vanilla Biome: {}""", biome.getID(), vanilla == null ? biome.getPlatformBiome() : vanilla.identifier());
return;
}
proto.setParentEntries(parents.biomeEntries(packParents, vanilla, vanillaBiome));
if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.wrapAsHolder(registry.getValue(vanilla)));
} else {
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
net.minecraft.world.level.biome.Biome vanilaBiome = registry.getValue(vanilla);
if(vanilaBiome == null) {
String vanillaBiomeName;
if(vanilla != null) {
vanillaBiomeName = vanilla.identifier().toString();
} else {
vanillaBiomeName = "NULL";
}
logger.error("""
Failed to get Vanilla Biome!
Terra Biome ID: {}
Vanilla Biome: {}""", biome.getID(), vanillaBiomeName);
return;
}
net.minecraft.world.level.biome.Biome minecraftBiome = BiomeUtil.createBiome(Objects.requireNonNull(vanilaBiome),
vanillaBiomeProperties);
Identifier identifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id));
if(registry.containsKey(identifier)) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(MinecraftUtil.getEntry(registry, identifier)
.orElseThrow());
} else {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(Registry.registerForHolder(registry,
MinecraftUtil.registerBiomeKey(identifier)
.identifier(),
minecraftBiome));
}
Map<ResourceKey<net.minecraft.world.level.biome.Biome>, ResourceKey<VillagerType>> villagerMap =
VillagerTypeAccessor.getBiomeTypeToIdMap();
villagerMap.put(ResourceKey.create(Registries.BIOME, identifier),
Objects.requireNonNullElse(vanillaBiomeProperties.getVillagerType(),
villagerMap.getOrDefault(vanilla, VillagerType.PLAINS)));
BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.identifier(), i -> new ArrayList<>()).add(identifier);
proto.setDelegate(registry.wrapAsHolder(vanillaBiome));
return;
}
}
Identifier identifier = Identifier.fromNamespaceAndPath("terra", BiomeUtil.createBiomeID(pack, id));
if(registry.containsKey(identifier)) {
// Registered by an earlier load; edits wait for the next registry load.
proto.setDelegate(MinecraftUtil.getEntry(registry, identifier).orElseThrow());
} else {
MinecraftBiomeFactory.Built built = factory.create(vanilla, vanillaBiome, biome, packParents, packParents.report());
proto.setDelegate(Registry.registerForHolder(registry, MinecraftUtil.registerBiomeKey(identifier).identifier(),
built.biome()));
VillagerTypeAccessor.getBiomeTypeToIdMap().put(ResourceKey.create(Registries.BIOME, identifier), built.villagerType());
}
BiomeUtil.TERRA_BIOME_PLATFORM_TAGS.put(identifier,
new TagUtil.PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags()));
BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.identifier(), i -> new ArrayList<>()).add(identifier);
}
}
@@ -6,16 +6,52 @@ import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraft.world.timeline.Timeline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import com.dfsek.terra.mod.attribute.AttributeReport;
import com.dfsek.terra.mod.attribute.MinecraftAttributeParents;
import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory;
import com.dfsek.terra.mod.attribute.MinecraftTimelines;
import com.dfsek.terra.mod.attribute.PackParents;
import com.dfsek.terra.mod.attribute.VanillaContext;
public final class LifecycleUtil {
public static void initialize(WritableRegistry<Biome> biomeMutableRegistry, WritableRegistry<WorldPreset> worldPresetMutableRegistry) {
CommonPlatform.get().getEventManager().callEvent(new PlatformInitializationEvent());
LifecycleBiomeUtil.registerBiomes(biomeMutableRegistry);
CommonPlatform.get().registerWorldTypes(
private static final Logger LOGGER = LoggerFactory.getLogger(LifecycleUtil.class);
/**
* Timelines go before world types: the dimension types name the packs' timeline tags.
*/
public static void initialize(WritableRegistry<Biome> biomeMutableRegistry, WritableRegistry<Timeline> timelineMutableRegistry,
WritableRegistry<WorldPreset> worldPresetMutableRegistry) {
ModPlatform platform = CommonPlatform.get();
platform.getEventManager().callEvent(new PlatformInitializationEvent());
LifecycleBiomeUtil.registerBiomes(biomeMutableRegistry, biomeFactory(platform));
registerTimelines(platform, timelineMutableRegistry);
platform.registerWorldTypes(
(id, preset) -> Registry.register(worldPresetMutableRegistry, ResourceKey.create(Registries.WORLD_PRESET, id), preset));
MinecraftTimelines.bindPendingTags(timelineMutableRegistry);
}
private static void registerTimelines(ModPlatform platform, WritableRegistry<Timeline> timelines) {
MinecraftAttributeParents parents = platform.attributeParents();
VanillaContext context = parents.context();
if(context == null) throw new IllegalStateException("no registry load has begun");
platform.getConfigRegistry().forEach(pack -> {
PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack),
AttributeReport.logging(pack));
MinecraftTimelines.register(pack, packParents, timelines, platform.getAttributeHandle(), context);
});
}
public static MinecraftBiomeFactory biomeFactory(ModPlatform platform) {
VanillaContext context = platform.attributeParents().context();
if(context == null) throw new IllegalStateException("no registry load has begun");
return new MinecraftBiomeFactory(platform.getAttributeHandle(), context);
}
}
@@ -0,0 +1,13 @@
package com.dfsek.terra.lifecycle.util;
import net.minecraft.core.HolderLookup;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public interface LoadContextHolder {
@Nullable List<HolderLookup.RegistryLookup<?>> terra_contextRegistries();
void terra_setContextRegistries(List<HolderLookup.RegistryLookup<?>> contextRegistries);
}
@@ -7,6 +7,7 @@
"RandomStateMixin",
"HolderReferenceInvoker",
"RegistryLoadTaskAccessor",
"RegistryLoadTaskMixin",
"BuiltInRegistriesMixin",
"MappedRegistryMixin",
"lifecycle.MinecraftServerMixin",