From 8a940f7e1f90702e10a4740228772be7af2f7989 Mon Sep 17 00:00:00 2001 From: Zoe Gidiere Date: Sat, 7 Nov 2026 18:02:53 -0700 Subject: [PATCH] perf: replace biome tag checks with bitset columns --- .../biome-provider-extrusion/build.gradle.kts | 3 +- .../extrusions/ReplaceExtrusionTemplate.java | 5 +- .../extrusions/ReplaceExtrusion.java | 28 +-- .../src/main/resources/terra.addon.yml | 2 - .../java/extrusion/ReplaceExtrusionTest.java | 101 ++++++++++ .../biome-provider-pipeline/build.gradle.kts | 2 +- .../biome/pipeline/BiomePipelineAddon.java | 2 +- .../api/biome/DelegatedPipelineBiome.java | 3 +- .../pipeline/api/biome/PipelineBiome.java | 49 ++++- .../api/biome/PlaceholderPipelineBiome.java | 17 +- .../pipeline/api/biome/SelfPipelineBiome.java | 4 +- .../pipeline/config/PipelineBiomeLoader.java | 10 +- .../mutator/BorderListStageTemplate.java | 5 +- .../stage/mutator/BorderStageTemplate.java | 5 +- .../mutator/ReplaceListStageTemplate.java | 3 +- .../stage/mutator/ReplaceStageTemplate.java | 3 +- .../stage/mutators/BorderListStage.java | 21 +- .../pipeline/stage/mutators/BorderStage.java | 11 +- .../stage/mutators/ReplaceListStage.java | 18 +- .../pipeline/stage/mutators/ReplaceStage.java | 9 +- .../pipeline/stage/mutators/ReplaceTable.java | 27 +++ .../java/pipeline/PipelineBiomeTagTest.java | 190 ++++++++++++++++++ common/addons/biome-query-api/README.md | 4 - .../addons/biome-query-api/build.gradle.kts | 5 - .../biome/query/BiomeQueryAPIAddon.java | 46 ----- .../addons/biome/query/api/BiomeQueries.java | 17 -- .../biome/query/impl/BiomeTagFlattener.java | 20 -- .../biome/query/impl/BiomeTagHolder.java | 26 --- .../biome/query/impl/SingleTagQuery.java | 31 --- .../src/main/resources/terra.addon.yml | 12 -- common/addons/config-biome/build.gradle.kts | 2 + .../terra/addons/biome/BiomeTemplate.java | 24 ++- .../terra/addons/biome/UserDefinedBiome.java | 19 +- .../src/test/java/biome/PlatformTagsTest.java | 68 +++++++ .../src/main/resources/terra.addon.yml | 2 +- .../dfsek/terra/api/config/ConfigPack.java | 6 + .../api/util/collection/TriStateIntCache.java | 67 ------ .../dfsek/terra/api/world/biome/Biome.java | 16 +- .../terra/api/world/biome/tag/BiomeTag.java | 79 ++++++++ .../api/world/biome/tag/BiomeTagIndex.java | 74 +++++++ .../world/biome/tag/BiomeTagIndexTest.java | 120 +++++++++++ .../terra/config/loaders/BiomeTagLoader.java | 34 ++++ .../terra/config/pack/ConfigPackImpl.java | 14 ++ .../config/loaders/BiomeTagLoaderTest.java | 41 ++++ platforms/cli/build.gradle.kts | 7 + 45 files changed, 938 insertions(+), 314 deletions(-) create mode 100644 common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java create mode 100644 common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java create mode 100644 common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java delete mode 100644 common/addons/biome-query-api/README.md delete mode 100644 common/addons/biome-query-api/build.gradle.kts delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java delete mode 100644 common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java delete mode 100644 common/addons/biome-query-api/src/main/resources/terra.addon.yml create mode 100644 common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java delete mode 100644 common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java create mode 100644 common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java create mode 100644 common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java create mode 100644 common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java create mode 100644 common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java diff --git a/common/addons/biome-provider-extrusion/build.gradle.kts b/common/addons/biome-provider-extrusion/build.gradle.kts index 7615a16d0..7b116d3a2 100644 --- a/common/addons/biome-provider-extrusion/build.gradle.kts +++ b/common/addons/biome-provider-extrusion/build.gradle.kts @@ -1,6 +1,5 @@ -version = version("1.0.0") +version = version("2.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) - compileOnlyApi(project(":common:addons:biome-query-api")) } diff --git a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java index dd29b282a..e821f22dd 100644 --- a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java +++ b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/config/extrusions/ReplaceExtrusionTemplate.java @@ -7,6 +7,7 @@ import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate { @@ -14,10 +15,10 @@ public class ReplaceExtrusionTemplate extends SamplerExtrusionTemplate { private @Meta ProbabilityCollection<@Meta ReplaceableBiome> biomes; @Value("from") - private @Meta String fromTag; + private @Meta BiomeTag from; @Override public Extrusion get() { - return new ReplaceExtrusion(sampler, range, biomes, fromTag); + return new ReplaceExtrusion(sampler, range, biomes, from); } } diff --git a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java index 4985a2f90..e880933ae 100644 --- a/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java +++ b/common/addons/biome-provider-extrusion/src/main/java/com/dfsek/terra/addons/biome/extrusion/extrusions/ReplaceExtrusion.java @@ -8,11 +8,10 @@ import java.util.stream.Collectors; import com.dfsek.terra.addons.biome.extrusion.api.Extrusion; import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; -import com.dfsek.terra.addons.biome.query.api.BiomeQueries; import com.dfsek.terra.api.util.collection.ProbabilityCollection; -import com.dfsek.terra.api.util.collection.TriStateIntCache; import com.dfsek.terra.api.util.range.Range; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; /** @@ -22,34 +21,19 @@ public class ReplaceExtrusion implements Extrusion { private final Sampler sampler; private final Range range; private final ProbabilityCollection biomes; - private final Predicate hasTag; - private final TriStateIntCache cache; + // Concrete final type keeps has() monomorphic for inlining. + private final BiomeTag from; - public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection biomes, String tag) { + public ReplaceExtrusion(Sampler sampler, Range range, ProbabilityCollection biomes, BiomeTag from) { this.sampler = sampler; this.range = range; this.biomes = biomes; - this.hasTag = BiomeQueries.has(tag); - this.cache = new TriStateIntCache(Biome.INT_ID_COUNTER.get()); + this.from = from; } @Override public Biome extrude(Biome original, int x, int y, int z, long seed) { - int id = original.getIntID(); - - long state = cache.get(id); - boolean passes; - - if(state == TriStateIntCache.STATE_UNSET) { - // Only run the test if unset in cache - passes = hasTag.test(original); - cache.set(id, passes); - } else { - // Read the primitive long directly - passes = (state == TriStateIntCache.STATE_TRUE); - } - - if(passes) { + if(from.has(original.getIntID())) { if(range.isInRange(y)) { return biomes.get(sampler, x, y, z, seed).get(original); } diff --git a/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml b/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml index 21992a6d1..b491cc3ae 100644 --- a/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml +++ b/common/addons/biome-provider-extrusion/src/main/resources/terra.addon.yml @@ -10,5 +10,3 @@ website: source: https://github.com/PolyhedralDev/Terra docs: https://terra.polydev.org license: MIT License -depends: - biome-query-api: "1.+" \ No newline at end of file diff --git a/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java b/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java new file mode 100644 index 000000000..6af5575ea --- /dev/null +++ b/common/addons/biome-provider-extrusion/src/test/java/extrusion/ReplaceExtrusionTest.java @@ -0,0 +1,101 @@ +package extrusion; + +import com.dfsek.seismic.type.sampler.Sampler; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.Map; +import java.util.Set; + +import com.dfsek.terra.addons.biome.extrusion.api.ReplaceableBiome; +import com.dfsek.terra.addons.biome.extrusion.extrusions.ReplaceExtrusion; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.util.range.ConstantRange; +import com.dfsek.terra.api.util.range.Range; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.*; + + +class ReplaceExtrusionTest { + private static final Sampler SAMPLER = new Sampler() { + @Override + public double getSample(long seed, double x, double y) { + return 0; + } + + @Override + public double getSample(long seed, double x, double y, double z) { + return 0; + } + }; + + private static final class StubBiome implements Biome { + private final String id; + private final Set tags; + private final int intId; + + StubBiome(BiomeTagIndex index, String id, Set tags) { + this.id = id; + this.tags = tags; + this.intId = index.register(tags); + } + + @Override + public PlatformBiome getPlatformBiome() { + return null; + } + + @Override + public int getColor() { + return 0; + } + + @Override + public Set getTags() { + return tags; + } + + @Override + public int getIntID() { + return intId; + } + + @Override + public Context getContext() { + return null; + } + + @Override + public String getID() { + return id; + } + } + + private final BiomeTagIndex index = new BiomeTagIndex(); + private final Map biomes = Map.of( + "tagged", new StubBiome(index, "tagged", Set.of("X")), + "untagged", new StubBiome(index, "untagged", Set.of("Y")), + "replacement", new StubBiome(index, "replacement", Set.of())); + + @ParameterizedTest(name = "{0}: {1} at y {2} -> {3}") + @CsvSource({ + "X, tagged, 10, replacement", + "X, untagged, 10, untagged", + "X, tagged, 100, tagged", + "TYPO, tagged, 10, tagged", + "TYPO, untagged, 10, untagged", + "TYPO, replacement, 10, replacement", + }) + void replacesTaggedBiomesInRange(String tag, String biome, int y, String expected) { + ProbabilityCollection to = new ProbabilityCollection() + .add(ReplaceableBiome.of(biomes.get("replacement")), 1); + Range range = new ConstantRange(0, 64); + ReplaceExtrusion extrusion = new ReplaceExtrusion(SAMPLER, range, to, index.tag(tag)); + index.seal(); + assertSame(biomes.get(expected), extrusion.extrude(biomes.get(biome), 0, y, 0, 0)); + } +} diff --git a/common/addons/biome-provider-pipeline/build.gradle.kts b/common/addons/biome-provider-pipeline/build.gradle.kts index 2bbce32db..7b64535ef 100644 --- a/common/addons/biome-provider-pipeline/build.gradle.kts +++ b/common/addons/biome-provider-pipeline/build.gradle.kts @@ -1,4 +1,4 @@ -version = version("2.0.0") +version = version("3.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java index 432fd4dec..17ff8bd73 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/BiomePipelineAddon.java @@ -83,7 +83,7 @@ public class BiomePipelineAddon implements AddonInitializer { .register(addon, ConfigPackPostLoadEvent.class) .then(event -> { Registry biomeRegistry = event.getPack().getRegistry(Biome.class); - event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry)); + event.getPack().applyLoader(PipelineBiome.class, new PipelineBiomeLoader(biomeRegistry, event.getPack().getBiomeTagIndex())); }); } } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java index a915e32f2..b33d8d01f 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/DelegatedPipelineBiome.java @@ -5,10 +5,11 @@ import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; -public final class DelegatedPipelineBiome implements PipelineBiome { +public final class DelegatedPipelineBiome extends PipelineBiome { private final Biome biome; public DelegatedPipelineBiome(Biome biome) { + super(biome.getIntID()); this.biome = biome; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java index fdcc77cc7..dd9f18a47 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PipelineBiome.java @@ -4,30 +4,61 @@ import java.util.Set; import com.dfsek.terra.api.registry.key.StringIdentifiable; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; -public interface PipelineBiome extends StringIdentifiable { - static PipelineBiome placeholder(String id) { - return new PlaceholderPipelineBiome(id); +public abstract sealed class PipelineBiome implements StringIdentifiable + permits DelegatedPipelineBiome, PlaceholderPipelineBiome, SelfPipelineBiome { + private final int intId; + + PipelineBiome(int intId) { + this.intId = intId; } - static PipelineBiome from(Biome biome) { + /** + * Registers a new ID per call; call before {@code index} is sealed. + */ + @ApiStatus.Internal + public static PipelineBiome placeholder(String id, BiomeTagIndex index) { + return new PlaceholderPipelineBiome(id, index); + } + + /** + * {@code biome} must come from the same pack as the index it is tested against. + */ + public static PipelineBiome from(Biome biome) { return new DelegatedPipelineBiome(biome); } - static PipelineBiome self() { + public static PipelineBiome self() { return SelfPipelineBiome.INSTANCE; } - Biome getBiome(); + /** + * Dense per pack, not stable across loads. + */ + @Contract(pure = true) + public final int getIntID() { + return intId; + } - Set getTags(); + @NotNull + public abstract Biome getBiome(); - default boolean isPlaceholder() { + @NotNull + public abstract Set getTags(); + + @Contract(pure = true) + public boolean isPlaceholder() { return false; } - default boolean isSelf() { + @Contract(pure = true) + public boolean isSelf() { return false; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java index 5a458676e..4bec743a7 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/PlaceholderPipelineBiome.java @@ -4,17 +4,28 @@ import java.util.HashSet; import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; -final class PlaceholderPipelineBiome implements PipelineBiome { +final class PlaceholderPipelineBiome extends PipelineBiome { private final Set tags; private final String id; - public PlaceholderPipelineBiome(String id) { + public PlaceholderPipelineBiome(String id, BiomeTagIndex index) { + this(id, tagsOf(id), index); + } + + private PlaceholderPipelineBiome(String id, Set tags, BiomeTagIndex index) { + super(index.register(tags)); this.id = id; - tags = new HashSet<>(); + this.tags = tags; + } + + private static Set tagsOf(String id) { + Set tags = new HashSet<>(); tags.add(id); tags.add("ALL"); + return Set.copyOf(tags); } @Override diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java index 7a00ef5fd..0ee712dc2 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/api/biome/SelfPipelineBiome.java @@ -6,11 +6,11 @@ import java.util.Set; import com.dfsek.terra.api.world.biome.Biome; -final class SelfPipelineBiome implements PipelineBiome { +final class SelfPipelineBiome extends PipelineBiome { public static final SelfPipelineBiome INSTANCE = new SelfPipelineBiome(); private SelfPipelineBiome() { - + super(0); // reserved in every pack's index, untagged } @Override diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java index afd249c25..53a7e0a45 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/PipelineBiomeLoader.java @@ -7,17 +7,23 @@ import com.dfsek.tectonic.api.loader.type.TypeLoader; import org.jetbrains.annotations.NotNull; import java.lang.reflect.AnnotatedType; +import java.util.concurrent.ConcurrentHashMap; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.api.registry.Registry; import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; public class PipelineBiomeLoader implements TypeLoader { private final Registry biomeRegistry; - public PipelineBiomeLoader(Registry biomeRegistry) { + private final BiomeTagIndex tagIndex; + private final ConcurrentHashMap placeholders = new ConcurrentHashMap<>(); + + public PipelineBiomeLoader(Registry biomeRegistry, BiomeTagIndex tagIndex) { this.biomeRegistry = biomeRegistry; + this.tagIndex = tagIndex; } @Override @@ -27,6 +33,6 @@ public class PipelineBiomeLoader implements TypeLoader { return biomeRegistry .getByID((String) c) .map(PipelineBiome::from) - .orElseGet(() -> PipelineBiome.placeholder((String) c)); + .orElseGet(() -> placeholders.computeIfAbsent((String) c, id -> PipelineBiome.placeholder(id, tagIndex))); } } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java index 4d767ef26..e5a70fe95 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderListStageTemplate.java @@ -17,15 +17,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class BorderListStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("default-replace") - private @Meta String defaultReplace; + private @Meta BiomeTag defaultReplace; @Value("default-to") private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java index 4aa3e83ed..b8694e471 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/BorderStageTemplate.java @@ -15,15 +15,16 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class BorderStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("replace") - private @Meta String replace; + private @Meta BiomeTag replace; @Value("to") private @Meta ProbabilityCollection<@Meta PipelineBiome> to; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java index e1cfcb4cb..42b237c80 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceListStageTemplate.java @@ -17,12 +17,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class ReplaceListStageTemplate extends StageTemplate { @Value("default-from") - private @Meta String defaultFrom; + private @Meta BiomeTag defaultFrom; @Value("default-to") private @Meta ProbabilityCollection<@Meta PipelineBiome> defaultTo; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java index 4c2d33266..92a33d5e1 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/config/stage/mutator/ReplaceStageTemplate.java @@ -15,12 +15,13 @@ import com.dfsek.terra.addons.biome.pipeline.config.stage.StageTemplate; import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage; import com.dfsek.terra.api.config.meta.Meta; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; @SuppressWarnings("unused") public class ReplaceStageTemplate extends StageTemplate { @Value("from") - private @Meta String from; + private @Meta BiomeTag from; @Value("to") private @Meta ProbabilityCollection<@Meta PipelineBiome> to; diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java index dd4e64e5d..01b96aa21 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderListStage.java @@ -21,24 +21,29 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class BorderListStage implements Stage { - private final String border; + private final BiomeTag border; private final Sampler Sampler; private final ProbabilityCollection replaceDefault; - private final String defaultReplace; + private final BiomeTag defaultReplace; private final Map> replace; + // By PipelineBiome#getIntID(); relies on one ID per biome name. + private final ProbabilityCollection[] replaceById; private final Vector2Int[] borderPoints; - public BorderListStage(Map> replace, String border, String defaultReplace, + public BorderListStage(Map> replace, BiomeTag border, + BiomeTag defaultReplace, Sampler Sampler, ProbabilityCollection replaceDefault) { this.border = border; this.Sampler = Sampler; this.replaceDefault = replaceDefault; this.defaultReplace = defaultReplace; this.replace = replace; + this.replaceById = ReplaceTable.byId(replace); List points = new ArrayList<>(); for(int x = -1; x <= 1; x++) { @@ -63,12 +68,14 @@ public class BorderListStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(center.getTags().contains(defaultReplace)) { + int centerId = center.getIntID(); + if(defaultReplace.has(centerId)) { for(Vector2Int point : borderPoints) { PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ()); - if(current != null && current.getTags().contains(border)) { - if(replace.containsKey(center)) { - PipelineBiome replacement = replace.get(center).get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), + if(current != null && border.has(current.getIntID())) { + ProbabilityCollection collection = centerId < replaceById.length ? replaceById[centerId] : null; + if(collection != null) { + PipelineBiome replacement = collection.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return replacement.isSelf() ? center : replacement; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java index 339fdb366..78a14cadb 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/BorderStage.java @@ -20,16 +20,17 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class BorderStage implements Stage { - private final String border; + private final BiomeTag border; private final Sampler Sampler; private final ProbabilityCollection replace; - private final String replaceTag; + private final BiomeTag replaceTag; private final Vector2Int[] borderPoints; - public BorderStage(String border, String replaceTag, Sampler Sampler, ProbabilityCollection replace) { + public BorderStage(BiomeTag border, BiomeTag replaceTag, Sampler Sampler, ProbabilityCollection replace) { this.border = border; this.Sampler = Sampler; this.replace = replace; @@ -47,10 +48,10 @@ public class BorderStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(center.getTags().contains(replaceTag)) { + if(replaceTag.has(center.getIntID())) { for(Vector2Int point : borderPoints) { PipelineBiome current = viewPoint.getRelativeBiome(point.getX(), point.getZ()); - if(current != null && current.getTags().contains(border)) { + if(current != null && border.has(current.getIntID())) { PipelineBiome replacement = replace.get(Sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return replacement.isSelf() ? center : replacement; } diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java index ca4f0db09..c14843ca7 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceListStage.java @@ -18,17 +18,21 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceListStage implements Stage { private final Map> replace; + // By PipelineBiome#getIntID(); relies on one ID per biome name. + private final ProbabilityCollection[] replaceById; private final Sampler sampler; private final ProbabilityCollection replaceDefault; - private final String defaultTag; + private final BiomeTag defaultTag; - public ReplaceListStage(Map> replace, String defaultTag, + public ReplaceListStage(Map> replace, BiomeTag defaultTag, ProbabilityCollection replaceDefault, Sampler sampler) { this.replace = replace; + this.replaceById = ReplaceTable.byId(replace); this.sampler = sampler; this.defaultTag = defaultTag; this.replaceDefault = replaceDefault; @@ -37,11 +41,13 @@ public class ReplaceListStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { PipelineBiome center = viewPoint.getBiome(); - if(replace.containsKey(center)) { - PipelineBiome biome = replace.get(center).get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); + int id = center.getIntID(); + ProbabilityCollection collection = id < replaceById.length ? replaceById[id] : null; + if(collection != null) { + PipelineBiome biome = collection.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } - if(viewPoint.getBiome().getTags().contains(defaultTag)) { + if(defaultTag.has(id)) { PipelineBiome biome = replaceDefault.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } @@ -60,7 +66,7 @@ public class ReplaceListStage implements Stage { Set reject = new HashSet<>(); biomes.forEach(biome -> { - if(!biome.getTags().contains(defaultTag) && !replace.containsKey(biome)) { + if(!biome.getTags().contains(defaultTag.name()) && !replace.containsKey(biome)) { biomeSet.add(biome); } else { reject.add(biome); diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java index 2c7ab9bf9..23c3be4ef 100644 --- a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceStage.java @@ -17,14 +17,15 @@ import com.dfsek.terra.addons.biome.pipeline.api.Stage; import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; import com.dfsek.terra.addons.biome.pipeline.pipeline.BiomeChunkImpl; import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; public class ReplaceStage implements Stage { - private final String replaceableTag; + private final BiomeTag replaceableTag; private final ProbabilityCollection replace; private final Sampler sampler; - public ReplaceStage(String replaceable, ProbabilityCollection replace, Sampler sampler) { + public ReplaceStage(BiomeTag replaceable, ProbabilityCollection replace, Sampler sampler) { this.replaceableTag = replaceable; this.replace = replace; this.sampler = sampler; @@ -32,7 +33,7 @@ public class ReplaceStage implements Stage { @Override public PipelineBiome apply(BiomeChunkImpl.ViewPoint viewPoint) { - if(viewPoint.getBiome().getTags().contains(replaceableTag)) { + if(replaceableTag.has(viewPoint.getBiome().getIntID())) { PipelineBiome biome = replace.get(sampler, viewPoint.worldX(), viewPoint.worldZ(), viewPoint.worldSeed()); return biome.isSelf() ? viewPoint.getBiome() : biome; } @@ -49,7 +50,7 @@ public class ReplaceStage implements Stage { Set biomeSet = new HashSet<>(); Set reject = new HashSet<>(); biomes.forEach(biome -> { - if(!biome.getTags().contains(replaceableTag)) { + if(!biome.getTags().contains(replaceableTag.name())) { biomeSet.add(biome); } else { reject.add(biome); diff --git a/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java new file mode 100644 index 000000000..d0e285898 --- /dev/null +++ b/common/addons/biome-provider-pipeline/src/main/java/com/dfsek/terra/addons/biome/pipeline/stage/mutators/ReplaceTable.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2020-2025 Polyhedral Development + * + * The Terra Core Addons are licensed under the terms of the MIT License. For more details, + * reference the LICENSE file in this module's root directory. + */ + +package com.dfsek.terra.addons.biome.pipeline.stage.mutators; + +import java.util.Map; + +import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; + + +final class ReplaceTable { + private ReplaceTable() { } + + @SuppressWarnings("unchecked") + static ProbabilityCollection[] byId(Map> replace) { + int max = -1; + for(PipelineBiome key : replace.keySet()) max = Math.max(max, key.getIntID()); + ProbabilityCollection[] table = new ProbabilityCollection[max + 1]; + replace.forEach((key, value) -> table[key.getIntID()] = value); + return table; + } +} diff --git a/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java b/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java new file mode 100644 index 000000000..ffe9f5373 --- /dev/null +++ b/common/addons/biome-provider-pipeline/src/test/java/pipeline/PipelineBiomeTagTest.java @@ -0,0 +1,190 @@ +package pipeline; + +import com.dfsek.seismic.type.sampler.Sampler; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.AnnotatedType; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import com.dfsek.terra.addons.biome.pipeline.api.Source; +import com.dfsek.terra.addons.biome.pipeline.api.Stage; +import com.dfsek.terra.addons.biome.pipeline.api.biome.PipelineBiome; +import com.dfsek.terra.addons.biome.pipeline.config.PipelineBiomeLoader; +import com.dfsek.terra.addons.biome.pipeline.pipeline.PipelineImpl; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.BorderListStage; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceListStage; +import com.dfsek.terra.addons.biome.pipeline.stage.mutators.ReplaceStage; +import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.registry.Registry; +import com.dfsek.terra.api.util.cache.SeededVector2Key; +import com.dfsek.terra.api.util.collection.ProbabilityCollection; +import com.dfsek.terra.api.world.biome.Biome; +import com.dfsek.terra.api.world.biome.PlatformBiome; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.*; + + +class PipelineBiomeTagTest { + private static final Sampler SAMPLER = new Sampler() { + @Override + public double getSample(long seed, double x, double y) { + return 0; + } + + @Override + public double getSample(long seed, double x, double y, double z) { + return 0; + } + }; + + private static final class StubBiome implements Biome { + private final String id; + private final Set tags; + private final int intId; + + StubBiome(BiomeTagIndex index, String id, Set tags) { + this.id = id; + this.tags = tags; + this.intId = index.register(tags); + } + + @Override + public PlatformBiome getPlatformBiome() { + return null; + } + + @Override + public int getColor() { + return 0; + } + + @Override + public Set getTags() { + return tags; + } + + @Override + public int getIntID() { + return intId; + } + + @Override + public Context getContext() { + return null; + } + + @Override + public String getID() { + return id; + } + } + + @SuppressWarnings("unchecked") + private static Registry emptyRegistry() { + return (Registry) Proxy.newProxyInstance(Registry.class.getClassLoader(), new Class[]{ Registry.class }, + (proxy, method, args) -> { + if(method.getName().equals("getByID")) return Optional.empty(); + throw new UnsupportedOperationException(method.getName()); + }); + } + + private final BiomeTagIndex index = new BiomeTagIndex(); + private final Map biomes = new LinkedHashMap<>(); + + { + biome("border", "border"); + biome("c", "R", "D"); + biome("a", "R"); + biome("b", "R"); + biome("x"); + biome("y"); + biome("e"); + biome("f", "R", "D"); + } + + private void biome(String id, String... tags) { + biomes.put(id, PipelineBiome.from(new StubBiome(index, id, Set.of(tags)))); + } + + private static ProbabilityCollection only(PipelineBiome biome) { + return new ProbabilityCollection().add(biome, 1); + } + + private Map> replaceTable() { + Map> replace = new HashMap<>(); + replace.put(biomes.get("a"), only(biomes.get("x"))); + replace.put(biomes.get("b"), only(PipelineBiome.self())); + return replace; + } + + private String run(Stage stage, String centre) { + index.seal(); + PipelineBiome centreBiome = biomes.get(centre); + PipelineBiome border = biomes.get("border"); + Source source = new Source() { + @Override + public PipelineBiome get(long seed, int x, int z) { + return x == 0 && z == 0 ? centreBiome : border; + } + + @Override + public Iterable getBiomes() { + return List.of(centreBiome, border); + } + }; + return new PipelineImpl(source, List.of(stage), 1, 3).generateChunk(new SeededVector2Key(0, 0, 0)).get(0, 0).getID(); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" }) + void borderListStage(String centre, String expected) { + assertEquals(expected, run(new BorderListStage(replaceTable(), index.tag("border"), index.tag("R"), SAMPLER, + only(biomes.get("y"))), centre)); + } + + @ParameterizedTest(name = "{0} -> {1}") + @CsvSource({ "a, x", "b, b", "c, y", "e, e", "f, y" }) + void replaceListStage(String centre, String expected) { + assertEquals(expected, run(new ReplaceListStage(replaceTable(), index.tag("D"), only(biomes.get("y")), SAMPLER), centre)); + } + + @ParameterizedTest(name = "{0}: {1} -> {2}") + @CsvSource({ "D, c, y", "D, e, e", "TYPO, c, c", "TYPO, e, e" }) + void replaceStage(String tag, String centre, String expected) { + assertEquals(expected, run(new ReplaceStage(index.tag(tag), only(biomes.get("y")), SAMPLER), centre)); + } + + @Test + void placeholderRegistration() { + PipelineBiomeLoader loader = new PipelineBiomeLoader(emptyRegistry(), index); + int before = index.size(); + PipelineBiome first = load(loader, "OCEAN"); + assertSame(first, load(loader, "OCEAN")); + assertEquals(before + 1, index.size()); + assertDoesNotThrow(() -> load(loader, "ALL")); + index.seal(); + assertTrue(index.tag("OCEAN").has(first.getIntID())); + assertTrue(index.tag("ALL").has(first.getIntID())); + assertFalse(index.tag("OTHER").has(first.getIntID())); + } + + @Test + void selfHasNoTags() { + assertEquals(0, PipelineBiome.self().getIntID()); + index.seal(); + assertFalse(index.tag("ALL").has(PipelineBiome.self().getIntID())); + } + + private static PipelineBiome load(PipelineBiomeLoader loader, String id) { + return loader.load((AnnotatedType) null, id, null, null); + } +} diff --git a/common/addons/biome-query-api/README.md b/common/addons/biome-query-api/README.md deleted file mode 100644 index e8e2a800c..000000000 --- a/common/addons/biome-query-api/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Biome Query API - -This addon contains an API to allow other addons to quickly query -Biome data, by baking queries and using Contexts on biomes. \ No newline at end of file diff --git a/common/addons/biome-query-api/build.gradle.kts b/common/addons/biome-query-api/build.gradle.kts deleted file mode 100644 index 9d0aac37f..000000000 --- a/common/addons/biome-query-api/build.gradle.kts +++ /dev/null @@ -1,5 +0,0 @@ -version = version("1.0.0") - -dependencies { - compileOnlyApi(project(":common:addons:manifest-addon-loader")) -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java deleted file mode 100644 index 40afa4130..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/BiomeQueryAPIAddon.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.dfsek.terra.addons.biome.query; - -import java.util.Collection; - -import com.dfsek.terra.addons.biome.query.impl.BiomeTagFlattener; -import com.dfsek.terra.addons.biome.query.impl.BiomeTagHolder; -import com.dfsek.terra.addons.manifest.api.AddonInitializer; -import com.dfsek.terra.api.Platform; -import com.dfsek.terra.api.addon.BaseAddon; -import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent; -import com.dfsek.terra.api.event.functional.FunctionalEventHandler; -import com.dfsek.terra.api.inject.annotations.Inject; -import com.dfsek.terra.api.properties.Context; -import com.dfsek.terra.api.properties.PropertyKey; -import com.dfsek.terra.api.world.biome.Biome; - - -public class BiomeQueryAPIAddon implements AddonInitializer { - public static PropertyKey BIOME_TAG_KEY = Context.create(BiomeTagHolder.class); - @Inject - private Platform platform; - @Inject - private BaseAddon addon; - - @Override - public void initialize() { - - platform.getEventManager() - .getHandler(FunctionalEventHandler.class) - .register(addon, ConfigPackPostLoadEvent.class) - .then(event -> { - Collection biomes = event - .getPack() - .getRegistry(Biome.class) - .entries(); - - BiomeTagFlattener flattener = new BiomeTagFlattener(biomes - .stream() - .flatMap(biome -> biome.getTags().stream()) - .toList()); - - biomes.forEach(biome -> biome.getContext().put(BIOME_TAG_KEY, new BiomeTagHolder(biome, flattener))); - }) - .global(); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java deleted file mode 100644 index 4066e048e..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/api/BiomeQueries.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.dfsek.terra.addons.biome.query.api; - -import java.util.function.Predicate; - -import com.dfsek.terra.addons.biome.query.impl.SingleTagQuery; -import com.dfsek.terra.api.world.biome.Biome; - - -public final class BiomeQueries { - private BiomeQueries() { - - } - - public static Predicate has(String tag) { - return new SingleTagQuery(tag); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java deleted file mode 100644 index c52851598..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagFlattener.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import java.util.List; - - -public class BiomeTagFlattener { - private final List tags; - - public BiomeTagFlattener(List tags) { - this.tags = tags; - } - - public int index(String tag) { - return tags.indexOf(tag); - } - - public int size() { - return tags.size(); - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java deleted file mode 100644 index 4d4f34fea..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/BiomeTagHolder.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import com.dfsek.terra.api.properties.Properties; -import com.dfsek.terra.api.world.biome.Biome; - - -public class BiomeTagHolder implements Properties { - private final boolean[] tags; - private final BiomeTagFlattener flattener; - - public BiomeTagHolder(Biome biome, BiomeTagFlattener flattener) { - this.tags = new boolean[flattener.size()]; - this.flattener = flattener; - for(String tag : biome.getTags()) { - tags[flattener.index(tag)] = true; - } - } - - boolean get(int index) { - return tags[index]; - } - - public BiomeTagFlattener getFlattener() { - return flattener; - } -} diff --git a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java b/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java deleted file mode 100644 index 1e39408c2..000000000 --- a/common/addons/biome-query-api/src/main/java/com/dfsek/terra/addons/biome/query/impl/SingleTagQuery.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.dfsek.terra.addons.biome.query.impl; - -import java.util.function.Predicate; - -import com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon; -import com.dfsek.terra.api.world.biome.Biome; - - -public class SingleTagQuery implements Predicate { - private final String tag; - private int tagIndex = -1; - - public SingleTagQuery(String tag) { - this.tag = tag; - } - - @Override - public boolean test(Biome biome) { - if(tagIndex < 0) { - tagIndex = biome - .getContext() - .get(BiomeQueryAPIAddon.BIOME_TAG_KEY) - .getFlattener() - .index(tag); - } - return biome - .getContext() - .get(BiomeQueryAPIAddon.BIOME_TAG_KEY) - .get(tagIndex); - } -} diff --git a/common/addons/biome-query-api/src/main/resources/terra.addon.yml b/common/addons/biome-query-api/src/main/resources/terra.addon.yml deleted file mode 100644 index 8a55ce2dc..000000000 --- a/common/addons/biome-query-api/src/main/resources/terra.addon.yml +++ /dev/null @@ -1,12 +0,0 @@ -schema-version: 1 -contributors: - - Terra contributors -id: biome-query-api -version: @VERSION@ -entrypoints: - - "com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon" -website: - issues: https://github.com/PolyhedralDev/Terra/issues - source: https://github.com/PolyhedralDev/Terra - docs: https://terra.polydev.org -license: MIT License \ No newline at end of file diff --git a/common/addons/config-biome/build.gradle.kts b/common/addons/config-biome/build.gradle.kts index 9d0aac37f..57b95fdb4 100644 --- a/common/addons/config-biome/build.gradle.kts +++ b/common/addons/config-biome/build.gradle.kts @@ -2,4 +2,6 @@ version = version("1.0.0") dependencies { compileOnlyApi(project(":common:addons:manifest-addon-loader")) + + testImplementation("com.dfsek.tectonic", "common", Versions.Libraries.tectonic) } diff --git a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java index 102a70ef5..2c371f6f6 100644 --- a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java +++ b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/BiomeTemplate.java @@ -11,6 +11,7 @@ import com.dfsek.tectonic.api.config.template.ValidatedConfigTemplate; import com.dfsek.tectonic.api.config.template.annotations.Default; import com.dfsek.tectonic.api.config.template.annotations.Final; import com.dfsek.tectonic.api.config.template.annotations.Value; +import com.dfsek.tectonic.api.exception.ValidationException; import java.util.Collections; import java.util.HashSet; @@ -21,6 +22,7 @@ import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.config.AbstractableTemplate; import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.meta.Meta; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.world.biome.PlatformBiome; @@ -48,13 +50,29 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl @Default private @Meta Set<@Meta String> tags = new HashSet<>(); + private Set platformTags = Set.of(); + public BiomeTemplate(ConfigPack pack, Platform platform) { this.pack = pack; } @Override - public boolean validate() { + public boolean validate() throws ValidationException { color |= 0xff000000; // Alpha adjustment + Set parsed = new HashSet<>(); + for(String tag : tags) { + int colon = tag.indexOf(':'); + if(colon < 0) continue; + // RegistryKey.parse accepts an empty namespace or ID. + if(colon == 0) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the namespace is empty"); + if(colon == tag.length() - 1) throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": the ID is empty"); + try { + parsed.add(RegistryKey.parse(tag)); + } catch(IllegalArgumentException e) { + throw new ValidationException("Invalid namespaced biome tag \"" + tag + "\": " + e.getMessage()); + } + } + platformTags = Set.copyOf(parsed); return true; } @@ -66,6 +84,10 @@ public class BiomeTemplate implements AbstractableTemplate, ValidatedConfigTempl return tags; } + public Set getPlatformTags() { + return platformTags; + } + public int getColor() { return color; } diff --git a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java index 4729f60df..443871b11 100644 --- a/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java +++ b/common/addons/config-biome/src/main/java/com/dfsek/terra/addons/biome/UserDefinedBiome.java @@ -7,10 +7,11 @@ package com.dfsek.terra.addons.biome; +import java.util.HashSet; import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import com.dfsek.terra.api.properties.Context; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.world.biome.Biome; import com.dfsek.terra.api.world.biome.PlatformBiome; @@ -24,6 +25,7 @@ public class UserDefinedBiome implements Biome { private final BiomeTemplate config; private final int color; private final Set tags; + private final Set platformTags; private final Context context = new Context(); private final int intID; @@ -33,10 +35,12 @@ public class UserDefinedBiome implements Biome { this.id = config.getID(); this.config = config; this.color = config.getColor(); - this.tags = config.getTags(); - this.intID = INT_ID_COUNTER.getAndIncrement(); - tags.add("BIOME:" + id); - tags.add("ALL"); + Set allTags = new HashSet<>(config.getTags()); + allTags.add("BIOME:" + id); + allTags.add("ALL"); + this.tags = Set.copyOf(allTags); + this.platformTags = Set.copyOf(config.getPlatformTags()); + this.intID = config.getPack().getBiomeTagIndex().register(tags); } @Override @@ -64,6 +68,11 @@ public class UserDefinedBiome implements Biome { return tags; } + @Override + public Set getPlatformTags() { + return platformTags; + } + @Override public int getIntID() { return intID; diff --git a/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java b/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java new file mode 100644 index 000000000..6ab3113b7 --- /dev/null +++ b/common/addons/config-biome/src/test/java/biome/PlatformTagsTest.java @@ -0,0 +1,68 @@ +package biome; + +import com.dfsek.tectonic.api.exception.ValidationException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.util.HashSet; +import java.util.Set; + +import com.dfsek.terra.addons.biome.BiomeTemplate; +import com.dfsek.terra.addons.biome.UserDefinedBiome; +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.key.RegistryKey; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class PlatformTagsTest { + private static BiomeTemplate template(String... tags) throws ReflectiveOperationException { + BiomeTagIndex index = new BiomeTagIndex(); + ConfigPack pack = (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> { + if(method.getName().equals("getBiomeTagIndex")) return index; + throw new UnsupportedOperationException(method.getName()); + }); + BiomeTemplate template = new BiomeTemplate(pack, null); + set(template, "id", "TEST"); + set(template, "tags", new HashSet<>(Set.of(tags))); + return template; + } + + private static void set(BiomeTemplate template, String field, Object value) throws ReflectiveOperationException { + Field f = BiomeTemplate.class.getDeclaredField(field); + f.setAccessible(true); + f.set(template, value); + } + + @Test + void platformTags() throws Exception { + BiomeTemplate template = template("USE_RIVER", "minecraft:is_forest", "c:hot"); + template.validate(); + UserDefinedBiome biome = new UserDefinedBiome(null, template); + + assertEquals(Set.of(RegistryKey.parse("minecraft:is_forest"), RegistryKey.parse("c:hot")), biome.getPlatformTags()); + assertEquals(Set.of("USE_RIVER", "minecraft:is_forest", "c:hot", "BIOME:TEST", "ALL"), biome.getTags()); + assertThrows(UnsupportedOperationException.class, () -> biome.getTags().add("X")); + assertFalse(template.getTags().contains("BIOME:TEST")); + } + + @ParameterizedTest(name = "{0}") + @CsvSource(delimiter = '|', value = { + "minecraft:Bad Tag | minecraft:Bad Tag", + ":is_forest | empty", + "minecraft: | empty", + }) + void invalidNamespacedTag(String tag, String reasonPart) throws Exception { + ValidationException e = assertThrows(ValidationException.class, template(tag)::validate); + assertTrue(e.getMessage().contains("\"" + tag + "\""), e.getMessage()); + assertTrue(e.getMessage().contains(reasonPart), e.getMessage()); + } +} diff --git a/common/addons/pipeline-image/src/main/resources/terra.addon.yml b/common/addons/pipeline-image/src/main/resources/terra.addon.yml index 750434fba..4be0186ed 100644 --- a/common/addons/pipeline-image/src/main/resources/terra.addon.yml +++ b/common/addons/pipeline-image/src/main/resources/terra.addon.yml @@ -12,4 +12,4 @@ website: license: MIT License depends: library-image: "1.+" - biome-provider-pipeline: "2.+" + biome-provider-pipeline: "3.+" diff --git a/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java b/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java index a9fd6982b..ebc621471 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java +++ b/common/api/src/main/java/com/dfsek/terra/api/config/ConfigPack.java @@ -26,6 +26,7 @@ import com.dfsek.terra.api.tectonic.LoaderRegistrar; import com.dfsek.terra.api.tectonic.ShortcutLoader; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; import com.dfsek.terra.api.world.chunk.generation.util.provider.ChunkGeneratorProvider; @@ -43,6 +44,11 @@ public interface ConfigPack extends LoaderRegistrar, BiomeProvider getBiomeProvider(); + /** + * @return this pack's biome tag index; sealed once the pack has finished loading + */ + BiomeTagIndex getBiomeTagIndex(); + List getStages(); Path getRootPath(); diff --git a/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java b/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java deleted file mode 100644 index 6b2ac54e9..000000000 --- a/common/api/src/main/java/com/dfsek/terra/api/util/collection/TriStateIntCache.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.dfsek.terra.api.util.collection; - -import java.lang.invoke.MethodHandles; -import java.lang.invoke.VarHandle; - -import com.dfsek.seismic.util.UnsafeUtils; - - -public class TriStateIntCache { - public static final long STATE_UNSET = 0L; - public static final long STATE_FALSE = 1L; - public static final long STATE_TRUE = 2L; - - private static final long BIT_MASK = 3L; - private final long[] data; - - private static final VarHandle ARRAY_HANDLE = MethodHandles.arrayElementVarHandle(long[].class); - - private static int getOptimalMaxKeys(int requestedKeys) { - // 192 keys fill the first cache line exactly (along with the 16-byte header) - if (requestedKeys <= 192) { - return 192; - } - - // For every additional line, we fit 256 keys (64 bytes * 4 keys/byte) - // We calculate the overflow beyond 192, round up to the nearest 256, and add it back. - int overflow = requestedKeys - 192; - int chunks = (overflow + 255) >>> 8; // Fast ceil division by 256 - - return 192 + (chunks << 8); // chunks * 256 - } - - public TriStateIntCache(int maxKeySize) { - this.data = new long[(getOptimalMaxKeys(maxKeySize) + 31) >>> 5]; - } - - /** - * Checks the cache state without any allocation. - * - * @return STATE_UNSET (0), STATE_FALSE (1), or STATE_TRUE (2) - */ - public long get(int key) { - long offset = UnsafeUtils.LONG_ARRAY_BASE + ((long)(key >>> 5) << UnsafeUtils.LONG_ARRAY_SHIFT); - long currentWord = UnsafeUtils.UNSAFE.getLong(data, offset); - return (currentWord >>> ((key << 1) & 63)) & BIT_MASK; - } - - /** - * Sets the value safely. Handles race conditions internally. - */ - public void set(int key, boolean value) { - int index = key >>> 5; - int shift = (key << 1) & 63; - - long targetWord = (value ? STATE_TRUE : STATE_FALSE) << shift; - - long current; - do { - current = (long) ARRAY_HANDLE.getVolatile(data, index); - - if (((current >>> shift) & BIT_MASK) != STATE_UNSET) { - return; - } - - } while (!ARRAY_HANDLE.compareAndSet(data, index, current, current | targetWord)); - } -} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java index e43a4d2ff..aedf2c4eb 100644 --- a/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/Biome.java @@ -8,10 +8,12 @@ package com.dfsek.terra.api.world.biome; +import org.jetbrains.annotations.NotNull; + import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; import com.dfsek.terra.api.properties.PropertyHolder; +import com.dfsek.terra.api.registry.key.RegistryKey; import com.dfsek.terra.api.registry.key.StringIdentifiable; @@ -19,8 +21,6 @@ import com.dfsek.terra.api.registry.key.StringIdentifiable; * Represents a Terra biome */ public interface Biome extends PropertyHolder, StringIdentifiable { - AtomicInteger INT_ID_COUNTER = new AtomicInteger(0); - /** * Gets the platform biome this custom biome delegates to. * @@ -42,9 +42,17 @@ public interface Biome extends PropertyHolder, StringIdentifiable { */ Set getTags(); + /** + * Get the namespaced entries of this biome's config {@code tags:}, as written. + */ + default @NotNull Set getPlatformTags() { + return Set.of(); + } + /** - * Get the numeric ID of this biome, generated at registration time + * Get the numeric ID of this biome: dense per pack, from 1, issued by {@code getBiomeTagIndex().register(...)} during pack + * load. * * @return The numeric ID. */ diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java new file mode 100644 index 000000000..90c3be619 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTag.java @@ -0,0 +1,79 @@ +package com.dfsek.terra.api.world.biome.tag; + +import com.dfsek.seismic.util.UnsafeUtils; + +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import com.dfsek.terra.api.world.biome.Biome; + +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + + +/** + * Biome IDs are not stable across loads; never persist one. + */ +public final class BiomeTag implements Predicate { + // Lets has() on an unsealed tag return false for IDs below 512. + private static final long[] UNSEALED = new long[8]; + + private final String name; + private final BiomeTagIndex index; + + // Not volatile: published by the index's volatile sealed flag, or by the index lock for tags created after seal. + private long[] bits = UNSEALED; + + BiomeTag(String name, BiomeTagIndex index) { + this.name = name; + this.index = index; + } + + @NotNull + @Contract(pure = true) + public String name() { + return name; + } + + /** + * No bounds checks. Only call after the owning {@link BiomeTagIndex} is sealed, with IDs from that index. + */ + public boolean has(int biomeId) { + long word = UnsafeUtils.UNSAFE.getLong(bits, + UnsafeUtils.LONG_ARRAY_BASE + ((long) (biomeId >>> 6) << UnsafeUtils.LONG_ARRAY_SHIFT)); + return ((word >>> biomeId) & 1L) != 0L; + } + + /** + * Doesn't detect a biome from another pack whose ID is in range. + * + * @throws IllegalArgumentException if sealed and the biome's ID is outside this tag's bitset + */ + @Override + public boolean test(Biome biome) { + if(!index.isSealed()) { // volatile read: also publishes bits built by seal + return biome.getTags().contains(name); + } + int id = biome.getIntID(); + if(id < 0 || id >= (bits.length << 6)) { + throw new IllegalArgumentException("biome id " + id + " is not from this tag's pack"); + } + return has(id); + } + + long[] bits() { + return bits; + } + + void build(int size, List> tagSets) { + // Whole 64-byte lines: every ID below size is in bounds. + long[] built = new long[((size + 511) >>> 9) << 3]; + for(int id = 1; id < size; id++) { + if(tagSets.get(id).contains(name)) { + built[id >>> 6] |= 1L << id; + } + } + this.bits = built; + } +} diff --git a/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java new file mode 100644 index 000000000..dbee73498 --- /dev/null +++ b/common/api/src/main/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndex.java @@ -0,0 +1,74 @@ +package com.dfsek.terra.api.world.biome.tag; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + + +/** + * ID 0 is reserved. Biomes register during pack load; the platform seals the index once the pack is built. + */ +public final class BiomeTagIndex { + private final ConcurrentHashMap tags = new ConcurrentHashMap<>(); + private final List> tagSets = new ArrayList<>(); // guarded by this + private volatile boolean sealed = false; + + public BiomeTagIndex() { + tagSets.add(Set.of()); + } + + /** + * @return a dense ID, at least 1 + * + * @throws IllegalStateException if sealed + */ + public synchronized int register(Set biomeTags) { + if(sealed) throw new IllegalStateException("BiomeTagIndex is sealed"); + tagSets.add(Set.copyOf(biomeTags)); + return tagSets.size() - 1; + } + + /** + * Never released: resolve each tag once at pack load, not per sample. + */ + @NotNull + public BiomeTag tag(String name) { + BiomeTag existing = tags.get(name); + // The volatile read of sealed publishes the bits; before seal, the lock does. + if(existing != null && sealed) return existing; + synchronized(this) { + BiomeTag tag = tags.get(name); + if(tag == null) { + tag = new BiomeTag(name, this); + if(sealed) tag.build(tagSets.size(), tagSets); + tags.put(name, tag); + } + return tag; + } + } + + @ApiStatus.Internal + public synchronized void seal() { + if(sealed) return; + int size = tagSets.size(); + for(BiomeTag tag : tags.values()) tag.build(size, tagSets); + sealed = true; + } + + @Contract(pure = true) + public boolean isSealed() { + return sealed; + } + + /** + * @return number of IDs including the reserved 0 + */ + public synchronized int size() { + return tagSets.size(); + } +} diff --git a/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java b/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java new file mode 100644 index 000000000..975974b3e --- /dev/null +++ b/common/api/src/test/java/com/dfsek/terra/api/world/biome/tag/BiomeTagIndexTest.java @@ -0,0 +1,120 @@ +package com.dfsek.terra.api.world.biome.tag; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import com.dfsek.terra.api.world.biome.Biome; + +import static org.junit.jupiter.api.Assertions.*; + + +public class BiomeTagIndexTest { + @Test + public void denseIds() { + BiomeTagIndex index = new BiomeTagIndex(); + assertEquals(1, index.register(Set.of("A"))); + assertEquals(2, index.register(Set.of("B"))); + assertEquals(3, index.register(Set.of())); + assertEquals(4, index.size()); + } + + @Test + public void membershipAndInterning() { + BiomeTagIndex index = new BiomeTagIndex(); + int a = index.register(Set.of("X", "Z")); + int b = index.register(Set.of("X")); + int c = index.register(Set.of("Y")); + BiomeTag x = index.tag("X"); + index.seal(); + assertSame(x, index.tag("X")); + BiomeTag z = index.tag("Z"); + assertSame(z, index.tag("Z")); + assertEquals("Z", z.name()); + BiomeTag y = index.tag("Y"); + BiomeTag unknown = index.tag("NOPE"); + for(int id = 0; id < index.size(); id++) { + assertEquals(id == a || id == b, x.has(id), "X has " + id); + assertEquals(id == c, y.has(id), "Y has " + id); + assertEquals(id == a, z.has(id), "Z has " + id); + assertFalse(unknown.has(id), "unknown tag has " + id); + } + } + + @Test + public void sealing() { + BiomeTagIndex index = new BiomeTagIndex(); + int a = index.register(Set.of("X")); + index.seal(); + index.seal(); + assertTrue(index.isSealed()); + assertTrue(index.tag("X").has(a)); + assertThrows(IllegalStateException.class, () -> index.register(Set.of("X"))); + } + + @Test + public void parallelRegister() { + BiomeTagIndex index = new BiomeTagIndex(); + Set ids = IntStream.range(0, 10_000).parallel() + .mapToObj(i -> index.register(Set.of("T" + (i % 7)))) + .collect(Collectors.toSet()); + assertEquals(10_000, ids.size()); + assertEquals(1, ids.stream().mapToInt(Integer::intValue).min().getAsInt()); + assertEquals(10_000, ids.stream().mapToInt(Integer::intValue).max().getAsInt()); + assertEquals(10_001, index.size()); + index.seal(); + for(int id : ids) { + int matches = 0; + for(int t = 0; t < 7; t++) { + if(index.tag("T" + t).has(id)) matches++; + } + assertEquals(1, matches); + } + } + + @Test + public void bitsetSize() { + BiomeTagIndex index = new BiomeTagIndex(); + for(int i = 0; i < 600; i++) index.register(Set.of("X")); + BiomeTag x = index.tag("X"); + index.seal(); + assertEquals(0, x.bits().length % 8); + assertTrue(x.bits().length * 64L >= index.size()); + assertTrue(x.has(600)); + BiomeTag late = index.tag("LATE"); + assertEquals(0, late.bits().length % 8); + assertTrue(late.bits().length * 64L >= index.size()); + } + + private static Biome biome(int id, Set tags) { + return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class[]{ Biome.class }, (proxy, method, args) -> + switch(method.getName()) { + case "getIntID" -> id; + case "getTags" -> tags; + default -> throw new UnsupportedOperationException(method.getName()); + }); + } + + @Test + public void testBeforeAndAfterSeal() { + BiomeTagIndex index = new BiomeTagIndex(); + Set tagsA = Set.of("X"); + Set tagsB = Set.of("Y"); + Biome a = biome(index.register(tagsA), tagsA); + Biome b = biome(index.register(tagsB), tagsB); + BiomeTag x = index.tag("X"); + assertTrue(x.test(a)); + assertFalse(x.test(b)); + for(int i = 0; i < 512; i++) assertFalse(x.has(i)); + index.seal(); + assertTrue(x.has(a.getIntID())); + assertTrue(x.test(a)); + assertFalse(x.test(b)); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(512, Set.of()))); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(100_000, Set.of()))); + assertThrows(IllegalArgumentException.class, () -> x.test(biome(-1, Set.of()))); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java new file mode 100644 index 000000000..3b49d141e --- /dev/null +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/loaders/BiomeTagLoader.java @@ -0,0 +1,34 @@ +package com.dfsek.terra.config.loaders; + +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.exception.LoadException; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.loader.type.TypeLoader; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.AnnotatedType; + +import com.dfsek.terra.api.world.biome.tag.BiomeTag; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + + +public class BiomeTagLoader implements TypeLoader { + private final BiomeTagIndex index; + + public BiomeTagLoader(BiomeTagIndex index) { + this.index = index; + } + + @Override + public BiomeTag load(@NotNull AnnotatedType t, @NotNull Object c, @NotNull ConfigLoader loader, DepthTracker depthTracker) + throws LoadException { + if(!(c instanceof String name)) { + throw new LoadException("expected a tag name, got " + describe(c), depthTracker); + } + return index.tag(name); + } + + private static String describe(Object value) { + return value == null ? "null" : "type " + value.getClass().getCanonicalName(); + } +} diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java index 42530b81f..6bb0ce13d 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java @@ -73,8 +73,11 @@ import com.dfsek.terra.api.util.generic.pair.Pair; import com.dfsek.terra.api.util.reflection.ReflectionUtil; import com.dfsek.terra.api.util.reflection.TypeKey; import com.dfsek.terra.api.world.biome.generation.BiomeProvider; +import com.dfsek.terra.api.world.biome.tag.BiomeTag; +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; import com.dfsek.terra.api.world.chunk.generation.stage.GenerationStage; import com.dfsek.terra.api.world.chunk.generation.util.provider.ChunkGeneratorProvider; +import com.dfsek.terra.config.loaders.BiomeTagLoader; import com.dfsek.terra.config.loaders.GenericTemplateSupplierLoader; import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor; import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor; @@ -106,6 +109,8 @@ public class ConfigPackImpl implements ConfigPack { private final BiomeProvider seededBiomeProvider; + private final BiomeTagIndex biomeTagIndex = new BiomeTagIndex(); + private final Map> registryMap = new HashMap<>(); private final Map> shortcuts = new HashMap<>(); @@ -148,6 +153,8 @@ public class ConfigPackImpl implements ConfigPack { register(abstractConfigLoader); platform.register(abstractConfigLoader); + applyLoader(BiomeTag.class, new BiomeTagLoader(biomeTagIndex)); + ConfigPackAddonsTemplate addonsTemplate = new ConfigPackAddonsTemplate(); selfLoader.load(addonsTemplate, packManifest); this.addons = addonsTemplate.getAddons(); @@ -222,6 +229,8 @@ public class ConfigPackImpl implements ConfigPack { selfLoader.load(packPostTemplate, packManifest); seededBiomeProvider = template.getBiomeCache() ? packPostTemplate.getProviderBuilder().caching(platform) : packPostTemplate.getProviderBuilder(); + // Must stay inside the constructor: generation threads read tag bitsets without volatile reads. + biomeTagIndex.seal(); checkDeadEntries(); } @@ -297,6 +306,11 @@ public class ConfigPackImpl implements ConfigPack { return seededBiomeProvider; } + @Override + public BiomeTagIndex getBiomeTagIndex() { + return biomeTagIndex; + } + @Override public CheckedRegistry getOrCreateRegistry(TypeKey typeKey) { return (CheckedRegistry) registryMap.computeIfAbsent(typeKey.getType(), c -> { diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java new file mode 100644 index 000000000..f62a7656a --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/config/loaders/BiomeTagLoaderTest.java @@ -0,0 +1,41 @@ +package com.dfsek.terra.config.loaders; + +import com.dfsek.tectonic.impl.MapConfiguration; +import com.dfsek.tectonic.api.depth.DepthTracker; +import com.dfsek.tectonic.api.exception.LoadException; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.AnnotatedType; +import java.util.List; +import java.util.Map; + +import com.dfsek.terra.api.world.biome.tag.BiomeTagIndex; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class BiomeTagLoaderTest { + private final BiomeTagIndex index = new BiomeTagIndex(); + private final BiomeTagLoader loader = new BiomeTagLoader(index); + + private static DepthTracker tracker() { + return new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml")); + } + + @Test + void nonString() { + LoadException e = assertThrows(LoadException.class, () -> loader.load((AnnotatedType) null, 42, null, tracker())); + assertTrue(e.getMessage().contains("expected a tag name"), e.getMessage()); + assertTrue(e.getMessage().contains("type java.lang.Integer"), e.getMessage()); + } + + @Test + void stringInterns() throws LoadException { + Object first = loader.load((AnnotatedType) null, "FOO", null, tracker()); + assertSame(first, loader.load((AnnotatedType) null, "FOO", null, tracker())); + assertSame(index.tag("FOO"), first); + } +} diff --git a/platforms/cli/build.gradle.kts b/platforms/cli/build.gradle.kts index 1d5cb6f73..c28c25f17 100644 --- a/platforms/cli/build.gradle.kts +++ b/platforms/cli/build.gradle.kts @@ -41,4 +41,11 @@ application { tasks.getByName("run").setProperty("workingDir", file("./run")) +// CLIPlatform uses "./" as its data folder. +tasks.withType { + workingDir = file("./run").also { it.mkdirs() } +} + +tasks.withType { dependsOn("moveAddonsrun") } + addonDir(project.file("./run/addons"), tasks.named("run").get())