feat: add environment attribute system

This commit is contained in:
Zoe Gidiere committed 2026-11-09 16:34:50 -07:00
1 parent 8a940f7e1f
commit 4e37c361ea
127 files changed
+9022 -19

No files matched your search

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,8 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:manifest-addon-loader"))
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.world.attribute.RawValue;
public record AmbientParticle(RawValue particle, float probability) { }
@@ -0,0 +1,18 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import java.util.Optional;
public record AmbientSounds(Optional<SoundRef> loop, Optional<Mood> mood, List<Additions> additions) {
public static final AmbientSounds EMPTY = new AmbientSounds(Optional.empty(), Optional.empty(), List.of());
public AmbientSounds {
additions = List.copyOf(additions);
}
public record Mood(SoundRef sound, int tickDelay, int blockSearchExtent, double offset) { }
public record Additions(SoundRef sound, double tickChance) { }
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
public record BackgroundMusic(Optional<Music> defaultMusic, Optional<Music> creative, Optional<Music> underwater) {
public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty());
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.world.attribute.RawValue;
public record BedRule(Rule canSleep, Rule canSetSpawn, boolean destroyOnUse, boolean destroyOnLeave, Optional<RawValue> errorMessage) {
public enum Rule implements StringIdentifiable {
ALWAYS("always"),
WHEN_DARK("when_dark"),
NEVER("never");
private final String id;
Rule(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
}
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum CardinalLight implements StringIdentifiable {
DEFAULT("default"),
NETHER("nether");
private final String id;
CardinalLight(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum GrassColorModifier implements StringIdentifiable {
NONE("none"),
DARK_FOREST("dark_forest"),
SWAMP("swamp");
private final String id;
GrassColorModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,15 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.world.attribute.RawValue;
public record IntProviderValue(OptionalInt constant, Optional<RawValue> provider) {
public IntProviderValue {
if(constant.isPresent() == provider.isPresent()) {
throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider");
}
}
}
@@ -0,0 +1,159 @@
package com.dfsek.terra.addons.attribute.minecraft;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributeTable {
private static final RawValue NO_SLEEP_MESSAGE = new RawValue(Map.of("translate", "block.minecraft.bed.no_sleep"));
private static final BedRule CAN_SLEEP_WHEN_DARK = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.ALWAYS, false, false,
Optional.of(NO_SLEEP_MESSAGE));
private static final BedRule DESTROY_ON_LEAVE = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true,
Optional.of(NO_SLEEP_MESSAGE));
private static final IntProviderValue MONSTER_SPAWN_LIGHT_LEVEL = new IntProviderValue(OptionalInt.empty(), Optional.of(
new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))));
private MinecraftAttributeTable() { }
public static List<Attribute<?>> create(AttributeHandle handle) {
AttributeTypes t = handle.types();
MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle);
AttributeType<TemperatureModifier> temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class);
AttributeType<GrassColorModifier> grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class);
AttributeType<Skybox> skybox = t.enumType("skybox", Skybox.class);
AttributeType<CardinalLight> cardinalLight = t.enumType("cardinal_light", CardinalLight.class);
Table table = new Table(handle);
table.row(MinecraftAttributes.VISUAL_FOG_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_FOG_START_DISTANCE, t.floatType(), 0f);
table.row(MinecraftAttributes.VISUAL_FOG_END_DISTANCE, t.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE, t.floatType(), 512f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_CLOUD_FOG_END_DISTANCE, t.floatType(), 2048f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_COLOR, t.rgbColor(), Color.rgb(0x050533));
table.row(MinecraftAttributes.VISUAL_WATER_FOG_START_DISTANCE, t.floatType(), -8f);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, t.floatType(), 96f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_SUNRISE_SUNSET_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_HEIGHT, t.floatType(), 192.33f);
table.row(MinecraftAttributes.VISUAL_SUN_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_STAR_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_PHASE, m.moonPhase(), MoonPhase.FULL_MOON);
table.row(MinecraftAttributes.VISUAL_STAR_BRIGHTNESS, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_BLOCK_LIGHT_TINT, t.rgbColor(), Color.rgb(0xffd88c));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_COLOR, t.rgbColor(), Color.rgb(0xffffff));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_FACTOR, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_NIGHT_VISION_COLOR, t.rgbColor(), Color.rgb(0x999999));
table.row(MinecraftAttributes.VISUAL_AMBIENT_LIGHT_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_DEFAULT_DRIPSTONE_PARTICLE, m.particle(),
new RawValue(Map.of("type", "minecraft:dripping_dripstone_water")));
table.row(MinecraftAttributes.VISUAL_AMBIENT_PARTICLES, m.ambientParticles(), List.of());
table.row(MinecraftAttributes.AUDIO_BACKGROUND_MUSIC, m.backgroundMusic(), BackgroundMusic.EMPTY);
table.row(MinecraftAttributes.AUDIO_MUSIC_VOLUME, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.AUDIO_AMBIENT_SOUNDS, m.ambientSounds(), AmbientSounds.EMPTY);
table.row(MinecraftAttributes.AUDIO_FIREFLY_BUSH_SOUNDS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL, t.floatType(), 15f).range(0, 15).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_CAN_START_RAID, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_WATER_EVAPORATES, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_BED_RULE, m.bedRule(), CAN_SLEEP_WHEN_DARK);
table.row(MinecraftAttributes.GAMEPLAY_STRAW_BED_RULE, m.bedRule(), DESTROY_ON_LEAVE);
table.row(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_FAST_LAVA, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_INCREASED_FIRE_BURNOUT, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_EYEBLOSSOM_OPEN, t.triState(), TriState.DEFAULT);
table.row(MinecraftAttributes.GAMEPLAY_TURTLE_EGG_HATCH_CHANCE, t.floatType(), 0.002f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_PIGLINS_ZOMBIFY, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_SNOW_GOLEM_MELTS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CREAKING_ACTIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_BEES_STAY_IN_HIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_MONSTERS_BURN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_NATURAL_MOB_SPAWNS, m.mobSpawnSettings(), MobSpawnSettings.EMPTY);
table.row(MinecraftAttributes.GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY, t.floatType(), 0.1f).range(0, 0.9999999);
table.row(MinecraftAttributes.GAMEPLAY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.GAMEPLAY_BABY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.BIOME_HAS_PRECIPITATION, t.booleanType(), true);
table.row(MinecraftAttributes.BIOME_TEMPERATURE, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_TEMPERATURE_MODIFIER, temperatureModifier, TemperatureModifier.NONE);
table.row(MinecraftAttributes.BIOME_DOWNFALL, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_WATER_COLOR, t.rgbColor(), Color.rgb(0x3f76e4));
table.row(MinecraftAttributes.BIOME_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_DRY_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR_MODIFIER, grassColorModifier, GrassColorModifier.NONE);
table.row(MinecraftAttributes.BIOME_VILLAGER_TYPE, m.identifier(), RegistryKey.parse("minecraft:plains"));
table.row(MinecraftAttributes.DIMENSION_HAS_FIXED_TIME, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_SKYLIGHT, t.booleanType(), true).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_CEILING, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_ENDER_DRAGON_FIGHT, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_COORDINATE_SCALE, t.floatType(), 1f).packOnly().range(1e-5, 3e7);
table.row(MinecraftAttributes.DIMENSION_MIN_Y, t.integerOverrideOnly(), -64).packOnly().range(-2032, 2031).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(16, 4064).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_LOGICAL_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(0, 4064);
table.row(MinecraftAttributes.DIMENSION_INFINIBURN, m.identifierOrTag(),
Either.right(TagKey.parse("#minecraft:infiniburn_overworld"))).packOnly();
table.row(MinecraftAttributes.DIMENSION_AMBIENT_LIGHT, t.floatType(), 0f).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL, m.intProvider(), MONSTER_SPAWN_LIGHT_LEVEL).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT, t.integer(), 0).packOnly().range(0, 15);
table.row(MinecraftAttributes.DIMENSION_SKYBOX, skybox, Skybox.OVERWORLD).packOnly();
table.row(MinecraftAttributes.DIMENSION_CARDINAL_LIGHT, cardinalLight, CardinalLight.DEFAULT).packOnly();
table.row(MinecraftAttributes.DIMENSION_DEFAULT_CLOCK, m.identifier(), RegistryKey.parse("minecraft:overworld")).packOnly();
table.row(MinecraftAttributes.WORLD_SEA_LEVEL, t.integer(), 63).packOnly();
table.row(MinecraftAttributes.WORLD_SPAWN_HEIGHT, t.integer(), 64).packOnly();
table.row(MinecraftAttributes.WORLD_MOB_GENERATION, t.booleanType(), true).packOnly();
List<Attribute<?>> attributes = table.build();
if(!attributes.stream().map(Attribute::key).toList().equals(MinecraftAttributes.all())) {
throw new IllegalStateException("the Minecraft attribute table does not match MinecraftAttributes.all()");
}
return attributes;
}
private static final class Table {
private final AttributeHandle handle;
private final List<Attribute.Builder<?>> rows = new ArrayList<>();
private Table(AttributeHandle handle) {
this.handle = handle;
}
private <T> Attribute.Builder<T> row(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue) {
MinecraftIds.requireLowerCase(key.getRegistryKey());
Attribute.Builder<T> builder = handle.attributeBuilder(key, type, defaultValue);
rows.add(builder);
return builder;
}
private List<Attribute<?>> build() {
List<Attribute<?>> built = new ArrayList<>(rows.size());
for(Attribute.Builder<?> row : rows) built.add(row.build());
return List.copyOf(built);
}
}
}
@@ -0,0 +1,109 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftAttributeTypes {
private final AttributeType<MoonPhase> moonPhase;
private final AttributeType<BedRule> bedRule;
private final AttributeType<RawValue> particle;
private final AttributeType<List<AmbientParticle>> ambientParticles;
private final AttributeType<BackgroundMusic> backgroundMusic;
private final AttributeType<AmbientSounds> ambientSounds;
private final AttributeType<MobSpawnSettings> mobSpawnSettings;
private final AttributeType<RegistryKey> identifier;
private final AttributeType<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeType<IntProviderValue> intProvider;
public MinecraftAttributeTypes(AttributeHandle handle) {
MinecraftCodecs codecs = new MinecraftCodecs(handle);
this.moonPhase = handle.typeBuilder("moon_phase", codecs.moonPhase()).build();
this.bedRule = handle.typeBuilder("bed_rule", codecs.bedRule()).build();
this.particle = handle.typeBuilder("particle", codecs.particle()).build();
this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles())
.op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append)
.build();
this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build();
this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build();
this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings())
.op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay)
.build();
this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build();
this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build();
this.intProvider = handle.typeBuilder("int_provider", codecs.intProvider()).build();
}
public AttributeType<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeType<BedRule> bedRule() {
return bedRule;
}
public AttributeType<RawValue> particle() {
return particle;
}
public AttributeType<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeType<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeType<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeType<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
public AttributeType<RegistryKey> identifier() {
return identifier;
}
public AttributeType<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeType<IntProviderValue> intProvider() {
return intProvider;
}
private static List<AmbientParticle> append(List<AmbientParticle> s, List<AmbientParticle> a) {
if(a.isEmpty()) return s;
if(s.isEmpty()) return a;
List<AmbientParticle> out = new ArrayList<>(s.size() + a.size());
out.addAll(s);
out.addAll(a);
return List.copyOf(out);
}
private static MobSpawnSettings overlay(MobSpawnSettings first, MobSpawnSettings second) {
if(first.spawnsByCategory().isEmpty() && first.spawnCosts().isEmpty()) return second;
if(second.spawnsByCategory().isEmpty() && second.spawnCosts().isEmpty()) return first;
if(second.spawnsByCategory().keySet().containsAll(first.spawnsByCategory().keySet())
&& second.spawnCosts().keySet().containsAll(first.spawnCosts().keySet())) {
return second;
}
Map<String, List<MobSpawnSettings.Spawner>> categories = new LinkedHashMap<>(first.spawnsByCategory());
categories.putAll(second.spawnsByCategory());
Map<RegistryKey, MobSpawnSettings.Cost> costs = new LinkedHashMap<>(first.spawnCosts());
costs.putAll(second.spawnCosts());
return new MobSpawnSettings(categories, costs);
}
}
@@ -0,0 +1,128 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.List;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributes {
private static List<AttributeKey<?>> building = new ArrayList<>();
public static final AttributeKey<Color> VISUAL_FOG_COLOR = vanilla("visual/fog_color");
public static final AttributeKey<Float> VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance");
public static final AttributeKey<Float> VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance");
public static final AttributeKey<Float> VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance");
public static final AttributeKey<Float> VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance");
public static final AttributeKey<Color> VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color");
public static final AttributeKey<Float> VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance");
public static final AttributeKey<Float> VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance");
public static final AttributeKey<Color> VISUAL_SKY_COLOR = vanilla("visual/sky_color");
public static final AttributeKey<Color> VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color");
public static final AttributeKey<Color> VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color");
public static final AttributeKey<Float> VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height");
public static final AttributeKey<Float> VISUAL_SUN_ANGLE = vanilla("visual/sun_angle");
public static final AttributeKey<Float> VISUAL_MOON_ANGLE = vanilla("visual/moon_angle");
public static final AttributeKey<Float> VISUAL_STAR_ANGLE = vanilla("visual/star_angle");
public static final AttributeKey<MoonPhase> VISUAL_MOON_PHASE = vanilla("visual/moon_phase");
public static final AttributeKey<Float> VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness");
public static final AttributeKey<Color> VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint");
public static final AttributeKey<Color> VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color");
public static final AttributeKey<Float> VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor");
public static final AttributeKey<Color> VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color");
public static final AttributeKey<Color> VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color");
public static final AttributeKey<RawValue> VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle");
public static final AttributeKey<List<AmbientParticle>> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles");
public static final AttributeKey<BackgroundMusic> AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music");
public static final AttributeKey<Float> AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume");
public static final AttributeKey<AmbientSounds> AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds");
public static final AttributeKey<Boolean> AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds");
public static final AttributeKey<Float> GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid");
public static final AttributeKey<Boolean> GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates");
public static final AttributeKey<BedRule> GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule");
public static final AttributeKey<BedRule> GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule");
public static final AttributeKey<Boolean> GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works");
public static final AttributeKey<Boolean> GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin");
public static final AttributeKey<Boolean> GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava");
public static final AttributeKey<Boolean> GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout");
public static final AttributeKey<TriState> GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open");
public static final AttributeKey<Float> GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance");
public static final AttributeKey<Boolean> GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify");
public static final AttributeKey<Boolean> GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts");
public static final AttributeKey<Boolean> GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active");
public static final AttributeKey<Float> GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance");
public static final AttributeKey<Float> GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance");
public static final AttributeKey<Boolean> GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive");
public static final AttributeKey<Boolean> GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn");
public static final AttributeKey<MobSpawnSettings> GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns");
public static final AttributeKey<Float> GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY =
vanilla("gameplay/creature_world_gen_spawn_probability");
public static final AttributeKey<RegistryKey> GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity");
public static final AttributeKey<RegistryKey> GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity");
public static final AttributeKey<Boolean> BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation");
public static final AttributeKey<Float> BIOME_TEMPERATURE = terra("biome/temperature");
public static final AttributeKey<TemperatureModifier> BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier");
public static final AttributeKey<Float> BIOME_DOWNFALL = terra("biome/downfall");
public static final AttributeKey<Color> BIOME_WATER_COLOR = terra("biome/water_color");
public static final AttributeKey<Color> BIOME_FOLIAGE_COLOR = terra("biome/foliage_color");
public static final AttributeKey<Color> BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color");
public static final AttributeKey<Color> BIOME_GRASS_COLOR = terra("biome/grass_color");
public static final AttributeKey<GrassColorModifier> BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier");
public static final AttributeKey<RegistryKey> BIOME_VILLAGER_TYPE = terra("biome/villager_type");
public static final AttributeKey<Boolean> DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time");
public static final AttributeKey<Boolean> DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight");
public static final AttributeKey<Boolean> DIMENSION_HAS_CEILING = terra("dimension/has_ceiling");
public static final AttributeKey<Boolean> DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight");
public static final AttributeKey<Float> DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale");
public static final AttributeKey<Integer> DIMENSION_MIN_Y = terra("dimension/min_y");
public static final AttributeKey<Integer> DIMENSION_HEIGHT = terra("dimension/height");
public static final AttributeKey<Integer> DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height");
public static final AttributeKey<Either<RegistryKey, TagKey>> DIMENSION_INFINIBURN = terra("dimension/infiniburn");
public static final AttributeKey<Float> DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light");
public static final AttributeKey<IntProviderValue> DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level");
public static final AttributeKey<Integer> DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT =
terra("dimension/monster_spawn_block_light_limit");
public static final AttributeKey<Skybox> DIMENSION_SKYBOX = terra("dimension/skybox");
public static final AttributeKey<CardinalLight> DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light");
public static final AttributeKey<RegistryKey> DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock");
public static final AttributeKey<Integer> WORLD_SEA_LEVEL = terra("world/sea_level");
public static final AttributeKey<Integer> WORLD_SPAWN_HEIGHT = terra("world/spawn_height");
public static final AttributeKey<Boolean> WORLD_MOB_GENERATION = terra("world/mob_generation");
private static final List<AttributeKey<?>> VIEW = seal();
private MinecraftAttributes() { }
public static List<AttributeKey<?>> all() {
return VIEW;
}
private static List<AttributeKey<?>> seal() {
List<AttributeKey<?>> view = List.copyOf(building);
building = null;
return view;
}
private static <T> AttributeKey<T> vanilla(String path) {
return add(RegistryKey.of("minecraft", path));
}
private static <T> AttributeKey<T> terra(String path) {
return add(RegistryKey.of("terra", path));
}
private static <T> AttributeKey<T> add(RegistryKey key) {
AttributeKey<T> attributeKey = AttributeKey.of(key);
building.add(attributeKey);
return attributeKey;
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
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.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.world.attribute.Attribute;
public class MinecraftAttributesAddon implements AddonInitializer {
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
List<Attribute<?>> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle());
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
CheckedRegistry<Attribute<?>> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
})
.failThrough();
}
}
@@ -0,0 +1,349 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeSet;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeCodec;
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftCodecs {
public static final String NAMESPACE = "minecraft";
// Same wording as the core identifier codec.
private static final String EXPECTED_IDENTIFIER = "expected an identifier like \"" + NAMESPACE + ":id\"";
private static final Set<String> MOB_CATEGORIES = Set.of("monster", "creature", "ambient", "axolotls", "underground_water_creature",
"water_creature", "water_ambient", "misc");
private final AttributeCodecs codecs;
private final DecodeContext plain;
private final AttributeCodec<String> idString;
private final AttributeCodec<RegistryKey> identifier;
private final AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeCodec<MoonPhase> moonPhase;
private final AttributeCodec<RawValue> particle;
private final AttributeCodec<AmbientParticle> ambientParticle;
private final AttributeCodec<List<AmbientParticle>> ambientParticles;
private final AttributeCodec<IntProviderValue> intProvider;
private final AttributeCodec<SoundRef> soundRef;
private final AttributeCodec<Music> music;
private final AttributeCodec<BackgroundMusic> backgroundMusic;
private final AttributeCodec<AmbientSounds.Mood> mood;
private final AttributeCodec<List<AmbientSounds.Additions>> additions;
private final AttributeCodec<AmbientSounds> ambientSounds;
private final AttributeCodec<BedRule.Rule> bedRuleRule;
private final AttributeCodec<BedRule> bedRule;
private final AttributeCodec<List<MobSpawnSettings.Spawner>> spawners;
private final AttributeCodec<MobSpawnSettings.Cost> spawnCost;
private final AttributeCodec<Map<String, List<MobSpawnSettings.Spawner>>> spawnsByCategory;
private final AttributeCodec<Map<RegistryKey, MobSpawnSettings.Cost>> spawnCosts;
private final AttributeCodec<MobSpawnSettings> mobSpawnSettings;
public MinecraftCodecs(AttributeHandle handle) {
AttributeCodecs c = handle.codecs();
this.codecs = c;
this.plain = handle.plainContext();
this.idString = c.string(EXPECTED_IDENTIFIER);
AttributeCodec<RegistryKey> coreIdentifier = c.identifier(NAMESPACE);
this.identifier = c.of((raw, context) -> {
String s = idString.decode(raw, context);
return lowerCase(coreIdentifier.decode(s, plain), s);
}, coreIdentifier::encode);
AttributeCodec<Either<RegistryKey, TagKey>> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE);
this.identifierOrTag = c.of((raw, context) -> {
String s = idString.decode(raw, context);
Either<RegistryKey, TagKey> id = coreIdentifierOrTag.decode(s, plain);
lowerCase(id.hasLeft() ? id.getLeft().orElseThrow() : id.getRight().orElseThrow().key(), s);
return id;
}, coreIdentifierOrTag::encode);
this.moonPhase = c.enumCodec("moon phase", MoonPhase.class);
this.particle = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(!(value instanceof Map<?, ?> map) || !map.containsKey("type")) {
throw new DecodeException("expected a particle object with a \"type\" key, got " + c.describe(value));
}
if(map.get("type") instanceof String type) {
try {
identifier.decode(type, plain);
} catch(DecodeException e) {
throw new DecodeException("\"type\" of particle: " + e.getMessage(), e);
}
}
return c.raw().decode(value, context);
}, RawValue::value);
this.ambientParticle = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient particle", raw, context);
RawValue value = f.required("particle", this.particle);
float probability = f.required("probability", c.unitFloat());
f.finish();
return new AmbientParticle(value, probability);
}, value -> c.writer()
.put("particle", particle, value.particle())
.put("probability", c.unitFloat(), value.probability())
.map());
this.ambientParticles = c.list(ambientParticle);
this.intProvider = c.of((raw, context) -> {
String expected = "expected an integer or an int provider object";
Object value = context.resolve(raw);
if(value instanceof Map<?, ?> map) {
if(!map.containsKey("type")) throw new DecodeException("int provider object is missing \"type\"");
return new IntProviderValue(OptionalInt.empty(), Optional.of(c.raw().decode(value, context)));
}
if(value instanceof Number) return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
if(value instanceof String) {
try {
return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
} catch(DecodeException e) {
throw new DecodeException(expected + ", got " + c.describe(value), e);
}
}
throw new DecodeException(expected + ", got " + c.describe(value));
}, value -> value.constant().isPresent() ? (Object) value.constant().getAsInt() : value.provider().orElseThrow().value());
this.soundRef = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(value instanceof String) return new SoundRef(identifier.decode(value, context), OptionalDouble.empty());
if(value instanceof Map<?, ?>) {
ObjectReader f = c.reader("sound", value, context);
RegistryKey id = f.required("sound_id", identifier);
Optional<Double> range = f.optional("range", c.doubleCodec());
f.finish();
return new SoundRef(id, range.map(OptionalDouble::of).orElse(OptionalDouble.empty()));
}
throw new DecodeException("expected a sound ID or a {sound_id, range} object, got " + c.describe(value));
}, value -> {
if(value.range().isEmpty()) return identifier.encode(value.id());
return c.writer()
.put("sound_id", identifier, value.id())
.put("range", c.doubleCodec(), value.range().getAsDouble())
.map();
});
this.music = c.of((raw, context) -> {
ObjectReader f = c.reader("music", raw, context);
SoundRef sound = f.required("sound", soundRef);
int min = f.required("min_delay", c.nonNegativeInt());
int max = f.required("max_delay", c.nonNegativeInt());
boolean replace = f.orDefault("replace_current_music", c.booleanCodec(), false);
f.finish();
return new Music(sound, min, max, replace);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("min_delay", c.nonNegativeInt(), value.minDelay())
.put("max_delay", c.nonNegativeInt(), value.maxDelay())
.put("replace_current_music", c.booleanCodec(), value.replaceCurrentMusic())
.map());
this.backgroundMusic = c.of((raw, context) -> {
ObjectReader f = c.reader("background music", raw, context);
Optional<Music> def = f.optional("default", music);
Optional<Music> creative = f.optional("creative", music);
Optional<Music> underwater = f.optional("underwater", music);
f.finish();
return new BackgroundMusic(def, creative, underwater);
}, value -> c.writer()
.optional("default", music, value.defaultMusic())
.optional("creative", music, value.creative())
.optional("underwater", music, value.underwater())
.map());
this.mood = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient mood", raw, context);
SoundRef sound = f.required("sound", soundRef);
int tickDelay = f.required("tick_delay", c.intCodec());
int extent = f.required("block_search_extent", c.intCodec());
double offset = f.required("offset", c.doubleCodec());
f.finish();
return new AmbientSounds.Mood(sound, tickDelay, extent, offset);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_delay", c.intCodec(), value.tickDelay())
.put("block_search_extent", c.intCodec(), value.blockSearchExtent())
.put("offset", c.doubleCodec(), value.offset())
.map());
this.additions = c.compactList(c.of((raw, context) -> {
ObjectReader f = c.reader("ambient additions", raw, context);
SoundRef sound = f.required("sound", soundRef);
double chance = f.required("tick_chance", c.doubleCodec());
f.finish();
return new AmbientSounds.Additions(sound, chance);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_chance", c.doubleCodec(), value.tickChance())
.map()));
this.ambientSounds = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient sounds", raw, context);
Optional<SoundRef> loop = f.optional("loop", soundRef);
Optional<AmbientSounds.Mood> moodValue = f.optional("mood", mood);
List<AmbientSounds.Additions> additionsValue = f.orDefault("additions", additions, List.of());
f.finish();
return new AmbientSounds(loop, moodValue, additionsValue);
}, value -> c.writer()
.optional("loop", soundRef, value.loop())
.optional("mood", mood, value.mood())
.put("additions", additions, value.additions())
.map());
this.bedRuleRule = c.enumCodec("bed rule", BedRule.Rule.class);
this.bedRule = c.of((raw, context) -> {
ObjectReader f = c.reader("bed rule", raw, context);
BedRule.Rule canSleep = f.required("can_sleep", bedRuleRule);
BedRule.Rule canSetSpawn = f.required("can_set_spawn", bedRuleRule);
boolean onUse = f.orDefault("destroy_on_use", c.booleanCodec(), false);
boolean onLeave = f.orDefault("destroy_on_leave", c.booleanCodec(), false);
Optional<RawValue> message = f.optional("error_message", c.raw());
f.finish();
return new BedRule(canSleep, canSetSpawn, onUse, onLeave, message);
}, value -> c.writer()
.put("can_sleep", bedRuleRule, value.canSleep())
.put("can_set_spawn", bedRuleRule, value.canSetSpawn())
.put("destroy_on_use", c.booleanCodec(), value.destroyOnUse())
.put("destroy_on_leave", c.booleanCodec(), value.destroyOnLeave())
.optional("error_message", c.raw(), value.errorMessage())
.map());
this.spawners = c.list(c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawner", raw, context);
RegistryKey type = f.required("type", identifier);
int weight = f.required("weight", c.nonNegativeInt());
IntProviderValue count = f.required("count", intProvider);
f.finish();
return new MobSpawnSettings.Spawner(type, weight, count);
}, value -> c.writer()
.put("type", identifier, value.type())
.put("weight", c.nonNegativeInt(), value.weight())
.put("count", intProvider, value.count())
.map()));
this.spawnCost = c.of((raw, context) -> {
ObjectReader f = c.reader("spawn cost", raw, context);
double budget = f.required("energy_budget", c.doubleCodec());
double charge = f.required("charge", c.doubleCodec());
f.finish();
return new MobSpawnSettings.Cost(budget, charge);
}, value -> c.writer()
.put("energy_budget", c.doubleCodec(), value.energyBudget())
.put("charge", c.doubleCodec(), value.charge())
.map());
this.spawnsByCategory = c.of((raw, context) -> {
ObjectReader categories = c.reader("spawns_by_category", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> out = new LinkedHashMap<>();
for(String key : categories.keys()) {
if(!MOB_CATEGORIES.contains(key)) {
throw new DecodeException("unknown mob category \"" + key + "\", expected one of " + new TreeSet<>(MOB_CATEGORIES));
}
out.put(key, categories.required(key, spawners));
}
categories.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((category, list) -> out.put(category, spawners.encode(list)));
return out;
});
// Map keys are never preprocessed.
this.spawnCosts = c.of((raw, context) -> {
ObjectReader costs = c.reader("spawn_costs", raw, context);
Map<RegistryKey, MobSpawnSettings.Cost> out = new LinkedHashMap<>();
for(String key : costs.keys()) {
out.put(identifier.decode(key, plain), costs.required(key, spawnCost));
}
costs.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((entity, cost) -> out.put((String) identifier.encode(entity), spawnCost.encode(cost)));
return out;
});
this.mobSpawnSettings = c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawn settings", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> byCategory = f.required("spawns_by_category", spawnsByCategory);
Map<RegistryKey, MobSpawnSettings.Cost> costs = f.required("spawn_costs", spawnCosts);
f.finish();
return new MobSpawnSettings(byCategory, costs);
}, value -> c.writer()
.put("spawns_by_category", spawnsByCategory, value.spawnsByCategory())
.put("spawn_costs", spawnCosts, value.spawnCosts())
.map());
}
private RegistryKey lowerCase(RegistryKey key, String written) throws DecodeException {
try {
return MinecraftIds.requireLowerCase(key, written);
} catch(IllegalArgumentException e) {
throw new DecodeException(EXPECTED_IDENTIFIER + ", got " + codecs.describe(written), e);
}
}
public AttributeCodec<RegistryKey> identifier() {
return identifier;
}
public AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeCodec<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeCodec<RawValue> particle() {
return particle;
}
public AttributeCodec<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeCodec<IntProviderValue> intProvider() {
return intProvider;
}
public AttributeCodec<SoundRef> soundRef() {
return soundRef;
}
public AttributeCodec<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeCodec<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeCodec<BedRule> bedRule() {
return bedRule;
}
public AttributeCodec<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.regex.Pattern;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class MinecraftIds {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private MinecraftIds() { }
public static RegistryKey requireLowerCase(RegistryKey key) {
return requireLowerCase(key, key.toString());
}
public static RegistryKey requireLowerCase(RegistryKey key, String written) {
if(!NAMESPACE.matcher(key.getNamespace()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -");
}
if(!PATH.matcher(key.getID()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -");
}
return key;
}
}
@@ -0,0 +1,25 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record MobSpawnSettings(Map<String, List<Spawner>> spawnsByCategory, Map<RegistryKey, Cost> spawnCosts) {
public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of());
public MobSpawnSettings {
Map<String, List<Spawner>> copy = new LinkedHashMap<>();
spawnsByCategory.forEach((k, v) -> copy.put(k, List.copyOf(v)));
spawnsByCategory = Collections.unmodifiableMap(copy);
spawnCosts = Collections.unmodifiableMap(new LinkedHashMap<>(spawnCosts));
}
public record Spawner(RegistryKey type, int weight, IntProviderValue count) { }
public record Cost(double energyBudget, double charge) { }
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum MoonPhase implements StringIdentifiable {
FULL_MOON("full_moon"),
WANING_GIBBOUS("waning_gibbous"),
THIRD_QUARTER("third_quarter"),
WANING_CRESCENT("waning_crescent"),
NEW_MOON("new_moon"),
WAXING_CRESCENT("waxing_crescent"),
FIRST_QUARTER("first_quarter"),
WAXING_GIBBOUS("waxing_gibbous");
private final String id;
MoonPhase(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,3 @@
package com.dfsek.terra.addons.attribute.minecraft;
public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { }
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum Skybox implements StringIdentifiable {
NONE("none"),
OVERWORLD("overworld"),
END("end");
private final String id;
Skybox(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.OptionalDouble;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record SoundRef(RegistryKey id, OptionalDouble range) { }
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum TemperatureModifier implements StringIdentifiable {
NONE("none"),
FROZEN("frozen");
private final String id;
TemperatureModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,12 @@
schema-version: 1
contributors:
- Terra contributors
id: minecraft-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
@@ -0,0 +1,450 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class MinecraftAttributeTypesTest {
private static final float EPS = 1e-6f;
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final MinecraftCodecs CODECS = new MinecraftCodecs(HANDLE);
private static <T> T mod(AttributeType<T> type, Operation op, T subject, Object rawArg) throws DecodeException {
return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN));
}
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
@Test
void everyTypeSupportsOverride() {
List<AttributeType<?>> all = List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.ambientParticles(),
TYPES.backgroundMusic(), TYPES.ambientSounds(), TYPES.mobSpawnSettings(), TYPES.identifier(), TYPES.identifierOrTag(),
TYPES.intProvider());
for(AttributeType<?> t : all) assertTrue(t.operations().contains(Operation.OVERRIDE), t.id());
}
@Test
void operationSets() {
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifier().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifierOrTag().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations());
}
@Test
void idsAreVanillaTypeIds() {
assertEquals("moon_phase", TYPES.moonPhase().id());
assertEquals("bed_rule", TYPES.bedRule().id());
assertEquals("particle", TYPES.particle().id());
assertEquals("ambient_particles", TYPES.ambientParticles().id());
assertEquals("background_music", TYPES.backgroundMusic().id());
assertEquals("ambient_sounds", TYPES.ambientSounds().id());
assertEquals("mob_spawn_settings", TYPES.mobSpawnSettings().id());
assertEquals("identifier", TYPES.identifier().id());
assertEquals("identifier_or_tag", TYPES.identifierOrTag().id());
assertEquals("int_provider", TYPES.intProvider().id());
}
@Test
void decodeFailuresReadTheSameEverywhere() {
String bedRule = assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage();
assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule);
String moonPhase = assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("x", PLAIN)).getMessage();
assertTrue(moonPhase.startsWith("unknown moon phase \"x\", expected one of [full_moon, "), moonPhase);
}
@Test
void enumsAreStringIdentifiable() {
assertEquals("waxing_gibbous", MoonPhase.WAXING_GIBBOUS.getID());
assertEquals("when_dark", BedRule.Rule.WHEN_DARK.getID());
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
}
@Test
void ambientParticlesAppend() throws DecodeException {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
List<AmbientParticle> one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN);
List<AmbientParticle> two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN);
assertEquals(1, one.size());
assertEquals(0.025f, one.get(0).probability(), EPS);
assertEquals(new RawValue(map("type", "minecraft:crimson_spore")), one.get(0).particle());
assertEquals(one, t.apply(Operation.APPEND, one, List.of()));
assertEquals(two, t.apply(Operation.APPEND, List.of(), two));
assertEquals(List.of(one.get(0), two.get(0)), t.apply(Operation.APPEND, one, two));
assertEquals(List.of(one.get(0), two.get(0)),
mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1))));
}
@Test
void ambientParticleValidation() {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 1.5)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"))), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", "x", "probability", 0.5)), PLAIN));
assertThrows(DecodeException.class,
() -> t.decode(List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(map("particle", map("type", "x"), "probability", 0.5), PLAIN));
}
private static MobSpawnSettings spawns(Map<String, Object> raw) throws DecodeException {
return TYPES.mobSpawnSettings().decode(raw, PLAIN);
}
private static Map<String, Object> spawner(String type, int weight, int count) {
return map("type", type, "weight", weight, "count", count);
}
@Test
void mobSpawnDecode() throws DecodeException {
MobSpawnSettings s = spawns(map(
"spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8))),
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15))));
MobSpawnSettings.Spawner sp = s.spawnsByCategory().get("ambient").get(0);
assertEquals(RegistryKey.parse("minecraft:bat"), sp.type());
assertEquals(10, sp.weight());
assertEquals(8, sp.count().constant().getAsInt());
assertEquals(0.7, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).energyBudget(), 1e-9);
assertEquals(0.15, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).charge(), 1e-9);
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map(), "spawn_costs", map(), "x", 1)));
}
@Test
void mobSpawnCountMapIsKeptRaw() throws DecodeException {
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(
map("type", "minecraft:zombie", "weight", 5,
"count", map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)))),
"spawn_costs", map()));
IntProviderValue c = s.spawnsByCategory().get("monster").get(0).count();
assertTrue(c.constant().isEmpty());
assertTrue(c.provider().isPresent());
}
@Test
void mobSpawnOverlayRules() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings empty = MobSpawnSettings.EMPTY;
MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))),
"spawn_costs", map()));
assertSame(a, t.apply(Operation.OVERLAY, empty, a));
assertSame(a, t.apply(Operation.OVERLAY, a, empty));
MobSpawnSettings sup = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:husk", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map()));
assertSame(sup, t.apply(Operation.OVERLAY, a, sup));
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))),
"spawn_costs", map("minecraft:a", map("energy_budget", 1, "charge", 1))));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))),
"spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2))));
MobSpawnSettings r = t.apply(Operation.OVERLAY, s, arg);
assertEquals(RegistryKey.parse("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type());
assertEquals(RegistryKey.parse("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type());
assertEquals(RegistryKey.parse("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type());
assertEquals(Set.of(RegistryKey.parse("minecraft:a"), RegistryKey.parse("minecraft:b")), r.spawnCosts().keySet());
}
@Test
void mobSpawnOverlayEmptyCategoryClears() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))), "spawn_costs", map()));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
assertTrue(r.spawnsByCategory().get("monster").isEmpty());
assertEquals(1, r.spawnsByCategory().get("creature").size());
assertEquals(r, t.apply(Operation.OVERLAY, s, arg));
}
@Test
void ambientSoundsDecode() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map(
"additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111),
"loop", "minecraft:ambient.crimson_forest.loop",
"mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood", "tick_delay", 6000)),
PLAIN);
assertEquals(1, a.additions().size());
assertEquals(0.0111, a.additions().get(0).tickChance(), 1e-9);
assertEquals(RegistryKey.parse("minecraft:ambient.crimson_forest.loop"), a.loop().orElseThrow().id());
assertEquals(6000, a.mood().orElseThrow().tickDelay());
assertEquals(8, a.mood().orElseThrow().blockSearchExtent());
assertEquals(2.0, a.mood().orElseThrow().offset(), 1e-9);
AmbientSounds list = TYPES.ambientSounds().decode(map(
"additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "a:c", "tick_chance", 0.2))), PLAIN);
assertEquals(2, list.additions().size());
assertTrue(list.loop().isEmpty());
assertEquals(AmbientSounds.EMPTY, TYPES.ambientSounds().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("looop", "a:b"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("mood", map("sound", "a:b")), PLAIN));
}
@Test
void soundRefForms() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b", "range", 16)), PLAIN);
assertEquals(RegistryKey.parse("a:b"), a.loop().orElseThrow().id());
assertEquals(16.0, a.loop().orElseThrow().range().getAsDouble(), 1e-9);
AmbientSounds b = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b")), PLAIN);
assertTrue(b.loop().orElseThrow().range().isEmpty());
assertEquals(RegistryKey.parse("minecraft:ambient.cave"),
TYPES.ambientSounds().decode(map("loop", "ambient.cave"), PLAIN).loop().orElseThrow().id());
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", 5), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", "Not Valid"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", map("range", 1)), PLAIN));
}
@Test
void upperCaseIdRejected() {
DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN));
assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage());
assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage());
assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN)));
}
private static String path(String written) {
return "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -";
}
private static String namespace(String written) {
return "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -";
}
private static String lowerCaseFailure(Executable decode) {
Throwable t = assertThrows(DecodeException.class, decode);
while(t != null && !(t instanceof IllegalArgumentException)) t = t.getCause();
assertNotNull(t, "no lower-case rule failure in the cause chain");
return t.getMessage();
}
@Test
void lowerCaseIds() {
assertEquals(path("minecraft:Music.Game"),
lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN)));
assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode(
map("default", map("sound", "Music.Game", "min_delay", 1, "max_delay", 2)), PLAIN)));
assertEquals(path("minecraft:Flame"), lowerCaseFailure(() -> TYPES.particle().decode(map("type", "minecraft:Flame"), PLAIN)));
assertEquals(path("Idle"), lowerCaseFailure(() -> TYPES.identifier().decode("Idle", PLAIN)));
assertEquals(path("#minecraft:Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#minecraft:Logs", PLAIN)));
assertEquals(path("#Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#Logs", PLAIN)));
assertEquals(namespace("Minecraft:stone"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("Minecraft:stone", PLAIN)));
assertEquals(path("minecraft:Zombie"), lowerCaseFailure(() -> spawns(map(
"spawns_by_category", map("monster", List.of(spawner("minecraft:Zombie", 1, 1))), "spawn_costs", map()))));
assertEquals(namespace("Minecraft:enderman"), lowerCaseFailure(() -> spawns(map("spawns_by_category", map(),
"spawn_costs", map("Minecraft:enderman", map("energy_budget", 1, "charge", 1))))));
}
@Test
void requireLowerCase() {
RegistryKey key = RegistryKey.parse("minecraft:visual/fog_color");
assertSame(key, MinecraftIds.requireLowerCase(key));
assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color"));
assertEquals(namespace("Mod:thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("Mod:thing"))).getMessage());
assertEquals(path("mod:Thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("mod:Thing"))).getMessage());
assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class,
() -> MinecraftIds.requireLowerCase(RegistryKey.parse("minecraft:Thing"), "Thing")).getMessage());
}
@Test
void integersFollowTheCoreRule() {
String weight = assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category",
map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))).getMessage();
assertTrue(weight.endsWith("\"weight\" of mob spawner: expected an integer, got 1.5"), weight);
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(99999999999L, PLAIN));
}
@Test
void backgroundMusicDecode() throws DecodeException {
BackgroundMusic m = TYPES.backgroundMusic().decode(map(
"default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game", "replace_current_music", true),
"underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")), PLAIN);
assertTrue(m.defaultMusic().orElseThrow().replaceCurrentMusic());
assertFalse(m.underwater().orElseThrow().replaceCurrentMusic());
assertEquals(12000, m.underwater().orElseThrow().minDelay());
assertEquals(24000, m.underwater().orElseThrow().maxDelay());
assertTrue(m.creative().isEmpty());
assertEquals(BackgroundMusic.EMPTY, TYPES.backgroundMusic().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("bogus", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", 1)), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1)), PLAIN));
}
@Test
void bedRuleDecode() throws DecodeException {
BedRule r = TYPES.bedRule().decode(map("can_set_spawn", "never", "can_sleep", "when_dark", "destroy_on_leave", true,
"error_message", map("translate", "block.minecraft.bed.no_sleep")), PLAIN);
assertEquals(BedRule.Rule.WHEN_DARK, r.canSleep());
assertEquals(BedRule.Rule.NEVER, r.canSetSpawn());
assertFalse(r.destroyOnUse());
assertTrue(r.destroyOnLeave());
assertTrue(r.errorMessage().isPresent());
BedRule plain = TYPES.bedRule().decode(map("can_set_spawn", "always", "can_sleep", "always"), PLAIN);
assertTrue(plain.errorMessage().isEmpty());
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "always"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "always", "can_set_spawn", "always", "nope", 1), PLAIN));
}
@Test
void simpleTypesDecode() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, TYPES.moonPhase().decode("new_moon", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("blue_moon", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("minecraft:idle", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("idle", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("Not Valid", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode(3, PLAIN));
assertEquals("expected an identifier, not a tag, got \"#minecraft:logs\"",
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("#minecraft:logs", PLAIN)).getMessage());
assertEquals(Either.left(RegistryKey.parse("minecraft:stone")), TYPES.identifierOrTag().decode("stone", PLAIN));
assertEquals(Either.right(TagKey.parse("#minecraft:logs")), TYPES.identifierOrTag().decode("#logs", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifierOrTag().decode("#", PLAIN));
}
@Test
void particleDecode() throws DecodeException {
RawValue p = TYPES.particle().decode(map("type", "minecraft:dripping_dripstone_lava"), PLAIN);
assertEquals(new RawValue(map("type", "minecraft:dripping_dripstone_lava")), p);
assertThrows(DecodeException.class, () -> TYPES.particle().decode(map("color", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.particle().decode("minecraft:flame", PLAIN));
}
@Test
void intProviderDecode() throws DecodeException {
IntProviderValue c = TYPES.intProvider().decode(7, PLAIN);
assertEquals(7, c.constant().getAsInt());
assertTrue(c.provider().isEmpty());
IntProviderValue p = TYPES.intProvider().decode(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3), PLAIN);
assertTrue(p.constant().isEmpty());
assertTrue(p.provider().isPresent());
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode("x", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(1.5, PLAIN));
}
@Test
void overrideArgumentDecodesWithValueDecoder() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, mod(TYPES.moonPhase(), Operation.OVERRIDE, MoonPhase.FULL_MOON, "new_moon"));
}
@Test
void nestedDecodeContext() throws DecodeException {
List<Object> seen = new ArrayList<>();
DecodeContext recording = new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
seen.add(raw);
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
return raw;
}
};
Map<String, Object> music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2);
TYPES.backgroundMusic().decode(map("default", music), recording);
assertTrue(seen.contains("minecraft:music.game"), seen.toString());
assertTrue(seen.contains(1), seen.toString());
assertTrue(seen.contains(2), seen.toString());
assertTrue(seen.contains(music), seen.toString());
}
private static DecodeContext referencing(Map<String, Object> targets) {
return new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s));
if(raw instanceof Map<?, ?> m) {
Map<String, Object> out = new LinkedHashMap<>();
m.forEach((k, v) -> out.put((String) k, resolve(v)));
return out;
}
if(raw instanceof List<?> l) return l.stream().map(this::resolve).toList();
return raw;
}
};
}
@Test
void resolveBeforeShape() throws DecodeException {
DecodeContext context = referencing(map(
"@sound", map("sound_id", "minecraft:ambient.cave", "range", 4.0),
"@additions", List.of(map("sound", "minecraft:a", "tick_chance", 0.5), map("sound", "minecraft:b", "tick_chance", 0.25)),
"@provider", map("type", "minecraft:uniform", "min_inclusive", "@min", "max_inclusive", 4),
"@min", 1,
"@flame", "minecraft:flame",
"@message", map("translate", "@key"),
"@key", "block.minecraft.bed.no_sleep"));
AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context);
assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow());
assertEquals(2, sounds.additions().size());
IntProviderValue provider = TYPES.intProvider().decode("@provider", context);
assertEquals(new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 4)),
provider.provider().orElseThrow());
List<AmbientParticle> particles = TYPES.ambientParticles().decode(
List.of(map("particle", map("type", "@flame"), "probability", 0.5)), context);
assertEquals(new RawValue(map("type", "minecraft:flame")), particles.get(0).particle());
BedRule rule = TYPES.bedRule().decode(map("can_sleep", "never", "can_set_spawn", "never", "error_message", "@message"),
context);
assertEquals(new RawValue(map("translate", "block.minecraft.bed.no_sleep")), rule.errorMessage().orElseThrow());
}
@Test
void mapKeysInsideValuesAreNotPreprocessed() throws DecodeException {
DecodeContext context = referencing(map("minecraft:zombie", "minecraft:cow"));
MobSpawnSettings settings = TYPES.mobSpawnSettings().decode(map(
"spawns_by_category", map(),
"spawn_costs", map("minecraft:zombie", map("energy_budget", 1.0, "charge", 0.5))), context);
assertEquals(List.of(RegistryKey.parse("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet()));
}
}
@@ -0,0 +1,99 @@
package attribute.minecraft;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.inject.Injector;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.event.EventManagerImpl;
import com.dfsek.terra.registry.CheckedRegistryImpl;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftAttributesAddonTest {
private static final BaseAddon ADDON = new BaseAddon() {
@Override
public String getID() {
return "minecraft-attributes";
}
@Override
public Version getVersion() {
return null;
}
};
private static final VersionRange ONE = Versions.getVersionRange(Versions.getVersion(1, 0, 0), true, Versions.getVersion(2, 0, 0),
false);
private static Platform platform(EventManager events, AttributeHandle handle) {
return (Platform) Proxy.newProxyInstance(Platform.class.getClassLoader(), new Class<?>[]{ Platform.class },
(proxy, method, args) -> switch(method.getName()) {
case "getEventManager" -> events;
case "getAttributeHandle" -> handle;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static ConfigPack pack(Map<BaseAddon, VersionRange> addons) {
Map<TypeKey<?>, CheckedRegistry<?>> registries = new HashMap<>();
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "addons" -> addons;
case "getOrCreateRegistry" -> registries.computeIfAbsent((TypeKey<?>) args[0],
type -> new CheckedRegistryImpl<>(new OpenRegistryImpl<>(type)));
default -> throw new UnsupportedOperationException(method.getName());
});
}
@Test
void dependentPacksOnly() {
EventManager events = new EventManagerImpl();
AttributeHandle handle = new AttributeHandleImpl();
MinecraftAttributesAddon initializer = new MinecraftAttributesAddon();
Injector<Platform> platformInjector = Injector.get(platform(events, handle));
platformInjector.addExplicitTarget(Platform.class);
platformInjector.inject(initializer);
Injector<BaseAddon> addonInjector = Injector.get(ADDON);
addonInjector.addExplicitTarget(BaseAddon.class);
addonInjector.inject(initializer);
initializer.initialize();
ConfigPack dependent = pack(Map.of(ADDON, ONE));
ConfigPack other = pack(Map.of());
events.callEvent(new ConfigPackPreLoadEvent(dependent, template -> { }));
events.callEvent(new ConfigPackPreLoadEvent(other, template -> { }));
CheckedRegistry<Attribute<?>> registered = dependent.getOrCreateRegistry(Attribute.REGISTRY_TYPE);
assertEquals(79, registered.entries().size());
assertTrue(other.getOrCreateRegistry(Attribute.REGISTRY_TYPE).entries().isEmpty());
Attribute<?> fog = MinecraftAttributes.VISUAL_FOG_COLOR.lookup(registered).orElseThrow();
assertSame(fog, registered.get(fog.getRegistryKey()).orElseThrow());
ConfigPack second = pack(Map.of(ADDON, ONE));
events.callEvent(new ConfigPackPreLoadEvent(second, template -> { }));
assertSame(fog, MinecraftAttributes.VISUAL_FOG_COLOR.lookup(second.getOrCreateRegistry(Attribute.REGISTRY_TYPE)).orElseThrow());
assertEquals(79, handle.attributeCount());
}
}
@@ -0,0 +1,194 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.registry.CheckedRegistryImpl;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
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 MinecraftAttributesTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final List<Attribute<?>> ALL = MinecraftAttributeTable.create(HANDLE);
private static final CheckedRegistry<Attribute<?>> REGISTRY = registry();
private static CheckedRegistry<Attribute<?>> registry() {
CheckedRegistry<Attribute<?>> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE));
ALL.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute));
return registry;
}
private static Attribute<?> byId(String id) {
return REGISTRY.get(RegistryKey.parse(id)).orElseThrow();
}
@SuppressWarnings("unchecked")
private static <T> Attribute<T> typed(String id) {
return (Attribute<T>) byId(id);
}
@Test
void tableOrder() {
assertEquals(MinecraftAttributes.all(), ALL.stream().map(Attribute::key).toList());
int first = ALL.get(0).index();
for(int i = 0; i < ALL.size(); i++) {
assertEquals(first + i, ALL.get(i).index(), ALL.get(i).key().toString());
assertSame(ALL.get(i), REGISTRY.get(ALL.get(i).getRegistryKey()).orElseThrow());
}
assertTrue(HANDLE.attributeCount() >= first + ALL.size());
}
@Test
void scopes() {
Set<String> packOnly = ALL.stream().filter(a -> a.key().getNamespace().equals("minecraft"))
.filter(a -> a.scope() == AttributeScope.PACK_ONLY).map(a -> a.key().toString()).collect(Collectors.toSet());
assertEquals(Set.of("minecraft:gameplay/sky_light_level", "minecraft:gameplay/fast_lava"), packOnly);
for(Attribute<?> a : ALL) {
if(!a.key().getNamespace().equals("terra")) continue;
boolean packWide = a.key().getID().startsWith("dimension/") || a.key().getID().startsWith("world/");
assertEquals(packWide ? AttributeScope.PACK_ONLY : AttributeScope.ANYWHERE, a.scope(), a.key().toString());
}
}
@Test
void terraDefaults() {
assertNull(byId("terra:biome/foliage_color").defaultValue());
assertNull(byId("terra:biome/dry_foliage_color").defaultValue());
assertNull(byId("terra:biome/grass_color").defaultValue());
assertEquals(Color.rgb(0x3f76e4), byId("terra:biome/water_color").defaultValue());
assertEquals(-64, byId("terra:dimension/min_y").defaultValue());
assertEquals(384, byId("terra:dimension/height").defaultValue());
assertEquals(Either.right(TagKey.parse("#minecraft:infiniburn_overworld")),
byId("terra:dimension/infiniburn").defaultValue());
assertEquals(RegistryKey.parse("minecraft:plains"), byId("terra:biome/villager_type").defaultValue());
assertEquals(RegistryKey.parse("minecraft:overworld"), byId("terra:dimension/default_clock").defaultValue());
IntProviderValue light = (IntProviderValue) byId("terra:dimension/monster_spawn_light_level").defaultValue();
assertEquals(Optional.of(new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))),
light.provider());
}
@Test
void rangeValidation() throws Exception {
Attribute<Float> spawn = typed("minecraft:gameplay/creature_world_gen_spawn_probability");
assertEquals(0.5f, spawn.validate(0.5f));
assertThrows(DecodeException.class, () -> spawn.validate(1.0f));
assertThrows(DecodeException.class, () -> spawn.validate(-0.1f));
assertThrows(DecodeException.class, () -> spawn.validate(Float.NaN));
Attribute<Float> unit = typed("minecraft:audio/music_volume");
assertEquals("value 2.0 is outside [0, 1]", assertThrows(DecodeException.class, () -> unit.validate(2f)).getMessage());
Attribute<Float> fogEnd = typed("minecraft:visual/fog_end_distance");
assertThrows(DecodeException.class, () -> fogEnd.validate(-1f));
assertEquals(1e9f, fogEnd.validate(1e9f));
assertEquals(-5f, typed("minecraft:visual/fog_start_distance").validate(-5f));
Attribute<Float> scale = typed("terra:dimension/coordinate_scale");
assertEquals(1f, scale.validate(1f));
assertThrows(DecodeException.class, () -> scale.validate(0f));
Attribute<Integer> light = typed("terra:dimension/monster_spawn_block_light_limit");
assertThrows(DecodeException.class, () -> light.validate(16));
}
@Test
void dimensionGeometry() throws Exception {
for(String id : List.of("terra:dimension/min_y", "terra:dimension/height", "terra:dimension/logical_height")) {
assertEquals(EnumSet.of(Operation.OVERRIDE), byId(id).type().operations(), id);
}
Attribute<Integer> minY = typed("terra:dimension/min_y");
assertEquals(-2032, minY.validate(-2032));
assertThrows(DecodeException.class, () -> minY.validate(-2048));
assertThrows(DecodeException.class, () -> minY.validate(2032));
assertThrows(DecodeException.class, () -> minY.validate(-60));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(16, height.validate(16));
assertThrows(DecodeException.class, () -> height.validate(0));
assertEquals("value 100 is not a multiple of 16", assertThrows(DecodeException.class, () -> height.validate(100)).getMessage());
assertEquals(37, typed("terra:dimension/logical_height").validate(37));
}
@Test
void sanitizeClamps() {
Attribute<Float> sky = typed("minecraft:gameplay/sky_light_level");
assertEquals(15f, sky.sanitize(20f));
assertEquals(0f, sky.sanitize(-3f));
assertEquals(7f, sky.sanitize(7f));
Attribute<Boolean> flag = typed("minecraft:gameplay/can_start_raid");
assertEquals(true, flag.sanitize(true));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(4064, height.sanitize(9999));
}
@Test
void typedKeys() throws ReflectiveOperationException {
Set<AttributeKey<?>> constants = new HashSet<>();
for(Field field : MinecraftAttributes.class.getFields()) {
if(!Modifier.isStatic(field.getModifiers()) || field.getType() != AttributeKey.class) continue;
AttributeKey<?> key = (AttributeKey<?>) field.get(null);
Type argument = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
Class<?> valueClass = (Class<?>) (argument instanceof ParameterizedType p ? p.getRawType() : argument);
Attribute<?> attribute = key.lookup(REGISTRY).orElseThrow(() -> new AssertionError("Not registered: " + key));
assertSame(key, attribute.key(), field.getName());
Object defaultValue = attribute.defaultValue();
if(defaultValue != null) {
assertTrue(valueClass.isInstance(defaultValue),
field.getName() + ": " + defaultValue.getClass() + " is not a " + valueClass);
}
constants.add(key);
}
assertEquals(79, constants.size());
assertEquals(Set.copyOf(MinecraftAttributes.all()), constants);
assertEquals(79, ALL.size());
}
@Test
void typedLookup() {
AttributeKey<Float> lookalike = AttributeKey.parse("minecraft:visual/fog_color");
assertEquals(MinecraftAttributes.VISUAL_FOG_COLOR, lookalike);
assertTrue(lookalike.lookup(REGISTRY).isEmpty());
assertTrue(REGISTRY.get(lookalike.getRegistryKey()).isPresent());
}
@Test
void keyIds() {
for(AttributeKey<?> key : MinecraftAttributes.all()) {
String namespace = key.getRegistryKey().getNamespace();
String path = key.getRegistryKey().getID();
assertTrue(namespace.matches("[a-z0-9_.-]+") && path.matches("[a-z0-9_./-]+"), key.toString());
}
}
}
@@ -0,0 +1,177 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.CardinalLight;
import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
import com.dfsek.terra.addons.attribute.minecraft.Music;
import com.dfsek.terra.addons.attribute.minecraft.Skybox;
import com.dfsek.terra.addons.attribute.minecraft.SoundRef;
import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier;
import com.dfsek.terra.api.registry.key.RegistryKey;
import com.dfsek.terra.api.registry.key.TagKey;
import com.dfsek.terra.api.util.generic.either.Either;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftCodecRoundTripTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final AttributeTypes CORE = HANDLE.types();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final RawValue FLAME = new RawValue(map("type", "minecraft:flame"));
private static final RawValue UNIFORM = new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3));
private static final SoundRef SOUND = new SoundRef(RegistryKey.parse("minecraft:music.game"), OptionalDouble.empty());
private static final SoundRef RANGED_SOUND = new SoundRef(RegistryKey.parse("minecraft:ambient.cave"), OptionalDouble.of(16));
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private record Case<T>(AttributeType<T> type, List<T> values, Map<Operation, List<?>> arguments) { }
private static <T> Case<T> of(AttributeType<T> type, List<T> values, Object... opArgs) {
Map<Operation, List<?>> arguments = new LinkedHashMap<>();
for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List<?>) opArgs[i + 1]);
return new Case<>(type, values, arguments);
}
private static List<Case<?>> cases() {
MobSpawnSettings spawns = new MobSpawnSettings(
Map.of("monster", List.of(
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:zombie"), 95,
new IntProviderValue(OptionalInt.of(4), Optional.empty())),
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:husk"), 5,
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
"ambient", List.of()),
Map.of(RegistryKey.parse("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15)));
return List.of(
of(TYPES.moonPhase(), List.of(MoonPhase.values())),
of(TYPES.bedRule(), List.of(
new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, true, false,
Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep")))),
new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, true, Optional.empty()))),
of(TYPES.particle(), List.of(FLAME, new RawValue(map("type", "minecraft:dust", "color", List.of(1.0, 0.5, 0.0), "scale", 2)))),
of(TYPES.ambientParticles(), List.of(List.of(), List.of(new AmbientParticle(FLAME, 0.025f))),
Operation.APPEND, List.of(List.of(new AmbientParticle(FLAME, 0.5f), new AmbientParticle(FLAME, 1f)))),
of(TYPES.backgroundMusic(), List.of(BackgroundMusic.EMPTY,
new BackgroundMusic(Optional.of(new Music(SOUND, 12000, 24000, true)), Optional.empty(),
Optional.of(new Music(RANGED_SOUND, 0, 1, false))))),
of(TYPES.ambientSounds(), List.of(AmbientSounds.EMPTY,
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.of(new AmbientSounds.Mood(SOUND, 6000, 8, 2.0)),
List.of(new AmbientSounds.Additions(SOUND, 0.0111), new AmbientSounds.Additions(RANGED_SOUND, 0.5))))),
of(TYPES.mobSpawnSettings(), List.of(MobSpawnSettings.EMPTY, spawns),
Operation.OVERLAY, List.of(MobSpawnSettings.EMPTY, spawns)),
of(TYPES.identifier(), List.of(RegistryKey.parse("minecraft:stone"), RegistryKey.parse("my.pack:a/b"))),
of(TYPES.identifierOrTag(), List.<Either<RegistryKey, TagKey>>of(
Either.left(RegistryKey.parse("minecraft:stone")), Either.right(TagKey.parse("#my.pack:logs")))),
of(TYPES.intProvider(), List.of(new IntProviderValue(OptionalInt.of(-4), Optional.empty()),
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
of(CORE.enumType("skybox", Skybox.class), List.of(Skybox.values())),
of(CORE.enumType("cardinal_light", CardinalLight.class), List.of(CardinalLight.values())),
of(CORE.enumType("grass_color_modifier", GrassColorModifier.class), List.of(GrassColorModifier.values())),
of(CORE.enumType("temperature_modifier", TemperatureModifier.class), List.of(TemperatureModifier.values())));
}
private static void assertPlain(Object encoded, String where) {
if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return;
if(encoded instanceof List<?> list) {
for(Object element : list) assertPlain(element, where);
return;
}
if(encoded instanceof Map<?, ?> m) {
m.forEach((k, v) -> {
assertTrue(k instanceof String, where + ": map key " + k + " is not a string");
assertPlain(v, where);
});
return;
}
fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded);
}
private static <T> void assertValuesRoundTrip(Case<T> c) throws DecodeException {
for(T value : c.values()) {
Object encoded = c.type().encode(value);
assertPlain(encoded, c.type().id());
assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded);
}
}
@Test
void everyMinecraftType() throws DecodeException {
for(Case<?> c : cases()) assertValuesRoundTrip(c);
}
@Test
void everyArgument() throws DecodeException {
for(Case<?> c : cases()) {
AttributeType<?> type = c.type();
List<Operation> unsampled = new ArrayList<>(type.operations());
unsampled.remove(Operation.OVERRIDE);
unsampled.removeAll(c.arguments().keySet());
assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled);
Map<Operation, List<?>> arguments = new LinkedHashMap<>(c.arguments());
arguments.put(Operation.OVERRIDE, c.values());
for(Map.Entry<Operation, List<?>> e : arguments.entrySet()) {
for(Object argument : e.getValue()) {
Object encoded = type.encodeArgument(e.getKey(), argument);
assertPlain(encoded, type.id() + " " + e.getKey().getID());
assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN),
type.id() + " " + e.getKey().getID() + " via " + encoded);
}
}
}
}
@Test
void canonicalForms() {
assertEquals("minecraft:stone", TYPES.identifier().encode(RegistryKey.parse("minecraft:stone")));
assertEquals("#minecraft:logs", TYPES.identifierOrTag().encode(Either.right(TagKey.parse("#minecraft:logs"))));
assertEquals("minecraft:stone", TYPES.identifierOrTag().encode(Either.left(RegistryKey.parse("minecraft:stone"))));
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
assertEquals("end", CORE.enumType("skybox", Skybox.class).encode(Skybox.END));
assertEquals(map("type", "minecraft:flame"), TYPES.particle().encode(FLAME));
assertEquals(7, TYPES.intProvider().encode(new IntProviderValue(OptionalInt.of(7), Optional.empty())));
Map<?, ?> plainLoop = (Map<?, ?>) TYPES.ambientSounds().encode(new AmbientSounds(Optional.of(SOUND), Optional.empty(), List.of()));
assertEquals("minecraft:music.game", plainLoop.get("loop"));
Map<?, ?> rangedLoop = (Map<?, ?>) TYPES.ambientSounds().encode(
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.empty(), List.of()));
assertEquals(map("sound_id", "minecraft:ambient.cave", "range", 16.0), rangedLoop.get("loop"));
Map<?, ?> bedRule = (Map<?, ?>) TYPES.bedRule().encode(
new BedRule(BedRule.Rule.NEVER, BedRule.Rule.NEVER, false, false, Optional.empty()));
assertFalse(bedRule.containsKey("error_message"));
}
}