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

@@ -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",