Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Loonium with data-driven structure loot #4639

Open
wants to merge 21 commits into
base: 1.20.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
c3969ac
Add structure detection to Loonium
TheRealWormbo May 7, 2024
d3b2ab5
Datagen for Loonium loot tables
TheRealWormbo May 8, 2024
7cd3bfa
Remove igloo bottom from loot structures
TheRealWormbo May 8, 2024
5d5e216
Adjust loot table definitions
TheRealWormbo May 8, 2024
420f919
Update lexicon description of Loonium
TheRealWormbo May 8, 2024
2807ba6
Expand wand HUD to indicate Loonium structure detection
TheRealWormbo May 9, 2024
37d1686
Datagen for structure-specific Loonium configurations
TheRealWormbo May 9, 2024
39db350
Datagen for and loading of structure-specific Loonium configurations
TheRealWormbo May 10, 2024
3086c97
Loonium uses structure configs and loot
TheRealWormbo May 10, 2024
40c8422
Remove unintended non-Loonium drops from additional mobs
TheRealWormbo May 12, 2024
1f52560
Limit number of spawned mobs around Loonium
TheRealWormbo May 12, 2024
1f2ec79
Loonium-spawned mobs have no instant despawn range
TheRealWormbo May 12, 2024
5d4214d
Fix structure configuration lookup
TheRealWormbo May 13, 2024
18658f4
Apply bonuses to additionally spawned Loonium mobs
TheRealWormbo May 17, 2024
6903b3d
General Loonium structure config cleanup
TheRealWormbo May 18, 2024
0ec339e
Add equipment table support to Loonium
TheRealWormbo May 20, 2024
afca0bf
Fix spawned mobs suffocating and add spawn effect to flower
TheRealWormbo May 24, 2024
20814da
Actually consume the configured amount of mana
TheRealWormbo May 24, 2024
e9df32d
Loonium mobs are on a team and grant an advancement
TheRealWormbo May 30, 2024
1c516fd
Hint at Loonium item exclusion list in lexicon description
TheRealWormbo Jun 17, 2024
39cc716
Code style improvements and review findings
TheRealWormbo Aug 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import vazkii.botania.common.brew.BotaniaBrews;
import vazkii.botania.common.brew.BotaniaMobEffects;
import vazkii.botania.common.command.SkyblockCommand;
import vazkii.botania.common.config.ConfigDataManager;
import vazkii.botania.common.crafting.BotaniaRecipeTypes;
import vazkii.botania.common.entity.BotaniaEntities;
import vazkii.botania.common.entity.GaiaGuardianEntity;
Expand Down Expand Up @@ -138,6 +139,7 @@ public void onInitialize() {
PatchouliAPI.get().registerMultiblock(prefix("gaia_ritual"), GaiaGuardianEntity.ARENA_MULTIBLOCK.get());

OrechidManager.registerListener();
ConfigDataManager.registerListener();
CraftyCrateBlockEntity.registerListener();
CorporeaNodeDetectors.register(new FabricTransferCorporeaNodeDetector());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
import vazkii.botania.common.brew.BotaniaMobEffects;
import vazkii.botania.common.brew.effect.SoulCrossMobEffect;
import vazkii.botania.common.command.SkyblockCommand;
import vazkii.botania.common.config.ConfigDataManager;
import vazkii.botania.common.crafting.BotaniaRecipeTypes;
import vazkii.botania.common.entity.BotaniaEntities;
import vazkii.botania.common.entity.GaiaGuardianEntity;
Expand Down Expand Up @@ -166,6 +167,7 @@ public void commonSetup(FMLCommonSetupEvent evt) {
PatchouliAPI.get().registerMultiblock(prefix("gaia_ritual"), GaiaGuardianEntity.ARENA_MULTIBLOCK.get());

OrechidManager.registerListener();
ConfigDataManager.registerListener();
CraftyCrateBlockEntity.registerListener();
CorporeaNodeDetectors.register(new ForgeCapCorporeaNodeDetector());
if (ModList.get().isLoaded("inventorysorter")) {
Expand Down
9 changes: 9 additions & 0 deletions Xplat/src/main/java/vazkii/botania/api/BotaniaAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import vazkii.botania.api.corporea.CorporeaNodeDetector;
import vazkii.botania.api.internal.DummyManaNetwork;
import vazkii.botania.api.internal.ManaNetwork;
import vazkii.botania.common.config.ConfigDataManager;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(forgive me if this changes in a later commit)

I don't think you can import a non-api class in the api. Someone depending on just the API wouldn't be able to call this method anyway.

Also, i'm not entirely clear on the purpose of this method. From what i can tell, the api impl starts with an instance of the config manager, and another instance is registered as a listener from the class itself. Then, whenever data is reloaded, setConfigData is called with that instance, which has the correct data. But, the instance stays there and doesn't need to be set again on next reload, so this all just seems a bit weird.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, right. Probably need to extract an API interface for the ConfigDataManager to use in those methods.

The way data pack reloading (for vanilla, and also for this) works is as follows: The game starts without any loaded data, which is an empty accessible instance of the data manager. When data packs are reloaded, a new instance (not yet accessible outside the loading logic) is created, and when loading is done, that instance replaces the previous accessible one.

I'm not sure if there's any better place to put this, but BotaniaAPI seemed like a good place for the method that returns the currently valid config data instance. I'm also not quite sure if the setter should be publicly accessible, but I couldn't figure out a clean way to set the instance to return.


import java.util.Collections;
import java.util.Map;
Expand Down Expand Up @@ -216,4 +217,12 @@ default void sparkleFX(Level world, double x, double y, double z, float r, float
default void registerCorporeaNodeDetector(CorporeaNodeDetector detector) {

}

default ConfigDataManager getConfigData() {
return null;
}

default void setConfigData(ConfigDataManager configDataManager) {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,35 +20,42 @@
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import vazkii.botania.api.BotaniaAPI;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

public class LooniumStructureConfiguration {
public static final Codec<LooniumStructureConfiguration> CODEC = RecordCodecBuilder.create(
instance -> instance.group(
ExtraCodecs.POSITIVE_INT.fieldOf("manaCost").forGetter(o -> o.manaCost),
StructureSpawnOverride.BoundingBoxType.CODEC.fieldOf("boundingBoxType").forGetter(o -> o.boundingBoxType),
WeightedRandomList.codec(MobSpawnData.CODEC).fieldOf("spawnedMobs").forGetter(o -> o.spawnedMobs),
Codec.list(MobAttributeModifier.CODEC).fieldOf("attributeModifiers").forGetter(o -> o.attributeModifiers),
Codec.list(MobEffectToApply.CODEC).fieldOf("effectsToApply").forGetter(o -> o.effectsToApply)
).apply(instance, LooniumStructureConfiguration::new)
);
public static final Codec<LooniumStructureConfiguration> OPTIONAL_CODEC = RecordCodecBuilder.create(
instance -> instance.group(
ResourceLocation.CODEC.fieldOf("parent").forGetter(o -> o.parent),
ExtraCodecs.POSITIVE_INT.optionalFieldOf("manaCost").forGetter(o -> Optional.ofNullable(o.manaCost)),
StructureSpawnOverride.BoundingBoxType.CODEC.optionalFieldOf("boundingBoxType")
.forGetter(o -> Optional.ofNullable(o.boundingBoxType)),
WeightedRandomList.codec(MobSpawnData.CODEC).optionalFieldOf("spawnedMobs")
.forGetter(o -> Optional.ofNullable(o.spawnedMobs)),
Codec.list(MobAttributeModifier.CODEC).optionalFieldOf("attributeModifiers")
.forGetter(o -> Optional.ofNullable(o.attributeModifiers)),
Codec.list(MobEffectToApply.CODEC).optionalFieldOf("effectsToApply")
.forGetter(o -> Optional.ofNullable(o.effectsToApply))
).apply(instance, LooniumStructureConfiguration::new)
);
public static final Codec<LooniumStructureConfiguration> CODEC = ExtraCodecs.validate(
RecordCodecBuilder.create(
instance -> instance.group(
ResourceLocation.CODEC.optionalFieldOf("parent")
.forGetter(lsc -> Optional.ofNullable(lsc.parent)),
ExtraCodecs.POSITIVE_INT.optionalFieldOf("manaCost")
.forGetter(lsc -> Optional.ofNullable(lsc.manaCost)),
StructureSpawnOverride.BoundingBoxType.CODEC.optionalFieldOf("boundingBoxType")
.forGetter(lsc -> Optional.ofNullable(lsc.boundingBoxType)),
WeightedRandomList.codec(MobSpawnData.CODEC).optionalFieldOf("spawnedMobs")
.forGetter(lsc -> Optional.ofNullable(lsc.spawnedMobs)),
Codec.list(MobAttributeModifier.CODEC).optionalFieldOf("attributeModifiers")
.forGetter(lsc -> Optional.ofNullable(lsc.attributeModifiers)),
Codec.list(MobEffectToApply.CODEC).optionalFieldOf("effectsToApply")
.forGetter(lsc -> Optional.ofNullable(lsc.effectsToApply))
).apply(instance, LooniumStructureConfiguration::new)
), lsc -> {
if (lsc.parent == null && (lsc.manaCost == null || lsc.boundingBoxType == null || lsc.spawnedMobs == null)) {
return DataResult.error(() -> "Mana cost, bounding box type, and spawned mobs must be specified if there is no parent configuration");
}
if (lsc.spawnedMobs != null && lsc.spawnedMobs.isEmpty()) {
return DataResult.error(() -> "Spawned mobs cannot be empty");
}
return DataResult.success(lsc);
});
public static final ResourceLocation DEFAULT_CONFIG_ID = new ResourceLocation(BotaniaAPI.MODID, "default");

public final Integer manaCost;
public final StructureSpawnOverride.BoundingBoxType boundingBoxType;
Expand All @@ -74,20 +81,34 @@ public LooniumStructureConfiguration(ResourceLocation parent, @Nullable Integer
this.parent = parent;
}

private LooniumStructureConfiguration(ResourceLocation parent, Optional<Integer> manaCost,
private LooniumStructureConfiguration(Optional<ResourceLocation> parent, Optional<Integer> manaCost,
Optional<StructureSpawnOverride.BoundingBoxType> boundingBoxType,
Optional<WeightedRandomList<MobSpawnData>> spawnedMobs,
Optional<List<MobAttributeModifier>> attributeModifiers,
Optional<List<MobEffectToApply>> effectsToApply) {
this(manaCost.orElse(null), boundingBoxType.orElse(null), spawnedMobs.orElse(null),
attributeModifiers.orElse(null), effectsToApply.orElse(null));
this(parent.orElse(null), manaCost.orElse(null), boundingBoxType.orElse(null),
spawnedMobs.orElse(null), attributeModifiers.orElse(null), effectsToApply.orElse(null));
}

public LooniumStructureConfiguration(ResourceLocation parent,
StructureSpawnOverride.BoundingBoxType boundingBoxType) {
this(parent, null, boundingBoxType, null, null, null);
}

public LooniumStructureConfiguration getEffectiveConfig(
Function<ResourceLocation, LooniumStructureConfiguration> parentSupplier) {
if (parent == null) {
return this;
}
var parentConfig = parentSupplier.apply(parent).getEffectiveConfig(parentSupplier);

return new LooniumStructureConfiguration(manaCost != null ? manaCost : parentConfig.manaCost,
boundingBoxType != null ? boundingBoxType : parentConfig.boundingBoxType,
spawnedMobs != null ? spawnedMobs : parentConfig.spawnedMobs,
attributeModifiers != null ? attributeModifiers : parentConfig.attributeModifiers,
effectsToApply != null ? effectsToApply : parentConfig.effectsToApply);
}

public static class MobSpawnData extends WeightedEntry.IntrusiveBase {
public static final Codec<MobSpawnData> CODEC = RecordCodecBuilder.create(
instance -> instance.group(
Expand Down Expand Up @@ -216,6 +237,11 @@ private MobEffectToApply(MobEffect effect, Optional<Integer> optionalDuration, O
this(effect, optionalDuration.orElse(MobEffectInstance.INFINITE_DURATION), optionalAmplifier.orElse(0));
}

@NotNull
public MobEffectInstance createMobEffectInstance() {
return new MobEffectInstance(effect, duration, amplifier);
}

private Optional<Integer> getOptionalDuration() {
return duration != MobEffectInstance.INFINITE_DURATION ? Optional.of(duration) : Optional.empty();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package vazkii.botania.common.config;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;

import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener;
import net.minecraft.util.profiling.ProfilerFiller;

import org.jetbrains.annotations.NotNull;

import vazkii.botania.api.BotaniaAPI;
import vazkii.botania.api.configdata.LooniumStructureConfiguration;
import vazkii.botania.xplat.XplatAbstractions;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

import static vazkii.botania.common.lib.ResourceLocationHelper.prefix;

public class ConfigDataManager implements PreparableReloadListener {
public static void registerListener() {
XplatAbstractions.INSTANCE.registerReloadListener(PackType.SERVER_DATA, prefix("configdata"), new ConfigDataManager());
}

private final Map<ResourceLocation, LooniumStructureConfiguration> looniumConfigs = new HashMap<>();

public LooniumStructureConfiguration getEffectiveLooniumStructureConfiguration(ResourceLocation id) {
LooniumStructureConfiguration configuration = this.looniumConfigs.get(id);
return configuration != null ? configuration.getEffectiveConfig(looniumConfigs::get) : null;
}

private static void validateLooniumConfig(Map<ResourceLocation, LooniumStructureConfiguration> map) {
Set<ResourceLocation> errorEntries = new HashSet<>();
Set<ResourceLocation> visitedEntries = new LinkedHashSet<>();
do {
errorEntries.clear();
for (var entry : map.entrySet()) {
ResourceLocation id = entry.getKey();
ResourceLocation parent = entry.getValue().parent;
if (id.equals(parent)) {
BotaniaAPI.LOGGER.warn("Ignoring Loonium structure configuration, because it specified itself as parent: {}", id);
errorEntries.add(id);
} else {
visitedEntries.clear();
if (!findTopmostParent(map, id, parent, visitedEntries)) {
BotaniaAPI.LOGGER.warn("Ignoring Loonium structure configuration(s) without top-most parent: {}", visitedEntries);
errorEntries.addAll(visitedEntries);
break;
}
}
}
errorEntries.forEach(map::remove);
} while (!errorEntries.isEmpty() && !map.isEmpty());

if (!map.containsKey(LooniumStructureConfiguration.DEFAULT_CONFIG_ID)) {
BotaniaAPI.LOGGER.error("Default Loonium configuration not found!");
}
}

private static boolean findTopmostParent(Map<ResourceLocation, LooniumStructureConfiguration> map,
ResourceLocation id, ResourceLocation parent, Set<ResourceLocation> visitedEntries) {
if (!visitedEntries.add(id)) {
BotaniaAPI.LOGGER.warn("Cyclic dependency between Loonium structure configurations detected: {}", visitedEntries);
return false;
}
if (parent == null) {
return true;
}
var parentConfig = map.get(parent);
return parentConfig != null && findTopmostParent(map, parent, parentConfig.parent, visitedEntries);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From what i can see, specifying a missing ID as the parent, will lead to the Ignoring Loonium structure configuration(s) without top-most parent error message. Or is that caught earlier? If not, maybe we should have an error specifically for that also

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The config loading logic should be validating that any specified parent ID actually exists.

}

private void applyLooniumConfig(Map<ResourceLocation, LooniumStructureConfiguration> looniumConfigs) {
this.looniumConfigs.putAll(looniumConfigs);
}

@NotNull
@Override
public CompletableFuture<Void> reload(@NotNull PreparationBarrier barrier, @NotNull ResourceManager manager,
@NotNull ProfilerFiller prepProfiler, @NotNull ProfilerFiller reloadProfiler,
@NotNull Executor backgroundExecutor, @NotNull Executor gameExecutor) {
var looniumTask = scheduleConfigParse(barrier, manager, backgroundExecutor, gameExecutor, ConfigDataType.LOONUIM);

return CompletableFuture.allOf(looniumTask).thenRun(() -> BotaniaAPI.instance().setConfigData(this));
}

private <T> CompletableFuture<Void> scheduleConfigParse(PreparationBarrier barrier, ResourceManager manager,
Executor backgroundExecutor, Executor gameExecutor, ConfigDataType<T> type) {
return CompletableFuture.supplyAsync(() -> {
Map<ResourceLocation, JsonElement> resourceMap = new HashMap<>();
SimpleJsonResourceReloadListener.scanDirectory(manager, "config/" + type.directory, new Gson(), resourceMap);
Map<ResourceLocation, T> configs = new HashMap<>(resourceMap.size());
resourceMap.forEach((id, jsonElement) -> type.codec.parse(JsonOps.INSTANCE, jsonElement).result().ifPresent(c -> configs.put(id, c)));
type.validateFunction.accept(configs);
return configs;
}, backgroundExecutor)
.thenCompose(barrier::wait)
.thenAcceptAsync(c -> type.applyFunction.accept(this, c), gameExecutor);
}

private record ConfigDataType<T> (Codec<T> codec, String directory,
Consumer<Map<ResourceLocation, T>> validateFunction,
BiConsumer<ConfigDataManager, Map<ResourceLocation, T>> applyFunction) {
private static final ConfigDataType<LooniumStructureConfiguration> LOONUIM =
new ConfigDataType<>(LooniumStructureConfiguration.CODEC, "loonium",
ConfigDataManager::validateLooniumConfig, ConfigDataManager::applyLooniumConfig);

}
}
13 changes: 13 additions & 0 deletions Xplat/src/main/java/vazkii/botania/common/impl/BotaniaAPIImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import vazkii.botania.api.internal.ManaNetwork;
import vazkii.botania.client.fx.SparkleParticleData;
import vazkii.botania.common.block.flower.functional.SolegnoliaBlockEntity;
import vazkii.botania.common.config.ConfigDataManager;
import vazkii.botania.common.handler.BotaniaSounds;
import vazkii.botania.common.handler.EquipmentHandler;
import vazkii.botania.common.handler.ManaNetworkHandler;
Expand Down Expand Up @@ -202,6 +203,8 @@ public Ingredient getRepairIngredient() {
}
}

private ConfigDataManager configDataManager = new ConfigDataManager();

@Override
public int apiVersion() {
return 2;
Expand Down Expand Up @@ -291,4 +294,14 @@ public void registerPaintableBlock(ResourceLocation block, Function<DyeColor, Bl
public void registerCorporeaNodeDetector(CorporeaNodeDetector detector) {
CorporeaNodeDetectors.register(detector);
}

@Override
public ConfigDataManager getConfigData() {
return configDataManager;
}

@Override
public void setConfigData(ConfigDataManager configDataManager) {
this.configDataManager = configDataManager;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import static vazkii.botania.common.lib.ResourceLocationHelper.prefix;
import static vazkii.botania.data.LooniumStructureLootProvider.getStructureId;

public class LooniumStructureConfigurationProvider implements DataProvider {
Expand All @@ -50,7 +49,7 @@ public CompletableFuture<?> run(@NotNull CachedOutput cache) {
CompoundTag chargedCreeperNbt = new CompoundTag();
chargedCreeperNbt.putBoolean("powered", true);

ResourceLocation defaultConfigId = prefix("default");
ResourceLocation defaultConfigId = LooniumStructureConfiguration.DEFAULT_CONFIG_ID;
configs.put(defaultConfigId, new LooniumStructureConfiguration(
35000, StructureSpawnOverride.BoundingBoxType.PIECE,
WeightedRandomList.create(
Expand Down Expand Up @@ -101,11 +100,8 @@ public CompletableFuture<?> run(@NotNull CachedOutput cache) {
for (var e : configs.entrySet()) {
Path path = pathProvider.json(e.getKey());
var config = e.getValue();
var jsonTree = (config.parent != null
? LooniumStructureConfiguration.OPTIONAL_CODEC
: LooniumStructureConfiguration.CODEC)
.encodeStart(JsonOps.INSTANCE, config)
.getOrThrow(false, BotaniaAPI.LOGGER::error);
var jsonTree = LooniumStructureConfiguration.CODEC.encodeStart(JsonOps.INSTANCE, config)
.getOrThrow(false, BotaniaAPI.LOGGER::error);
output.add(DataProvider.saveStable(cache, jsonTree, path));
}
return CompletableFuture.allOf(output.toArray(CompletableFuture[]::new));
Expand Down