diff --git a/buildSrc/src/main/kotlin/Versions.kt b/buildSrc/src/main/kotlin/Versions.kt index bdfec58ce..64a681d91 100644 --- a/buildSrc/src/main/kotlin/Versions.kt +++ b/buildSrc/src/main/kotlin/Versions.kt @@ -63,7 +63,7 @@ object Versions { const val paperBuild = "$minecraft.build.244-stable" const val paper = paperBuild const val runPaper = "3.0.2" - const val wyck = "4.0.0-837d6ec" + const val wyck = "4.0.0-0f573ad7" const val cloud = "2.0.1" const val multiverse = "5.3.0" } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java index 8a3ce64b5..aad800abe 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/AbstractPlatform.java @@ -129,11 +129,9 @@ public abstract class AbstractPlatform implements Platform { public static int getMoonriseGenerationThreadsWithReflection() { try { - Class prioritisedThreadPoolClazz = Class.forName("ca.spottedleaf.concurrentutil.executor.thread.PrioritisedThreadPool"); - Method getCoreThreadsMethod = prioritisedThreadPoolClazz.getDeclaredMethod("getCoreThreads"); - getCoreThreadsMethod.setAccessible(true); Class moonriseCommonClazz = Class.forName("ca.spottedleaf.moonrise.common.util.MoonriseCommon"); - Object pool = moonriseCommonClazz.getDeclaredField("WORKER_POOL").get(null); + Object pool = moonriseCommonClazz.getField("WORKER_POOL").get(null); + Method getCoreThreadsMethod = pool.getClass().getMethod("getCoreThreads"); int threads = ((Thread[]) getCoreThreadsMethod.invoke(pool)).length; logger.info("{} found, setting {} generation threads.", moonrise, threads); return threads; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java similarity index 84% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java rename to common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java index ac10cbf38..1a8091487 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeReport.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeReport.java @@ -1,8 +1,9 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.world.attribute.platform; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -22,6 +23,7 @@ public final class AttributeReport { private final Consumer warn; private final Consumer debug; private final Set notApplied = ConcurrentHashMap.newKeySet(); + private final Set> notAppliedToWorld = ConcurrentHashMap.newKeySet(); public AttributeReport(String pack, Consumer warn, Consumer debug) { this.pack = Objects.requireNonNull(pack, "pack"); @@ -65,4 +67,11 @@ public final class AttributeReport { public void notApplied(String key) { if(notApplied.add(key)) debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied on this platform"); } + + public void notAppliedToWorld(String key, String world) { + if(notAppliedToWorld.add(Map.entry(key, world))) { + debug.accept("Pack \"" + pack + "\": attribute \"" + key + "\" is not applied to world \"" + world + + "\": it is fixed when the world is created"); + } + } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java similarity index 95% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java rename to common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java index 067f03c80..4574b0d64 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/AttributeSlots.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/AttributeSlots.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.world.attribute.platform; import org.jetbrains.annotations.Nullable; diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java new file mode 100644 index 000000000..8c805e57a --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentEntryHolder.java @@ -0,0 +1,8 @@ +package com.dfsek.terra.world.attribute.platform; + +public interface ParentEntryHolder { + /** + * {@link AttributeSlots#EMPTY} until the platform sets them. + */ + AttributeSlots parentEntries(); +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java new file mode 100644 index 000000000..4c394e539 --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/world/attribute/platform/ParentFold.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.world.attribute.platform; + +import java.util.Objects; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; + + +public final class ParentFold { + private ParentFold() { + } + + /** + * Composes {@code upper} over {@code lower} per attribute, or overrides with their resolved value when they don't compose. + */ + public static AttributeSlots fold(AttributeHandle handle, Iterable> attributes, AttributeSlots lower, + AttributeSlots upper) { + Objects.requireNonNull(lower, "lower"); + Objects.requireNonNull(upper, "upper"); + AttributeEntry[] slots = new AttributeEntry[handle.attributeCount()]; + for(Attribute attribute : attributes) fold(handle, attribute, lower, upper, slots); + return AttributeSlots.of(slots); + } + + private static void fold(AttributeHandle handle, Attribute attribute, AttributeSlots lower, AttributeSlots upper, + AttributeEntry[] slots) { + AttributeEntry below = lower.get(attribute); + AttributeEntry above = upper.get(attribute); + if(below == null && above == null) return; + slots[attribute.index()] = handle.compose(attribute, below, above) + .orElseGet(() -> AttributeEntry.override(handle.resolve(attribute, below, above, null))); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java new file mode 100644 index 000000000..eb997f3dc --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeReportTest.java @@ -0,0 +1,51 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +class AttributeReportTest { + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + + @Test + void reportFormats() { + report.attributeSkipped("BIOME", "minecraft:visual/fog_color", "not a colour"); + report.scheduleSkipped("mypack:seasons", "no clock"); + report.trackDropped("mypack:seasons", "minecraft:visual/fog_color", "bad keyframe"); + report.timeMarkerDropped("mypack:seasons", "minecraft:noon", "minecraft:overworld"); + report.ignored("pack.yml", "vanilla", "no such dimension type \"minecraft:nope\""); + report.tagCreated("BIOME", "minecraft:is_custom"); + report.notApplied("test:custom"); + report.notApplied("test:custom"); + report.notApplied("test:other"); + + assertEquals(List.of( + "Pack \"test\", config \"BIOME\": attribute \"minecraft:visual/fog_color\" skipped: not a colour", + "Pack \"test\": schedule \"mypack:seasons\" skipped: no clock", + "Pack \"test\": schedule \"mypack:seasons\" track \"minecraft:visual/fog_color\" dropped: bad keyframe", + "Pack \"test\": schedule \"mypack:seasons\" time marker \"minecraft:noon\" dropped: already defined for clock " + + "\"minecraft:overworld\"", + "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"", + "Pack \"test\", config \"BIOME\": tag \"minecraft:is_custom\" created: no such tag in the minecraft namespace"), warnings); + assertEquals(List.of( + "Pack \"test\": attribute \"test:custom\" is not applied on this platform", + "Pack \"test\": attribute \"test:other\" is not applied on this platform"), debugs); + } + + @Test + void notAppliedToWorldOnce() { + report.notAppliedToWorld("terra:dimension/min_y", "world"); + report.notAppliedToWorld("terra:dimension/min_y", "world"); + + assertEquals(List.of(), warnings); + assertEquals(List.of( + "Pack \"test\": attribute \"terra:dimension/min_y\" is not applied to world \"world\": it is fixed when the world is created"), + debugs); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java new file mode 100644 index 000000000..2c1702cc3 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/AttributeSlotsTest.java @@ -0,0 +1,27 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + + +class AttributeSlotsTest { + @Test + void outOfRangeIsNull() { + AttributeHandle handle = new AttributeHandleImpl(); + Attribute attribute = null; + for(int i = 0; i <= 5; i++) { + attribute = handle.attributeBuilder(AttributeKey.parse("test:a" + i), handle.types().floatType(), 0f).build(); + } + assertEquals(5, attribute.index()); + + assertNull(AttributeSlots.of(new AttributeEntry[1]).get(attribute)); + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java new file mode 100644 index 000000000..0ee531cbb --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/world/attribute/platform/ParentFoldTest.java @@ -0,0 +1,54 @@ +package com.dfsek.terra.world.attribute.platform; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; +import com.dfsek.terra.api.world.attribute.AttributeKey; +import com.dfsek.terra.api.world.attribute.Operation; +import com.dfsek.terra.world.attribute.AttributeHandleImpl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + + +class ParentFoldTest { + private static final AttributeHandle HANDLE = new AttributeHandleImpl(); + private static final Attribute FOG_END = HANDLE.attributeBuilder(AttributeKey.parse("test:fog_end"), + HANDLE.types().floatType(), 1024f).build(); + + private static AttributeSlots slots(AttributeEntry entry) { + AttributeEntry[] entries = new AttributeEntry[HANDLE.attributeCount()]; + entries[FOG_END.index()] = entry; + return AttributeSlots.of(entries); + } + + private static AttributeEntry fold(AttributeEntry lower, AttributeEntry upper) { + return ParentFold.fold(HANDLE, List.of(FOG_END), slots(lower), slots(upper)).get(FOG_END); + } + + @Test + void foldComposes() { + assertNull(fold(null, null)); + AttributeEntry lower = AttributeEntry.override(2f); + assertSame(lower, fold(lower, null)); + AttributeEntry upper = AttributeEntry.override(2f); + assertSame(upper, fold(null, upper)); + assertEquals(AttributeEntry.of(Operation.ADD, 3f), fold(AttributeEntry.of(Operation.ADD, 1f), AttributeEntry.of(Operation.ADD, 2f))); + } + + @Test + void foldOverrides() { + AttributeEntry lower = AttributeEntry.of(Operation.ADD, 1f); + AttributeEntry upper = AttributeEntry.of(Operation.MULTIPLY, 2f); + AttributeEntry folded = fold(lower, upper); + assertNotNull(folded); + assertEquals(Operation.OVERRIDE, folded.operation()); + assertEquals(HANDLE.resolve(FOG_END, lower, upper, null), folded.argument()); + } +} diff --git a/platforms/bukkit/build.gradle.kts b/platforms/bukkit/build.gradle.kts index 19e82e6ae..5f006ce52 100644 --- a/platforms/bukkit/build.gradle.kts +++ b/platforms/bukkit/build.gradle.kts @@ -27,11 +27,18 @@ tasks { minecraftVersion(Versions.Bukkit.minecraft) dependsOn(shadowJar) pluginJars(shadowJar.get().archiveFile) + // Modrinth's Wyck lacks our fixes. + val wyckJar = file("${System.getProperty("user.home")}/Wyck/paper/build/libs/Wyck-${Versions.Bukkit.wyck}.jar") + pluginJars(wyckJar) + doFirst { + if(!wyckJar.isFile) { + throw GradleException("No Wyck plugin jar at $wyckJar: build and publish ~/Wyck (Wyck ${Versions.Bukkit.wyck}) first") + } + } downloadPlugins { modrinth("viaversion", "5.12.2") modrinth("viabackwards", "5.12.2") - modrinth("wyck", Versions.Bukkit.wyck) } } } diff --git a/platforms/bukkit/common/build.gradle.kts b/platforms/bukkit/common/build.gradle.kts index 3a3d3805a..bd5750e05 100644 --- a/platforms/bukkit/common/build.gradle.kts +++ b/platforms/bukkit/common/build.gradle.kts @@ -1,6 +1,19 @@ -repositories { - +plugins { + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom } + +// Loom here is in another classloader than minecraft-common's and must not read its extension. +extra["fabric.loom.disableProjectDependentMods"] = "true" + +loom { + accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) +} + +// Paper and Multiverse declare runtime-only libraries that break Loom's mod scan. +configurations.matching { it.name.endsWith("CompileDependencyResolve") }.configureEach { + attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage.JAVA_API)) +} + tasks.withType().configureEach { options.release = 25 } @@ -8,13 +21,23 @@ tasks.withType().configureEach { dependencies { shadedApi(project(":common:implementation:base")) + // Paper runs vanilla unobfuscated and Mojang-named. + minecraft("com.mojang:minecraft:${Versions.Bukkit.minecraft}") + + implementation(project(":platforms:minecraft-common")) { isTransitive = false } + shaded(project(":platforms:minecraft-common")) { isTransitive = false } + compileOnly("io.papermc.paper", "paper-api", Versions.Bukkit.paper) - compileOnly("dev.wyck", "Wyck", Versions.Bukkit.wyck) + compileOnly("com.dfsek.wyck", "Wyck", Versions.Bukkit.wyck) compileOnly("org.mvplugins.multiverse.core", "multiverse-core", Versions.Bukkit.multiverse) shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava) shadedApi("org.incendo", "cloud-paper", Versions.Bukkit.cloud) + + testImplementation(testFixtures(project(":platforms:minecraft-common"))) + testImplementation(project(":common:addons:minecraft-attributes")) + testImplementation("io.papermc.paper", "paper-api", Versions.Bukkit.paper) } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java index 958096c87..720cc664c 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitAddon.java @@ -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 diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java index b3491ef77..1d3cc1c09 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/BukkitPlatform.java @@ -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 { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java new file mode 100644 index 000000000..681bf2435 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitBootstrap.java @@ -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 . + */ +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()); + }); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java index 5caa27e39..2edb9872a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/TerraBukkitPlugin.java @@ -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 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 diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java new file mode 100644 index 000000000..ba2e1d13d --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperDimensions.java @@ -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 . + */ +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 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> 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 info; + private final Consumer warn; + // Direct lists survive tag reloads. + private final Map 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 info, Consumer 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 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 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 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> 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> keys = contents.stream().flatMap(holder -> holder.unwrapKey().stream()).toList(); + resolvedTimelines.put(pack.getID(), new TimelineRef.Direct(keys)); + } + + public Optional typeFor(ConfigPack pack, ResourceKey worldTypeKey, DimensionType worldType, String worldName) { + Optional 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 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 @Nullable Object resolveEncoded(Attribute 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 current = server.dimensionType(world); + ResourceKey currentKey = current.unwrapKey() + .orElseThrow(() -> new IllegalStateException("the world's dimension type has no key")); + Optional 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 attributes) { + return parents.prepare(pack, attributes, AttributeReport.logging(pack)); + } + + + public record Built(Identifier key, DimensionType type, WorldSettings settings) { } + + + interface Server { + void registerTimelines(Consumer> registration); + + Registry timelines(); + + Holder 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> registration) { + WyckBridge.registerTimelines(registration); + } + + @Override + public Registry timelines() { + return PaperVanilla.server().registryAccess().lookupOrThrow(Registries.TIMELINE); + } + + @Override + public Holder 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(); + } + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java new file mode 100644 index 000000000..b81a0c42f --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/PaperVanilla.java @@ -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 . + */ +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> 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> villagerTypes() { + Map, ResourceKey> 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>) map; + } + return villagerTypes; + } + } + + public static VanillaContext context(HolderLookup.Provider registries) { + return VanillaContext.of(registries, villagerTypes()::get); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java new file mode 100644 index 000000000..e5ffb3c37 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/attribute/WyckBridge.java @@ -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 . + */ +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 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 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> registration) { + WyckRegistry.of(RegistryId.TIMELINE).whileUnfrozen(r -> registration.accept((WritableRegistry) 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 biomes) { + BiomeRegistry.registry().register(biomes); + } + + public static void appendBiomeTag(TagKey tag, Collection biomes) { + Set 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()); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java deleted file mode 100644 index ae39c84ac..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeAdditionsSoundTemplate.java +++ /dev/null @@ -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 { - @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(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java deleted file mode 100644 index 37f621819..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeMoodSoundTemplate.java +++ /dev/null @@ -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 { - @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(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java deleted file mode 100644 index bf567032c..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/BiomeParticleConfigTemplate.java +++ /dev/null @@ -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 { - 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; - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java deleted file mode 100644 index 5472bad00..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/EntityTypeTemplate.java +++ /dev/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 { - @Value("id") - @Default - private ResourceKey id = null; - - @Override - public EntityType get() { - return RegistryAccess.registryAccess().getRegistry(RegistryKey.ENTITY_TYPE) - .getOrThrow(id); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java deleted file mode 100644 index d5438675e..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/MusicSoundTemplate.java +++ /dev/null @@ -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 { - @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(); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java deleted file mode 100644 index 6af7bee60..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SoundEventTemplate.java +++ /dev/null @@ -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 { - @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); - } - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java deleted file mode 100644 index eb5b522d5..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnCostConfig.java +++ /dev/null @@ -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 { - @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; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java deleted file mode 100644 index 7369822ce..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnEntryConfig.java +++ /dev/null @@ -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 { - @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; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java deleted file mode 100644 index 686524c28..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnSettingsTemplate.java +++ /dev/null @@ -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 { - - private static final Logger LOGGER = LoggerFactory.getLogger(SpawnSettingsTemplate.class); - private static final AtomicBoolean PROBABILITY_WARNING_LOGGED = new AtomicBoolean(false); - - @Value("spawns") - @Default - private List spawns = null; - - @Value("costs") - @Default - private List 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(); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java deleted file mode 100644 index 577857bc9..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/SpawnTypeConfig.java +++ /dev/null @@ -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 { - @Value("group") - @Default - private MobCategory group = null; - - @Value("entries") - @Default - private List entries = null; - - public MobCategory getGroup() { - return group; - } - - public List getEntries() { - return entries; - } - - @Override - public SpawnTypeConfig get() { - return this; - } -} \ No newline at end of file diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java deleted file mode 100644 index c6c30bb0d..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VanillaBiomeProperties.java +++ /dev/null @@ -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; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java deleted file mode 100644 index ff3974d3e..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/config/VillagerTypeTemplate.java +++ /dev/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.Villager; - - -public class VillagerTypeTemplate implements ObjectTemplate { - @Value("id") - @Default - private ResourceKey id = null; - - @Override - public Villager.Type get() { - return RegistryAccess.registryAccess().getRegistry(RegistryKey.VILLAGER_TYPE) - .getOrThrow(id); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java index 04c8f3be9..1ffe29967 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBiomeProvider.java @@ -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())); diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java index 27f52de47..b008b788a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitBlockPopulator.java @@ -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; diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java index 7f60527aa..708bac0d5 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/generator/BukkitChunkGeneratorWrapper.java @@ -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 diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java deleted file mode 100644 index 7e7321f7b..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/BiomeListener.java +++ /dev/null @@ -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 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; - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java index 9a06dd3c9..4071bb71a 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/CommonListener.java @@ -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 -> { diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java new file mode 100644 index 000000000..352a911e1 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/listeners/DimensionListener.java @@ -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 . + */ +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); + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java new file mode 100644 index 000000000..ee2c9f0a6 --- /dev/null +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/ServerThread.java @@ -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 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(); + } + } +} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java deleted file mode 100644 index 5f22c6868..000000000 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/util/VanillaParticles.java +++ /dev/null @@ -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(); - } -} diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java index e89517d1f..baf27b448 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BiomeHandler.java @@ -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 VILLAGER_TYPES = new ConcurrentHashMap<>(); + private static final Map> BY_PARENT = new HashMap<>(); + private static final Map 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 registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); org.bukkit.Registry bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); - List toRegister = new ArrayList<>(); - List 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 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 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 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> 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, Set> 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 vanillaKey = TypedKey.create(RegistryKey.BIOME, info.vanillaKey().key()); - terraBiomesByVanilla.computeIfAbsent(vanillaKey, k -> new HashSet<>()).add(Biome.reference(info.biomeKey())); + static Run collect(Iterable packs, Function prepare, PackCollector collectPack, + Consumer warn) { + Run 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 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 bukkitRegistry = RegistryAccess.registryAccess().getRegistry(RegistryKey.BIOME); - int count = 0; - for(Tag tag : bukkitRegistry.getTags()) { - Set members = new HashSet<>(); - terraBiomesByVanilla.forEach((vanillaKey, terraBiomes) -> { - if(tag.contains(vanillaKey)) { - members.addAll(terraBiomes); + @FunctionalInterface + interface PackCollector { + void collect(ConfigPack pack, P prepared, Run run); + } + + static AttributeSlots parentEntries(Supplier read, String pack, String config, Consumer 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 { + private final @Nullable Run before; + final List toRegister = new ArrayList<>(); + final Map> villagerTypes = new LinkedHashMap<>(); + final Map> byParent = new LinkedHashMap<>(); + final Map platformTags = new LinkedHashMap<>(); + final List afterRegistration = new ArrayList<>(); + + Run(@Nullable Run before) { + this.before = before; + } + + void add(Identifier terraId, Identifier parent, boolean registered, Supplier<@Nullable Registration> registration, + PlatformTagSource tags, Runnable after, String pack, String config, Consumer 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 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 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 void registerNew(List biomes, Consumer> register, Consumer 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 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 registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); + Map, List>> before = new LinkedHashMap<>(); + registry.getTags().forEach(tag -> before.put(tag.key(), new ArrayList<>(tag.stream().toList()))); + Map, List>> 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, List> 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 registrar) { + try { + Registry registry = PaperVanilla.server().registryAccess().lookupOrThrow(Registries.BIOME); + Map, List> 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, List> 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, List> reloadAdditions(Map, List> tags, + Function>> lookup, + Map> byParent, + Map platformTags) { + Map, List>> before = new LinkedHashMap<>(); + Map, List>> after = new LinkedHashMap<>(); + tags.forEach((tag, members) -> { + List> old = members.stream().map(lookup).flatMap(Optional::stream).toList(); + List> 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, List> additions(Map, List>> before, + Map, List>> after) { + Map, List> additions = new LinkedHashMap<>(); + after.forEach((tag, members) -> { + Set> old = new HashSet<>(before.getOrDefault(tag, List.of())); + Set added = new LinkedHashSet<>(); + for(Holder 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 biome, ResourceKey villagerType) { } + + static @Nullable Registration registration(Supplier build, Function wyck, + Biome parent, ResourceKey parentVillagerType, String pack, + String config, Consumer 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 @Nullable Registration parent(Function wyck, Biome parent, ResourceKey villagerType, + String prefix, String reason, String skipReason, Consumer warn) { + try { + Registration 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, List> additions, BiConsumer, List> append, + String failure, Consumer warn) { + int appended = 0; + for(Map.Entry, List> 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 EnvironmentAttributeMap override(EnvironmentAttributeMap map, EnvironmentAttributeSupplier 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; - } } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java index 5be1be7d8..c11a6e024 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitBiomeInfo.java @@ -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 { } diff --git a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java index 9af8e9db5..386a0faa1 100644 --- a/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java +++ b/platforms/bukkit/common/src/main/java/com/dfsek/terra/bukkit/world/BukkitPlatformBiome.java @@ -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"); + } } diff --git a/platforms/bukkit/common/src/main/resources/paper-plugin.yml b/platforms/bukkit/common/src/main/resources/paper-plugin.yml index 2a1b472a5..d69c8e10d 100644 --- a/platforms/bukkit/common/src/main/resources/paper-plugin.yml +++ b/platforms/bukkit/common/src/main/resources/paper-plugin.yml @@ -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" ] diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java new file mode 100644 index 000000000..47438ee8e --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/BukkitParentsTest.java @@ -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 . + */ +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> REGISTRY = registry(); + private static final ConfigPack PACK = pack("test"); + private static final Attribute PRECIPITATION = attribute(MinecraftAttributes.BIOME_HAS_PRECIPITATION.getRegistryKey().toString()); + private static final Attribute HAS_CEILING = attribute(MinecraftAttributes.DIMENSION_HAS_CEILING.getRegistryKey().toString()); + + private final List 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> types = PaperVanilla.villagerTypes(); + assertSame(types, PaperVanilla.villagerTypes(), "read once"); + assertEquals(VillagerType.DESERT, types.get(Biomes.DESERT)); + + ResourceKey test = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test_biome")); + ResourceKey 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; + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java new file mode 100644 index 000000000..b8aa1c6da --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperBiomeTest.java @@ -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 . + */ +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 warnings = new ArrayList<>(); + private final List 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 vanilla(ResourceKey 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 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 biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); + Holder forest = biomes.register(Biomes.FOREST, vanilla(Biomes.FOREST).value(), RegistrationInfo.BUILT_IN); + Holder ocean = biomes.register(Biomes.OCEAN, vanilla(Biomes.OCEAN).value(), RegistrationInfo.BUILT_IN); + Identifier terraId = Identifier.fromNamespaceAndPath("terra", "t/b"); + Holder terra = biomes.register(ResourceKey.create(Registries.BIOME, terraId), vanilla(Biomes.PLAINS).value(), + RegistrationInfo.BUILT_IN); + TagKey isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest")); + TagKey isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean")); + TagKey hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow")); + + Map, List>> before = new LinkedHashMap<>(); + before.put(isForest, List.of(forest)); + before.put(isOcean, List.of(ocean)); + Map, List>> 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)); + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java new file mode 100644 index 000000000..31488daa8 --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/attribute/PaperDimensionsTest.java @@ -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 . + */ +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> REGISTRY = registry(); + private static final VanillaContext PAPER = PaperVanilla.context(REGISTRIES); + private static final Map NETHER = Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")); + private static final Map OVERWORLD = Map.of("vanilla", RegistryKey.parse("minecraft:overworld")); + private static final ResourceKey SEASONS = ResourceKey.create(Registries.TIMELINE, Identifier.parse("mypack:seasons")); + + private final List warnings = new ArrayList<>(); + private final List debugs = new ArrayList<>(); + private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add); + private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE); + private final List worldInfos = new ArrayList<>(); + private final List 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) { + 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 entries, Map parentIds, + List> 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 entries, Map 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 void put(AttributeMap.Builder builder, Attribute attribute, AttributeEntry entry) { + builder.put(attribute.key(), (AttributeEntry) 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 key) { + return context.dimensionTypes().getOrThrow(key).value(); + } + + private PaperDimensions.Built typeFor(VanillaContext context, ConfigPack pack, ResourceKey world, String worldName) { + return dimensions.typeFor(pack, world, dimensionType(context, world), worldName).orElseThrow(); + } + + private PaperDimensions.Built typeFor(ConfigPack pack, ResourceKey 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 timelines() { + MappedRegistry timelines = new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable()); + REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements() + .forEach(holder -> timelines.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN)); + RegistryOps 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, List>> 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 timelines) { + Map, HolderLookup.RegistryLookup> lookups = new LinkedHashMap<>(); + REGISTRIES.listRegistries().forEach(lookup -> lookups.put(lookup.key(), lookup)); + lookups.put(Registries.TIMELINE, timelines); + RegistryOps ops = HolderLookup.Provider.create(lookups.values().stream()).createSerializationContext(JavaOps.INSTANCE); + + MappedRegistry 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 reread(Codec codec, T value, RegistryOps from, RegistryOps to) { + try { + return VanillaCodecs.parse(codec, VanillaCodecs.encode(codec, value, from), to); + } catch(DecodeException e) { + throw new AssertionError(e.getMessage(), e); + } + } + + private static Either id(String id) { + return Either.left(RegistryKey.parse(id)); + } + + private static Either tag(String namespace, String id) { + return Either.right(com.dfsek.terra.api.registry.key.TagKey.of(RegistryKey.of(namespace, id))); + } + + private static List> 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 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 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 registered = new HashSet<>(); + private final List registrations = new ArrayList<>(); + private final List applications = new ArrayList<>(); + private @Nullable RuntimeException lookupFailure; + private @Nullable RuntimeException registerFailure; + private @Nullable RuntimeException applyFailure; + + @Override + public void registerTimelines(Consumer> registration) { + registration.accept(new MappedRegistry<>(Registries.TIMELINE, Lifecycle.stable())); + } + + @Override + public Registry timelines() { + return PaperDimensionsTest.timelines(); + } + + @Override + public Holder 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); + } + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java new file mode 100644 index 000000000..ec201cef0 --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/util/ServerThreadTest.java @@ -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 ranOn = new AtomicReference<>(); + + ServerThread.run(() -> ranOn.set(Thread.currentThread().getName()), server, () -> false, () -> false, 10); + + assertEquals("server", ranOn.get()); + } + + @Test + void runsDirectlyOnServerThread() { + List 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 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()); + } +} diff --git a/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java new file mode 100644 index 000000000..3020dd90c --- /dev/null +++ b/platforms/bukkit/common/src/test/java/com/dfsek/terra/bukkit/world/BiomeHandlerTest.java @@ -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 . + */ +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 warnings = new ArrayList<>(); + + private static Biome biome(net.minecraft.resources.ResourceKey key) { + return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value(); + } + + private BiomeHandler.Registration register(MinecraftBiomeFactory.Built built, Function 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 registrations() { + Function readsAll = b -> b; + Function rejectsBuilt = b -> rejecting(b, BUILT); + Function 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 wyck, @Nullable Biome biome, + @Nullable ResourceKey villagerType, @Nullable String warning) { + BiomeHandler.Registration 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 isForest = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_forest")); + TagKey isOcean = TagKey.create(Registries.BIOME, Identifier.withDefaultNamespace("is_ocean")); + TagKey hasSnow = TagKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("mypack", "has_snow")); + List terra = List.of(Identifier.fromNamespaceAndPath("terra", "t/b")); + Map, List> additions = new LinkedHashMap<>(); + additions.put(isForest, terra); + additions.put(isOcean, terra); + additions.put(hasSnow, terra); + List> 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 info = new ArrayList<>(); + List> registered = new ArrayList<>(); + + BiomeHandler.registerNew(List.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 run, String pack, String config, String key, Identifier parent, boolean registered, + net.minecraft.resources.ResourceKey type, List 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 after = new ArrayList<>(); + + BiomeHandler.Run run = BiomeHandler.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 after = new ArrayList<>(); + BiomeHandler.Run 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 after = new ArrayList<>(); + + BiomeHandler.Run run = BiomeHandler.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 tag(String id) { + return TagKey.create(Registries.BIOME, Identifier.parse(id)); + } + + private static Optional> 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 villagePlains = tag("minecraft:has_structure/village_plains"); + TagKey isForest = tag("minecraft:is_forest"); + TagKey hasSnow = tag("mypack:has_snow"); + TagKey isOcean = tag("minecraft:is_ocean"); + Map, List> tags = new LinkedHashMap<>(); + tags.put(villagePlains, List.of(plains)); + tags.put(isForest, List.of(forest)); + tags.put(isOcean, List.of(Biomes.OCEAN.identifier())); + Set 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, List> 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, List> 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))); + } +} diff --git a/platforms/fabric/build.gradle.kts b/platforms/fabric/build.gradle.kts index 02a3458bf..f6af74c43 100644 --- a/platforms/fabric/build.gradle.kts +++ b/platforms/fabric/build.gradle.kts @@ -16,6 +16,9 @@ dependencies { implementation(project(":platforms:mixin-common")) { isTransitive = false } "developmentFabric"(project(":platforms:mixin-common")) { isTransitive = false } shaded(project(path = ":platforms:mixin-common", configuration = "transformProductionFabric")) { isTransitive = false } + implementation(project(":platforms:minecraft-common")) { isTransitive = false } + "developmentFabric"(project(":platforms:minecraft-common")) { isTransitive = false } + shaded(project(path = ":platforms:minecraft-common", configuration = "transformProductionFabric")) { isTransitive = false } implementation(project(":platforms:mixin-lifecycle")) { isTransitive = false } "developmentFabric"(project(":platforms:mixin-lifecycle")) { isTransitive = false } shaded(project(path = ":platforms:mixin-lifecycle", configuration = "transformProductionFabric")) { isTransitive = false } diff --git a/platforms/minecraft-common/build.gradle.kts b/platforms/minecraft-common/build.gradle.kts new file mode 100644 index 000000000..7bdf05c70 --- /dev/null +++ b/platforms/minecraft-common/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("dev.architectury.loom-no-remap") version Versions.Mod.architecturyLoom + id("architectury-plugin") version Versions.Mod.architecturyPlugin + `java-test-fixtures` +} + +loom { + accessWidenerPath.set(project(":platforms:mixin-common").file("src/main/resources/terra.accesswidener")) +} + +dependencies { + shadedApi(project(":common:implementation:base")) + + minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") + + // Tests only: the addon ships as its own jar. + testImplementation(project(":common:addons:minecraft-attributes")) + testFixturesImplementation(project(":common:addons:minecraft-attributes")) +} + +architectury { + common("fabric") + minecraft = Versions.Mod.minecraft +} + +// Loom puts Minecraft on the main and test classpaths only. +configurations.matching { it.name == "minecraftNamedCompile" }.configureEach { + configurations["testFixturesCompileClasspath"].extendsFrom(this) +} + +tasks.withType().configureEach { + options.release = 25 +} diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java new file mode 100644 index 000000000..c18b93122 --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/BiomeTags.java @@ -0,0 +1,71 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.core.Holder; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; + +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.world.attribute.platform.AttributeReport; + + +public final class BiomeTags { + private static final Logger logger = LoggerFactory.getLogger(BiomeTags.class); + + private BiomeTags() { + + } + + public record PlatformTagSource(AttributeReport report, String config, Set tags) { } + + public static void addTerraBiomes(Map, List>> collect, + Function>> lookup, + Map> byParent, Map platformTags) { + byParent.forEach((vb, terraBiomes) -> + lookup.apply(vb).ifPresentOrElse( + vanilla -> terraBiomes.forEach(tb -> lookup.apply(tb).ifPresentOrElse( + terra -> { + logger.debug(vanilla.unwrapKey().orElseThrow().identifier() + " (vanilla for " + + terra.unwrapKey().orElseThrow().identifier() + ": " + vanilla.tags().toList()); + vanilla.tags().forEach(tag -> collect.computeIfAbsent(tag, t -> new ArrayList<>()).add(terra)); + }, + () -> logger.error("No such biome: {}", tb))), + () -> logger.error("No vanilla biome: {}", vb))); + + Set> existing = new HashSet<>(collect.keySet()); + platformTags.forEach((tb, source) -> { + if(source.tags().isEmpty()) return; + Optional> terra = lookup.apply(tb); + if(terra.isEmpty()) { + logger.error("No such biome: {}", tb); + return; + } + for(RegistryKey key : source.tags()) { + Identifier id; + try { + id = VanillaIds.identifier(key); + } catch(IllegalArgumentException e) { + source.report().ignored(source.config(), key.toString(), e.getMessage()); + continue; + } + TagKey tag = TagKey.create(Registries.BIOME, id); + if(!existing.contains(tag) && id.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) { + source.report().tagCreated(source.config(), key.toString()); + } + List> biomes = collect.computeIfAbsent(tag, t -> new ArrayList<>()); + if(!biomes.contains(terra.get())) biomes.add(terra.get()); + } + }); + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java similarity index 70% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java index 6950dc9ca..ed213f699 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParents.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParents.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.HolderGetter; import net.minecraft.core.Registry; @@ -24,7 +24,10 @@ import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.api.world.attribute.AttributeParents; import com.dfsek.terra.api.world.attribute.PackAttributes; -import com.dfsek.terra.mod.config.ProtoPlatformBiome; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; +import com.dfsek.terra.world.attribute.platform.ParentFold; public final class MinecraftAttributeParents implements AttributeParents { @@ -67,20 +70,32 @@ public final class MinecraftAttributeParents implements AttributeParents { return state.context(); } - public synchronized PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report) { + public PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report) { + return prepare(pack, attributes, report, BuiltinDimensionTypes.OVERWORLD); + } + + public synchronized PackParents prepare(ConfigPack pack, Optional attributes, AttributeReport report, + ResourceKey defaultDimension) { State current = state; VanillaContext context = current.context(); if(context == null) throw new IllegalStateException("no registry load has begun"); + ResourceKey fallback = context.dimensionTypes().get(defaultDimension).isPresent() + ? defaultDimension + : BuiltinDimensionTypes.OVERWORLD; PackAttributes packAttributes = attributes.orElse(null); PackParents[] prepared = current.packs(); for(int i = current.reloadedFrom(); i < prepared.length; i++) { - if(prepared[i].pack() == pack && prepared[i].attributes() == packAttributes) return prepared[i]; + PackParents candidate = prepared[i]; + if(candidate.pack() == pack && candidate.attributes() == packAttributes + && (!candidate.dimensionDefaulted() || candidate.dimensionKey().equals(fallback))) return candidate; } - ResourceKey dimensionKey = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(), - BuiltinDimensionTypes.OVERWORLD, "dimension type", report); - ResourceKey generationKey = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS, - context.noiseSettings(), NoiseGeneratorSettings.OVERWORLD, "noise settings", report); + ResourceKey named = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(), + "dimension type", report); + ResourceKey dimensionKey = named == null ? fallback : named; + ResourceKey namedGeneration = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS, + context.noiseSettings(), "noise settings", report); + ResourceKey generationKey = namedGeneration == null ? NoiseGeneratorSettings.OVERWORLD : namedGeneration; DimensionType dimension = context.dimensionTypes().getOrThrow(dimensionKey).value(); NoiseGeneratorSettings generation = context.noiseSettings().getOrThrow(generationKey).value(); @@ -89,7 +104,7 @@ public final class MinecraftAttributeParents implements AttributeParents { AttributeSlots dimensionSlots = reader.dimension(dimension, table, parentSkipped(report, dimensionKey.identifier().toString())); AttributeSlots generationSlots = reader.generation(generation, table); - PackParents parents = new PackParents(pack, dimensionKey, dimension, generationKey, generation, table, + PackParents parents = new PackParents(pack, dimensionKey, named == null, dimension, generationKey, generation, table, fold(table, dimensionSlots, generationSlots), packAttributes, report, reader); PackParents[] packs = Arrays.copyOf(prepared, prepared.length + 1); packs[packs.length - 1] = parents; @@ -114,9 +129,10 @@ public final class MinecraftAttributeParents implements AttributeParents { @Override public @Nullable AttributeEntry biomeOrNull(com.dfsek.terra.api.world.biome.Biome biome, Attribute attribute) { - return biome.getPlatformBiome() instanceof ProtoPlatformBiome proto ? proto.parentEntries().get(attribute) : null; + return biome.getPlatformBiome() instanceof ParentEntryHolder holder ? holder.parentEntries().get(attribute) : null; } + // Hot path: no allocation, hashing or boxing. @Override public @Nullable AttributeEntry packOrNull(PackAttributes pack, Attribute attribute) { PackParents[] packs = state.packs(); @@ -126,38 +142,30 @@ public final class MinecraftAttributeParents implements AttributeParents { return null; } - private static ResourceKey parent(@Nullable PackAttributes attributes, String configKey, - ResourceKey> registry, HolderGetter getter, - ResourceKey fallback, String what, AttributeReport report) { + private static @Nullable ResourceKey parent(@Nullable PackAttributes attributes, String configKey, + ResourceKey> registry, HolderGetter getter, + String what, AttributeReport report) { RegistryKey id = attributes == null ? null : attributes.parents().get(configKey); - if(id == null) return fallback; + if(id == null) return null; ResourceKey key; try { key = ResourceKey.create(registry, VanillaIds.identifier(id)); } catch(IllegalArgumentException e) { report.ignored(PACK_CONFIG, configKey, e.getMessage()); - return fallback; + return null; } if(getter.get(key).isPresent()) return key; report.ignored(PACK_CONFIG, configKey, "no such " + what + " \"" + key.identifier() + "\""); - return fallback; + return null; } private AttributeSlots fold(PackAttributeTable table, AttributeSlots dimension, AttributeSlots generation) { - AttributeEntry[] slots = new AttributeEntry[handle.attributeCount()]; - for(PackAttributeTable.Bound bound : table.environment()) fold(bound.attribute(), dimension, generation, slots); - for(PackAttributeTable.Field field : table.dimension()) fold(field.attribute(), dimension, generation, slots); - if(table.seaLevel() != null) fold(table.seaLevel(), dimension, generation, slots); - if(table.mobGeneration() != null) fold(table.mobGeneration(), dimension, generation, slots); - return AttributeSlots.of(slots); - } - - private void fold(Attribute attribute, AttributeSlots dimension, AttributeSlots generation, AttributeEntry[] slots) { - AttributeEntry lower = dimension.get(attribute); - AttributeEntry upper = generation.get(attribute); - if(lower == null && upper == null) return; - slots[attribute.index()] = handle.compose(attribute, lower, upper) - .orElseGet(() -> AttributeEntry.override(handle.resolve(attribute, lower, upper, null))); + List> attributes = new ArrayList<>(); + for(PackAttributeTable.Bound bound : table.environment()) attributes.add(bound.attribute()); + for(PackAttributeTable.Field field : table.dimension()) attributes.add(field.attribute()); + if(table.seaLevel() != null) attributes.add(table.seaLevel()); + if(table.mobGeneration() != null) attributes.add(table.mobGeneration()); + return ParentFold.fold(handle, attributes, dimension, generation); } static BiConsumer, String> parentSkipped(AttributeReport report, String parent) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java similarity index 93% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java index 7b4e5a331..0c8cd9f04 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactory.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactory.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.registries.BuiltInRegistries; @@ -8,6 +8,7 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.world.attribute.EnvironmentAttributeMap; import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; import org.jetbrains.annotations.Nullable; @@ -22,7 +23,9 @@ import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.api.world.attribute.DecodeException; import com.dfsek.terra.api.world.attribute.PackAttributes; -import com.dfsek.terra.mod.config.ProtoPlatformBiome; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; public final class MinecraftBiomeFactory { @@ -40,7 +43,8 @@ public final class MinecraftBiomeFactory { * {@code terraBiome}'s parent entries must already be set from {@link MinecraftAttributeParents#biomeEntries}. */ public Built create(ResourceKey parentKey, Biome parent, com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack, - AttributeReport report) { + AttributeReport report, BiomeGenerationSettings generation) { + Objects.requireNonNull(generation, "generation"); String config = terraBiome.getID(); PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); @@ -67,7 +71,7 @@ public final class MinecraftBiomeFactory { .downfall(climate.downfall()) .specialEffects(effects) .putAttributes(environment) - .generationSettings(parent.getGenerationSettings()) + .generationSettings(generation) .build(); return new Built(biome, villagerType); } @@ -119,8 +123,8 @@ public final class MinecraftBiomeFactory { private EnvironmentAttributeMap environment(EnvironmentAttributeMap parent, PackAttributeTable table, PackAttributes attributes, com.dfsek.terra.api.world.biome.Biome terraBiome, String config, AttributeReport report) { - AttributeSlots parentSlots = terraBiome.getPlatformBiome() instanceof ProtoPlatformBiome proto - ? proto.parentEntries() + AttributeSlots parentSlots = terraBiome.getPlatformBiome() instanceof ParentEntryHolder holder + ? holder.parentEntries() : AttributeSlots.EMPTY; Map, AttributeEntry> entries = new LinkedHashMap<>(); for(PackAttributeTable.Bound bound : table.environment()) { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java similarity index 72% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java index cd0163fc6..6f424c9ca 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactory.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactory.java @@ -1,27 +1,30 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; -import net.minecraft.tags.TagKey; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; import net.minecraft.world.attribute.EnvironmentAttributeMap; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.timeline.Timeline; import org.jetbrains.annotations.Nullable; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; -import com.dfsek.terra.api.util.range.ConstantRange; +import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.attribute.Attribute; import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.api.world.attribute.DecodeException; import com.dfsek.terra.api.world.attribute.PackAttributes; -import com.dfsek.terra.mod.generation.GenerationSettings; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class MinecraftDimensionFactory { + private static final String TERRA = "terra"; private static final String PACK_CONFIG = "pack.yml"; private static final String ATTRIBUTES = "attributes"; private static final String TIMELINES = "timelines"; @@ -38,7 +41,7 @@ public final class MinecraftDimensionFactory { this.maps = new VanillaAttributeMaps(handle, context); } - public DimensionType create(PackParents pack, @Nullable TagKey timelines) { + public DimensionType create(PackParents pack, @Nullable TimelineRef timelines) { DimensionType parent = pack.dimension(); PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); @@ -47,25 +50,36 @@ public final class MinecraftDimensionFactory { Map original = (Map) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, parent, context.ops()); Map all = new LinkedHashMap<>(original); if(attributes != null) { - for(PackAttributeTable.Field field : table.dimension()) set(all, field, attributes); + for(PackAttributeTable.Field field : table.dimension()) set(all, field, pack); all.put(ATTRIBUTES, environment(parent.attributes(), pack, attributes, report)); for(Attribute unapplied : table.unapplied()) { if(attributes.entries().get(unapplied.key()).isPresent()) report.notApplied(unapplied.getRegistryKey().toString()); } } - if(timelines != null) all.put(TIMELINES, "#" + timelines.location()); + if(timelines != null) all.put(TIMELINES, timelines.encoded()); if(all.equals(original)) return copy(parent); DimensionType built; try { built = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, all, context.ops()); } catch(DecodeException whole) { - built = fieldByField(parent, original, all, table.dimension(), attributes, timelines, report); + built = fieldByField(parent, original, all, table.dimension(), pack, timelines, report); } // Terra may encode a field in another number type, e.g. coordinate_scale as a float. return original.equals(VanillaCodecs.encode(DimensionType.DIRECT_CODEC, built, context.ops())) ? copy(parent) : built; } + /** + * Fabric saves this ID in the world: it must not depend on the pack's {@code vanilla} parent. Overworld keeps + * {@code terra:} for worlds from older Terra versions. + */ + public static Identifier typeId(ConfigPack pack, ResourceKey base, boolean baseValuesApplied) { + String id = pack.getID().toLowerCase(Locale.ROOT); + if(!baseValuesApplied && BuiltinDimensionTypes.OVERWORLD.equals(base)) return Identifier.fromNamespaceAndPath(TERRA, id); + Identifier key = base.identifier(); + return Identifier.fromNamespaceAndPath(TERRA, id + "/" + key.getNamespace() + "/" + key.getPath()); + } + // A registry refuses the same value under a second key. private static DimensionType copy(DimensionType parent) { return new DimensionType(parent.hasFixedTime(), parent.hasSkyLight(), parent.hasCeiling(), parent.hasEnderDragonFight(), @@ -75,8 +89,9 @@ public final class MinecraftDimensionFactory { } private DimensionType fieldByField(DimensionType parent, Map original, Map all, - List fields, @Nullable PackAttributes attributes, - @Nullable TagKey timelines, AttributeReport report) { + List fields, PackParents pack, + @Nullable TimelineRef timelines, AttributeReport report) { + PackAttributes attributes = pack.attributes(); DimensionType value = parent; Map accepted = new LinkedHashMap<>(original); if(all.containsKey(ATTRIBUTES)) { @@ -93,7 +108,7 @@ public final class MinecraftDimensionFactory { for(PackAttributeTable.Field field : fields) { if(attributes.entries().get(field.attribute().key()).isEmpty()) continue; Map trial = new LinkedHashMap<>(accepted); - set(trial, field, attributes); + set(trial, field, pack); if(trial.equals(accepted)) continue; try { value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops()); @@ -115,8 +130,8 @@ public final class MinecraftDimensionFactory { return value; } - private static void set(Map fields, PackAttributeTable.Field field, PackAttributes attributes) { - Object value = resolveEncoded(field.attribute(), attributes); + private void set(Map fields, PackAttributeTable.Field field, PackParents pack) { + Object value = resolveEncoded(field.attribute(), pack); if(value == null) { fields.remove(field.name()); } else { @@ -124,15 +139,15 @@ public final class MinecraftDimensionFactory { } } - private static @Nullable Object resolveEncoded(Attribute attribute, PackAttributes attributes) { - T value = attributes.resolvePack(attribute); + private @Nullable Object resolveEncoded(Attribute attribute, PackParents pack) { + T value = pack.resolvePack(handle, attribute); return value == null ? null : attribute.type().encode(value); } private Object environment(EnvironmentAttributeMap parent, PackParents pack, PackAttributes attributes, AttributeReport report) { Map, AttributeEntry> entries = new LinkedHashMap<>(); for(PackAttributeTable.Bound bound : pack.table().environment()) { - AttributeEntry entry = entry(bound.attribute(), pack.packEntries(), attributes); + AttributeEntry entry = entry(bound.attribute(), pack, attributes); if(entry != null) entries.put(bound.attribute(), entry); } EnvironmentAttributeMap map = entries.isEmpty() ? parent : maps.toVanilla(parent, entries, false, @@ -140,15 +155,15 @@ public final class MinecraftDimensionFactory { return VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops()); } - private @Nullable AttributeEntry entry(Attribute attribute, AttributeSlots packEntries, PackAttributes attributes) { + private @Nullable AttributeEntry entry(Attribute attribute, PackParents pack, PackAttributes attributes) { Optional> entry = attributes.entries().get(attribute.key()); if(entry.isEmpty()) return null; - return handle.compose(attribute, packEntries.get(attribute), entry.get()) - .orElseGet(() -> AttributeEntry.override(attributes.resolvePack(attribute))); + return handle.compose(attribute, pack.packEntries().get(attribute), entry.get()) + .orElseGet(() -> AttributeEntry.override(pack.resolvePack(handle, attribute))); } @SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry - public GenerationSettings generationSettings(PackParents pack, DimensionType dimension) { + public WorldSettings worldSettings(PackParents pack, DimensionType dimension) { PackAttributes attributes = pack.attributes(); PackAttributeTable table = pack.table(); int minY = dimension.minY(); @@ -157,17 +172,17 @@ public final class MinecraftDimensionFactory { boolean mobGeneration = !pack.generation().disableMobGeneration(); int spawnHeight = DEFAULT_SPAWN_HEIGHT; if(attributes != null) { - seaLevel = intValue(table.seaLevel(), attributes, seaLevel); - spawnHeight = intValue(table.spawnHeight(), attributes, spawnHeight); - if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), attributes) instanceof Boolean value) { + seaLevel = intValue(table.seaLevel(), pack, seaLevel); + spawnHeight = intValue(table.spawnHeight(), pack, spawnHeight); + if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), pack) instanceof Boolean value) { mobGeneration = value; } } - return new GenerationSettings(new ConstantRange(minY, minY + height), seaLevel, mobGeneration, spawnHeight); + return new WorldSettings(minY, height, seaLevel, mobGeneration, spawnHeight); } - private static int intValue(@Nullable Attribute attribute, PackAttributes attributes, int fallback) { + private int intValue(@Nullable Attribute attribute, PackParents pack, int fallback) { if(attribute == null) return fallback; - return resolveEncoded(attribute, attributes) instanceof Number value ? value.intValue() : fallback; + return resolveEncoded(attribute, pack) instanceof Number value ? value.intValue() : fallback; } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java similarity index 84% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java index f512d27e8..e02eaab77 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/MinecraftTimelines.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelines.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.datafixers.util.Either; import net.minecraft.core.Holder; @@ -24,10 +24,10 @@ import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.registry.key.RegistryKey; @@ -38,11 +38,11 @@ import com.dfsek.terra.api.world.attribute.PackAttributes; import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class MinecraftTimelines { private static final Logger LOGGER = LoggerFactory.getLogger(MinecraftTimelines.class); - private static final String TERRA = "terra"; private static final String EXISTS = "a timeline with this ID already exists"; private static final String NO_TIMELINE = "no such timeline"; private static final String NO_TAG = "no such timeline tag"; @@ -177,7 +177,17 @@ public final class MinecraftTimelines { return markers; } - public static @Nullable TagKey tagFor(ConfigPack pack, PackParents parents) { + public static @Nullable TagKey tagFor(Identifier type, ConfigPack pack, PackParents parents) { + Pending pending = pending(pack, parents); + if(pending == null) return null; + TagKey key = TagKey.create(Registries.TIMELINE, type); + synchronized(PENDING) { + PENDING.put(key, pending); + } + return key; + } + + public static @Nullable Pending pending(ConfigPack pack, PackParents parents) { PackAttributes attributes = parents.attributes(); if(attributes == null || attributes.scheduleRefs().isEmpty()) return null; AttributeReport report = parents.report(); @@ -196,12 +206,7 @@ public final class MinecraftTimelines { report.scheduleSkipped(id.map(Object::toString).orElseGet(() -> String.valueOf(tag.orElse(null))), e.getMessage()); } } - TagKey key = TagKey.create(Registries.TIMELINE, - Identifier.fromNamespaceAndPath(TERRA, pack.getID().toLowerCase(Locale.ROOT))); - synchronized(PENDING) { - PENDING.put(key, new Pending(report, refs, parents.dimension().timelines())); - } - return key; + return new Pending(report, refs, parents.dimension().timelines()); } /** @@ -220,33 +225,39 @@ public final class MinecraftTimelines { public static void fillTags(Map, List>> collect, Registry registry) { synchronized(PENDING) { - PENDING.forEach((key, pending) -> { - Set> contents = new LinkedHashSet<>(); - for(Either> ref : pending.refs()) { - ref.ifLeft(id -> registry.get(id).ifPresentOrElse(contents::add, - () -> pending.report().scheduleSkipped(id.toString(), NO_TIMELINE))) - .ifRight(tag -> { - List> members = collect.get(tag); - if(members == null) { - pending.report().scheduleSkipped("#" + tag.location(), NO_TAG); - } else { - contents.addAll(members); - } - }); - } - if(contents.isEmpty()) { - pending.report().ignored(PACK_CONFIG, SCHEDULES, NO_VALID_SCHEDULE); - parentTimelines(pending.parent(), collect, registry, contents); - } - collect.put(key, List.copyOf(contents)); - }); + PENDING.forEach((key, pending) -> collect.put(key, contents(pending, collect::get, registry))); } } - private static void parentTimelines(HolderSet parent, Map, List>> collect, + public static List> contents(Pending pending, Function, @Nullable List>> tags, + Registry registry) { + Set> contents = new LinkedHashSet<>(); + for(Either> ref : pending.refs()) { + ref.ifLeft(id -> registry.get(id).ifPresentOrElse(contents::add, + () -> pending.report().scheduleSkipped(id.toString(), NO_TIMELINE))) + .ifRight(tag -> { + List> members = tags.apply(tag); + if(members == null) { + pending.report().scheduleSkipped("#" + tag.location(), NO_TAG); + } else { + contents.addAll(members); + } + }); + } + if(contents.isEmpty()) { + pending.report().ignored(PACK_CONFIG, SCHEDULES, NO_VALID_SCHEDULE); + parentTimelines(pending.parent(), tags, registry, contents); + } + return List.copyOf(contents); + } + + private static void parentTimelines(HolderSet parent, Function, @Nullable List>> tags, Registry registry, Set> contents) { parent.unwrap() - .ifLeft(tag -> contents.addAll(collect.getOrDefault(tag, List.of()))) + .ifLeft(tag -> { + List> members = tags.apply(tag); + if(members != null) contents.addAll(members); + }) .ifRight(direct -> { for(Holder holder : direct) holder.unwrapKey().flatMap(registry::get).ifPresent(contents::add); }); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java similarity index 99% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java index dfafb53e4..724664b4b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackAttributeTable.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackAttributeTable.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.Identifier; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java similarity index 71% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java index 4c08d03a3..2d80b8d0b 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/PackParents.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/PackParents.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.biome.Biome; @@ -10,12 +10,18 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.world.attribute.Attribute; +import com.dfsek.terra.api.world.attribute.AttributeEntry; +import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.api.world.attribute.PackAttributes; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; public final class PackParents { private final ConfigPack pack; private final ResourceKey dimensionKey; + private final boolean dimensionDefaulted; private final DimensionType dimension; private final ResourceKey generationKey; private final NoiseGeneratorSettings generation; @@ -26,11 +32,12 @@ public final class PackParents { private final VanillaParentReader reader; private final Map, AttributeSlots> biomeEntries = new ConcurrentHashMap<>(); - PackParents(ConfigPack pack, ResourceKey dimensionKey, DimensionType dimension, + PackParents(ConfigPack pack, ResourceKey dimensionKey, boolean dimensionDefaulted, DimensionType dimension, ResourceKey generationKey, NoiseGeneratorSettings generation, PackAttributeTable table, AttributeSlots packEntries, @Nullable PackAttributes attributes, AttributeReport report, VanillaParentReader reader) { this.pack = pack; this.dimensionKey = dimensionKey; + this.dimensionDefaulted = dimensionDefaulted; this.dimension = dimension; this.generationKey = generationKey; this.generation = generation; @@ -45,6 +52,10 @@ public final class PackParents { return dimensionKey; } + public boolean dimensionDefaulted() { + return dimensionDefaulted; + } + public DimensionType dimension() { return dimension; } @@ -65,6 +76,14 @@ public final class PackParents { return packEntries; } + /** + * Unlike {@link PackAttributes#resolvePack}, uses these parents, which may be another default's. Allocates. + */ + public @Nullable T resolvePack(AttributeHandle handle, Attribute attribute) { + AttributeEntry own = attributes == null ? null : attributes.entries().get(attribute.key()).orElse(null); + return handle.resolve(attribute, packEntries.get(attribute), own, null); + } + public @Nullable PackAttributes attributes() { return attributes; } diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java new file mode 100644 index 000000000..f557b3bb3 --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/TimelineRef.java @@ -0,0 +1,38 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.resources.ResourceKey; +import net.minecraft.tags.TagKey; +import net.minecraft.world.timeline.Timeline; + +import java.util.List; +import java.util.Objects; + + +public sealed interface TimelineRef { + Object encoded(); + + record Tag(TagKey key) implements TimelineRef { + public Tag { + Objects.requireNonNull(key, "key"); + } + + @Override + public Object encoded() { + return "#" + key.location(); + } + } + + /** + * Every key must be registered where the dimension type is decoded. + */ + record Direct(List> keys) implements TimelineRef { + public Direct { + keys = List.copyOf(keys); + } + + @Override + public Object encoded() { + return keys.stream().map(key -> key.identifier().toString()).toList(); + } + } +} diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java similarity index 98% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java index 537b490bb..325875891 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaAttributeMaps.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaAttributeMaps.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.registries.BuiltInRegistries; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java similarity index 96% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java index b0cd768c2..f4ceabef6 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaCodecs.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaCodecs.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java similarity index 98% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java index 48bfeac6b..49bbbac85 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaContext.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaContext.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.JavaOps; import net.minecraft.core.Holder; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java similarity index 92% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java index 5bb5f35dc..2e3e32a4c 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaIds.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaIds.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.Identifier; diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java similarity index 97% rename from platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java rename to platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java index e1400c0de..83eeac62f 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/attribute/VanillaParentReader.java +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/VanillaParentReader.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.resources.ResourceKey; @@ -16,6 +16,7 @@ import com.dfsek.terra.api.world.attribute.Attribute; import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeHandle; import com.dfsek.terra.api.world.attribute.DecodeException; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; final class VanillaParentReader { diff --git a/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java new file mode 100644 index 000000000..71c33c4ed --- /dev/null +++ b/platforms/minecraft-common/src/main/java/com/dfsek/terra/minecraft/attribute/WorldSettings.java @@ -0,0 +1,4 @@ +package com.dfsek.terra.minecraft.attribute; + +public record WorldSettings(int minY, int height, int seaLevel, boolean mobGeneration, int spawnHeight) { +} diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java similarity index 82% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java index 5b2ee4bcb..fd7ab79dd 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TagUtilTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/BiomeTagsTest.java @@ -1,11 +1,10 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.Holder; import net.minecraft.core.MappedRegistry; import net.minecraft.core.registries.Registries; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; -import net.minecraft.tags.BiomeTags; import net.minecraft.tags.TagKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biomes; @@ -22,17 +21,18 @@ import java.util.Optional; import java.util.Set; import com.dfsek.terra.api.registry.key.RegistryKey; -import com.dfsek.terra.mod.util.TagUtil; -import com.dfsek.terra.mod.util.TagUtil.PlatformTagSource; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; +import com.dfsek.terra.world.attribute.platform.AttributeReport; -import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy; +import static com.dfsek.terra.minecraft.attribute.VanillaContextTest.copy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -class TagUtilTest { +class BiomeTagsTest { private static final Identifier TERRA_ID = Identifier.parse("terra:test/biome"); private static final TagKey HAS_SNOW = tag("mypack:has_snow"); + private static final TagKey IS_FOREST = net.minecraft.tags.BiomeTags.IS_FOREST; private final List warnings = new ArrayList<>(); private final AttributeReport report = new AttributeReport("test", warnings::add, m -> { }); @@ -52,7 +52,7 @@ class TagUtilTest { private void add(Map> byParent, String... tags) { Set keys = new LinkedHashSet<>(); for(String t : tags) keys.add(RegistryKey.parse(t)); - TagUtil.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys))); + BiomeTags.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys))); } private static void bindTags(Holder holder, TagKey tag) throws ReflectiveOperationException { @@ -64,24 +64,24 @@ class TagUtilTest { @Test void platformTagsAreAdded() { Holder forest = registry.get(Biomes.FOREST).orElseThrow(); - collect.put(BiomeTags.IS_FOREST, new ArrayList<>(List.of(forest))); + collect.put(IS_FOREST, new ArrayList<>(List.of(forest))); add(Map.of(), "mypack:has_snow", "minecraft:is_forest"); assertEquals(List.of(terra), collect.get(HAS_SNOW)); - assertEquals(List.of(forest, terra), collect.get(BiomeTags.IS_FOREST)); + assertEquals(List.of(forest, terra), collect.get(IS_FOREST)); assertEquals(List.of(), warnings); } @Test void inheritedTagsStillApply() throws ReflectiveOperationException { Holder forest = registry.get(Biomes.FOREST).orElseThrow(); - bindTags(forest, BiomeTags.IS_FOREST); + bindTags(forest, IS_FOREST); Identifier forestId = Biomes.FOREST.identifier(); add(Map.of(forestId, List.of(TERRA_ID))); - assertEquals(List.of(terra), collect.get(BiomeTags.IS_FOREST)); + assertEquals(List.of(terra), collect.get(IS_FOREST)); assertEquals(List.of(), warnings); } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java similarity index 77% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java index fa9558f87..58ba6aff0 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftAttributeParentsTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftAttributeParentsTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; import net.minecraft.core.MappedRegistry; @@ -29,12 +29,14 @@ import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeKey; import com.dfsek.terra.api.world.attribute.AttributeMap; import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; +import static com.dfsek.terra.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.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -91,39 +93,6 @@ class MinecraftAttributeParentsTest { return PackAttributeTable.of(REGISTRY); } - @Test - void reportFormats() { - report.attributeSkipped("BIOME", "minecraft:visual/fog_color", "not a colour"); - report.scheduleSkipped("mypack:seasons", "no clock"); - report.trackDropped("mypack:seasons", "minecraft:visual/fog_color", "bad keyframe"); - report.timeMarkerDropped("mypack:seasons", "minecraft:noon", "minecraft:overworld"); - report.ignored("pack.yml", "vanilla", "no such dimension type \"minecraft:nope\""); - report.tagCreated("BIOME", "minecraft:is_custom"); - report.notApplied("test:custom"); - report.notApplied("test:custom"); - report.notApplied("test:other"); - - assertEquals(List.of( - "Pack \"test\", config \"BIOME\": attribute \"minecraft:visual/fog_color\" skipped: not a colour", - "Pack \"test\": schedule \"mypack:seasons\" skipped: no clock", - "Pack \"test\": schedule \"mypack:seasons\" track \"minecraft:visual/fog_color\" dropped: bad keyframe", - "Pack \"test\": schedule \"mypack:seasons\" time marker \"minecraft:noon\" dropped: already defined for clock " - + "\"minecraft:overworld\"", - "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"", - "Pack \"test\", config \"BIOME\": tag \"minecraft:is_custom\" created: no such tag in the minecraft namespace"), warnings); - assertEquals(List.of( - "Pack \"test\": attribute \"test:custom\" is not applied on this platform", - "Pack \"test\": attribute \"test:other\" is not applied on this platform"), debugs); - } - - @Test - void unreadableParentValueNamesTheParent() { - MinecraftAttributeParents.parentSkipped(report, "minecraft:plains").accept(HAS_CEILING, "not a boolean"); - - assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"" + HAS_CEILING.getRegistryKey() - + "\" skipped: vanilla parent \"minecraft:plains\": not a boolean"), warnings); - } - @Test void overworldByDefault() { parents.beginLoad(CONTEXT); @@ -153,29 +122,48 @@ class MinecraftAttributeParentsTest { } @Test - void vanillaParentIsUsed() { + void namedParentsAreUsed() { parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); - PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + FakePackAttributes dimension = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + PackParents nether = parents.prepare(PACK, Optional.of(dimension), report); + assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey()); + assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), nether.dimension()); + assertEquals(AttributeEntry.override(true), parents.packOrNull(dimension, HAS_CEILING)); + assertEquals(AttributeEntry.override(4f), parents.packOrNull(dimension, SKY_LIGHT)); + assertEquals(NoiseGeneratorSettings.OVERWORLD, nether.generationKey()); + assertEquals(AttributeEntry.override(63), parents.packOrNull(dimension, SEA_LEVEL)); - assertEquals(BuiltinDimensionTypes.NETHER, pack.dimensionKey()); - assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), pack.dimension()); - assertEquals(AttributeEntry.override(true), parents.packOrNull(fake, HAS_CEILING)); - assertEquals(AttributeEntry.override(4f), parents.packOrNull(fake, SKY_LIGHT)); - assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); - assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL)); + FakePackAttributes generation = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))); + PackParents netherGeneration = parents.prepare(PACK, Optional.of(generation), report); + assertEquals(NoiseGeneratorSettings.NETHER, netherGeneration.generationKey()); + assertEquals(AttributeEntry.override(32), parents.packOrNull(generation, SEA_LEVEL)); + assertEquals(BuiltinDimensionTypes.OVERWORLD, netherGeneration.dimensionKey()); assertEquals(List.of(), warnings); } @Test - void generationParentSuppliesWorld() { + void givenDefaultDimension() { parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether"))); - PackParents pack = parents.prepare(PACK, Optional.of(fake), report); + FakePackAttributes fake = fake(Map.of()); + PackParents nether = parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER); + assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey()); + assertTrue(nether.dimensionDefaulted()); + assertEquals(AttributeEntry.override(true), nether.packEntries().get(HAS_CEILING)); + assertSame(nether, parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER)); - assertEquals(NoiseGeneratorSettings.NETHER, pack.generationKey()); - assertEquals(AttributeEntry.override(32), parents.packOrNull(fake, SEA_LEVEL)); - assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey()); + PackParents overworld = parents.prepare(PACK, Optional.of(fake), report); + assertNotSame(nether, overworld); + assertEquals(BuiltinDimensionTypes.OVERWORLD, overworld.dimensionKey()); + assertTrue(overworld.dimensionDefaulted()); + + ResourceKey missing = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("terra:nope")); + assertSame(overworld, parents.prepare(PACK, Optional.of(fake), report, missing)); + + FakePackAttributes named = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + PackParents explicit = parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.OVERWORLD); + assertEquals(BuiltinDimensionTypes.NETHER, explicit.dimensionKey()); + assertFalse(explicit.dimensionDefaulted()); + assertSame(explicit, parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.END)); assertEquals(List.of(), warnings); } @@ -184,9 +172,9 @@ class MinecraftAttributeParentsTest { parents.beginLoad(CONTEXT); PackParents upper = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:The_Nether")))), report); - PackParents unknown = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"), - "vanilla-generation", RegistryKey.parse("minecraft:nope")))), - report); + FakePackAttributes unknownIds = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"), + "vanilla-generation", RegistryKey.parse("minecraft:nope"))); + PackParents unknown = parents.prepare(PACK, Optional.of(unknownIds), report); assertEquals(List.of( "Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: invalid ID \"minecraft:The_Nether\": Minecraft IDs use only " @@ -199,6 +187,12 @@ class MinecraftAttributeParentsTest { assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey()); assertEquals(AttributeEntry.override(false), pack.packEntries().get(HAS_CEILING)); } + + assertSame(unknown, parents.prepare(PACK, Optional.of(unknownIds), report)); + assertEquals(3, warnings.size(), warnings.toString()); + PackParents bare = parents.prepare(PACK, Optional.empty(), report); + assertNotSame(unknown, bare); + assertSame(bare, parents.prepare(PACK, Optional.empty(), report)); } @Test @@ -224,16 +218,16 @@ class MinecraftAttributeParentsTest { } @Test - void biomeOrNullReadsProtoBiome() { + void biomeOrNullReadsEntryHolder() { parents.beginLoad(CONTEXT); PackParents pack = parents.prepare(PACK, Optional.empty(), report); TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier()); - assertSame(AttributeSlots.EMPTY, biome.proto().parentEntries()); + assertSame(AttributeSlots.EMPTY, biome.platform().parentEntries()); assertNull(parents.biomeOrNull(biome, PRECIPITATION)); AttributeSlots desert = parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); assertSame(desert, parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)), "cached per parent key"); - biome.proto().setParentEntries(desert); + biome.platform().setParentEntries(desert); assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION)); PlatformBiome other = () -> "other"; @@ -271,7 +265,7 @@ class MinecraftAttributeParentsTest { Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")), Map.of(biome, AttributeMap.builder().put(HAS_CEILING.key(), AttributeEntry.override(true)).build())); PackParents pack = parents.prepare(PACK, Optional.of(fake), report); - biome.proto().setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT))); + biome.platform().setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT))); FakePackAttributes unprepared = fake(Map.of()); assertEquals(List.of(), warnings); assertEquals(1023, reads(fake, unprepared, biome, plain), "every read sees the expected entry or value"); @@ -305,7 +299,7 @@ class MinecraftAttributeParentsTest { } @Test - void beginLoadDropsOldPacks() { + void beginLoadAndClearPacksDropOldPacks() { parents.beginLoad(CONTEXT); FakePackAttributes fake = fake(Map.of()); PackParents first = parents.prepare(PACK, Optional.of(fake), report); @@ -316,10 +310,23 @@ class MinecraftAttributeParentsTest { PackParents second = parents.prepare(PACK, Optional.of(fake), report); assertNotSame(first, second); assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING)); + AttributeSlots desert = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); parents.clearPacks(); assertSame(CONTEXT, parents.context()); assertNull(parents.packOrNull(fake, HAS_CEILING)); + FakePackAttributes reloaded = fake(Map.of()); + assertNull(parents.packOrNull(reloaded, HAS_CEILING)); + PackParents third = parents.prepare(PACK, Optional.of(reloaded), report); + + assertNotSame(second, third); + assertSame(third, parents.prepare(PACK, Optional.of(reloaded), report)); + assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING)); + assertNull(parents.packOrNull(fake, HAS_CEILING), "the old pack's attributes get no parents"); + AttributeSlots again = parents.biomeEntries(third, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); + assertNotSame(desert, again, "biome entries are read again for the new pack"); + assertEquals(AttributeEntry.override(false), again.get(PRECIPITATION)); + assertEquals(List.of(), warnings); } @Test @@ -349,28 +356,6 @@ class MinecraftAttributeParentsTest { assertNull(parents.packOrNull(reloaded, HAS_CEILING), "not prepared again, so dropped"); } - @Test - void prepareAfterClearPacksIsFresh() { - parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of()); - PackParents first = parents.prepare(PACK, Optional.of(fake), report); - AttributeSlots desert = parents.biomeEntries(first, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); - - parents.clearPacks(); - FakePackAttributes reloaded = fake(Map.of()); - assertNull(parents.packOrNull(reloaded, HAS_CEILING)); - PackParents second = parents.prepare(PACK, Optional.of(reloaded), report); - - assertNotSame(first, second); - assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report)); - assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING)); - assertNull(parents.packOrNull(fake, HAS_CEILING), "the old pack's attributes get no parents"); - AttributeSlots again = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)); - assertNotSame(desert, again, "biome entries are read again for the new pack"); - assertEquals(AttributeEntry.override(false), again.get(PRECIPITATION)); - assertEquals(List.of(), warnings); - } - @Test void unpreparedPackHasNoParents() { FakePackAttributes fake = fake(Map.of()); @@ -382,19 +367,4 @@ class MinecraftAttributeParentsTest { assertSame(CONTEXT, parents.context()); assertNull(parents.packOrNull(fake, HAS_CEILING)); } - - @Test - void prepareIsIdempotent() { - parents.beginLoad(CONTEXT); - FakePackAttributes fake = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"))); - PackParents first = parents.prepare(PACK, Optional.of(fake), report); - assertEquals(1, warnings.size()); - - assertSame(first, parents.prepare(PACK, Optional.of(fake), report)); - assertEquals(1, warnings.size()); - - PackParents bare = parents.prepare(PACK, Optional.empty(), report); - assertNotSame(first, bare); - assertSame(bare, parents.prepare(PACK, Optional.empty(), report)); - } } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java similarity index 83% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java index e041dfbc0..206c5784c 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftBiomeFactoryTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftBiomeFactoryTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import com.mojang.serialization.Lifecycle; @@ -13,6 +13,7 @@ import net.minecraft.world.attribute.EnvironmentAttributeMap; import net.minecraft.world.attribute.EnvironmentAttributes; import net.minecraft.world.entity.npc.villager.VillagerType; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.biome.BiomeSpecialEffects; import net.minecraft.world.level.biome.Biomes; import org.junit.jupiter.api.Test; @@ -35,14 +36,16 @@ import com.dfsek.terra.api.world.attribute.DecodeContext; import com.dfsek.terra.api.world.attribute.DecodeException; import com.dfsek.terra.api.world.attribute.value.Color; import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -113,7 +116,11 @@ class MinecraftBiomeFactoryTest { private record Fixture(TestBiome biome, FakePackAttributes attributes, PackParents pack, MinecraftBiomeFactory factory, ResourceKey parentKey, Biome parent) { MinecraftBiomeFactory.Built create(AttributeReport report) { - return factory.create(parentKey, parent, biome, pack, report); + return create(report, parent.getGenerationSettings()); + } + + MinecraftBiomeFactory.Built create(AttributeReport report, BiomeGenerationSettings generation) { + return factory.create(parentKey, parent, biome, pack, report, generation); } } @@ -130,7 +137,7 @@ class MinecraftBiomeFactoryTest { Map.of(biome, builder.build())); parents.beginLoad(context); PackParents prepared = parents.prepare(pack, Optional.of(attributes), report); - biome.proto().setParentEntries(parents.biomeEntries(prepared, parentKey, parent)); + biome.platform().setParentEntries(parents.biomeEntries(prepared, parentKey, parent)); return new Fixture(biome, attributes, prepared, new MinecraftBiomeFactory(HANDLE, context), parentKey, parent); } @@ -157,41 +164,33 @@ class MinecraftBiomeFactoryTest { @Test void noEntriesMatchesParent() { Biome plains = biome(Biomes.PLAINS); - MinecraftBiomeFactory.Built built = fixture(Biomes.PLAINS, plains, Map.of()).create(report); + Fixture fixture = fixture(Biomes.PLAINS, plains, Map.of()); + MinecraftBiomeFactory.Built built = fixture.create(report); assertMatches(plains, built.biome()); - assertNotSame(plains, built.biome()); assertEquals(VillagerType.PLAINS, built.villagerType()); - assertEquals(List.of(), warnings); - assertEquals(List.of(), debugs); - } - - @Test - void createdBiomeRegistersBesideItsParent() { - Biome plains = biome(Biomes.PLAINS); - Biome built = fixture(Biomes.PLAINS, plains, Map.of()).create(report).biome(); MappedRegistry registry = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable()); registry.register(Biomes.PLAINS, plains, RegistrationInfo.BUILT_IN); ResourceKey key = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test")); + assertDoesNotThrow(() -> registry.register(key, built.biome(), RegistrationInfo.BUILT_IN)); - assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); - } + Biome empty = fixture.create(report, BiomeGenerationSettings.EMPTY).biome(); + assertSame(BiomeGenerationSettings.EMPTY, empty.getGenerationSettings()); + assertEquals(plains.climateSettings, empty.climateSettings); + assertEquals(climate(plains), climate(empty)); + assertEquals(effects(plains), effects(empty)); + assertEquals(environment(plains), environment(empty)); - @Test - void noAttributesMatchesTheParent() { - Biome plains = biome(Biomes.PLAINS); parents.beginLoad(CONTEXT); PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); - assertNull(bare.attributes()); assertSame(PackAttributeTable.EMPTY, bare.table()); TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier()); - biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains)); - - MinecraftBiomeFactory.Built built = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, bare, report); - - assertMatches(plains, built.biome()); - assertNotSame(plains, built.biome()); - assertEquals(VillagerType.PLAINS, built.villagerType()); + biome.platform().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains)); + MinecraftBiomeFactory.Built withoutAttributes = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, + bare, report, plains.getGenerationSettings()); + assertMatches(plains, withoutAttributes.biome()); + assertNotSame(plains, withoutAttributes.biome()); + assertEquals(VillagerType.PLAINS, withoutAttributes.villagerType()); assertEquals(List.of(), warnings); assertEquals(List.of(), debugs); } @@ -270,7 +269,7 @@ class MinecraftBiomeFactoryTest { AttributeEntry multiply = decoded(FOG_COLOR, Map.of("modifier", "multiply", "argument", "#808080")); Fixture fixture = fixture(parentKey, parent, Map.of(fog, multiply)); - assertEquals(blend, fixture.biome().proto().parentEntries().get(fog), "the parent's modifier is read"); + assertEquals(blend, fixture.biome().platform().parentEntries().get(fog), "the parent's modifier is read"); assertTrue(composed(fog, blend, multiply).isEmpty(), "alpha_blend then multiply has no single entry"); Biome built = fixture.create(report).biome(); @@ -288,19 +287,32 @@ class MinecraftBiomeFactoryTest { } @Test - void badEntryIsSkippedAlone() { + void rejectedEntriesAreSkippedAlone() { Biome plains = biome(Biomes.PLAINS); Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand")); - Map, AttributeEntry> entries = entries( + PackAttributeTable.Bound nonPositional = PackAttributeTable.of(REGISTRY).environment().stream() + .filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null) + .findFirst().orElseThrow(); + String nonPositionalId = nonPositional.attribute().getRegistryKey().toString(); + Map, AttributeEntry> entries = new LinkedHashMap<>(entries( AMBIENT_PARTICLES, List.of(Map.of("particle", oldParticle, "probability", 0.01)), - FOG_COLOR, "#123456"); + FOG_COLOR, "#123456")); + entries.put(nonPositional.attribute(), AttributeEntry.override(nonPositional.attribute().defaultValue())); Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome(); - String reason = rejection(AMBIENT_PARTICLES, entries.get(attribute(AMBIENT_PARTICLES))); - assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + AMBIENT_PARTICLES + "\" skipped: " + reason), warnings); + List expected = new ArrayList<>(); + for(PackAttributeTable.Bound bound : PackAttributeTable.of(REGISTRY).environment()) { + String id = bound.attribute().getRegistryKey().toString(); + if(id.equals(AMBIENT_PARTICLES) || id.equals(nonPositionalId)) { + expected.add("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: " + + rejection(id, entries.get(bound.attribute()))); + } + } + assertEquals(expected, warnings); assertEquals(plains.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES), built.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES)); + assertFalse(built.getAttributes().contains(nonPositional.vanilla())); assertFogApplied(entries.get(attribute(FOG_COLOR)), built); } @@ -346,25 +358,6 @@ class MinecraftBiomeFactoryTest { assertEquals(plains.hasPrecipitation(), built.hasPrecipitation()); } - @Test - void nonPositionalOnBiomeIsSkipped() { - PackAttributeTable.Bound bound = PackAttributeTable.of(REGISTRY).environment().stream() - .filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null) - .findFirst().orElseThrow(); - String id = bound.attribute().getRegistryKey().toString(); - Map, AttributeEntry> entries = new LinkedHashMap<>(); - entries.put(bound.attribute(), AttributeEntry.override(bound.attribute().defaultValue())); - entries.putAll(entries(FOG_COLOR, "#123456")); - Biome plains = biome(Biomes.PLAINS); - - Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome(); - - assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: " - + rejection(id, entries.get(bound.attribute()))), warnings); - assertFalse(built.getAttributes().contains(bound.vanilla())); - assertFogApplied(entries.get(attribute(FOG_COLOR)), built); - } - @Test void unknownParentAttributeIsKept() { OpenRegistryImpl> withoutSky = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); @@ -377,7 +370,7 @@ class MinecraftBiomeFactoryTest { Map, AttributeEntry> entries = entries(FOG_COLOR, "#123456"); Fixture fixture = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("nosky", withoutSky), Biomes.PLAINS, plains, entries); - assertNull(fixture.biome().proto().parentEntries().get(attribute(SKY_COLOR)), "the pack does not know sky colour"); + assertNull(fixture.biome().platform().parentEntries().get(attribute(SKY_COLOR)), "the pack does not know sky colour"); Biome built = fixture.create(report).biome(); assertSame(plains.getAttributes().get(sky), built.getAttributes().get(sky)); @@ -415,27 +408,26 @@ class MinecraftBiomeFactoryTest { .create(report).villagerType()); assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " + "no such villager type \"minecraft:nope\""), warnings); + warnings.clear(); + + Map, AttributeEntry> upper = Map.of(attribute(VILLAGER_TYPE), + AttributeEntry.override(RegistryKey.of("minecraft", "Snow"))); + assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, upper).create(report).villagerType()); + assertEquals(1, warnings.size(), warnings.toString()); + assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " + + "invalid ID \"minecraft:Snow\""), warnings.getFirst()); + warnings.clear(); assertEquals(VillagerType.PLAINS, fixture(villagers, PACK, Biomes.PLAINS, biome(Biomes.PLAINS), Map.of()) .create(report).villagerType()); parents.beginLoad(villagers); PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); TestBiome biome = new TestBiome(CONFIG, 0, Biomes.DESERT.identifier()); - biome.proto().setParentEntries(parents.biomeEntries(bare, Biomes.DESERT, desert)); + biome.platform().setParentEntries(parents.biomeEntries(bare, Biomes.DESERT, desert)); assertEquals(VillagerType.DESERT, - new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report).villagerType()); - } - - @Test - void upperCaseVillagerTypeWarns() { - VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null); - Map, AttributeEntry> entries = Map.of(attribute(VILLAGER_TYPE), - AttributeEntry.override(RegistryKey.of("minecraft", "Snow"))); - assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, biome(Biomes.DESERT), entries).create(report) - .villagerType()); - assertEquals(1, warnings.size(), warnings.toString()); - assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: " - + "invalid ID \"minecraft:Snow\""), warnings.getFirst()); + new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report, + desert.getGenerationSettings()).villagerType()); + assertEquals(List.of(), warnings); } @Test @@ -454,8 +446,9 @@ class MinecraftBiomeFactoryTest { Map.of(biome, builder.build())); PackParents again = parents.prepare(PACK, Optional.of(reloaded), report); assertNotSame(before.pack(), again); - biome.proto().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains)); - Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report).biome(); + biome.platform().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains)); + Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report, + plains.getGenerationSettings()).biome(); assertEquals(0.3f, second.getBaseTemperature()); assertEquals(climate(first), climate(second)); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java similarity index 65% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java index 7f5a03565..1dbe03dea 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftDimensionFactoryTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftDimensionFactoryTest.java @@ -1,6 +1,7 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; +import net.minecraft.core.Holder; import net.minecraft.core.HolderLookup; import net.minecraft.core.HolderSet; import net.minecraft.core.MappedRegistry; @@ -14,6 +15,7 @@ import net.minecraft.world.attribute.EnvironmentAttributeMap; import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.timeline.Timeline; +import net.minecraft.world.timeline.Timelines; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -31,20 +33,20 @@ import com.dfsek.terra.api.world.attribute.AttributeEntry; import com.dfsek.terra.api.world.attribute.AttributeKey; import com.dfsek.terra.api.world.attribute.AttributeMap; import com.dfsek.terra.api.world.attribute.DecodeException; -import com.dfsek.terra.mod.generation.GenerationSettings; import com.dfsek.terra.registry.OpenRegistryImpl; +import com.dfsek.terra.world.attribute.platform.AttributeReport; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -100,39 +102,35 @@ class MinecraftDimensionFactoryTest { return parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); } + @Test + void typeIdFollowsFilledDimension() { + Identifier plain = Identifier.parse("terra:test"); + Identifier nether = Identifier.parse("terra:test/minecraft/the_nether"); + + assertEquals(plain, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, false)); + assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, false)); + assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, true)); + assertEquals(Identifier.parse("terra:test/minecraft/overworld"), + MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, true)); + } + @Test void noEntriesMatchesParent() { - DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD); - DimensionType built = factory.create(prepare(Map.of()), null); - - assertEquals(overworld, built); - assertNotSame(overworld, built); + assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(prepare(Map.of()), null)); + assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(bare(), null)); + assertRegistersBesideParent(BuiltinDimensionTypes.NETHER, factory.create( + prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))), null)); assertEquals(List.of(), warnings); assertEquals(List.of(), debugs); } - @Test - void noAttributesMatchesTheParent() { - DimensionType overworld = dimensionType(BuiltinDimensionTypes.OVERWORLD); - DimensionType built = factory.create(bare(), null); - - assertEquals(overworld, built); - assertNotSame(overworld, built); - assertEquals(List.of(), warnings); - assertEquals(List.of(), debugs); - } - - @Test - void createdTypeRegistersBesideItsParent() { - assertRegistersBesideOverworld(factory.create(prepare(Map.of()), null)); - assertRegistersBesideOverworld(factory.create(bare(), null)); - } - - private static void assertRegistersBesideOverworld(DimensionType built) { + private static void assertRegistersBesideParent(ResourceKey parentKey, DimensionType built) { + DimensionType parent = dimensionType(parentKey); + assertEquals(parent, built, parentKey.toString()); MappedRegistry registry = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable()); - registry.register(BuiltinDimensionTypes.OVERWORLD, dimensionType(BuiltinDimensionTypes.OVERWORLD), RegistrationInfo.BUILT_IN); + registry.register(parentKey, parent, RegistrationInfo.BUILT_IN); ResourceKey key = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("terra", "test")); - assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN)); + assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN), parentKey.toString()); } @Test @@ -174,60 +172,29 @@ class MinecraftDimensionFactoryTest { assertEquals(List.of(), warnings); } - @Test - void netherParentHasNoClock() { - PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); - DimensionType built = factory.create(pack, null); - - assertEquals(Optional.empty(), built.defaultClock()); - assertEquals(dimensionType(BuiltinDimensionTypes.NETHER), built); - assertEquals(List.of(), warnings); - } - - @Test - void packEntriesGoOnTheDimension() { - String fastLava = "minecraft:gameplay/fast_lava"; - DimensionType built = factory.create(prepare(Map.of(attribute(fastLava), decoded(fastLava, true))), null); - - assertTrue(built.attributes().contains(vanilla(fastLava))); - assertEquals(true, environment(built.attributes()).get(fastLava)); - assertEquals(List.of(), warnings); - } - @Test void invalidHeightIsSkippedAlone() { - String ambientLight = "terra:dimension/ambient_light"; - Map, AttributeEntry> entries = new LinkedHashMap<>(); - entries.put(attribute("terra:dimension/height"), AttributeEntry.override(100)); - entries.put(attribute(ambientLight), decoded(ambientLight, 0.5)); - - PackParents pack = prepare(entries); - DimensionType built = factory.create(pack, null); - - assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: " - + "logical_height cannot be higher than height"), warnings); - assertEquals(384, built.height()); - assertEquals(0.5f, built.ambientLight()); - assertEquals(384, factory.generationSettings(pack, built).height().getRange()); - } - - @Test - void invalidHeightKeepsThePacksAttributes() { String fastLava = "minecraft:gameplay/fast_lava"; String height = "terra:dimension/height"; + String ambientLight = "terra:dimension/ambient_light"; Map, AttributeEntry> entries = new LinkedHashMap<>(); entries.put(attribute(height), AttributeEntry.override(100)); entries.put(attribute(fastLava), decoded(fastLava, true)); - assertInvalidHeightKeepsFastLava(prepare(entries), fastLava); + entries.put(attribute(ambientLight), decoded(ambientLight, 0.5)); + PackParents pack = prepare(entries); + DimensionType built = assertInvalidHeightKeepsFastLava(pack, fastLava); + assertEquals(0.5f, built.ambientLight()); + assertEquals(384, factory.worldSettings(pack, built).height()); warnings.clear(); OpenRegistryImpl> narrow = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); narrow.register(attribute(height).getRegistryKey(), attribute(height)); narrow.register(attribute(fastLava).getRegistryKey(), attribute(fastLava)); + entries.remove(attribute(ambientLight)); assertInvalidHeightKeepsFastLava(prepare(MinecraftAttributeParentsTest.pack("test", narrow), entries, Map.of()), fastLava); } - private void assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) { + private DimensionType assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) { DimensionType built = factory.create(pack, null); assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: " @@ -235,37 +202,25 @@ class MinecraftDimensionFactoryTest { assertEquals(384, built.height()); assertTrue(built.attributes().contains(vanilla(fastLava))); assertEquals(true, environment(built.attributes()).get(fastLava)); + return built; } @Test - void validHeightOverrideReachesBoth() { - String minY = "terra:dimension/min_y"; - String height = "terra:dimension/height"; - Map, AttributeEntry> entries = new LinkedHashMap<>(); - entries.put(attribute(minY), decoded(minY, -128)); - entries.put(attribute(height), decoded(height, 512)); - PackParents pack = prepare(entries); - - DimensionType built = factory.create(pack, null); - GenerationSettings settings = factory.generationSettings(pack, built); - - assertEquals(-128, built.minY()); - assertEquals(512, built.height()); - assertEquals(-128, settings.height().getMin()); - assertEquals(512, settings.height().getRange()); - assertEquals(List.of(), warnings); - } - - @Test - void timelineTagIsUsed() { + void timelinesAreUsed() { TagKey tag = TagKey.create(Registries.TIMELINE, Identifier.parse("minecraft:in_overworld")); DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER); assertNotEquals(Optional.of(tag), nether.timelines().unwrapKey()); - PackParents pack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); - DimensionType built = factory.create(pack, tag); + PackParents netherPack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))); + DimensionType tagged = factory.create(netherPack, new TimelineRef.Tag(tag)); - assertTrue(built.timelines() instanceof HolderSet.Named, String.valueOf(built.timelines())); - assertEquals(Optional.of(tag), built.timelines().unwrapKey()); + assertTrue(tagged.timelines() instanceof HolderSet.Named, String.valueOf(tagged.timelines())); + assertEquals(Optional.of(tag), tagged.timelines().unwrapKey()); + + List> keys = List.of(Timelines.OVERWORLD_DAY, Timelines.MOON); + DimensionType direct = factory.create(prepare(Map.of()), new TimelineRef.Direct(keys)); + + assertTrue(direct.timelines() instanceof HolderSet.Direct, String.valueOf(direct.timelines())); + assertEquals(keys.stream().map(Optional::of).toList(), direct.timelines().stream().map(Holder::unwrapKey).toList()); assertEquals(List.of(), warnings); } @@ -288,7 +243,7 @@ class MinecraftDimensionFactoryTest { .map(lookup -> lookup.key().equals(Registries.TIMELINE) ? withoutTag : lookup)); MinecraftDimensionFactory strict = new MinecraftDimensionFactory(HANDLE, VanillaContext.of(registries, key -> null)); - DimensionType built = strict.create(prepare(Map.of()), tag); + DimensionType built = strict.create(prepare(Map.of()), new TimelineRef.Tag(tag)); assertEquals(1, warnings.size(), String.valueOf(warnings)); String prefix = "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: "; @@ -309,50 +264,29 @@ class MinecraftDimensionFactoryTest { assertEquals(List.of("Pack \"test\": attribute \"addon:own\" is not applied on this platform"), debugs); } - private static void assertOverworldGeneration(GenerationSettings settings) { - assertEquals(-64, settings.height().getMin()); - assertEquals(384, settings.height().getRange()); - assertEquals(63, settings.sealevel()); - assertEquals(true, settings.mobGeneration()); - assertEquals(64, settings.spawnHeight()); - } - - private GenerationSettings generation(PackParents pack) { - return factory.generationSettings(pack, factory.create(pack, null)); - } - @Test - void generationSettingsFromAttributes() { - assertOverworldGeneration(generation(prepare(Map.of()))); - - String seaLevel = "terra:world/sea_level"; - String spawnHeight = "terra:world/spawn_height"; - String mobGeneration = "terra:world/mob_generation"; - Map, AttributeEntry> entries = new LinkedHashMap<>(); - entries.put(attribute(seaLevel), decoded(seaLevel, 40)); - entries.put(attribute(spawnHeight), decoded(spawnHeight, 90)); - entries.put(attribute(mobGeneration), decoded(mobGeneration, false)); - GenerationSettings settings = generation(prepare(entries)); - - assertEquals(40, settings.sealevel()); - assertEquals(90, settings.spawnHeight()); - assertEquals(false, settings.mobGeneration()); - assertEquals(-64, settings.height().getMin()); - assertEquals(384, settings.height().getRange()); - assertEquals(List.of(), warnings); - } - - @Test - void generationWithoutAttributes() { - assertOverworldGeneration(generation(bare())); - + void worldSettingsFromAttributes() { OpenRegistryImpl> noWorld = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); ATTRIBUTES.stream() .filter(attribute -> !attribute.getRegistryKey().toString().startsWith("terra:world/")) .forEach(attribute -> noWorld.register(attribute.getRegistryKey(), attribute)); - PackParents pack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of()); - assertNull(pack.table().seaLevel()); - assertOverworldGeneration(generation(pack)); + PackParents noWorldPack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of()); + assertNull(noWorldPack.table().seaLevel()); + for(PackParents pack : List.of(noWorldPack, prepare(Map.of()), bare())) { + assertEquals(new WorldSettings(-64, 384, 63, true, 64), factory.worldSettings(pack, factory.create(pack, null))); + } + + Map, AttributeEntry> entries = new LinkedHashMap<>(); + for(Map.Entry entry : Map.of("terra:dimension/min_y", -128, "terra:dimension/height", 512, + "terra:world/sea_level", 40, "terra:world/spawn_height", 90, + "terra:world/mob_generation", false).entrySet()) { + entries.put(attribute(entry.getKey()), decoded(entry.getKey(), entry.getValue())); + } + PackParents pack = prepare(entries); + DimensionType built = factory.create(pack, null); + assertEquals(-128, built.minY()); + assertEquals(512, built.height()); + assertEquals(new WorldSettings(-128, 512, 40, false, 90), factory.worldSettings(pack, built)); assertEquals(List.of(), warnings); } } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java similarity index 78% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java index 0e0200e98..abb520d8b 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTimelinesTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/MinecraftTimelinesTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.core.Holder; import net.minecraft.core.HolderSet; @@ -8,7 +8,9 @@ import net.minecraft.core.registries.Registries; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.tags.TagKey; +import net.minecraft.tags.TagLoader.LoadResult; import net.minecraft.tags.TimelineTags; +import net.minecraft.world.level.dimension.BuiltinDimensionTypes; import net.minecraft.world.clock.WorldClock; import net.minecraft.world.timeline.Timeline; import net.minecraft.world.timeline.Timelines; @@ -37,15 +39,15 @@ import com.dfsek.terra.api.world.attribute.schedule.Easing; import com.dfsek.terra.api.world.attribute.schedule.Keyframe; import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack; import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; -import com.dfsek.terra.mod.util.TagUtil; +import com.dfsek.terra.world.attribute.platform.AttributeReport; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; -import static com.dfsek.terra.mod.attribute.VanillaContextTest.copy; +import static 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 com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.attribute.VanillaContextTest.copy; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -159,42 +161,6 @@ class MinecraftTimelinesTest { @Test void definitionParses() { - Timeline timeline = MinecraftTimelines.create(SEASONS, skySchedule(), TABLE, HANDLE, CONTEXT, report); - - assertNotNull(timeline, String.valueOf(warnings)); - assertEquals(Optional.of(24000), timeline.periodTicks()); - assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes()); - assertEquals(Optional.of(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.parse("minecraft:overworld"))), - timeline.clock().unwrapKey()); - assertEquals(List.of(), warnings); - assertEquals(List.of(), debugs); - } - - @Test - void upperCaseIdsWarn() { - assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE, - CONTEXT, report))); - assertOneWarningStartingWith(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\"")); - - warnings.clear(); - assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"), - Map.of()), TABLE, HANDLE, CONTEXT, report))); - assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\"")); - - warnings.clear(); - AttributeSchedule upperMarker = schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"), new TimeMarker(6000, false))); - assertNull(assertDoesNotThrow(() -> MinecraftTimelines.create(SEASONS, upperMarker, TABLE, HANDLE, CONTEXT, report))); - assertOneWarningStartingWith(skipped("mypack:seasons", "invalid ID \"mypack:Noon\"")); - } - - @Test - void unknownClockIsSkipped() { - assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE, CONTEXT, report)); - assertEquals(List.of(skipped("mypack:seasons", "no such clock \"test:nope\"")), warnings); - } - - @Test - void terraTracksAreDropped() { Attribute sky = attribute(SKY_COLOR); Attribute temperature = attribute("terra:biome/temperature"); Map, ScheduleTrack> tracks = new LinkedHashMap<>(); @@ -205,11 +171,37 @@ class MinecraftTimelinesTest { Timeline timeline = MinecraftTimelines.create(SEASONS, schedule, TABLE, HANDLE, CONTEXT, report); assertNotNull(timeline, String.valueOf(warnings)); + assertEquals(Optional.of(24000), timeline.periodTicks()); assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes()); + assertEquals(Optional.of(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.parse("minecraft:overworld"))), + timeline.clock().unwrapKey()); assertEquals(List.of(), warnings); assertEquals(List.of("Pack \"test\": attribute \"terra:biome/temperature\" is not applied on this platform"), debugs); } + @Test + void badIdsSkipSchedule() { + Map cases = new LinkedHashMap<>(); + cases.put(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\""), + () -> assertNull(MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE, CONTEXT, + report))); + cases.put(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"), Map.of()), TABLE, + HANDLE, CONTEXT, report))); + cases.put(skipped("mypack:seasons", "invalid ID \"mypack:Noon\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"), + new TimeMarker(6000, false))), + TABLE, HANDLE, CONTEXT, report))); + cases.put(skipped("mypack:seasons", "no such clock \"test:nope\""), + () -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE, + CONTEXT, report))); + cases.forEach((prefix, create) -> { + warnings.clear(); + assertDoesNotThrow(create::run, prefix); + assertOneWarningStartingWith(prefix); + }); + } + @Test void definitionsAreRegistered() { Load load = Load.create(); @@ -286,28 +278,16 @@ class MinecraftTimelinesTest { @Test void noRefsMeansNoTag() { - assertNull(MinecraftTimelines.tagFor(PACK, prepare(List.of(), Map.of()))); + PackParents empty = prepare(List.of(), Map.of()); + assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, empty)); + assertNull(MinecraftTimelines.pending(PACK, empty)); parents.beginLoad(CONTEXT); - assertNull(MinecraftTimelines.tagFor(PACK, parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), - report))); + PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report); + assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, bare)); + assertNull(MinecraftTimelines.pending(PACK, bare)); assertEquals(List.of(), warnings); } - @Test - void upperCaseRefIsSkipped() { - Load load = Load.create(); - PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of()); - - TagKey tag = assertDoesNotThrow(() -> MinecraftTimelines.tagFor(PACK, pack)); - - assertEquals(TERRA_TEST, tag); - assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); - Map, List>> collect = new HashMap<>(); - MinecraftTimelines.fillTags(collect, load.timelines()); - assertEquals(List.of(load.timeline(Timelines.OVERWORLD_DAY)), collect.get(TERRA_TEST)); - assertEquals(1, warnings.size()); - } - @Test void tagsAreFilled() { Load load = Load.create(); @@ -316,7 +296,7 @@ class MinecraftTimelinesTest { Holder.Reference villagers = load.timeline(Timelines.VILLAGER_SCHEDULE); PackParents pack = prepare(List.of(id("minecraft:day"), tag("minecraft", "in_overworld"), id("minecraft:nope"), tag("minecraft", "nope")), Map.of()); - assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); assertEquals(List.of(), warnings); Map, List>> collect = new HashMap<>(); @@ -335,7 +315,7 @@ class MinecraftTimelinesTest { Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); Holder.Reference moon = load.timeline(Timelines.MOON); PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:nope"), tag("minecraft", "nope")), Map.of()); - assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); warnings.clear(); @@ -351,6 +331,41 @@ class MinecraftTimelinesTest { warnings); } + @Test + void tagPerDimensionType() { + Load load = Load.create(); + Holder.Reference day = load.timeline(Timelines.OVERWORLD_DAY); + Holder.Reference moon = load.timeline(Timelines.MOON); + PackParents overworld = prepare(List.of(id("minecraft:nope")), Map.of()); + PackParents nether = parents.prepare(PACK, Optional.ofNullable(overworld.attributes()), report, BuiltinDimensionTypes.NETHER); + TagKey netherTag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test/minecraft/the_nether")); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, overworld)); + assertEquals(netherTag, MinecraftTimelines.tagFor(netherTag.location(), PACK, nether)); + + Map, List>> collect = new HashMap<>(); + collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon)); + MinecraftTimelines.fillTags(collect, load.timelines()); + + assertEquals(List.of(day, moon), collect.get(TERRA_TEST)); + assertFalse(collect.get(netherTag).contains(day), "the nether has no day cycle: " + collect.get(netherTag)); + } + + @Test + void pendingSkipsBadRefs() { + Load load = Load.create(); + PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of()); + + MinecraftTimelines.Pending pending = assertDoesNotThrow(() -> MinecraftTimelines.pending(PACK, pack)); + + assertNotNull(pending); + assertEquals(List.of(com.mojang.datafixers.util.Either.left(Identifier.parse("minecraft:day"))), pending.refs()); + assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\"")); + Map, List>> collect = new HashMap<>(); + MinecraftTimelines.fillTags(collect, load.timelines()); + assertEquals(Map.of(), collect, "nothing recorded"); + assertEquals(1, warnings.size()); + } + @Test void tagRefillsOnReload() { Load load = Load.create(); @@ -361,7 +376,7 @@ class MinecraftTimelinesTest { Map.of(SEASONS, skySchedule())); MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context()); - TagKey tag = MinecraftTimelines.tagFor(PACK, pack); + TagKey tag = MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack); assertEquals(TERRA_TEST, tag); HolderSet.Named dimensionTimelines = load.context().ops().getter(Registries.TIMELINE).orElseThrow().get(tag) .orElseThrow(); @@ -372,7 +387,7 @@ class MinecraftTimelinesTest { Timeline.validateRegistry(timelines, errors); assertEquals(Map.of(), errors); - TagUtil.registerTimelineTags(timelines); + registerTimelineTags(timelines); Holder.Reference seasons = timelines.get(Identifier.parse("mypack:seasons")).orElseThrow(); assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList()); assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow()); @@ -384,7 +399,7 @@ class MinecraftTimelinesTest { parents.prepare(PACK, Optional.of(new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(), List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")), Map.of(SEASONS, skySchedule()))), report); - TagUtil.registerTimelineTags(timelines); + registerTimelineTags(timelines); parents.endPackReload(); assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow()); assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList()); @@ -392,6 +407,13 @@ class MinecraftTimelinesTest { assertEquals(List.of(), warnings); } + private static void registerTimelineTags(Registry registry) { + Map, List>> collect = new HashMap<>(); + registry.getTags().forEach(tag -> collect.put(tag.key(), new ArrayList<>(tag.stream().toList()))); + MinecraftTimelines.fillTags(collect, registry); + registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); + } + private static Map frozenTags(MappedRegistry registry) { try { java.lang.reflect.Field field = MappedRegistry.class.getDeclaredField("frozenTags"); @@ -406,7 +428,7 @@ class MinecraftTimelinesTest { void beginLoadDropsPendingTags() { Load load = Load.create(); PackParents pack = prepare(List.of(id("minecraft:day")), Map.of()); - assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(PACK, pack)); + assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack)); parents.beginLoad(CONTEXT); Map, List>> collect = new HashMap<>(); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java similarity index 93% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java index 26e85d2c4..679c63f7e 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaCodecHarnessTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaCodecHarnessTest.java @@ -1,16 +1,13 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceKey; import net.minecraft.util.ARGB; import net.minecraft.world.attribute.EnvironmentAttribute; import net.minecraft.world.attribute.EnvironmentAttributeMap; -import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.timeline.Timeline; import org.joml.Vector3f; import org.joml.Vector3fc; @@ -44,12 +41,12 @@ import com.dfsek.terra.api.world.attribute.schedule.TimeMarker; import com.dfsek.terra.api.world.attribute.value.Color; import com.dfsek.terra.api.world.attribute.value.TriState; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.LOOKUP; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.LOOKUP; +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.vanilla; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -91,15 +88,6 @@ class VanillaCodecHarnessTest { return attribute.type().decodeArgument(operation, raw, PLAIN); } - @Test - void bootstrapsVanilla() { - assertTrue(REGISTRIES.lookupOrThrow(Registries.BIOME).get(Biomes.PLAINS).isPresent()); - assertTrue(REGISTRIES.lookupOrThrow(Registries.WORLD_CLOCK) - .get(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.withDefaultNamespace("overworld"))).isPresent()); - assertTrue(REGISTRIES.lookupOrThrow(Registries.TIMELINE) - .get(ResourceKey.create(Registries.TIMELINE, Identifier.withDefaultNamespace("day"))).isPresent()); - } - @Test void hexColorsMatchVanilla() throws DecodeException { Attribute fog = attribute(FOG_COLOR); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java similarity index 96% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java index 71ab528c7..416e2ad1d 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaContextTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaContextTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Lifecycle; import net.minecraft.core.Holder; @@ -23,8 +23,8 @@ import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java similarity index 89% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java rename to platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java index b4f8c6072..3d2089a7b 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/VanillaParentReaderTest.java +++ b/platforms/minecraft-common/src/test/java/com/dfsek/terra/minecraft/attribute/VanillaParentReaderTest.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import com.mojang.serialization.Codec; import net.minecraft.core.Holder; @@ -38,19 +38,20 @@ import com.dfsek.terra.api.world.attribute.AttributeScope; import com.dfsek.terra.api.world.attribute.DecodeContext; import com.dfsek.terra.api.world.attribute.DecodeException; import com.dfsek.terra.api.world.attribute.value.Color; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.ATTRIBUTES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.CONTEXT; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.HANDLE; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.REGISTRIES; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.attribute; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.registry; -import static com.dfsek.terra.mod.attribute.MinecraftTestSupport.vanilla; +import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES; +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.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @@ -111,8 +112,7 @@ class VanillaParentReaderTest { bound.add(b.vanilla()); } assertEquals(Set.copyOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.stream().toList()), bound); - assertEquals(51, bound.size()); - assertEquals(51, TABLE.environment().size()); + assertEquals(bound.size(), TABLE.environment().size(), "each vanilla attribute is bound once"); assertEquals(List.of(), TABLE.unapplied()); assertEquals(4, TABLE.climate().size()); @@ -140,22 +140,13 @@ class VanillaParentReaderTest { @Test void noRegistryMeansEmptyTable() { PackAttributeTable table = PackAttributeTable.of(null); - assertEquals(List.of(), table.environment()); - assertEquals(List.of(), table.climate()); - assertEquals(List.of(), table.effects()); - assertEquals(List.of(), table.dimension()); - assertEquals(List.of(), table.unapplied()); - assertNull(table.villagerType()); - assertNull(table.seaLevel()); - assertNull(table.spawnHeight()); - assertNull(table.mobGeneration()); + assertSame(PackAttributeTable.EMPTY, table); VanillaParentReader reader = new VanillaParentReader(HANDLE, VanillaContext.of(REGISTRIES, key -> VillagerType.DESERT)); assertNoEntries(reader.biome(Biomes.PLAINS, biome(Biomes.PLAINS), table, FAIL), "biome"); assertNoEntries(reader.dimension(dimensionType(BuiltinDimensionTypes.NETHER), table, FAIL), "dimension"); assertNoEntries(reader.generation(REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS) .getOrThrow(NoiseGeneratorSettings.OVERWORLD).value(), table), "generation"); - assertNoEntries(AttributeSlots.EMPTY, "empty"); } @Test @@ -164,7 +155,7 @@ class VanillaParentReaderTest { .build(); PackAttributeTable table = PackAttributeTable.of(registry(custom)); assertEquals(List.of(custom), table.unapplied()); - assertEquals(51, table.environment().size()); + assertEquals(TABLE.environment(), table.environment()); assertNull(READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(custom)); } @@ -200,17 +191,14 @@ class VanillaParentReaderTest { @Test void oldParticleFormIsRejected() throws DecodeException { Attribute particles = attribute(AMBIENT_PARTICLES); - Attribute fog = attribute(FOG_COLOR); Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand")); Object newParticle = VanillaCodecs.encode(ParticleTypes.CODEC, new BlockParticleOption(ParticleTypes.FALLING_DUST, Blocks.SAND.defaultBlockState()), OPS); - Map, AttributeEntry> entries = new LinkedHashMap<>(); - entries.put(particles, HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN)); - entries.put(fog, HANDLE.decodeEntry(fog, "#123456", PLAIN)); + AttributeEntry old = HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN); List skipped = new ArrayList<>(); - EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, true, + EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, old), true, (attribute, reason) -> { assertEquals(particles, attribute); skipped.add(reason); @@ -218,7 +206,6 @@ class VanillaParentReaderTest { assertEquals(1, skipped.size()); assertFalse(skipped.getFirst().isBlank()); assertFalse(rejected.contains(EnvironmentAttributes.AMBIENT_PARTICLES)); - assertTrue(rejected.contains(vanilla(FOG_COLOR)), "the other entry still applies"); AttributeEntry accepted = HANDLE.decodeEntry(particles, List.of(Map.of("particle", newParticle, "probability", 0.01)), PLAIN); @@ -240,7 +227,7 @@ class VanillaParentReaderTest { } @Test - void readsBiomeFields() { + void readsBiomeFieldsAndEnvironment() { Attribute temperature = attribute("terra:biome/temperature"); Attribute precipitation = attribute("terra:biome/has_precipitation"); Attribute villager = attribute("terra:biome/villager_type"); @@ -261,19 +248,14 @@ class VanillaParentReaderTest { assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:desert")), withVillagers.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL).get(villager)); assertNull(withVillagers.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(villager)); - } - @Test - void readsBiomeEnvironment() { - Biome plains = biome(Biomes.PLAINS); - AttributeSlots slots = READER.biome(Biomes.PLAINS, plains, TABLE, FAIL); int present = 0; for(PackAttributeTable.Bound b : TABLE.environment()) { - if(plains.getAttributes().contains(b.vanilla())) { - assertNotNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString()); + if(biome(Biomes.PLAINS).getAttributes().contains(b.vanilla())) { + assertNotNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString()); present++; } else { - assertNull(slots.get(b.attribute()), b.attribute().getRegistryKey().toString()); + assertNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString()); } } assertTrue(present > 0); diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java similarity index 91% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java index aa200aff6..cebab7087 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/FakePackAttributes.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/FakePackAttributes.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import org.jetbrains.annotations.Nullable; @@ -22,7 +22,7 @@ import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule; import com.dfsek.terra.api.world.biome.Biome; -final class FakePackAttributes implements PackAttributes { +public final class FakePackAttributes implements PackAttributes { private static final AttributeEntry UNREAD = AttributeEntry.override(new Object()); private final AttributeHandle handle; @@ -35,12 +35,12 @@ final class FakePackAttributes implements PackAttributes { private final AttributeEntry[] packSlots; private final IdentityHashMap[]> biomeSlots = new IdentityHashMap<>(); - FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, + public FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, Map biomes) { this(handle, platformParents, pack, parents, biomes, List.of(), Map.of()); } - FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, + public FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map parents, Map biomes, List> scheduleRefs, Map scheduleDefinitions) { this.handle = handle; diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java similarity index 74% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java index 4cba2c23f..944dd46e4 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/MinecraftTestSupport.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/MinecraftTestSupport.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.SharedConstants; import net.minecraft.core.HolderLookup; @@ -24,20 +24,20 @@ import com.dfsek.terra.registry.OpenRegistryImpl; import com.dfsek.terra.world.attribute.AttributeHandleImpl; -final class MinecraftTestSupport { +public final class MinecraftTestSupport { static { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); } - static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup(); - static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null); - static final AttributeHandle HANDLE = new AttributeHandleImpl(); - static final List> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE); + public static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup(); + public static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null); + public static final AttributeHandle HANDLE = new AttributeHandleImpl(); + public static final List> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE); private static final Registry> TABLE = registry(); - static final AttributeLookup LOOKUP = key -> { + public static final AttributeLookup LOOKUP = key -> { RegistryKey id; try { id = RegistryKey.parseNamespaced(key); @@ -49,11 +49,11 @@ final class MinecraftTestSupport { private MinecraftTestSupport() { } - static List> loadContext(net.minecraft.core.Registry.PendingTags... pending) { + public static List> loadContext(net.minecraft.core.Registry.PendingTags... pending) { return TagLoader.buildUpdatedLookups(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), List.of(pending)); } - static Registry> registry(Attribute... extra) { + public static Registry> registry(Attribute... extra) { OpenRegistryImpl> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE); ATTRIBUTES.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute)); for(Attribute attribute : extra) registry.register(attribute.getRegistryKey(), attribute); @@ -61,12 +61,12 @@ final class MinecraftTestSupport { } @SuppressWarnings("unchecked") - static Attribute attribute(String id) { + public static Attribute attribute(String id) { AttributeKey key = AttributeKey.parse(id); return (Attribute) TABLE.get(key.getRegistryKey()).orElseThrow(() -> new IllegalArgumentException("no attribute " + id)); } - static EnvironmentAttribute vanilla(String id) { + public static EnvironmentAttribute vanilla(String id) { return BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getOptional(Identifier.parse(id)) .orElseThrow(() -> new IllegalArgumentException("no vanilla attribute " + id)); } diff --git a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java similarity index 72% rename from platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java rename to platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java index 32eb2c046..076c973e7 100644 --- a/platforms/mixin-common/src/test/java/com/dfsek/terra/mod/attribute/TestBiome.java +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestBiome.java @@ -1,4 +1,4 @@ -package com.dfsek.terra.mod.attribute; +package com.dfsek.terra.minecraft.attribute; import net.minecraft.resources.Identifier; @@ -7,27 +7,26 @@ import java.util.Set; import com.dfsek.terra.api.properties.Context; import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.api.world.biome.PlatformBiome; -import com.dfsek.terra.mod.config.ProtoPlatformBiome; -final class TestBiome implements Biome { +public final class TestBiome implements Biome { private final String id; private final int intId; private final PlatformBiome platformBiome; private final Context context = new Context(); - TestBiome(String id, int intId, Identifier parent) { - this(id, intId, new ProtoPlatformBiome(parent)); + public TestBiome(String id, int intId, Identifier parent) { + this(id, intId, new TestPlatformBiome(parent)); } - TestBiome(String id, int intId, PlatformBiome platformBiome) { + public TestBiome(String id, int intId, PlatformBiome platformBiome) { this.id = id; this.intId = intId; this.platformBiome = platformBiome; } - ProtoPlatformBiome proto() { - return (ProtoPlatformBiome) platformBiome; + public TestPlatformBiome platform() { + return (TestPlatformBiome) platformBiome; } @Override diff --git a/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java new file mode 100644 index 000000000..3c3a0279f --- /dev/null +++ b/platforms/minecraft-common/src/testFixtures/java/com/dfsek/terra/minecraft/attribute/TestPlatformBiome.java @@ -0,0 +1,37 @@ +package com.dfsek.terra.minecraft.attribute; + +import net.minecraft.resources.Identifier; + +import java.util.Objects; + +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 final class TestPlatformBiome implements PlatformBiome, ParentEntryHolder { + private final Identifier parent; + private AttributeSlots parentEntries = AttributeSlots.EMPTY; + + public TestPlatformBiome(Identifier parent) { + this.parent = Objects.requireNonNull(parent); + } + + public Identifier parent() { + return parent; + } + + @Override + public Identifier getHandle() { + return parent; + } + + @Override + public AttributeSlots parentEntries() { + return parentEntries; + } + + public void setParentEntries(AttributeSlots parentEntries) { + this.parentEntries = Objects.requireNonNull(parentEntries); + } +} diff --git a/platforms/mixin-common/build.gradle.kts b/platforms/mixin-common/build.gradle.kts index 2d3848be4..9c725ba39 100644 --- a/platforms/mixin-common/build.gradle.kts +++ b/platforms/mixin-common/build.gradle.kts @@ -12,10 +12,9 @@ dependencies { compileOnly("net.fabricmc:sponge-mixin:${Versions.Mod.mixin}") - minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") + api(project(":platforms:minecraft-common")) { isTransitive = false } - // Tests only: the addon ships as its own jar. - testImplementation(project(":common:addons:minecraft-attributes")) + minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") } architectury { diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java index 503eb9c4a..ebd0fb5c0 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/ModPlatform.java @@ -24,7 +24,7 @@ import com.dfsek.terra.api.handle.ItemHandle; import com.dfsek.terra.api.handle.WorldHandle; import com.dfsek.terra.api.world.attribute.AttributeParents; import com.dfsek.terra.api.world.biome.PlatformBiome; -import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.handle.MinecraftItemHandle; import com.dfsek.terra.mod.handle.MinecraftWorldHandle; @@ -47,7 +47,7 @@ public abstract class ModPlatform extends AbstractPlatform { getRawConfigRegistry() .forEach(pack -> { boolean packInMetapack = configPacksInMetaPack.contains(pack.getID()); - PresetUtil.createDefault(pack, this, packInMetapack, packInMetapack).apply(registerFunction); + PresetUtil.createDefault(pack, this, packInMetapack).apply(registerFunction); }); } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java index e2bc1703f..7ad853618 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/config/ProtoPlatformBiome.java @@ -26,11 +26,12 @@ import net.minecraft.world.level.biome.Biome; import java.util.Objects; import com.dfsek.terra.api.world.biome.PlatformBiome; -import com.dfsek.terra.mod.attribute.AttributeSlots; import com.dfsek.terra.mod.util.MinecraftUtil; +import com.dfsek.terra.world.attribute.platform.AttributeSlots; +import com.dfsek.terra.world.attribute.platform.ParentEntryHolder; -public class ProtoPlatformBiome implements PlatformBiome { +public class ProtoPlatformBiome implements PlatformBiome, ParentEntryHolder { private final Identifier identifier; private Holder delegate; @@ -59,6 +60,7 @@ public class ProtoPlatformBiome implements PlatformBiome { this.delegate = Objects.requireNonNull(delegate); } + @Override public AttributeSlots parentEntries() { return parentEntries; } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java index 54079e095..591ae8675 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/BiomeUtil.java @@ -8,13 +8,14 @@ import java.util.Locale; import java.util.Map; import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource; public class BiomeUtil { public static final Map> TERRA_BIOME_MAP = new HashMap<>(); - public static final Map + public static final Map TERRA_BIOME_PLATFORM_TAGS = new HashMap<>(); public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { @@ -26,7 +27,7 @@ public class BiomeUtil { return Map.copyOf(TERRA_BIOME_MAP); } - public static Map getTerraBiomePlatformTags() { + public static Map getTerraBiomePlatformTags() { return Map.copyOf(TERRA_BIOME_PLATFORM_TAGS); } } diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java index 8fe0a3307..58905e0a9 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/PresetUtil.java @@ -5,6 +5,7 @@ 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.level.biome.Biome; import net.minecraft.world.level.biome.MultiNoiseBiomeSource; import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterList; @@ -17,6 +18,7 @@ import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; import net.minecraft.world.level.levelgen.presets.WorldPreset; +import net.minecraft.world.timeline.Timeline; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,24 +30,26 @@ import java.util.Locale; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.MetaPack; import com.dfsek.terra.api.util.generic.pair.Pair; +import com.dfsek.terra.api.util.range.ConstantRange; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftDimensionFactory; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.TimelineRef; +import com.dfsek.terra.minecraft.attribute.VanillaContext; +import com.dfsek.terra.minecraft.attribute.WorldSettings; import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.attribute.AttributeReport; -import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; -import com.dfsek.terra.mod.attribute.MinecraftDimensionFactory; -import com.dfsek.terra.mod.attribute.MinecraftTimelines; -import com.dfsek.terra.mod.attribute.PackParents; -import com.dfsek.terra.mod.attribute.VanillaContext; import com.dfsek.terra.mod.generation.GenerationSettings; import com.dfsek.terra.mod.generation.MinecraftChunkGeneratorWrapper; import com.dfsek.terra.mod.generation.TerraBiomeSource; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public class PresetUtil { private static final Logger LOGGER = LoggerFactory.getLogger(PresetUtil.class); private static final List> PRESETS = new ArrayList<>(); - public static Pair createDefault(ConfigPack pack, ModPlatform platform, boolean extended, - boolean packInMetapack) { + public static Pair createDefault(ConfigPack pack, ModPlatform platform, boolean extended) { Registry dimensionTypeRegistry = platform.dimensionTypeRegistry(); Registry chunkGeneratorSettingsRegistry = platform.chunkGeneratorSettingsRegistry(); Registry multiNoiseBiomeSourceParameterLists = @@ -60,7 +64,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); - insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap, packInMetapack); + insertCustom(platform, "minecraft:overworld", pack, dimensionTypeRegistry, dimensionMap); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), dimensionMap); @@ -85,7 +89,7 @@ public class PresetUtil { HashMap, LevelStem> dimensionMap = new HashMap<>(); metaPack.packs().forEach((key, pack) -> { - insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap, false); + insertCustom(platform, key, pack, dimensionTypeRegistry, dimensionMap); }); insertDefaults(dimensionTypeRegistry, chunkGeneratorSettingsRegistry, multiNoiseBiomeSourceParameterLists, platform.biomeRegistry(), @@ -97,33 +101,37 @@ public class PresetUtil { } private static void insertCustom(ModPlatform platform, String key, ConfigPack pack, Registry dimensionTypeRegistry, - HashMap, LevelStem> dimensionMap, boolean packInMetapack) { + HashMap, LevelStem> dimensionMap) { Identifier demensionIdentifier = Identifier.parse(key); MinecraftAttributeParents parents = platform.attributeParents(); VanillaContext context = parents.context(); if(context == null) throw new IllegalStateException("no registry load has begun"); - PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack)); + ResourceKey filled = MinecraftUtil.registerDimensionTypeKey(demensionIdentifier); + if(context.dimensionTypes().get(filled).isEmpty()) filled = BuiltinDimensionTypes.OVERWORLD; + PackParents packParents = parents.prepare(pack, platform.getAttributeHandle().pack(pack), AttributeReport.logging(pack), filled); MinecraftDimensionFactory factory = new MinecraftDimensionFactory(platform.getAttributeHandle(), context); - Identifier dimensionTypeID = Identifier.fromNamespaceAndPath("terra", pack.getID().toLowerCase(Locale.ROOT)); + Identifier dimensionTypeID = MinecraftDimensionFactory.typeId(pack, filled, false); + ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey(dimensionTypeID); DimensionType dimensionType; - if(!packInMetapack) { - dimensionType = factory.create(packParents, MinecraftTimelines.tagFor(pack, packParents)); - ResourceKey dimensionTypeRegistryKey = MinecraftUtil.registerDimensionTypeKey( - dimensionTypeID); - - Registry.registerForHolder(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); + if(dimensionTypeRegistry.containsKey(dimensionTypeRegistryKey)) { + // Relies on Fabric API binding values at register; vanilla binds them at the freeze. + dimensionType = dimensionTypeRegistry.getValue(dimensionTypeRegistryKey); } else { - dimensionType = dimensionTypeRegistry.getValue(dimensionTypeID); + TagKey timelines = MinecraftTimelines.tagFor(dimensionTypeID, pack, packParents); + dimensionType = factory.create(packParents, timelines == null ? null : new TimelineRef.Tag(timelines)); + Registry.registerForHolder(dimensionTypeRegistry, dimensionTypeRegistryKey, dimensionType); } Holder dimensionTypeRegistryEntry = dimensionTypeRegistry.wrapAsHolder(dimensionType); TerraBiomeSource biomeSource = new TerraBiomeSource(pack); - GenerationSettings generatorSettings = factory.generationSettings(packParents, dimensionType); + WorldSettings s = factory.worldSettings(packParents, dimensionType); + GenerationSettings generatorSettings = new GenerationSettings(new ConstantRange(s.minY(), s.minY() + s.height()), + s.seaLevel(), s.mobGeneration(), s.spawnHeight()); ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, generatorSettings); diff --git a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java index bd65a7045..8c6ab0cb1 100644 --- a/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java +++ b/platforms/mixin-common/src/main/java/com/dfsek/terra/mod/util/TagUtil.java @@ -2,8 +2,6 @@ package com.dfsek.terra.mod.util; import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.core.registries.Registries; -import net.minecraft.resources.Identifier; import net.minecraft.tags.TagKey; import net.minecraft.tags.TagLoader.LoadResult; import net.minecraft.tags.WorldPresetTags; @@ -15,18 +13,12 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; import java.util.stream.Collectors; -import com.dfsek.terra.api.registry.key.RegistryKey; -import com.dfsek.terra.mod.attribute.AttributeReport; -import com.dfsek.terra.mod.attribute.MinecraftTimelines; -import com.dfsek.terra.mod.attribute.VanillaIds; +import com.dfsek.terra.minecraft.attribute.BiomeTags; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; public final class TagUtil { @@ -77,13 +69,11 @@ public final class TagUtil { registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); } - public record PlatformTagSource(AttributeReport report, String config, Set tags) { } - public static void registerBiomeTags(Registry registry) { logger.info("Doing biome tag garbage...."); Map, List>> collect = tagsToMutableMap(registry); - addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(), + BiomeTags.addTerraBiomes(collect, id -> MinecraftUtil.getEntry(registry, id), BiomeUtil.getTerraBiomeMap(), BiomeUtil.getTerraBiomePlatformTags()); registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply(); @@ -95,44 +85,4 @@ public final class TagUtil { .forEach(logger::debug); } } - - public static void addTerraBiomes(Map, List>> collect, - Function>> lookup, - Map> byParent, Map platformTags) { - byParent.forEach((vb, terraBiomes) -> - lookup.apply(vb).ifPresentOrElse( - vanilla -> terraBiomes.forEach(tb -> lookup.apply(tb).ifPresentOrElse( - terra -> { - logger.debug(vanilla.unwrapKey().orElseThrow().identifier() + " (vanilla for " + - terra.unwrapKey().orElseThrow().identifier() + ": " + vanilla.tags().toList()); - vanilla.tags().forEach(tag -> collect.computeIfAbsent(tag, t -> new ArrayList<>()).add(terra)); - }, - () -> logger.error("No such biome: {}", tb))), - () -> logger.error("No vanilla biome: {}", vb))); - - Set> existing = new HashSet<>(collect.keySet()); - platformTags.forEach((tb, source) -> { - if(source.tags().isEmpty()) return; - Optional> terra = lookup.apply(tb); - if(terra.isEmpty()) { - logger.error("No such biome: {}", tb); - return; - } - for(RegistryKey key : source.tags()) { - Identifier id; - try { - id = VanillaIds.identifier(key); - } catch(IllegalArgumentException e) { - source.report().ignored(source.config(), key.toString(), e.getMessage()); - continue; - } - TagKey tag = TagKey.create(Registries.BIOME, id); - if(!existing.contains(tag) && id.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) { - source.report().tagCreated(source.config(), key.toString()); - } - List> biomes = collect.computeIfAbsent(tag, t -> new ArrayList<>()); - if(!biomes.contains(terra.get())) biomes.add(terra.get()); - } - }); - } } diff --git a/platforms/mixin-lifecycle/build.gradle.kts b/platforms/mixin-lifecycle/build.gradle.kts index cca5e654a..7a3cae4c3 100644 --- a/platforms/mixin-lifecycle/build.gradle.kts +++ b/platforms/mixin-lifecycle/build.gradle.kts @@ -10,6 +10,7 @@ dependencies { compileOnly("io.github.llamalad7:mixinextras-common:${Versions.Mod.mixinExtras}") implementation(project(":platforms:mixin-common")) { isTransitive = false } + implementation(project(":platforms:minecraft-common")) { isTransitive = false } minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java index a366f43a0..cee0bbcdf 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/mixin/lifecycle/RegistryDataLoaderMixin.java @@ -33,9 +33,9 @@ import com.dfsek.terra.lifecycle.mixin.RegistryLoadTaskAccessor; import com.dfsek.terra.lifecycle.util.LifecycleUtil; import com.dfsek.terra.lifecycle.util.LoadContextHolder; import com.dfsek.terra.lifecycle.util.RegistryHack; +import com.dfsek.terra.minecraft.attribute.VanillaContext; import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.attribute.VanillaContext; import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor; diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java index bd102d54c..8e0c8151c 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleBiomeUtil.java @@ -11,18 +11,18 @@ import java.util.ArrayList; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.world.biome.Biome; +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.mod.CommonPlatform; import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.attribute.AttributeReport; -import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; -import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory; -import com.dfsek.terra.mod.attribute.PackParents; import com.dfsek.terra.mod.config.PreLoadCompatibilityOptions; import com.dfsek.terra.mod.config.ProtoPlatformBiome; import com.dfsek.terra.mod.mixin.access.VillagerTypeAccessor; import com.dfsek.terra.mod.util.BiomeUtil; import com.dfsek.terra.mod.util.MinecraftUtil; -import com.dfsek.terra.mod.util.TagUtil; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class LifecycleBiomeUtil { @@ -81,14 +81,15 @@ public final class LifecycleBiomeUtil { // Registered by an earlier load; edits wait for the next registry load. proto.setDelegate(MinecraftUtil.getEntry(registry, identifier).orElseThrow()); } else { - MinecraftBiomeFactory.Built built = factory.create(vanilla, vanillaBiome, biome, packParents, packParents.report()); + MinecraftBiomeFactory.Built built = factory.create(vanilla, vanillaBiome, biome, packParents, packParents.report(), + vanillaBiome.getGenerationSettings()); proto.setDelegate(Registry.registerForHolder(registry, MinecraftUtil.registerBiomeKey(identifier).identifier(), built.biome())); VillagerTypeAccessor.getBiomeTypeToIdMap().put(ResourceKey.create(Registries.BIOME, identifier), built.villagerType()); } BiomeUtil.TERRA_BIOME_PLATFORM_TAGS.put(identifier, - new TagUtil.PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags())); + new PlatformTagSource(packParents.report(), biome.getID(), biome.getPlatformTags())); BiomeUtil.TERRA_BIOME_MAP.computeIfAbsent(vanilla.identifier(), i -> new ArrayList<>()).add(identifier); } } diff --git a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java index ded62698d..3409ca484 100644 --- a/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java +++ b/platforms/mixin-lifecycle/src/main/java/com/dfsek/terra/lifecycle/util/LifecycleUtil.java @@ -11,14 +11,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dfsek.terra.api.event.events.platform.PlatformInitializationEvent; +import com.dfsek.terra.minecraft.attribute.MinecraftAttributeParents; +import com.dfsek.terra.minecraft.attribute.MinecraftBiomeFactory; +import com.dfsek.terra.minecraft.attribute.MinecraftTimelines; +import com.dfsek.terra.minecraft.attribute.PackParents; +import com.dfsek.terra.minecraft.attribute.VanillaContext; import com.dfsek.terra.mod.CommonPlatform; import com.dfsek.terra.mod.ModPlatform; -import com.dfsek.terra.mod.attribute.AttributeReport; -import com.dfsek.terra.mod.attribute.MinecraftAttributeParents; -import com.dfsek.terra.mod.attribute.MinecraftBiomeFactory; -import com.dfsek.terra.mod.attribute.MinecraftTimelines; -import com.dfsek.terra.mod.attribute.PackParents; -import com.dfsek.terra.mod.attribute.VanillaContext; +import com.dfsek.terra.world.attribute.platform.AttributeReport; public final class LifecycleUtil {