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

This commit is contained in:
Zoe Gidiere committed 2026-11-09 17:12:55 -07:00
1 parent 44408a1b72
commit bfa126bc12
85 files changed
+3191 -1621

No files matched your search

@@ -4,12 +4,9 @@ import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
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.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
public class BukkitAddon implements BaseAddon {
@@ -28,16 +25,6 @@ public class BukkitAddon implements BaseAddon {
.register(this, ConfigPackPreLoadEvent.class)
.then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions())))
.global();
terraBukkitPlugin.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
@@ -22,61 +22,48 @@ import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.bukkit.config.BiomeAdditionsSoundTemplate;
import com.dfsek.terra.bukkit.config.BiomeMoodSoundTemplate;
import com.dfsek.terra.bukkit.config.BiomeParticleConfigTemplate;
import com.dfsek.terra.bukkit.config.EntityTypeTemplate;
import com.dfsek.terra.bukkit.config.MusicSoundTemplate;
import com.dfsek.terra.bukkit.config.SoundEventTemplate;
import com.dfsek.terra.bukkit.config.SpawnCostConfig;
import com.dfsek.terra.bukkit.config.SpawnEntryConfig;
import com.dfsek.terra.bukkit.config.SpawnSettingsTemplate;
import com.dfsek.terra.bukkit.config.SpawnTypeConfig;
import com.dfsek.terra.bukkit.config.VillagerTypeTemplate;
import dev.wyck.biome.TemperatureModifier;
import dev.wyck.biome.entity.MobCategory;
import dev.wyck.biome.entity.MobSpawnSettings;
import dev.wyck.environment.GrassColorModifier;
import dev.wyck.environment.particle.ParticleCatalog;
import dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
import dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Villager;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CancellationException;
import com.dfsek.terra.AbstractPlatform;
import com.dfsek.terra.api.block.state.BlockState;
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.bukkit.attribute.PaperDimensions;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.bukkit.handles.BukkitItemHandle;
import com.dfsek.terra.bukkit.handles.BukkitWorldHandle;
import com.dfsek.terra.bukkit.util.ServerThread;
import com.dfsek.terra.bukkit.world.BiomeHandler;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
public class BukkitPlatform extends AbstractPlatform {
private static final Logger LOGGER = LoggerFactory.getLogger(BukkitPlatform.class);
private static final long SERVER_THREAD_POLL_MILLIS = 50;
private final ItemHandle itemHandle = new BukkitItemHandle();
private final WorldHandle handle = new BukkitWorldHandle();
private final MinecraftAttributeParents attributeParents = new MinecraftAttributeParents(getAttributeHandle());
private final PaperDimensions dimensions = new PaperDimensions(getAttributeHandle(), attributeParents,
() -> !Bukkit.getOnlinePlayers().isEmpty());
private final TerraBukkitPlugin plugin;
private int generationThreads;
@@ -94,12 +81,44 @@ public class BukkitPlatform extends AbstractPlatform {
return plugin;
}
@Override
public AttributeParents getAttributeParents() {
return attributeParents;
}
public MinecraftAttributeParents attributeParents() {
return attributeParents;
}
public PaperDimensions dimensions() {
return dimensions;
}
@Override
public boolean reload() {
getTerraConfig().load(this);
boolean succeed = loadConfigPacks();
BiomeHandler.registerBiomes(getRawConfigRegistry());
BiomeHandler.addToVanillaTags(getRawConfigRegistry());
attributeParents.beginPackReload();
try {
boolean succeed = loadConfigPacks();
// Packs load off the server thread; registries, tags and generators change on it.
ServerThread.run(this::applyReloadedPacks, task -> plugin.getGlobalRegionScheduler().execute(plugin, task),
Bukkit::isGlobalTickThread, () -> Bukkit.isStopping() || !plugin.isEnabled(), SERVER_THREAD_POLL_MILLIS);
if(succeed) {
LOGGER.info("Packs reloaded; dimension types, generation settings, timelines and existing biomes need a restart.");
}
return succeed;
} catch(CancellationException e) {
LOGGER.warn("Packs not reloaded: the server stopped before they could be applied");
return false;
} finally {
attributeParents.endPackReload();
}
}
private void applyReloadedPacks() {
BiomeHandler.registerBiomes(this);
BiomeHandler.addToVanillaTags(this);
Bukkit.getWorlds().forEach(world -> {
if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) {
@@ -109,8 +128,6 @@ public class BukkitPlatform extends AbstractPlatform {
});
}
});
return succeed;
}
@Override
@@ -152,30 +169,7 @@ public class BukkitPlatform extends AbstractPlatform {
public void register(TypeRegistry registry) {
super.register(registry);
registry.registerLoader(BlockState.class, (type, o, loader, depthTracker) -> handle.createBlockState((String) o))
.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker))
.registerLoader(ResourceKey.class, (type, o, loader, depthTracker) -> {
NamespacedKey key = NamespacedKey.fromString(((String) o).toLowerCase(Locale.ROOT));
if(key == null) throw new LoadException("Invalid identifier: " + o, depthTracker);
return ResourceKey.of(key);
})
.registerLoader(GrassColorModifier.class,
(type, o, loader, depthTracker) -> GrassColorModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(TemperatureModifier.class,
(type, o, loader, depthTracker) -> TemperatureModifier.valueOf(((String) o).toUpperCase(
Locale.ROOT)))
.registerLoader(MobCategory.class, (type, o, loader, depthTracker) -> MobCategory.valueOf((String) o))
.registerLoader(ParticleCatalog.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(Villager.Type.class, VillagerTypeTemplate::new);
.registerLoader(PlatformBiome.class, (type, o, loader, depthTracker) -> parseBiome((String) o, depthTracker));
}
protected BukkitPlatformBiome parseBiome(String id, DepthTracker depthTracker) throws LoadException {
@@ -0,0 +1,38 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit;
import io.papermc.paper.plugin.bootstrap.BootstrapContext;
import io.papermc.paper.plugin.bootstrap.PluginBootstrap;
import io.papermc.paper.plugin.lifecycle.event.registrar.ReloadableRegistrarEvent;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import io.papermc.paper.registry.RegistryKey;
import com.dfsek.terra.bukkit.world.BiomeHandler;
/**
* Paper only offers tag lifecycle events to a bootstrapper.
*/
public class TerraBukkitBootstrap implements PluginBootstrap {
@Override
public void bootstrap(BootstrapContext context) {
context.getLifecycleManager().registerEventHandler(LifecycleEvents.TAGS.postFlatten(RegistryKey.BIOME), event -> {
if(event.cause() == ReloadableRegistrarEvent.Cause.RELOAD) BiomeHandler.addToReloadedTags(event.registrar());
});
}
}
@@ -38,9 +38,10 @@ import com.dfsek.terra.api.command.CommandSender;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.events.platform.CommandRegistrationEvent;
import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent;
import com.dfsek.terra.bukkit.attribute.PaperVanilla;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.bukkit.listeners.BiomeListener;
import com.dfsek.terra.bukkit.listeners.CommonListener;
import com.dfsek.terra.bukkit.listeners.DimensionListener;
import com.dfsek.terra.bukkit.world.BiomeHandler;
import com.dfsek.terra.bukkit.world.BukkitAdapter;
@@ -56,8 +57,10 @@ public class TerraBukkitPlugin extends JavaPlugin {
platform = new BukkitPlatform(this);
platform.getEventManager().callEvent(new PlatformInitializationEvent()); // Loads config packs
BiomeHandler.registerBiomes(platform.getRawConfigRegistry());
BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry());
platform.attributeParents().beginLoad(PaperVanilla.context(PaperVanilla.server().registryAccess()));
BiomeHandler.registerBiomes(platform);
platform.dimensions().registerPacks(platform.getRawConfigRegistry().entries());
BiomeHandler.addToVanillaTags(platform);
try {
PaperCommandManager<CommandSender> commandManager = getCommandSenderPaperCommandManager();
@@ -76,7 +79,7 @@ public class TerraBukkitPlugin extends JavaPlugin {
}
Bukkit.getPluginManager().registerEvents(new CommonListener(platform), this); // Register master event listener
Bukkit.getPluginManager().registerEvents(new BiomeListener(platform), this);
Bukkit.getPluginManager().registerEvents(new DimensionListener(platform.dimensions()), this);
}
@NotNull
@@ -0,0 +1,331 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import net.minecraft.core.Holder;
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.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.attribute.EnvironmentAttributeSystem;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.timeline.Timeline;
import org.bukkit.World;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
import com.dfsek.terra.minecraft.attribute.MinecraftDimensionFactory;
import com.dfsek.terra.minecraft.attribute.MinecraftTimelines;
import com.dfsek.terra.minecraft.attribute.PackAttributeTable;
import com.dfsek.terra.minecraft.attribute.PackParents;
import com.dfsek.terra.minecraft.attribute.TimelineRef;
import com.dfsek.terra.minecraft.attribute.VanillaCodecs;
import com.dfsek.terra.minecraft.attribute.VanillaContext;
import com.dfsek.terra.minecraft.attribute.WorldSettings;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
public final class PaperDimensions {
// Paper fixes these when it builds the level.
static final List<String> LEVEL_FIXED = List.of("min_y", "height", "has_skylight");
private static final Logger LOGGER = LoggerFactory.getLogger(PaperDimensions.class);
private static final String PACK_CONFIG = "pack.yml";
private static final String NOT_ON_THIS_PLATFORM = "not applied on this platform";
private static final String VANILLA_GENERATION = "vanilla-generation";
private static final String HEIGHT = "height";
private static final String LOGICAL_HEIGHT = "logical_height";
private static final List<AttributeKey<?>> UNSUPPORTED_GENERATION = List.of(AttributeKey.parse("terra:world/sea_level"),
AttributeKey.parse("terra:world/spawn_height"));
private final AttributeHandle handle;
private final MinecraftAttributeParents parents;
private final BooleanSupplier playersOnline;
private final Server server;
private final Consumer<String> info;
private final Consumer<String> warn;
// Direct lists survive tag reloads.
private final Map<String, TimelineRef.Direct> resolvedTimelines = new ConcurrentHashMap<>();
public PaperDimensions(AttributeHandle handle, MinecraftAttributeParents parents, BooleanSupplier playersOnline) {
this(handle, parents, playersOnline, new PaperServer(), LOGGER::info, LOGGER::warn);
}
PaperDimensions(AttributeHandle handle, MinecraftAttributeParents parents, BooleanSupplier playersOnline, Server server,
Consumer<String> info, Consumer<String> warn) {
this.handle = Objects.requireNonNull(handle, "handle");
this.parents = Objects.requireNonNull(parents, "parents");
this.playersOnline = Objects.requireNonNull(playersOnline, "playersOnline");
this.server = Objects.requireNonNull(server, "server");
this.info = Objects.requireNonNull(info, "info");
this.warn = Objects.requireNonNull(warn, "warn");
}
public void registerPacks(Iterable<ConfigPack> packs) {
VanillaContext context = context();
for(ConfigPack pack : packs) {
try {
registerPack(pack, context);
} catch(RuntimeException e) {
LOGGER.debug("Failed to read the attributes of pack {}", pack.getID(), e);
warn.accept("Pack \"" + pack.getID() + "\": timelines and dimension type skipped: its attributes could not be read");
}
}
}
private void registerPack(ConfigPack pack, VanillaContext context) {
Optional<PackAttributes> attributes = handle.pack(pack);
if(attributes.isEmpty()) return;
PackParents packParents = prepare(pack, attributes);
warnUnsupportedGeneration(attributes.get(), packParents.report());
if(!attributes.get().scheduleDefinitions().isEmpty()) {
try {
server.registerTimelines(registry -> MinecraftTimelines.register(pack, packParents, registry, handle, context));
} catch(RuntimeException e) {
LOGGER.debug("Wyck failed to register the timelines of pack {}", pack.getID(), e);
packParents.report().ignored(PACK_CONFIG, "schedule-definitions", "wyck could not register the timelines");
}
}
try {
recordTimelines(pack, server.timelines());
} catch(RuntimeException e) {
LOGGER.debug("Failed to resolve the schedules of pack {}", pack.getID(), e);
packParents.report().ignored(PACK_CONFIG, "schedules", "the timelines could not be resolved; the parent's are kept");
}
}
private static void warnUnsupportedGeneration(PackAttributes attributes, AttributeReport report) {
for(AttributeKey<?> key : UNSUPPORTED_GENERATION) {
if(attributes.entries().get(key).isPresent()) report.ignored(PACK_CONFIG, key.toString(), NOT_ON_THIS_PLATFORM);
}
if(attributes.parents().containsKey(VANILLA_GENERATION)) report.ignored(PACK_CONFIG, VANILLA_GENERATION, NOT_ON_THIS_PLATFORM);
}
void recordTimelines(ConfigPack pack, Registry<Timeline> registry) {
PackParents packParents = prepare(pack, handle.pack(pack));
MinecraftTimelines.Pending pending = MinecraftTimelines.pending(pack, packParents);
if(pending == null) {
resolvedTimelines.remove(pack.getID());
return;
}
MinecraftTimelines.Pending named = new MinecraftTimelines.Pending(pending.report(), pending.refs(), HolderSet.empty());
List<Holder<Timeline>> contents = MinecraftTimelines.contents(named,
tag -> registry.get(tag).map(set -> set.stream().toList()).orElse(null), registry);
if(contents.isEmpty()) {
resolvedTimelines.remove(pack.getID());
return;
}
List<ResourceKey<Timeline>> keys = contents.stream().flatMap(holder -> holder.unwrapKey().stream()).toList();
resolvedTimelines.put(pack.getID(), new TimelineRef.Direct(keys));
}
public Optional<Built> typeFor(ConfigPack pack, ResourceKey<DimensionType> worldTypeKey, DimensionType worldType, String worldName) {
Optional<PackAttributes> attributes = handle.pack(pack);
if(attributes.isEmpty()) return Optional.empty();
VanillaContext context = context();
PackParents packParents = parents.prepare(pack, attributes, AttributeReport.logging(pack), worldTypeKey);
MinecraftDimensionFactory factory = new MinecraftDimensionFactory(handle, context);
DimensionType type = factory.create(packParents, resolvedTimelines.get(pack.getID()));
Map<?, ?> encoded = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, type, context.ops());
Map<?, ?> world = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, worldType, context.ops());
Map<Object, Object> pinned = new LinkedHashMap<>(encoded);
for(String field : LEVEL_FIXED) pinned.put(field, world.get(field));
reportPinned(packParents, world, worldName);
if(pinned.get(LOGICAL_HEIGHT) instanceof Number logical && world.get(HEIGHT) instanceof Number height
&& logical.intValue() > height.intValue()) {
pinned.put(LOGICAL_HEIGHT, height);
reportLogicalHeight(packParents, attributes.get(), height, worldName);
}
Identifier key = MinecraftDimensionFactory.typeId(pack, worldTypeKey, !pinned.equals(encoded));
if(!pinned.equals(encoded)) {
try {
type = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, pinned, context.ops());
} catch(DecodeException e) {
throw new IllegalStateException("the dimension type with the world's fields was rejected: " + e.getMessage(), e);
}
}
return Optional.of(new Built(key, type, factory.worldSettings(packParents, type)));
}
private void reportPinned(PackParents packParents, Map<?, ?> world, String worldName) {
for(String field : LEVEL_FIXED) {
for(PackAttributeTable.Field bound : packParents.table().dimension()) {
if(!bound.name().equals(field)) continue;
Object value = resolveEncoded(bound.attribute(), packParents);
if(value != null && !sameValue(value, world.get(field))) {
packParents.report().notAppliedToWorld(bound.attribute().getRegistryKey().toString(), worldName);
}
}
}
}
private void reportLogicalHeight(PackParents packParents, PackAttributes attributes, Number height, String worldName) {
for(PackAttributeTable.Field bound : packParents.table().dimension()) {
if(!bound.name().equals(LOGICAL_HEIGHT) || attributes.entries().get(bound.attribute().key()).isEmpty()) continue;
if(resolveEncoded(bound.attribute(), packParents) instanceof Number value && value.intValue() > height.intValue()) {
packParents.report().notAppliedToWorld(bound.attribute().getRegistryKey().toString(), worldName);
}
}
}
private <T> @Nullable Object resolveEncoded(Attribute<T> attribute, PackParents packParents) {
T value = packParents.resolvePack(handle, attribute);
return value == null ? null : attribute.type().encode(value);
}
private static boolean sameValue(Object value, @Nullable Object other) {
if(value instanceof Number number && other instanceof Number otherNumber) {
return number.doubleValue() == otherNumber.doubleValue();
}
return value.equals(other);
}
/**
* A new type isn't registered while players are online: their clients already hold the registries.
*/
public void onWorldInit(World world, BukkitChunkGeneratorWrapper wrapper) {
ConfigPack pack = wrapper.getPack();
String keeps = "Pack \"" + pack.getID() + "\": world \"" + world.getName() + "\" keeps its dimension type";
Built built;
try {
Holder<DimensionType> current = server.dimensionType(world);
ResourceKey<DimensionType> currentKey = current.unwrapKey()
.orElseThrow(() -> new IllegalStateException("the world's dimension type has no key"));
Optional<Built> typed = typeFor(pack, currentKey, current.value(), world.getName());
if(typed.isEmpty()) return;
built = typed.get();
} catch(RuntimeException e) {
LOGGER.debug("Failed to build the dimension type of pack {} for world {}", pack.getID(), world.getName(), e);
warn.accept(keeps + ": the pack's could not be built");
return;
}
wrapper.setMobGeneration(built.settings().mobGeneration());
try {
boolean registered = server.isRegistered(built.key());
boolean online = playersOnline.getAsBoolean();
if(shouldRegister(registered, online)) {
server.registerDimension(built.key(), built.type());
} else if(!registered) {
info.accept(keeps + " until the server restarts, since players are online");
return;
}
} catch(RuntimeException e) {
LOGGER.debug("Failed to register dimension type {}", built.key(), e);
warn.accept(keeps + ": the pack's could not be registered");
return;
}
try {
server.applyDimension(world, built.key());
} catch(RuntimeException e) {
LOGGER.debug("Wyck failed to give world {} dimension type {}", world.getName(), built.key(), e);
warn.accept(keeps + ": wyck could not apply the pack's");
}
}
static boolean shouldRegister(boolean registered, boolean playersOnline) {
return !registered && !playersOnline;
}
private VanillaContext context() {
VanillaContext context = parents.context();
if(context == null) throw new IllegalStateException("no registry load has begun");
return context;
}
private PackParents prepare(ConfigPack pack, Optional<PackAttributes> attributes) {
return parents.prepare(pack, attributes, AttributeReport.logging(pack));
}
public record Built(Identifier key, DimensionType type, WorldSettings settings) { }
interface Server {
void registerTimelines(Consumer<WritableRegistry<Timeline>> registration);
Registry<Timeline> timelines();
Holder<DimensionType> dimensionType(World world);
boolean isRegistered(Identifier key);
void registerDimension(Identifier key, DimensionType type);
void applyDimension(World world, Identifier key);
}
private static final class PaperServer implements Server {
@Override
public void registerTimelines(Consumer<WritableRegistry<Timeline>> registration) {
WyckBridge.registerTimelines(registration);
}
@Override
public Registry<Timeline> timelines() {
return PaperVanilla.server().registryAccess().lookupOrThrow(Registries.TIMELINE);
}
@Override
public Holder<DimensionType> dimensionType(World world) {
return PaperVanilla.level(world).dimensionTypeRegistration();
}
@Override
public boolean isRegistered(Identifier key) {
return PaperVanilla.server().registryAccess().lookupOrThrow(Registries.DIMENSION_TYPE).containsKey(key);
}
@Override
public void registerDimension(Identifier key, DimensionType type) {
WyckBridge.registerDimension(key, type);
}
@Override
public void applyDimension(World world, Identifier key) {
WyckBridge.applyDimension(world, key);
ServerLevel level = PaperVanilla.level(world);
level.setEnvironmentAttributes(EnvironmentAttributeSystem.builder().addDefaultLayers(level).build());
level.updateSkyBrightness();
}
}
}
@@ -0,0 +1,88 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import com.dfsek.terra.minecraft.attribute.VanillaContext;
public final class PaperVanilla {
private static volatile Map<ResourceKey<Biome>, ResourceKey<VillagerType>> villagerTypes;
private PaperVanilla() { }
public static MinecraftServer server() {
try {
Object server = Bukkit.getServer();
if(server != null && server.getClass().getMethod("getServer").invoke(server) instanceof MinecraftServer minecraft) {
return minecraft;
}
} catch(ReflectiveOperationException | RuntimeException e) {
throw new IllegalStateException("not running on Paper", e);
}
throw new IllegalStateException("not running on Paper");
}
/**
* CraftBukkit isn't on the compile classpath.
*/
public static ServerLevel level(World world) {
try {
if(world.getClass().getMethod("getHandle").invoke(world) instanceof ServerLevel level) return level;
} catch(ReflectiveOperationException e) {
throw new IllegalStateException("not a Paper world", e);
}
throw new IllegalStateException("not a Paper world");
}
@SuppressWarnings("unchecked")
public static Map<ResourceKey<Biome>, ResourceKey<VillagerType>> villagerTypes() {
Map<ResourceKey<Biome>, ResourceKey<VillagerType>> cached = villagerTypes;
if(cached != null) return cached;
synchronized(PaperVanilla.class) {
if(villagerTypes == null) {
Object byBiome;
try {
Field field = VillagerType.class.getDeclaredField("BY_BIOME");
field.setAccessible(true);
byBiome = field.get(null);
} catch(ReflectiveOperationException e) {
throw new IllegalStateException("villager types by biome are not readable", e);
}
if(!(byBiome instanceof HashMap<?, ?> map)) throw new IllegalStateException("villager types by biome is not a hash map");
villagerTypes = (Map<ResourceKey<Biome>, ResourceKey<VillagerType>>) map;
}
return villagerTypes;
}
}
public static VanillaContext context(HolderLookup.Provider registries) {
return VanillaContext.of(registries, villagerTypes()::get);
}
}
@@ -0,0 +1,93 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import com.mojang.serialization.Lifecycle;
import dev.wyck.keys.ResourceKey;
import dev.wyck.level.dimension.Dimension;
import dev.wyck.registry.BiomeRegistry;
import dev.wyck.registry.DimensionRegistry;
import dev.wyck.registry.internal.RegistryId;
import dev.wyck.registry.internal.WyckRegistry;
import dev.wyck.registry.level.LevelStemEditor;
import dev.wyck.tags.TagSet;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.timeline.Timeline;
import org.bukkit.World;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
public final class WyckBridge {
private WyckBridge() { }
/**
* Wyck's decoder refuses a biome without a registered key.
*/
public static dev.wyck.biome.Biome biome(Identifier key, Biome biome) {
MappedRegistry<Biome> owner = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
var holder = owner.register(net.minecraft.resources.ResourceKey.create(Registries.BIOME, key), biome, RegistrationInfo.BUILT_IN);
owner.freeze();
return dev.wyck.biome.Biome.decode(holder).toBuilder().resourceKey(key(key)).build();
}
private static Dimension dimension(Identifier key, DimensionType type) {
MappedRegistry<DimensionType> owner = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable());
var holder = owner.register(net.minecraft.resources.ResourceKey.create(Registries.DIMENSION_TYPE, key), type,
RegistrationInfo.BUILT_IN);
owner.freeze();
return Dimension.decode(holder).toBuilder().resourceKey(key(key)).build();
}
@SuppressWarnings("unchecked")
public static void registerTimelines(Consumer<WritableRegistry<Timeline>> registration) {
WyckRegistry.of(RegistryId.TIMELINE).whileUnfrozen(r -> registration.accept((WritableRegistry<Timeline>) r.registry()));
}
public static void registerDimension(Identifier key, DimensionType type) {
DimensionRegistry.registry().register(dimension(key, type));
}
public static void applyDimension(World world, Identifier key) {
LevelStemEditor.create().dimension(Dimension.reference(key(key))).apply(world);
}
public static void registerBiomes(List<dev.wyck.biome.Biome> biomes) {
BiomeRegistry.registry().register(biomes);
}
public static void appendBiomeTag(TagKey<Biome> tag, Collection<Identifier> biomes) {
Set<dev.wyck.biome.Biome> members = new LinkedHashSet<>();
for(Identifier biome : biomes) members.add(dev.wyck.biome.Biome.reference(key(biome)));
TagSet.ofBiomes(key(tag.location()), members).append();
}
private static ResourceKey key(Identifier id) {
return ResourceKey.of(id.getNamespace(), id.getPath());
}
}
@@ -1,30 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.SoundEvent;
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 AmbientAdditionsSettings.builder()
.soundEvent(sound)
.tickChance(soundChance)
.build();
}
}
}
@@ -1,40 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.SoundEvent;
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 AmbientMoodSettings.builder()
.soundEvent(sound)
.tickDelay(soundCultivationTicks)
.blockSearchExtent(soundSpawnRange)
.soundPositionOffset(soundExtraDistance)
.build();
}
}
}
@@ -1,42 +0,0 @@
package com.dfsek.terra.bukkit.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.exceptions.CommandSyntaxException;
import dev.wyck.environment.particle.AmbientParticle;
import dev.wyck.environment.particle.ParticleCatalog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import com.dfsek.terra.bukkit.util.VanillaParticles;
public class BiomeParticleConfigTemplate implements ObjectTemplate<ParticleCatalog> {
private static final Logger LOGGER = LoggerFactory.getLogger(BiomeParticleConfigTemplate.class);
@Value("particle")
@Default
private String particle = null;
@Value("probability")
@Default
private Float probability = 0.1f;
@Override
public ParticleCatalog get() {
if(particle == null) {
return null;
}
try {
AmbientParticle parsed = VanillaParticles.parse(particle, probability);
return parsed == null ? null : new ParticleCatalog(List.of(parsed));
} catch(CommandSyntaxException | RuntimeException e) {
LOGGER.warn("Skipping particle \"{}\": {}", particle, e.getMessage());
return null;
}
}
}
@@ -1,22 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.entity.EntityType;
public class EntityTypeTemplate implements ObjectTemplate<EntityType> {
@Value("id")
@Default
private ResourceKey id = null;
@Override
public EntityType get() {
return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE)
.getOrThrow(id);
}
}
@@ -1,40 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
public class MusicSoundTemplate implements ObjectTemplate<Music> {
@Value("sound")
@Default
private SoundEvent sound = null;
@Value("min-delay")
@Default
private Integer minDelay = null;
@Value("max-delay")
@Default
private Integer maxDelay = null;
@Value("replace-current-music")
@Default
private Boolean replaceCurrentMusic = null;
@Override
public Music get() {
if(sound == null || minDelay == null || maxDelay == null || replaceCurrentMusic == null) {
return null;
} else {
return Music.builder()
.sound(sound)
.minDelay(minDelay)
.maxDelay(maxDelay)
.replaceCurrentMusic(replaceCurrentMusic)
.build();
}
}
}
@@ -1,29 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.environment.sounds.SoundEvent;
import dev.wyck.keys.ResourceKey;
public class SoundEventTemplate implements ObjectTemplate<SoundEvent> {
@Value("id")
@Default
private ResourceKey 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.variableRange(id);
} else {
return SoundEvent.fixedRange(id, distanceToTravel);
}
}
}
@@ -1,38 +0,0 @@
package com.dfsek.terra.bukkit.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 org.bukkit.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,42 +0,0 @@
package com.dfsek.terra.bukkit.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;
import dev.wyck.worldgen.valueproviders.IntProvider;
import org.bukkit.entity.EntityType;
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 EntityType getType() {
return type;
}
public IntProvider getCount() {
return IntProvider.uniform(groupSize.getMin(), groupSize.getMax());
}
@Override
public SpawnEntryConfig get() {
return this;
}
}
@@ -1,54 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.biome.entity.MobCategory;
import dev.wyck.biome.entity.MobSpawnSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class SpawnSettingsTemplate implements ObjectTemplate<MobSpawnSettings> {
private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class);
private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(false);
@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 = MobSpawnSettings.builder();
if(spawns != null) {
for(SpawnTypeConfig spawn : spawns) {
MobCategory group = spawn.getGroup();
for(SpawnEntryConfig entry : spawn.getEntries()) {
builder.addSpawn(entry.getType(), group, entry.getWeight(), entry.getCount());
}
}
}
if(costs != null) {
for(SpawnCostConfig cost : costs) {
builder.addMobSpawnCost(cost.getType(), cost.getMass(), cost.getGravity());
}
}
if(probability != null && PROBABILITY_WARNING_LOGGED.compareAndSet(false, true)) {
LOGGER.warn("Biome spawning.probability is ignored on this server version.");
}
return builder.build();
}
}
@@ -1,32 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.biome.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.bukkit.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 com.dfsek.terra.api.properties.Properties;
import dev.wyck.biome.TemperatureModifier;
import dev.wyck.biome.entity.MobSpawnSettings;
import dev.wyck.environment.GrassColorModifier;
import dev.wyck.environment.particle.AmbientParticle;
import dev.wyck.environment.particle.ParticleCatalog;
import dev.wyck.environment.sounds.AmbientAdditionsSettings;
import dev.wyck.environment.sounds.AmbientMoodSettings;
import dev.wyck.environment.sounds.Music;
import dev.wyck.environment.sounds.SoundEvent;
import org.bukkit.entity.Villager;
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 ParticleCatalog particleConfig = null;
@Value("climate.precipitation")
@Default
private Boolean precipitation = true;
@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 Villager.Type villagerType = null;
public Integer getFogColor() {
return fogColor;
}
public Integer getFoliageColor() {
return foliageColor;
}
public Integer getDryFoliageColor() {
return dryFoliageColor;
}
public Integer getGrassColor() {
return grassColor;
}
public Integer getWaterColor() {
return waterColor;
}
public Integer getWaterFogColor() {
return waterFogColor;
}
public Integer getSkyColor() {
return skyColor;
}
public GrassColorModifier getGrassColorModifier() {
return grassColorModifier;
}
public ParticleCatalog getParticles() {
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 Villager.Type getVillagerType() {
return villagerType;
}
}
@@ -1,22 +0,0 @@
package com.dfsek.terra.bukkit.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 dev.wyck.keys.ResourceKey;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import org.bukkit.entity.Villager;
public class VillagerTypeTemplate implements ObjectTemplate<Villager.Type> {
@Value("id")
@Default
private ResourceKey id = null;
@Override
public Villager.Type get() {
return RegistryAccess.registryAccess().getRegistry(RegistryKey.VILLAGER_TYPE)
.getOrThrow(id);
}
}
@@ -15,10 +15,14 @@ import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
public class BukkitBiomeProvider extends BiomeProvider implements Handle {
private final com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate;
private volatile com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate;
public BukkitBiomeProvider(com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate) { this.delegate = delegate; }
public void setDelegate(com.dfsek.terra.api.world.biome.generation.BiomeProvider delegate) {
this.delegate = delegate;
}
@Override
public @NotNull org.bukkit.block.Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z) {
return toBukkit(delegate.getBiome(x, y, z, worldInfo.getSeed()));
@@ -14,7 +14,7 @@ import com.dfsek.terra.bukkit.world.BukkitProtoWorld;
public class BukkitBlockPopulator extends BlockPopulator {
private final BlockState air;
private ConfigPack pack;
private volatile ConfigPack pack;
public BukkitBlockPopulator(ConfigPack pack, BlockState air) {
this.pack = pack;
@@ -47,8 +47,10 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
private static final Logger LOGGER = LoggerFactory.getLogger(BukkitChunkGeneratorWrapper.class);
private final BlockState air;
private final BukkitBlockPopulator blockPopulator;
private ChunkGenerator delegate;
private ConfigPack pack;
private volatile @Nullable BukkitBiomeProvider biomeProvider;
private volatile ChunkGenerator delegate;
private volatile ConfigPack pack;
private volatile boolean mobGeneration = true;
public BukkitChunkGeneratorWrapper(ChunkGenerator delegate, ConfigPack pack, BlockState air) {
@@ -64,7 +66,9 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
@Override
public @Nullable BiomeProvider getDefaultBiomeProvider(@NotNull WorldInfo worldInfo) {
return new BukkitBiomeProvider(pack.getBiomeProvider());
BukkitBiomeProvider provider = new BukkitBiomeProvider(pack.getBiomeProvider());
biomeProvider = provider;
return provider;
}
@Override
@@ -117,7 +121,11 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
@Override
public boolean shouldGenerateMobs() {
return true;
return mobGeneration;
}
public void setMobGeneration(boolean mobGeneration) {
this.mobGeneration = mobGeneration;
}
@Override
@@ -132,6 +140,9 @@ public class BukkitChunkGeneratorWrapper extends org.bukkit.generator.ChunkGener
public void setPack(ConfigPack pack) {
this.pack = pack;
setDelegate(pack.getGeneratorProvider().newInstance(pack));
BukkitBiomeProvider provider = biomeProvider;
if(provider != null) provider.setDelegate(pack.getBiomeProvider());
blockPopulator.setPack(pack);
}
@Override
@@ -1,73 +0,0 @@
package com.dfsek.terra.bukkit.listeners;
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Villager;
import org.bukkit.entity.ZombieVillager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityBreedEvent;
import java.util.Set;
import com.dfsek.terra.bukkit.BukkitPlatform;
import com.dfsek.terra.bukkit.world.BiomeHandler;
public class BiomeListener implements Listener {
private static final Set<SpawnReason> BIOME_TYPED_VILLAGER_REASONS = Set.of(
SpawnReason.SPAWNER_EGG, SpawnReason.DISPENSE_EGG, SpawnReason.SPAWNER, SpawnReason.COMMAND);
private final BukkitPlatform platform;
public BiomeListener(BukkitPlatform platform) {
this.platform = platform;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
BiomeHandler.addToVanillaTags(platform.getRawConfigRegistry());
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
SpawnReason reason = event.getSpawnReason();
if(event.getEntity() instanceof Villager villager && BIOME_TYPED_VILLAGER_REASONS.contains(reason)) {
applyBiomeType(villager);
} else if(event.getEntity() instanceof ZombieVillager zombieVillager && reason != SpawnReason.INFECTION) {
Villager.Type type = biomeType(zombieVillager);
if(type != null && zombieVillager.getVillagerType() == Villager.Type.PLAINS) {
zombieVillager.setVillagerType(type);
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBreed(EntityBreedEvent event) {
if(event.getEntity() instanceof Villager child && isNotPlains(event.getMother()) && isNotPlains(event.getFather())) {
applyBiomeType(child);
}
}
private static void applyBiomeType(Villager villager) {
Villager.Type type = biomeType(villager);
if(type != null && villager.getVillagerType() == Villager.Type.PLAINS) {
villager.setVillagerType(type);
}
}
private static Villager.Type biomeType(Entity entity) {
Location location = entity.getLocation();
if(!entity.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) return null;
return BiomeHandler.getVillagerType(entity.getWorld().getBiome(location));
}
private static boolean isNotPlains(LivingEntity parent) {
return parent instanceof Villager villager && villager.getVillagerType() != Villager.Type.PLAINS;
}
}
@@ -36,6 +36,7 @@ import java.util.List;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.bukkit.hooks.MultiverseGeneratorPluginHook;
import com.dfsek.terra.bukkit.world.BukkitBiomeInfo;
@@ -89,10 +90,8 @@ public class CommonListener implements Listener {
ResourceKey biomeKey = ResourceKey.of(wolf.getWorld().getBiome(wolf.getLocation()).getKey());
pack.getBiomeProvider().stream()
.filter(biome -> {
ResourceKey key = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(BukkitBiomeInfo.class)
.biomeKey();
return key.equals(biomeKey);
Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext();
return context.has(BukkitBiomeInfo.class) && context.get(BukkitBiomeInfo.class).biomeKey().equals(biomeKey);
})
.findFirst()
.ifPresent(biome -> {
@@ -0,0 +1,41 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.listeners;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
import com.dfsek.terra.bukkit.attribute.PaperDimensions;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
public class DimensionListener implements Listener {
private final PaperDimensions dimensions;
public DimensionListener(PaperDimensions dimensions) {
this.dimensions = dimensions;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onWorldInit(WorldInitEvent event) {
World world = event.getWorld();
if(world.getGenerator() instanceof BukkitChunkGeneratorWrapper wrapper) dimensions.onWorldInit(world, wrapper);
}
}
@@ -0,0 +1,67 @@
package com.dfsek.terra.bukkit.util;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
public final class ServerThread {
private static final int PENDING = 0;
private static final int RUNNING = 1;
private static final int ABANDONED = 2;
private ServerThread() { }
/**
* The caller must not hold a lock the server thread could wait on.
*/
public static void run(Runnable task, Executor serverThread, BooleanSupplier onServerThread, BooleanSupplier stopping,
long pollMillis) {
if(onServerThread.getAsBoolean()) {
task.run();
return;
}
AtomicInteger state = new AtomicInteger(PENDING);
CompletableFuture<Void> done = new CompletableFuture<>();
serverThread.execute(() -> {
if(!state.compareAndSet(PENDING, RUNNING)) return;
try {
task.run();
done.complete(null);
} catch(Throwable t) {
done.completeExceptionally(t);
}
});
boolean interrupted = false;
try {
while(true) {
try {
done.get(pollMillis, TimeUnit.MILLISECONDS);
return;
} catch(TimeoutException e) {
if(stopping.getAsBoolean() && state.compareAndSet(PENDING, ABANDONED)) {
throw new CancellationException("the server stopped before the task ran");
}
} catch(InterruptedException e) {
interrupted = true;
if(state.compareAndSet(PENDING, ABANDONED)) throw new CancellationException("interrupted before the task ran");
} catch(ExecutionException e) {
switch(e.getCause()) {
case RuntimeException runtime -> throw runtime;
case Error error -> throw error;
default -> throw new CompletionException(e.getCause());
}
}
}
} finally {
if(interrupted) Thread.currentThread().interrupt();
}
}
}
@@ -1,86 +0,0 @@
package com.dfsek.terra.bukkit.util;
import com.mojang.brigadier.LiteralMessage;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import dev.wyck.environment.particle.AmbientParticle;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
public final class VanillaParticles {
private static final Logger LOGGER = LoggerFactory.getLogger(VanillaParticles.class);
private static final SimpleCommandExceptionType TRAILING_DATA = new SimpleCommandExceptionType(
new LiteralMessage("Unexpected text after the particle"));
private VanillaParticles() {
}
public static @Nullable AmbientParticle parse(String particle, float probability) throws CommandSyntaxException {
Handles handles = Holder.HANDLES;
if(handles == null) return null;
StringReader reader = new StringReader(particle.strip());
Object options;
Object ambient;
try {
options = handles.readParticle.invokeExact(reader, handles.registries);
ambient = handles.ambientParticle.invokeExact(options, probability);
} catch(CommandSyntaxException | RuntimeException | Error e) {
throw e;
} catch(Throwable e) {
throw new IllegalStateException(e);
}
if(reader.canRead()) throw TRAILING_DATA.createWithContext(reader);
return AmbientParticle.decode(ambient);
}
private static @Nullable Handles resolve() {
String step = "net.minecraft.server.MinecraftServer";
try {
ClassLoader loader = Bukkit.getServer().getClass().getClassLoader();
MethodHandles.Lookup lookup = MethodHandles.publicLookup();
Class<?> server = Class.forName(step, false, loader);
step = "MinecraftServer.getServer()";
Object instance = lookup.findStatic(server, "getServer", MethodType.methodType(server)).invoke();
if(instance == null) throw new IllegalStateException("the server has not started");
step = "MinecraftServer.registryAccess()";
Object registries = lookup.findVirtual(server, "registryAccess",
MethodType.methodType(Class.forName("net.minecraft.core.RegistryAccess$Frozen", false, loader))).invoke(instance);
step = "ParticleArgument.readParticle(StringReader, HolderLookup.Provider)";
Class<?> provider = Class.forName("net.minecraft.core.HolderLookup$Provider", false, loader);
Class<?> options = Class.forName("net.minecraft.core.particles.ParticleOptions", false, loader);
MethodHandle readParticle = lookup.findStatic(Class.forName("net.minecraft.commands.arguments.ParticleArgument", false, loader),
"readParticle", MethodType.methodType(options, StringReader.class, provider))
.asType(MethodType.methodType(Object.class, StringReader.class, Object.class));
step = "AmbientParticle(ParticleOptions, float)";
MethodHandle ambientParticle = lookup.findConstructor(Class.forName("net.minecraft.world.attribute.AmbientParticle", false, loader),
MethodType.methodType(void.class, options, float.class))
.asType(MethodType.methodType(Object.class, Object.class, float.class));
return new Handles(readParticle, registries, ambientParticle);
} catch(Throwable e) {
LOGGER.warn("Biome particles are disabled: could not find vanilla's {} ({}). " +
"This Minecraft version is probably not supported yet.", step, e.toString());
return null;
}
}
private record Handles(MethodHandle readParticle, Object registries, MethodHandle ambientParticle) {
}
private static final class Holder {
private static final @Nullable Handles HANDLES = resolve();
}
}
@@ -1,22 +1,21 @@
package com.dfsek.terra.bukkit.world;
import dev.wyck.biome.Biome;
import dev.wyck.biome.BiomeSpecialEffects;
import dev.wyck.biome.ClimateSettings;
import dev.wyck.environment.attribute.EnvironmentAttributeMap;
import dev.wyck.environment.attribute.EnvironmentAttributeSupplier;
import dev.wyck.environment.attribute.EnvironmentAttributes;
import dev.wyck.environment.sounds.AmbientSounds;
import dev.wyck.environment.sounds.BackgroundMusic;
import dev.wyck.keys.ResourceKey;
import dev.wyck.registry.BiomeRegistry;
import dev.wyck.tags.TagSet;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import io.papermc.paper.registry.TypedKey;
import io.papermc.paper.registry.tag.Tag;
import io.papermc.paper.tag.PostFlattenTagRegistrar;
import net.kyori.adventure.key.Key;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeGenerationSettings;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Villager;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -24,133 +23,340 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.dfsek.terra.bukkit.BukkitPlatform;
import com.dfsek.terra.bukkit.attribute.PaperVanilla;
import com.dfsek.terra.bukkit.attribute.WyckBridge;
import com.dfsek.terra.minecraft.attribute.BiomeTags;
import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory;
import com.dfsek.terra.minecraft.attribute.PackParents;
import com.dfsek.terra.minecraft.attribute.VanillaContext;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
public final class BiomeHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(BiomeHandler.class);
private static final Map<NamespacedKey, Villager.Type> VILLAGER_TYPES = new ConcurrentHashMap<>();
private static final Map<Identifier, List<Identifier>> BY_PARENT = new HashMap<>();
private static final Map<Identifier, PlatformTagSource> PLATFORM_TAGS = new HashMap<>();
private BiomeHandler() { }
public static void registerBiomes(ConfigRegistry configRegistry) {
/**
* Must run on the server thread.
*/
public static synchronized void registerBiomes(BukkitPlatform platform) {
MinecraftAttributeParents parents = platform.attributeParents();
VanillaContext context = parents.context();
if(context == null) throw new IllegalStateException("no registry load has begun");
MinecraftBiomeFactory factory = new MinecraftBiomeFactory(platform.getAttributeHandle(), context);
Registry<Biome> registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME);
org.bukkit.Registry<org.bukkit.block.Biome> bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME);
List<Biome> toRegister = new ArrayList<>();
List<Runnable> afterRegistration = new ArrayList<>();
boolean playersOnline = !Bukkit.getOnlinePlayers().isEmpty();
AtomicInteger deferred = new AtomicInteger();
configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((key, biome) -> {
BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome();
ResourceKey vanillaKey = ResourceKey.of(platformBiome.getHandle().getKey());
ResourceKey terraKey = ResourceKey.of("terra", createBiomeID(pack, key));
NamespacedKey bukkitKey = new NamespacedKey(terraKey.namespace(), terraKey.path());
VanillaBiomeProperties properties = biome.getContext().has(VanillaBiomeProperties.class)
? biome.getContext().get(VanillaBiomeProperties.class)
: new VanillaBiomeProperties();
if(bukkitRegistry.get(bukkitKey) == null) {
toRegister.add(createBiome(terraKey, getBiomeOrThrow(vanillaKey), properties));
}
afterRegistration.add(() -> {
org.bukkit.block.Biome bukkitBiome = bukkitRegistry.getOrThrow(bukkitKey);
platformBiome.getContext().put(new BukkitBiomeInfo(terraKey, vanillaKey, bukkitBiome));
if(properties.getVillagerType() != null) {
VILLAGER_TYPES.put(bukkitKey, properties.getVillagerType());
Run<dev.wyck.biome.Biome> run = collect(platform.getRawConfigRegistry().entries(),
pack -> parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack)),
(pack, packParents, packRun) -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach((id, biome) -> {
BukkitPlatformBiome platformBiome = (BukkitPlatformBiome) biome.getPlatformBiome();
ResourceKey<Biome> parentKey = ResourceKey.create(Registries.BIOME,
Identifier.parse(platformBiome.getHandle().getKey().toString()));
Biome parent = registry.getValue(parentKey);
if(parent == null) {
LOGGER.error("Pack \"{}\", config \"{}\": biome skipped: no vanilla biome \"{}\"", pack.getID(), biome.getID(),
parentKey.identifier());
return;
}
});
}));
platformBiome.setParentEntries(parentEntries(() -> parents.biomeEntries(packParents, parentKey, parent), pack.getID(),
biome.getID(), LOGGER::warn));
LOGGER.info("Registering {} custom biomes through Wyck...", toRegister.size());
BiomeRegistry.registry().register(toRegister);
afterRegistration.forEach(Runnable::run);
Identifier terraId = Identifier.fromNamespaceAndPath("terra", createBiomeID(pack, id));
packRun.add(terraId, parentKey.identifier(), registry.containsKey(terraId), () -> {
if(playersOnline) {
deferred.incrementAndGet();
return null;
}
ResourceKey<VillagerType> parentVillagerType = Objects.requireNonNullElse(context.villagerTypes().apply(parentKey),
VillagerType.PLAINS);
return registration(() -> build(factory, parentKey, parent, biome, packParents), b -> WyckBridge.biome(terraId, b),
parent, parentVillagerType, pack.getID(), biome.getID(), LOGGER::warn);
}, new PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags()), () -> {
NamespacedKey bukkitKey = new NamespacedKey(terraId.getNamespace(), terraId.getPath());
org.bukkit.block.Biome bukkitBiome = bukkitRegistry.get(bukkitKey);
if(bukkitBiome == null) {
LOGGER.error("Pack \"{}\", config \"{}\": biome not registered as \"{}\"", pack.getID(), biome.getID(),
terraId);
return;
}
platformBiome.getContext().put(new BukkitBiomeInfo(dev.wyck.keys.ResourceKey.of(bukkitKey), bukkitBiome));
}, pack.getID(), biome.getID(), LOGGER::warn);
}), LOGGER::warn);
if(deferred.get() > 0) {
LOGGER.info("Players are online, so {} new custom biomes generate as their vanilla biomes until the server restarts.",
deferred.get());
}
registerNew(run.toRegister, WyckBridge::registerBiomes, LOGGER::info);
Map<ResourceKey<Biome>, ResourceKey<VillagerType>> villagerTypes = PaperVanilla.villagerTypes();
run.villagerTypes.forEach((terraId, type) -> villagerTypes.put(ResourceKey.create(Registries.BIOME, terraId), type));
BY_PARENT.clear();
BY_PARENT.putAll(run.byParent);
PLATFORM_TAGS.clear();
PLATFORM_TAGS.putAll(run.platformTags);
run.afterRegistration.forEach(Runnable::run);
}
public static void addToVanillaTags(ConfigRegistry configRegistry) {
Map<TypedKey<org.bukkit.block.Biome>, Set<Biome>> terraBiomesByVanilla = new HashMap<>();
configRegistry.forEach(pack -> pack.getRegistry(com.dfsek.terra.api.world.biome.Biome.class).forEach(biome -> {
Context context = ((BukkitPlatformBiome) biome.getPlatformBiome()).getContext();
if(context.has(BukkitBiomeInfo.class)) {
BukkitBiomeInfo info = context.get(BukkitBiomeInfo.class);
TypedKey<org.bukkit.block.Biome> vanillaKey = TypedKey.create(RegistryKey.BIOME, info.vanillaKey().key());
terraBiomesByVanilla.computeIfAbsent(vanillaKey, k -> new HashSet<>()).add(Biome.reference(info.biomeKey()));
static <P, B> Run<B> collect(Iterable<ConfigPack> packs, Function<ConfigPack, P> prepare, PackCollector<P, B> collectPack,
Consumer<String> warn) {
Run<B> run = new Run<>(null);
for(ConfigPack pack : packs) {
P prepared;
try {
prepared = prepare.apply(pack);
} catch(RuntimeException e) {
LOGGER.debug("Failed to read the attributes of pack {}", pack.getID(), e);
warn.accept("Pack \"" + pack.getID() + "\": biomes skipped: its attributes could not be read");
continue;
}
}));
Run<B> packRun = new Run<>(run);
try {
collectPack.collect(pack, prepared, packRun);
} catch(RuntimeException e) {
LOGGER.debug("Failed to collect the biomes of pack {}", pack.getID(), e);
warn.accept("Pack \"" + pack.getID() + "\": biomes skipped: they could not be built");
continue;
}
run.addAll(packRun);
}
return run;
}
org.bukkit.Registry<org.bukkit.block.Biome> bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME);
int count = 0;
for(Tag<org.bukkit.block.Biome> tag : bukkitRegistry.getTags()) {
Set<Biome> members = new HashSet<>();
terraBiomesByVanilla.forEach((vanillaKey, terraBiomes) -> {
if(tag.contains(vanillaKey)) {
members.addAll(terraBiomes);
@FunctionalInterface
interface PackCollector<P, B> {
void collect(ConfigPack pack, P prepared, Run<B> run);
}
static AttributeSlots parentEntries(Supplier<AttributeSlots> read, String pack, String config, Consumer<String> warn) {
try {
return read.get();
} catch(RuntimeException e) {
LOGGER.debug("Failed to read the parent attributes of Terra biome {} of pack {}", config, pack, e);
warn.accept("Pack \"" + pack + "\", config \"" + config + "\": parent attributes ignored: they could not be read");
return AttributeSlots.EMPTY;
}
}
static final class Run<B> {
private final @Nullable Run<B> before;
final List<B> toRegister = new ArrayList<>();
final Map<Identifier, ResourceKey<VillagerType>> villagerTypes = new LinkedHashMap<>();
final Map<Identifier, List<Identifier>> byParent = new LinkedHashMap<>();
final Map<Identifier, PlatformTagSource> platformTags = new LinkedHashMap<>();
final List<Runnable> afterRegistration = new ArrayList<>();
Run(@Nullable Run<B> before) {
this.before = before;
}
void add(Identifier terraId, Identifier parent, boolean registered, Supplier<@Nullable Registration<B>> registration,
PlatformTagSource tags, Runnable after, String pack, String config, Consumer<String> warn) {
if(recorded(terraId)) {
warn.accept("Pack \"" + pack + "\", config \"" + config + "\": biome \"" + terraId
+ "\" shared with another config: their IDs differ only in case");
afterRegistration.add(after);
return;
}
if(!registered) {
Registration<B> queued = registration.get();
if(queued == null) return;
toRegister.add(queued.biome());
villagerTypes.put(terraId, queued.villagerType());
}
byParent.computeIfAbsent(parent, i -> new ArrayList<>()).add(terraId);
platformTags.put(terraId, tags);
afterRegistration.add(after);
}
private boolean recorded(Identifier terraId) {
return platformTags.containsKey(terraId) || (before != null && before.recorded(terraId));
}
private void addAll(Run<B> run) {
toRegister.addAll(run.toRegister);
villagerTypes.putAll(run.villagerTypes);
run.byParent.forEach((parent, biomes) -> byParent.computeIfAbsent(parent, i -> new ArrayList<>()).addAll(biomes));
platformTags.putAll(run.platformTags);
afterRegistration.addAll(run.afterRegistration);
}
}
static <B> void registerNew(List<B> biomes, Consumer<List<B>> register, Consumer<String> info) {
if(biomes.isEmpty()) {
info.accept("No new custom biomes to register.");
return;
}
info.accept("Registering " + biomes.size() + " custom biomes through Wyck...");
register.accept(biomes);
}
public static MinecraftBiomeFactory.Built build(MinecraftBiomeFactory factory, ResourceKey<Biome> parentKey, Biome parent,
com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack) {
return factory.create(parentKey, parent, terraBiome, pack, pack.report(), BiomeGenerationSettings.EMPTY);
}
/**
* Must run on the server thread.
*/
public static synchronized void addToVanillaTags(BukkitPlatform platform) {
Registry<Biome> registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME);
Map<TagKey<Biome>, List<Holder<Biome>>> before = new LinkedHashMap<>();
registry.getTags().forEach(tag -> before.put(tag.key(), new ArrayList<>(tag.stream().toList())));
Map<TagKey<Biome>, List<Holder<Biome>>> after = new LinkedHashMap<>();
before.forEach((tag, members) -> after.put(tag, new ArrayList<>(members)));
BiomeTags.addTerraBiomes(after, id -> registry.get(id).map(h -> h), BY_PARENT, PLATFORM_TAGS);
Map<TagKey<Biome>, List<Identifier>> additions = additions(before, after);
int added = appendAll(additions, WyckBridge::appendBiomeTag, "wyck could not append to the tag", LOGGER::warn);
LOGGER.info("Added Terra biomes to {} biome tags.", added);
}
/**
* Must not throw: an exception fails the data pack reload.
*/
public static synchronized void addToReloadedTags(PostFlattenTagRegistrar<org.bukkit.block.Biome> registrar) {
try {
Registry<Biome> registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME);
Map<TagKey<Biome>, List<Identifier>> tags = new LinkedHashMap<>();
registrar.getAllTags().forEach((tag, members) -> tags.put(TagKey.create(Registries.BIOME, identifier(tag.key())),
members.stream().map(member -> identifier(member.key())).toList()));
Map<TagKey<Biome>, List<Identifier>> additions = reloadAdditions(tags, id -> registry.get(id).map(h -> h), BY_PARENT,
PLATFORM_TAGS);
int added = appendAll(additions, (tag, biomes) -> registrar.addToTag(
io.papermc.paper.registry.tag.TagKey.create(RegistryKey.BIOME, key(tag.location())),
biomes.stream().map(biome -> TypedKey.create(RegistryKey.BIOME, key(biome))).toList()),
"the reload could not add them", LOGGER::warn);
LOGGER.info("Added Terra biomes to {} reloaded biome tags.", added);
} catch(RuntimeException e) {
LOGGER.debug("Failed to add Terra biomes to the reloaded biome tags", e);
LOGGER.warn("Terra biomes not added to the reloaded biome tags; restart the server to restore them");
}
}
/**
* Parent tags come from {@code tags}: the parent's holder still has its pre-reload tags.
*/
static Map<TagKey<Biome>, List<Identifier>> reloadAdditions(Map<TagKey<Biome>, List<Identifier>> tags,
Function<Identifier, Optional<Holder<Biome>>> lookup,
Map<Identifier, List<Identifier>> byParent,
Map<Identifier, PlatformTagSource> platformTags) {
Map<TagKey<Biome>, List<Holder<Biome>>> before = new LinkedHashMap<>();
Map<TagKey<Biome>, List<Holder<Biome>>> after = new LinkedHashMap<>();
tags.forEach((tag, members) -> {
List<Holder<Biome>> old = members.stream().map(lookup).flatMap(Optional::stream).toList();
List<Holder<Biome>> biomes = new ArrayList<>(old);
for(Identifier member : members) {
for(Identifier terra : byParent.getOrDefault(member, List.of())) {
lookup.apply(terra).ifPresentOrElse(biomes::add,
() -> LOGGER.debug("Terra biome {} is not registered, so it is not added to the reloaded tag {}", terra,
tag.location()));
}
});
if(!members.isEmpty()) {
TagSet.ofBiomes(ResourceKey.of(tag.tagKey().key()), members).append();
count++;
}
before.put(tag, old);
after.put(tag, biomes);
});
BiomeTags.addTerraBiomes(after, lookup, Map.of(), platformTags);
return additions(before, after);
}
private static Identifier identifier(Key key) {
return Identifier.fromNamespaceAndPath(key.namespace(), key.value());
}
private static Key key(Identifier id) {
return Key.key(id.getNamespace(), id.getPath());
}
public static Map<TagKey<Biome>, List<Identifier>> additions(Map<TagKey<Biome>, List<Holder<Biome>>> before,
Map<TagKey<Biome>, List<Holder<Biome>>> after) {
Map<TagKey<Biome>, List<Identifier>> additions = new LinkedHashMap<>();
after.forEach((tag, members) -> {
Set<Holder<Biome>> old = new HashSet<>(before.getOrDefault(tag, List.of()));
Set<Identifier> added = new LinkedHashSet<>();
for(Holder<Biome> member : members) {
if(!old.contains(member)) member.unwrapKey().ifPresent(key -> added.add(key.identifier()));
}
if(!added.isEmpty()) additions.put(tag, List.copyOf(added));
});
return additions;
}
record Registration<B>(B biome, ResourceKey<VillagerType> villagerType) { }
static <B> @Nullable Registration<B> registration(Supplier<MinecraftBiomeFactory.Built> build, Function<Biome, B> wyck,
Biome parent, ResourceKey<VillagerType> parentVillagerType, String pack,
String config, Consumer<String> warn) {
String prefix = "Pack \"" + pack + "\", config \"" + config + "\": ";
MinecraftBiomeFactory.Built built;
try {
built = build.get();
} catch(RuntimeException e) {
LOGGER.debug("Failed to build Terra biome {} of pack {}", config, pack, e);
return parent(wyck, parent, parentVillagerType, prefix, "its attributes could not be applied",
"its attributes could not be applied, and wyck could not read its parent", warn);
}
try {
return new Registration<>(wyck.apply(built.biome()), built.villagerType());
} catch(RuntimeException e) {
LOGGER.debug("Wyck failed to read Terra biome {} of pack {}", config, pack, e);
return parent(wyck, parent, parentVillagerType, prefix, "wyck could not read its attributes",
"wyck could not read its attributes or its parent", warn);
}
}
private static <B> @Nullable Registration<B> parent(Function<Biome, B> wyck, Biome parent, ResourceKey<VillagerType> villagerType,
String prefix, String reason, String skipReason, Consumer<String> warn) {
try {
Registration<B> registration = new Registration<>(wyck.apply(parent), villagerType);
warn.accept(prefix + "biome built from its parent: " + reason);
return registration;
} catch(RuntimeException e) {
LOGGER.debug("Wyck failed to read the parent of a Terra biome", e);
warn.accept(prefix + "biome skipped: " + skipReason);
return null;
}
}
static int appendAll(Map<TagKey<Biome>, List<Identifier>> additions, BiConsumer<TagKey<Biome>, List<Identifier>> append,
String failure, Consumer<String> warn) {
int appended = 0;
for(Map.Entry<TagKey<Biome>, List<Identifier>> entry : additions.entrySet()) {
try {
append.accept(entry.getKey(), entry.getValue());
appended++;
} catch(RuntimeException e) {
LOGGER.debug("Failed to append Terra biomes to biome tag {}", entry.getKey().location(), e);
warn.accept("Biome tag \"" + entry.getKey().location() + "\": terra biomes not added: " + failure);
}
}
LOGGER.info("Added Terra biomes to {} vanilla biome tags.", count);
}
public static @Nullable Villager.Type getVillagerType(org.bukkit.block.Biome biome) {
return VILLAGER_TYPES.get(biome.getKey());
}
public static Biome getBiomeOrThrow(ResourceKey key) {
return Biome.reference(key).wrap();
}
public static Biome createBiome(ResourceKey key, Biome vanilla, VanillaBiomeProperties properties) {
EnvironmentAttributeMap attributes = vanilla.attributes();
attributes = override(attributes, EnvironmentAttributes.FOG_COLOR, properties.getFogColor());
attributes = override(attributes, EnvironmentAttributes.WATER_FOG_COLOR, properties.getWaterFogColor());
attributes = override(attributes, EnvironmentAttributes.SKY_COLOR, properties.getSkyColor());
attributes = override(attributes, EnvironmentAttributes.AMBIENT_PARTICLES, properties.getParticles());
attributes = override(attributes, EnvironmentAttributes.MUSIC_VOLUME, properties.getMusicVolume());
attributes = override(attributes, EnvironmentAttributes.NATURAL_MOB_SPAWNS, properties.getSpawnSettings());
if(properties.getMusic() != null) {
attributes = attributes.with(EnvironmentAttributes.BACKGROUND_MUSIC,
BackgroundMusic.builder().defaultMusic(properties.getMusic()).build());
}
if(properties.getLoopSound() != null || properties.getMoodSound() != null || properties.getAdditionsSound() != null) {
AmbientSounds sounds = Objects.requireNonNullElse(attributes.get(EnvironmentAttributes.AMBIENT_SOUNDS), AmbientSounds.EMPTY);
attributes = attributes.with(EnvironmentAttributes.AMBIENT_SOUNDS, AmbientSounds.of(
properties.getLoopSound() != null ? properties.getLoopSound() : sounds.loop().orElse(null),
properties.getMoodSound() != null ? properties.getMoodSound() : sounds.mood().orElse(null),
properties.getAdditionsSound() != null ? List.of(properties.getAdditionsSound()) : sounds.additions()));
}
ClimateSettings climate = vanilla.climateSettings();
BiomeSpecialEffects effects = vanilla.specialEffects();
return Biome.builder(key)
.attributes(attributes)
.climateSettings(ClimateSettings.builder()
.hasPrecipitation(Objects.requireNonNullElse(properties.getPrecipitation(), climate.hasPrecipitation()))
.temperature(Objects.requireNonNullElse(properties.getTemperature(), climate.temperature()))
.temperatureModifier(Objects.requireNonNullElse(properties.getTemperatureModifier(), climate.temperatureModifier()))
.downfall(Objects.requireNonNullElse(properties.getDownfall(), climate.downfall()))
.build())
.specialEffects(BiomeSpecialEffects.builder()
.waterColor(Objects.requireNonNullElse(properties.getWaterColor(), effects.waterColor()))
.grassColorModifier(Objects.requireNonNullElse(properties.getGrassColorModifier(), effects.grassColorModifier()))
.grassColorOverride(orElse(properties.getGrassColor(), effects.grassColorOverride().orElse(null)))
.foliageColorOverride(orElse(properties.getFoliageColor(), effects.foliageColorOverride().orElse(null)))
.dryFoliageColorOverride(orElse(properties.getDryFoliageColor(), effects.dryFoliageColorOverride().orElse(null)))
.build())
.build();
return appended;
}
public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) {
@@ -158,13 +364,4 @@ public final class BiomeHandler {
+ "/" + biomeID.getNamespace().toLowerCase(Locale.ROOT)
+ "/" + biomeID.getID().toLowerCase(Locale.ROOT);
}
private static <T> EnvironmentAttributeMap override(EnvironmentAttributeMap map, EnvironmentAttributeSupplier<T> attribute,
@Nullable T value) {
return value == null ? map : map.with(attribute, value);
}
private static @Nullable Integer orElse(@Nullable Integer value, @Nullable Integer fallback) {
return value != null ? value : fallback;
}
}
@@ -5,5 +5,5 @@ import dev.wyck.keys.ResourceKey;
import com.dfsek.terra.api.properties.Properties;
public record BukkitBiomeInfo(ResourceKey biomeKey, ResourceKey vanillaKey, org.bukkit.block.Biome bukkitBiome) implements Properties {
public record BukkitBiomeInfo(ResourceKey biomeKey, org.bukkit.block.Biome bukkitBiome) implements Properties {
}
@@ -17,14 +17,19 @@
package com.dfsek.terra.bukkit.world;
import java.util.Objects;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.properties.PropertyHolder;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
import com.dfsek.terra.world.attribute.platform.ParentEntryHolder;
public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder {
public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder, ParentEntryHolder {
private final org.bukkit.block.Biome biome;
private final Context context = new Context();
private volatile AttributeSlots parentEntries = AttributeSlots.EMPTY;
public BukkitPlatformBiome(org.bukkit.block.Biome biome) {
this.biome = biome;
@@ -39,4 +44,13 @@ public class BukkitPlatformBiome implements PlatformBiome, PropertyHolder {
public Context getContext() {
return context;
}
@Override
public AttributeSlots parentEntries() {
return parentEntries;
}
public void setParentEntries(AttributeSlots parentEntries) {
this.parentEntries = Objects.requireNonNull(parentEntries, "parentEntries");
}
}
@@ -1,5 +1,6 @@
name: "Terra"
main: "com.dfsek.terra.bukkit.TerraBukkitPlugin"
bootstrapper: "com.dfsek.terra.bukkit.TerraBukkitBootstrap"
version: "@VERSION@"
load: "STARTUP"
authors: [ "dfsek", "duplexsystem", "Astrash", "solonovamax", "Sancires", "Aureus", "RogueShade", "OakLoaf" ]
@@ -0,0 +1,141 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.biome.PlatformBiome;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.minecraft.attribute.FakePackAttributes;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
import com.dfsek.terra.minecraft.attribute.PackParents;
import com.dfsek.terra.minecraft.attribute.TestBiome;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BukkitParentsTest {
private static final Registry<Attribute<?>> REGISTRY = registry();
private static final ConfigPack PACK = pack("test");
private static final Attribute<Boolean> PRECIPITATION = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION.getRegistryKey().toString());
private static final Attribute<Boolean> HAS_CEILING = attribute(MinecraftAttributes.DIMENSION_HAS_CEILING.getRegistryKey().toString());
private final List<String> warnings = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, s -> { });
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private static ConfigPack pack(String id) {
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "getID" -> id;
case "getRegistry" -> REGISTRY;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "ConfigPack[" + id + "]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static Biome desert() {
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.DESERT).value();
}
@Test
void vanillaVillagerTypes() {
Map<ResourceKey<Biome>, ResourceKey<VillagerType>> types = PaperVanilla.villagerTypes();
assertSame(types, PaperVanilla.villagerTypes(), "read once");
assertEquals(VillagerType.DESERT, types.get(Biomes.DESERT));
ResourceKey<Biome> test = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test_biome"));
ResourceKey<VillagerType> before = types.get(test);
try {
types.put(test, VillagerType.SNOW);
assertEquals(VillagerType.SNOW, types.get(test));
assertEquals(VillagerType.SNOW, PaperVanilla.context(REGISTRIES).villagerTypes().apply(test));
} finally {
if(before == null) types.remove(test);
else types.put(test, before);
}
assertEquals(before, types.get(test));
}
@Test
void parentEntriesAllocationFree() {
parents.beginLoad(CONTEXT);
FakePackAttributes fake = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of());
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
BukkitPlatformBiome platformBiome = new BukkitPlatformBiome(null);
assertSame(AttributeSlots.EMPTY, platformBiome.parentEntries());
assertThrows(NullPointerException.class, () -> platformBiome.setParentEntries(null));
TestBiome biome = new TestBiome("DESERT", 0, platformBiome);
assertNull(parents.biomeOrNull(biome, PRECIPITATION));
platformBiome.setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, desert()));
assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION));
TestBiome plain = new TestBiome("PLAIN", 1, (PlatformBiome) () -> "plain");
assertEquals(List.of(), warnings);
assertEquals(7, reads(fake, biome, plain), "every read sees the expected entry");
com.sun.management.ThreadMXBean threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long thread = Thread.currentThread().threadId();
int sink = 0;
for(int i = 0; i < 100_000; i++) sink += reads(fake, biome, plain);
long before = threads.getThreadAllocatedBytes(thread);
for(int i = 0; i < 10_000; i++) sink += reads(fake, biome, plain);
long allocated = threads.getThreadAllocatedBytes(thread) - before;
assertEquals(110_000 * 7, sink);
assertTrue(allocated < 1024, allocated + " bytes allocated");
}
private int reads(FakePackAttributes fake, TestBiome biome, TestBiome plain) {
int hash = 0;
hash += parents.biomeOrNull(biome, PRECIPITATION) == null ? 0 : 1;
hash += parents.biomeOrNull(plain, PRECIPITATION) == null ? 2 : 0;
hash += parents.packOrNull(fake, HAS_CEILING) == null ? 0 : 4;
return hash;
}
}
@@ -0,0 +1,138 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry;
import net.minecraft.core.RegistrationInfo;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
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.biome.Biomes;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.world.BiomeHandler;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory;
import com.dfsek.terra.minecraft.attribute.PackParents;
import com.dfsek.terra.minecraft.attribute.TestBiome;
import com.dfsek.terra.minecraft.attribute.VanillaCodecs;
import com.dfsek.terra.minecraft.attribute.VanillaContext;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PaperBiomeTest {
private static final String CONFIG = "BIOME";
private static final VanillaContext PAPER = PaperVanilla.context(REGISTRIES);
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private final MinecraftBiomeFactory factory = new MinecraftBiomeFactory(HANDLE, PAPER);
private static ConfigPack pack(String id) {
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "getID" -> id;
case "getRegistry" -> null;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "ConfigPack[" + id + "]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static Holder.Reference<Biome> vanilla(ResourceKey<Biome> key) {
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key);
}
private static Object network(Biome biome) {
return VanillaCodecs.encode(Biome.NETWORK_CODEC, biome, PAPER.ops());
}
private MinecraftBiomeFactory.Built build(TestBiome biome, PackParents pack, ResourceKey<Biome> parent) {
Biome parentBiome = vanilla(parent).value();
((BukkitPlatformBiome) biome.getPlatformBiome()).setParentEntries(parents.biomeEntries(pack, parent, parentBiome));
return BiomeHandler.build(factory, parent, parentBiome, biome, pack);
}
@Test
void noAttributesMatchesParent() {
Biome desert = vanilla(Biomes.DESERT).value();
assertFalse(desert.getGenerationSettings().features().isEmpty(), "the desert has features");
assertTrue(desert.getGenerationSettings().getCarvers().iterator().hasNext(), "the desert has carvers");
parents.beginLoad(PAPER);
PackParents bare = parents.prepare(pack("bare"), Optional.empty(), report);
TestBiome biome = new TestBiome(CONFIG, 0, new BukkitPlatformBiome(null));
MinecraftBiomeFactory.Built built = build(biome, bare, Biomes.DESERT);
assertEquals(network(desert), network(built.biome()));
assertEquals(List.of(), built.biome().getGenerationSettings().features());
assertFalse(built.biome().getGenerationSettings().getCarvers().iterator().hasNext(), "no carvers");
assertEquals(VillagerType.DESERT, built.villagerType());
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void additionsListOnlyNewMembers() {
MappedRegistry<Biome> biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
Holder<Biome> forest = biomes.register(Biomes.FOREST, vanilla(Biomes.FOREST).value(), RegistrationInfo.BUILT_IN);
Holder<Biome> ocean = biomes.register(Biomes.OCEAN, vanilla(Biomes.OCEAN).value(), RegistrationInfo.BUILT_IN);
Identifier terraId = Identifier.fromNamespaceAndPath("terra", "t/b");
Holder<Biome> terra = biomes.register(ResourceKey.create(Registries.BIOME, terraId), vanilla(Biomes.PLAINS).value(),
RegistrationInfo.BUILT_IN);
TagKey<Biome> isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest"));
TagKey<Biome> isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean"));
TagKey<Biome> hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow"));
Map<TagKey<Biome>, List<Holder<Biome>>> before = new LinkedHashMap<>();
before.put(isForest, List.of(forest));
before.put(isOcean, List.of(ocean));
Map<TagKey<Biome>, List<Holder<Biome>>> after = new LinkedHashMap<>();
after.put(isForest, List.of(forest, terra));
after.put(isOcean, List.of(ocean));
after.put(hasSnow, List.of(terra));
assertEquals(Map.of(isForest, List.of(terraId), hasSnow, List.of(terraId)), BiomeHandler.additions(before, after));
before.put(isForest, List.of(forest, terra));
after.put(isForest, List.of(forest, terra, terra));
assertEquals(Map.of(hasSnow, List.of(terraId)), BiomeHandler.additions(before, after));
}
}
@@ -0,0 +1,462 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.attribute;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JavaOps;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.MappedRegistry;
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.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.tags.TagKey;
import net.minecraft.tags.TimelineTags;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.timeline.Timeline;
import net.minecraft.world.timeline.Timelines;
import org.bukkit.World;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeEntry;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.PackAttributes;
import com.dfsek.terra.bukkit.generator.BukkitChunkGeneratorWrapper;
import com.dfsek.terra.minecraft.attribute.FakePackAttributes;
import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents;
import com.dfsek.terra.minecraft.attribute.VanillaCodecs;
import com.dfsek.terra.minecraft.attribute.VanillaContext;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PaperDimensionsTest {
private static final com.dfsek.terra.api.registry.Registry<Attribute<?>> REGISTRY = registry();
private static final VanillaContext PAPER = PaperVanilla.context(REGISTRIES);
private static final Map<String, RegistryKey> NETHER = Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"));
private static final Map<String, RegistryKey> OVERWORLD = Map.of("vanilla", RegistryKey.parse("minecraft:overworld"));
private static final ResourceKey<Timeline> SEASONS = ResourceKey.create(Registries.TIMELINE, Identifier.parse("mypack:seasons"));
private final List<String> warnings = new ArrayList<>();
private final List<String> debugs = new ArrayList<>();
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
private final List<String> worldInfos = new ArrayList<>();
private final List<String> worldWarnings = new ArrayList<>();
private final FakeServer server = new FakeServer();
private boolean playersOnline;
private final PaperDimensions dimensions = new PaperDimensions(HANDLE, parents, () -> playersOnline, server, worldInfos::add,
worldWarnings::add);
private static ConfigPack pack(@Nullable PackAttributes attributes) {
Context context = new Context();
if(attributes != null) context.put(Context.create(PackAttributes.class), attributes);
return pack("test", () -> context);
}
private static ConfigPack pack(String id, Supplier<Context> context) {
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "getID" -> id;
case "getRegistry" -> REGISTRY;
case "getContext" -> context.get();
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "ConfigPack[" + id + "]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private FakePackAttributes attributes(Map<String, Object> entries, Map<String, RegistryKey> parentIds,
List<Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey>> refs) {
AttributeMap.Builder builder = AttributeMap.builder();
entries.forEach((id, raw) -> put(builder, attribute(id), decoded(id, raw)));
return new FakePackAttributes(HANDLE, parents, builder.build(), parentIds, Map.of(), refs, Map.of());
}
private FakePackAttributes attributes(Map<String, Object> entries, Map<String, RegistryKey> parentIds) {
return attributes(entries, parentIds, List.of());
}
private static AttributeEntry<?> decoded(String id, Object raw) {
try {
return HANDLE.decodeEntry(attribute(id), raw, HANDLE.plainContext());
} catch(DecodeException e) {
throw new AssertionError(id + ": " + e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
private static <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, AttributeEntry<?> entry) {
builder.put(attribute.key(), (AttributeEntry<T>) entry);
}
private ConfigPack prepared(VanillaContext context, ConfigPack pack) {
parents.beginLoad(context);
parents.prepare(pack, HANDLE.pack(pack), report);
return pack;
}
private ConfigPack prepared(@Nullable PackAttributes attributes) {
return prepared(PAPER, pack(attributes));
}
private static DimensionType dimensionType(VanillaContext context, ResourceKey<DimensionType> key) {
return context.dimensionTypes().getOrThrow(key).value();
}
private PaperDimensions.Built typeFor(VanillaContext context, ConfigPack pack, ResourceKey<DimensionType> world, String worldName) {
return dimensions.typeFor(pack, world, dimensionType(context, world), worldName).orElseThrow();
}
private PaperDimensions.Built typeFor(ConfigPack pack, ResourceKey<DimensionType> world) {
return typeFor(PAPER, pack, world, "world");
}
private static String notApplied(String key) {
return notApplied(key, "world");
}
private static String notApplied(String key, String world) {
return "Pack \"test\": attribute \"" + key + "\" is not applied to world \"" + world
+ "\": it is fixed when the world is created";
}
private static MappedRegistry<Timeline> timelines() {
MappedRegistry<Timeline> timelines = new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable());
REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements()
.forEach(holder -> timelines.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN));
RegistryOps<Object> ops = PAPER.ops();
Timeline moon = REGISTRIES.lookupOrThrow(Registries.TIMELINE).getOrThrow(Timelines.MOON).value();
timelines.register(SEASONS, reread(Timeline.DIRECT_CODEC, moon, ops, ops), RegistrationInfo.BUILT_IN);
Map<TagKey<Timeline>, List<Holder<Timeline>>> tags = new HashMap<>();
REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements()
.forEach(type -> type.value().timelines().unwrapKey().ifPresent(tag -> tags.put(tag, List.of())));
tags.put(TimelineTags.IN_OVERWORLD, List.of(timelines.get(Timelines.OVERWORLD_DAY).orElseThrow(),
timelines.get(Timelines.MOON).orElseThrow(),
timelines.get(Timelines.VILLAGER_SCHEDULE).orElseThrow()));
timelines.bindTags(tags);
timelines.freeze();
return timelines;
}
private static VanillaContext contextWith(MappedRegistry<Timeline> timelines) {
Map<ResourceKey<?>, HolderLookup.RegistryLookup<?>> lookups = new LinkedHashMap<>();
REGISTRIES.listRegistries().forEach(lookup -> lookups.put(lookup.key(), lookup));
lookups.put(Registries.TIMELINE, timelines);
RegistryOps<Object> ops = HolderLookup.Provider.create(lookups.values().stream()).createSerializationContext(JavaOps.INSTANCE);
MappedRegistry<DimensionType> types = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable());
REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements().forEach(holder -> types.register(holder.key(),
reread(DimensionType.DIRECT_CODEC, holder.value(), PAPER.ops(), ops), RegistrationInfo.BUILT_IN));
types.freeze();
lookups.put(Registries.DIMENSION_TYPE, types);
return PaperVanilla.context(HolderLookup.Provider.create(lookups.values().stream()));
}
private static <T> T reread(Codec<T> codec, T value, RegistryOps<Object> from, RegistryOps<Object> to) {
try {
return VanillaCodecs.parse(codec, VanillaCodecs.encode(codec, value, from), to);
} catch(DecodeException e) {
throw new AssertionError(e.getMessage(), e);
}
}
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> id(String id) {
return Either.left(RegistryKey.parse(id));
}
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> tag(String namespace, String id) {
return Either.right(com.dfsek.terra.api.registry.key.TagKey.of(RegistryKey.of(namespace, id)));
}
private static List<ResourceKey<Timeline>> keys(DimensionType type) {
return type.timelines().stream().map(holder -> holder.unwrapKey().orElseThrow()).toList();
}
@Test
void pinnedFieldsFollowWorld() {
ConfigPack pack = prepared(attributes(Map.of(), NETHER));
PaperDimensions.Built built = typeFor(pack, BuiltinDimensionTypes.OVERWORLD);
DimensionType type = built.type();
assertEquals(Identifier.parse("terra:test/minecraft/overworld"), built.key());
assertEquals(-64, type.minY());
assertEquals(384, type.height());
assertTrue(type.hasSkyLight());
assertEquals(0.1f, type.ambientLight());
assertTrue(type.hasCeiling());
assertEquals(Optional.empty(), type.defaultClock());
assertEquals(List.of(), warnings);
assertEquals(List.of(notApplied("terra:dimension/min_y"), notApplied("terra:dimension/height"),
notApplied("terra:dimension/has_skylight")), debugs);
}
@Test
void worldTypeIsDefaultParent() {
ConfigPack pack = prepared(attributes(Map.of(), Map.of()));
DimensionType nether = dimensionType(PAPER, BuiltinDimensionTypes.NETHER);
PaperDimensions.Built inOverworld = typeFor(PAPER, pack, BuiltinDimensionTypes.OVERWORLD, "world");
PaperDimensions.Built inNether = typeFor(PAPER, pack, BuiltinDimensionTypes.NETHER, "world_nether");
assertNotSame(nether, inNether.type());
assertEquals(nether, inNether.type());
assertEquals(Identifier.parse("terra:test/minecraft/the_nether"), inNether.key());
DimensionType overworld = dimensionType(PAPER, BuiltinDimensionTypes.OVERWORLD);
assertNotSame(overworld, inOverworld.type());
assertEquals(overworld, inOverworld.type());
assertEquals(Identifier.parse("terra:test"), inOverworld.key());
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void directTimelinesFromRefs() {
MappedRegistry<Timeline> timelines = timelines();
VanillaContext context = contextWith(timelines);
ConfigPack pack = prepared(context, pack(attributes(Map.of(), Map.of(), List.of(tag("minecraft", "in_overworld"),
id("mypack:seasons")))));
dimensions.recordTimelines(pack, timelines);
DimensionType type = typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "world").type();
assertEquals(List.of(Timelines.OVERWORLD_DAY, Timelines.MOON, Timelines.VILLAGER_SCHEDULE, SEASONS), keys(type));
assertEquals(List.of(), warnings);
}
@Test
void noValidRefKeepsParent() {
MappedRegistry<Timeline> timelines = timelines();
VanillaContext context = contextWith(timelines);
ConfigPack pack = prepared(context, pack(attributes(Map.of(), Map.of(), List.of(id("mypack:nope")))));
dimensions.recordTimelines(pack, timelines);
DimensionType type = typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "world").type();
typeFor(context, pack, BuiltinDimensionTypes.OVERWORLD, "other");
DimensionType nether = typeFor(context, pack, BuiltinDimensionTypes.NETHER, "world_nether").type();
assertEquals(List.of(Timelines.OVERWORLD_DAY, Timelines.MOON, Timelines.VILLAGER_SCHEDULE), keys(type));
assertEquals(keys(dimensionType(context, BuiltinDimensionTypes.NETHER)), keys(nether));
assertEquals(List.of("Pack \"test\": schedule \"mypack:nope\" skipped: no such timeline",
"Pack \"test\", config \"pack.yml\": \"schedules\" ignored: no valid schedule; "
+ "the parent's timelines are kept"),
warnings);
}
@Test
void noAttributesLeavesWorld() {
ConfigPack pack = prepared(null);
assertEquals(Optional.empty(), dimensions.typeFor(pack, BuiltinDimensionTypes.OVERWORLD,
dimensionType(PAPER, BuiltinDimensionTypes.OVERWORLD), "world"));
assertEquals(List.of(), warnings);
assertEquals(List.of(), debugs);
}
@Test
void unsupportedGenerationWarnsOnce() {
ConfigPack pack = prepared(attributes(Map.of("terra:world/sea_level", 40, "terra:world/spawn_height", 80),
Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))));
dimensions.registerPacks(List.of(pack));
typeFor(PAPER, pack, BuiltinDimensionTypes.OVERWORLD, "world");
typeFor(PAPER, pack, BuiltinDimensionTypes.NETHER, "world_nether");
assertEquals(List.of("Pack \"test\", config \"pack.yml\": \"terra:world/sea_level\" ignored: not applied on this platform",
"Pack \"test\", config \"pack.yml\": \"terra:world/spawn_height\" ignored: not applied on this platform",
"Pack \"test\", config \"pack.yml\": \"vanilla-generation\" ignored: not applied on this platform"),
warnings);
}
@Test
void logicalHeightCappedToWorld() {
String reported = notApplied("terra:dimension/logical_height", "world_nether");
PaperDimensions.Built inherited = typeFor(PAPER, prepared(attributes(Map.of(), OVERWORLD)), BuiltinDimensionTypes.NETHER,
"world_nether");
assertEquals(256, inherited.type().logicalHeight());
assertEquals(256, inherited.type().height());
assertEquals(Identifier.parse("terra:test/minecraft/the_nether"), inherited.key());
assertFalse(debugs.contains(reported), String.valueOf(debugs));
ConfigPack set = prepared(attributes(Map.of("terra:dimension/logical_height", 384), OVERWORLD));
typeFor(PAPER, set, BuiltinDimensionTypes.NETHER, "world_nether");
assertEquals(256, typeFor(PAPER, set, BuiltinDimensionTypes.NETHER, "world_nether").type().logicalHeight());
assertEquals(1, debugs.stream().filter(reported::equals).count(), String.valueOf(debugs));
assertEquals(List.of(), warnings);
}
@Test
void unreadablePackSkipped() {
ConfigPack broken = pack("broken", () -> {
throw new IllegalStateException("boom");
});
ConfigPack pack = prepared(attributes(Map.of("terra:world/sea_level", 40), Map.of()));
dimensions.registerPacks(List.of(broken, pack));
assertEquals(List.of("Pack \"broken\": timelines and dimension type skipped: its attributes could not be read"), worldWarnings);
assertEquals(List.of("Pack \"test\", config \"pack.yml\": \"terra:world/sea_level\" ignored: not applied on this platform"),
warnings);
}
private static World world() {
return (World) Proxy.newProxyInstance(World.class.getClassLoader(), new Class<?>[]{ World.class },
(proxy, method, args) -> switch(method.getName()) {
case "getName" -> "world";
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "World[world]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private BukkitChunkGeneratorWrapper initialise() {
BukkitChunkGeneratorWrapper wrapper = new BukkitChunkGeneratorWrapper(null, prepared(attributes(
Map.of("terra:world/mob_generation", false), OVERWORLD)), null);
dimensions.onWorldInit(world(), wrapper);
return wrapper;
}
private static final Identifier TERRA_TEST = Identifier.parse("terra:test");
private static final String KEEPS = "Pack \"test\": world \"world\" keeps its dimension type";
@ParameterizedTest(name = "registered {0}, players online {1}")
@CsvSource({
"false, false, true, true, false",
"true, false, false, true, false",
"false, true, false, false, true",
"true, true, false, true, false"
})
void worldInitRegistersThenApplies(boolean registered, boolean online, boolean registers, boolean applies, boolean keeps) {
if(registered) server.registered.add(TERRA_TEST);
playersOnline = online;
assertFalse(initialise().shouldGenerateMobs());
assertEquals(registers ? List.of(TERRA_TEST) : List.of(), server.registrations);
assertEquals(applies ? List.of(TERRA_TEST) : List.of(), server.applications);
assertEquals(keeps ? List.of(KEEPS + " until the server restarts, since players are online") : List.of(), worldInfos);
assertEquals(List.of(), worldWarnings);
}
@ParameterizedTest(name = "{0} fails")
@CsvSource(delimiter = '|', quoteCharacter = '"', value = {
"lookup | false | : the pack's could not be registered",
"register | false | : the pack's could not be registered",
"apply | true | : wyck could not apply the pack's"
})
void failedStepKeepsTheWorldsType(String step, boolean registers, String warning) {
IllegalStateException boom = new IllegalStateException("boom");
switch(step) {
case "lookup" -> server.lookupFailure = boom;
case "register" -> server.registerFailure = boom;
case "apply" -> server.applyFailure = boom;
default -> throw new IllegalArgumentException(step);
}
assertFalse(initialise().shouldGenerateMobs());
assertEquals(registers ? List.of(TERRA_TEST) : List.of(), server.registrations);
assertEquals(List.of(), server.applications);
assertEquals(List.of(KEEPS + warning), worldWarnings);
}
private static final class FakeServer implements PaperDimensions.Server {
private final Set<Identifier> registered = new HashSet<>();
private final List<Identifier> registrations = new ArrayList<>();
private final List<Identifier> applications = new ArrayList<>();
private @Nullable RuntimeException lookupFailure;
private @Nullable RuntimeException registerFailure;
private @Nullable RuntimeException applyFailure;
@Override
public void registerTimelines(Consumer<WritableRegistry<Timeline>> registration) {
registration.accept(new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable()));
}
@Override
public Registry<Timeline> timelines() {
return PaperDimensionsTest.timelines();
}
@Override
public Holder<DimensionType> dimensionType(World world) {
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD);
}
@Override
public boolean isRegistered(Identifier key) {
if(lookupFailure != null) throw lookupFailure;
return registered.contains(key);
}
@Override
public void registerDimension(Identifier key, DimensionType type) {
if(registerFailure != null) throw registerFailure;
registrations.add(key);
registered.add(key);
}
@Override
public void applyDimension(World world, Identifier key) {
if(applyFailure != null) throw applyFailure;
applications.add(key);
}
}
}
@@ -0,0 +1,101 @@
package com.dfsek.terra.bukkit.util;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Timeout(10)
class ServerThreadTest {
private final ExecutorService server = Executors.newSingleThreadExecutor(r -> new Thread(r, "server"));
@AfterEach
void stopServer() {
server.shutdownNow();
}
@Test
void runsOnServerThread() {
AtomicReference<String> ranOn = new AtomicReference<>();
ServerThread.run(() -> ranOn.set(Thread.currentThread().getName()), server, () -> false, () -> false, 10);
assertEquals("server", ranOn.get());
}
@Test
void runsDirectlyOnServerThread() {
List<String> ran = new ArrayList<>();
ServerThread.run(() -> ran.add(Thread.currentThread().getName()), task -> {
throw new AssertionError("scheduled from the server thread");
}, () -> true, () -> false, 10);
assertEquals(List.of(Thread.currentThread().getName()), ran);
}
@Test
void rethrowsTaskException() {
IllegalStateException boom = new IllegalStateException("boom");
assertSame(boom, assertThrows(IllegalStateException.class, () -> ServerThread.run(() -> {
throw boom;
}, server, () -> false, () -> false, 10)));
}
@Test
void dropsPendingTaskOnStop() {
List<Runnable> scheduled = new ArrayList<>();
AtomicBoolean ran = new AtomicBoolean();
assertThrows(CancellationException.class, () -> ServerThread.run(() -> ran.set(true), scheduled::add, () -> false, () -> true,
10));
scheduled.forEach(Runnable::run);
assertFalse(ran.get());
}
@Test
void waitsForStartedTaskOnStop() throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicBoolean finished = new AtomicBoolean();
AtomicBoolean stopping = new AtomicBoolean();
Thread caller = new Thread(() -> ServerThread.run(() -> {
started.countDown();
try {
release.await();
} catch(InterruptedException e) {
throw new IllegalStateException(e);
}
finished.set(true);
}, server, () -> false, stopping::get, 10));
caller.start();
assertTrue(started.await(5, TimeUnit.SECONDS));
stopping.set(true);
caller.interrupt();
Thread.sleep(50);
assertTrue(caller.isAlive(), "the caller waits for the running task");
release.countDown();
caller.join();
assertTrue(finished.get());
}
}
@@ -0,0 +1,286 @@
/*
* This file is part of Terra.
*
* Terra is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Terra is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Terra. If not, see <https://www.gnu.org/licenses/>.
*/
package com.dfsek.terra.bukkit.world;
import net.minecraft.core.Holder;
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.entity.npc.villager.VillagerType;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
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.Stream;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource;
import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory;
import com.dfsek.terra.world.attribute.platform.AttributeReport;
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
import static org.junit.jupiter.api.Named.named;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
class BiomeHandlerTest {
private static final Biome PARENT = biome(Biomes.DESERT);
private static final Biome BUILT = biome(Biomes.PLAINS);
private static final String PREFIX = "Pack \"test\", config \"BIOME\": ";
private final List<String> warnings = new ArrayList<>();
private static Biome biome(net.minecraft.resources.ResourceKey<Biome> key) {
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value();
}
private BiomeHandler.Registration<Biome> register(MinecraftBiomeFactory.Built built, Function<Biome, Biome> wyck) {
return BiomeHandler.registration(() -> {
if(built == null) throw new IllegalStateException("boom");
return built;
}, wyck, PARENT, VillagerType.DESERT, "test", "BIOME", warnings::add);
}
private static Biome rejecting(Biome biome, Biome rejected) {
if(biome == rejected) throw new IllegalArgumentException("boom");
return biome;
}
private static Stream<Arguments> registrations() {
Function<Biome, Biome> readsAll = b -> b;
Function<Biome, Biome> rejectsBuilt = b -> rejecting(b, BUILT);
Function<Biome, Biome> rejectsAll = b -> rejecting(b, b);
return Stream.of(
Arguments.of(true, named("wyck reads all", readsAll), BUILT, VillagerType.SNOW, null),
Arguments.of(false, named("wyck reads all", readsAll), PARENT, VillagerType.DESERT,
"biome built from its parent: its attributes could not be applied"),
Arguments.of(true, named("wyck rejects the built biome", rejectsBuilt), PARENT, VillagerType.DESERT,
"biome built from its parent: wyck could not read its attributes"),
Arguments.of(true, named("wyck rejects all", rejectsAll), null, null,
"biome skipped: wyck could not read its attributes or its parent"),
Arguments.of(false, named("wyck rejects all", rejectsAll), null, null,
"biome skipped: its attributes could not be applied, and wyck could not read its parent"));
}
@ParameterizedTest(name = "builds {0}, {1}")
@MethodSource("registrations")
void registrationFallsBackToTheParent(boolean builds, Function<Biome, Biome> wyck, @Nullable Biome biome,
@Nullable ResourceKey<VillagerType> villagerType, @Nullable String warning) {
BiomeHandler.Registration<Biome> registration = register(builds ? new MinecraftBiomeFactory.Built(BUILT, VillagerType.SNOW)
: null, wyck);
if(biome == null) {
assertNull(registration);
} else {
assertSame(biome, registration.biome());
assertEquals(villagerType, registration.villagerType());
}
assertEquals(warning == null ? List.of() : List.of(PREFIX + warning), warnings);
}
@Test
void failedAppendSkipsTag() {
TagKey<Biome> isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest"));
TagKey<Biome> isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean"));
TagKey<Biome> hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow"));
List<Identifier> terra = List.of(Identifier.fromNamespaceAndPath("terra", "t/b"));
Map<TagKey<Biome>, List<Identifier>> additions = new LinkedHashMap<>();
additions.put(isForest, terra);
additions.put(isOcean, terra);
additions.put(hasSnow, terra);
List<TagKey<Biome>> appended = new ArrayList<>();
int count = BiomeHandler.appendAll(additions, (tag, biomes) -> {
if(tag == isOcean) throw new IllegalStateException("boom");
appended.add(tag);
}, "wyck could not append to the tag", warnings::add);
assertEquals(2, count);
assertEquals(List.of(isForest, hasSnow), appended);
assertEquals(List.of("Biome tag \"minecraft:is_ocean\": terra biomes not added: wyck could not append to the tag"), warnings);
}
@Test
void nothingNewSkipsRegistration() {
List<String> info = new ArrayList<>();
List<List<String>> registered = new ArrayList<>();
BiomeHandler.registerNew(List.<String>of(), registered::add, info::add);
BiomeHandler.registerNew(List.of("a", "b"), registered::add, info::add);
assertEquals(List.of(List.of("a", "b")), registered);
assertEquals(List.of("No new custom biomes to register.", "Registering 2 custom biomes through Wyck..."), info);
}
private static ConfigPack pack(String id) {
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "getID" -> id;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == args[0];
case "toString" -> "ConfigPack[" + id + "]";
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static final Identifier PLAINS = Biomes.PLAINS.identifier();
private static final Identifier DESERT = Biomes.DESERT.identifier();
private PlatformTagSource tags(String pack, String config) {
return new PlatformTagSource(new AttributeReport(pack, warnings::add, m -> { }), config, Set.of());
}
private void add(BiomeHandler.Run<String> run, String pack, String config, String key, Identifier parent, boolean registered,
net.minecraft.resources.ResourceKey<VillagerType> type, List<String> after) {
run.add(Identifier.fromNamespaceAndPath("terra", key), parent, registered,
() -> new BiomeHandler.Registration<>(pack + "/" + config, type), tags(pack, config), () -> after.add(pack + "/" + config),
pack, config, warnings::add);
}
@Test
void unreadablePackSkipped() {
List<String> after = new ArrayList<>();
BiomeHandler.Run<String> run = BiomeHandler.<String, String>collect(
List.of(pack("first"), pack("unreadable"), pack("broken"), pack("last")), pack -> {
if(pack.getID().equals("unreadable")) throw new ClassCastException("boom");
return pack.getID();
}, (pack, prepared, packRun) -> {
add(packRun, prepared, "a", prepared + "/a", PLAINS, false, VillagerType.PLAINS, after);
if(prepared.equals("broken")) throw new IllegalArgumentException("boom");
}, warnings::add);
run.afterRegistration.forEach(Runnable::run);
assertEquals(List.of("Pack \"unreadable\": biomes skipped: its attributes could not be read",
"Pack \"broken\": biomes skipped: they could not be built"), warnings);
assertEquals(List.of("first/a", "last/a"), run.toRegister);
assertEquals(List.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a")),
List.copyOf(run.villagerTypes.keySet()));
assertEquals(Map.of(PLAINS, List.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a"))), run.byParent);
assertEquals(Set.of(Identifier.parse("terra:first/a"), Identifier.parse("terra:last/a")), run.platformTags.keySet());
assertEquals(List.of("first/a", "last/a"), after);
}
@Test
void registeredBiomeNotQueued() {
List<String> after = new ArrayList<>();
BiomeHandler.Run<String> run = new BiomeHandler.Run<>(null);
add(run, "test", "a", "test/a", PLAINS, true, VillagerType.PLAINS, after);
assertEquals(List.of(), run.toRegister);
assertEquals(Map.of(), run.villagerTypes);
assertEquals(Map.of(PLAINS, List.of(Identifier.parse("terra:test/a"))), run.byParent);
assertEquals(1, run.afterRegistration.size());
}
@Test
void sameKeyIsQueuedOnce() {
List<String> after = new ArrayList<>();
BiomeHandler.Run<String> run = BiomeHandler.<ConfigPack, String>collect(List.of(pack("test"), pack("TEST")), pack -> pack,
(pack, prepared, packRun) -> {
if(pack.getID().equals("test")) {
add(packRun, "test", "Snowy", "test/snowy", PLAINS, false, VillagerType.SNOW, after);
add(packRun, "test", "SNOWY", "test/snowy", DESERT, false, VillagerType.DESERT, after);
} else {
add(packRun, "TEST", "snowy", "test/snowy", DESERT, false, VillagerType.DESERT, after);
}
}, warnings::add);
run.afterRegistration.forEach(Runnable::run);
Identifier snowy = Identifier.parse("terra:test/snowy");
assertEquals(List.of("test/Snowy"), run.toRegister);
assertEquals(Map.of(snowy, VillagerType.SNOW), run.villagerTypes);
assertEquals(Map.of(PLAINS, List.of(snowy)), run.byParent);
assertEquals("Snowy", run.platformTags.get(snowy).config());
assertEquals(List.of("test/Snowy", "test/SNOWY", "TEST/snowy"), after);
assertEquals(List.of(
"Pack \"test\", config \"SNOWY\": biome \"terra:test/snowy\" shared with another config: their IDs differ only in case",
"Pack \"TEST\", config \"snowy\": biome \"terra:test/snowy\" shared with another config: their IDs differ only in case"),
warnings);
}
@Test
void unreadableParentEntriesAreEmpty() {
AttributeSlots entries = BiomeHandler.parentEntries(() -> {
throw new ClassCastException("boom");
}, "test", "BIOME", warnings::add);
assertSame(AttributeSlots.EMPTY, entries);
assertEquals(List.of(PREFIX + "parent attributes ignored: they could not be read"), warnings);
}
private static TagKey<Biome> tag(String id) {
return TagKey.create(Registries.BIOME, Identifier.parse(id));
}
private static Optional<Holder<Biome>> lookup(Identifier id) {
return REGISTRIES.lookupOrThrow(Registries.BIOME).get(net.minecraft.resources.ResourceKey.create(Registries.BIOME, id))
.map(h -> h);
}
@Test
void reloadedTagsGetTerraBiomesOnce() {
Identifier plains = Biomes.PLAINS.identifier();
Identifier forest = Biomes.FOREST.identifier();
Identifier terra = Biomes.DESERT.identifier();
TagKey<Biome> villagePlains = tag("minecraft:has_structure/village_plains");
TagKey<Biome> isForest = tag("minecraft:is_forest");
TagKey<Biome> hasSnow = tag("mypack:has_snow");
TagKey<Biome> isOcean = tag("minecraft:is_ocean");
Map<TagKey<Biome>, List<Identifier>> tags = new LinkedHashMap<>();
tags.put(villagePlains, List.of(plains));
tags.put(isForest, List.of(forest));
tags.put(isOcean, List.of(Biomes.OCEAN.identifier()));
Set<RegistryKey> platformTags = new LinkedHashSet<>(List.of(RegistryKey.parse("mypack:has_snow"),
RegistryKey.parse("minecraft:is_forest")));
PlatformTagSource source = new PlatformTagSource(new AttributeReport("test", warnings::add, m -> { }), "BIOME", platformTags);
Map<TagKey<Biome>, List<Identifier>> additions = BiomeHandler.reloadAdditions(tags, BiomeHandlerTest::lookup,
Map.of(plains, List.of(terra)), Map.of(terra, source));
assertEquals(List.of(villagePlains, isForest, hasSnow), List.copyOf(additions.keySet()));
assertEquals(List.of(terra), additions.get(villagePlains));
assertEquals(List.of(terra), additions.get(isForest));
assertEquals(List.of(terra), additions.get(hasSnow));
assertEquals(List.of(), warnings);
Map<TagKey<Biome>, List<Identifier>> reloaded = new LinkedHashMap<>(tags);
additions.forEach((tag, ids) -> reloaded.merge(tag, ids, (old, added) -> Stream.concat(old.stream(), added.stream()).toList()));
assertEquals(Map.of(), BiomeHandler.reloadAdditions(reloaded, BiomeHandlerTest::lookup, Map.of(plains, List.of(terra)),
Map.of(terra, source)));
}
}