Replace StructureSpawnListGatherEvent with StructureModifiers (#8717)

This commit is contained in:
Sara Freimer authored and GitHub committed 2022-06-14 12:05:07 -07:00
1 parent 59b8ec5625
commit e386229b66
21 files changed
+863 -378

No files matched your search

@@ -32,6 +32,8 @@ import net.minecraftforge.common.loot.CanToolPerformAction;
import net.minecraftforge.common.loot.LootTableIdCondition;
import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.common.world.NoneBiomeModifier;
import net.minecraftforge.common.world.NoneStructureModifier;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fluids.FluidAttributes;
import net.minecraftforge.fluids.ForgeFlowingFluid;
@@ -93,6 +95,7 @@ public class ForgeMod
private static final DeferredRegister<Attribute> ATTRIBUTES = DeferredRegister.create(ForgeRegistries.Keys.ATTRIBUTES, "forge");
private static final DeferredRegister<ArgumentTypeInfo<?, ?>> COMMAND_ARGUMENT_TYPES = DeferredRegister.create(Registry.COMMAND_ARGUMENT_TYPE_REGISTRY, "forge");
private static final DeferredRegister<Codec<? extends BiomeModifier>> BIOME_MODIFIER_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.BIOME_MODIFIER_SERIALIZERS, "forge");
private static final DeferredRegister<Codec<? extends StructureModifier>> STRUCTURE_MODIFIER_SERIALIZERS = DeferredRegister.create(ForgeRegistries.Keys.STRUCTURE_MODIFIER_SERIALIZERS, "forge");
@SuppressWarnings({ "unchecked", "rawtypes" })
private static final RegistryObject<EnumArgument.Info> ENUM_COMMAND_ARGUMENT_TYPE = COMMAND_ARGUMENT_TYPES.register("enum", () ->
@@ -130,6 +133,10 @@ public class ForgeMod
* Noop biome modifier. Can be used in a biome modifier json with "type": "forge:none".
*/
public static final RegistryObject<Codec<NoneBiomeModifier>> NONE_BIOME_MODIFIER_TYPE = BIOME_MODIFIER_SERIALIZERS.register("none", () -> Codec.unit(NoneBiomeModifier.INSTANCE));
/**
* Noop structure modifier. Can be used in a structure modifier json with "type": "forge:none".
*/
public static final RegistryObject<Codec<NoneStructureModifier>> NONE_STRUCTURE_MODIFIER_TYPE = STRUCTURE_MODIFIER_SERIALIZERS.register("none", () -> Codec.unit(NoneStructureModifier.INSTANCE));
private static boolean enableMilkFluid = false;
@@ -177,6 +184,7 @@ public class ForgeMod
ATTRIBUTES.register(modEventBus);
COMMAND_ARGUMENT_TYPES.register(modEventBus);
BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
MinecraftForge.EVENT_BUS.addListener(this::serverStopping);
MinecraftForge.EVENT_BUS.addListener(this::missingSoundMapping);
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, ForgeConfig.clientSpec);
@@ -0,0 +1,130 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.data;
import com.mojang.logging.LogUtils;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Map;
import com.google.gson.JsonElement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.JsonOps;
import java.util.function.BiConsumer;
import cpw.mods.modlauncher.api.LamdbaExceptionUtils;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.RegistryOps;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraftforge.common.data.ExistingFileHelper.ResourceType;
import net.minecraftforge.forge.event.lifecycle.GatherDataEvent;
import org.slf4j.Logger;
/**
* <p>Dataprovider for using a Codec to generate jsons.
* Path names for jsons are derived from the given registry folder and each entry's namespaced id, in the format:</p>
* <pre>
* {@code <assets/data>/entryid/registryfolder/entrypath.json }
* </pre>
*
* @param <T> the type of thing being generated.
*/
public final class JsonCodecProvider<T> implements DataProvider
{
private static final Logger LOGGER = LogUtils.getLogger();
protected final DataGenerator dataGenerator;
protected final ExistingFileHelper existingFileHelper;
protected final String modid;
protected final DynamicOps<JsonElement> dynamicOps;
protected final PackType packType;
protected final String directory;
protected final Codec<T> codec;
protected final Map<ResourceLocation, T> entries;
/**
* @param dataGenerator DataGenerator provided by {@link GatherDataEvent}.
* @param dynamicOps DynamicOps to encode values to jsons with using the provided Codec, e.g. {@link JsonOps.INSTANCE}.
* @param packType PackType specifying whether to generate entries in assets or data.
* @param directory String representing the directory to generate jsons in, e.g. "dimension" or "cheesemod/cheese".
* @param codec Codec to encode values to jsons with using the provided DynamicOps.
* @param entries Map of named entries to serialize to jsons. Paths for values are derived from the ResourceLocation's entryid:entrypath as specified above.
*/
public JsonCodecProvider(DataGenerator dataGenerator, ExistingFileHelper existingFileHelper, String modid, DynamicOps<JsonElement> dynamicOps, PackType packType,
String directory, Codec<T> codec, Map<ResourceLocation, T> entries)
{
// Track generated data so other dataproviders can validate if needed.
final ResourceType resourceType = new ResourceType(packType, ".json", directory);
for (ResourceLocation id : entries.keySet())
{
existingFileHelper.trackGenerated(id, resourceType);
}
this.dataGenerator = dataGenerator;
this.existingFileHelper = existingFileHelper;
this.modid = modid;
this.dynamicOps = dynamicOps;
this.packType = packType;
this.directory = directory;
this.codec = codec;
this.entries = entries;
}
/**
* {@return DatapackRegistryProvider that encodes using the registered loading codec for the provided registry key}
* Ensures the correct directory and codec are used.
* Only vanilla datapack registries enumerated in {@link RegistryAccess} and custom forge datapack registries can
* be generated this way.
*
* @param <T> Registry element type, e.g. Biome
* @param dataGenerator DataGenerator provided by {@link GatherDataEvent}.
* @param modid namespace of the mod adding this DataProvider, for logging purposes.
* @param registryOps RegistryOps to encode values to json with.
* @param registryKey ResourceKey identifying the registry and its directory.
* @param entries Map of entries to encode and their ResourceLocations. Paths for values are derived from the ResourceLocation's entryid:entrypath.
*/
public static <T> JsonCodecProvider<T> forDatapackRegistry(DataGenerator dataGenerator, ExistingFileHelper existingFileHelper, String modid,
RegistryOps<JsonElement> registryOps, ResourceKey<Registry<T>> registryKey, Map<ResourceLocation, T> entries)
{
final ResourceLocation registryId = registryKey.location();
// Minecraft datapack registry folders are in data/json-namespace/registry-name/
// Non-vanilla registry folders are data/json-namespace/registry-namespace/registry-name/
final String registryFolder = registryId.getNamespace().equals("minecraft")
? registryId.getPath()
: registryId.getNamespace() + "/" + registryId.getPath();
final Codec<T> codec = (Codec<T>) RegistryAccess.REGISTRIES.get(registryKey).codec();
return new JsonCodecProvider<>(dataGenerator, existingFileHelper, modid, registryOps, PackType.SERVER_DATA, registryFolder, codec, entries);
}
@Override
public void run(final CachedOutput cache) throws IOException
{
final Path outputFolder = this.dataGenerator.getOutputFolder();
final String dataFolder = this.packType.getDirectory();
gather(LamdbaExceptionUtils.rethrowBiConsumer((id, value) -> {
final Path path = outputFolder.resolve(String.join("/", dataFolder, id.getNamespace(), this.directory, id.getPath() + ".json"));
JsonElement encoded = this.codec.encodeStart(this.dynamicOps, value)
.getOrThrow(false, msg -> LOGGER.error("Failed to encode {}: {}", path, msg));
DataProvider.saveStable(cache, encoded, path);
}));
}
protected void gather(BiConsumer<ResourceLocation, T> consumer)
{
this.entries.forEach(consumer);
}
@Override
public String getName()
{
return String.format("%s generator for %s", this.directory, this.modid);
}
}
@@ -37,7 +37,6 @@ public interface BiomeModifier
* Codec for (de)serializing biome modifiers inline.
* Mods can use this for data generation.
*/
@SuppressWarnings("unchecked")
Codec<BiomeModifier> DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.BIOME_MODIFIER_SERIALIZERS.get().getCodec())
.dispatch(BiomeModifier::codec, Function.identity());
@@ -0,0 +1,128 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
import java.util.List;
import java.util.Locale;
import net.minecraft.core.Holder;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.Structure.StructureSettings;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Holds lazy-evaluable modified structure info.
* Memoizers are not used because it's important to return null
* without evaluating the structure info if it's accessed outside of a server context.
*/
public class ModifiableStructureInfo
{
@NotNull
private final StructureInfo originalStructureInfo;
@Nullable
private StructureInfo modifiedStructureInfo = null;
/**
* @param originalStructureInfo StructureInfo representing the original state of a structure when the structure was constructed.
*/
public ModifiableStructureInfo(@NotNull final StructureInfo originalStructureInfo)
{
this.originalStructureInfo = originalStructureInfo;
}
/**
* {@return The modified structure info if modified structure info has been generated, otherwise gets original structure info}
*/
@NotNull
public StructureInfo get()
{
return this.modifiedStructureInfo == null
? originalStructureInfo
: modifiedStructureInfo;
}
/**
* {@return The original structure info that the associated structure was created with}
*/
@NotNull
public StructureInfo getOriginalStructureInfo()
{
return this.originalStructureInfo;
}
/**
* {@return Modified structure info; null if it hasn't been set yet}
*/
@Nullable
public StructureInfo getModifiedStructureInfo()
{
return this.modifiedStructureInfo;
}
/**
* Internal forge method; the game will crash if mods invoke this.
* Creates and caches the modified structure info.
* @param structure named structure with original data.
* @param structureModifiers structure modifiers to apply.
*
* @throws IllegalStateException if invoked more than once.
*/
@ApiStatus.Internal
public void applyStructureModifiers(final Holder<Structure> structure, final List<StructureModifier> structureModifiers)
{
if (this.modifiedStructureInfo != null)
throw new IllegalStateException(String.format(Locale.ENGLISH, "Structure %s already modified", structure));
StructureInfo original = this.getOriginalStructureInfo();
final StructureInfo.Builder builder = StructureInfo.Builder.copyOf(original);
for (StructureModifier.Phase phase : StructureModifier.Phase.values())
{
for (StructureModifier modifier : structureModifiers)
{
modifier.modify(structure, phase, builder);
}
}
this.modifiedStructureInfo = builder.build();
}
/**
* Record containing raw structure data.
* @param structureSettings Structure settings.
*/
public record StructureInfo(StructureSettings structureSettings)
{
public static class Builder
{
private StructureSettingsBuilder structureSettings;
/**
* @param original Original structure information
* @return A ModifiedStructureInfo.StructureInfo.Builder with a copy of the structure's data
*/
public static Builder copyOf(final StructureInfo original)
{
final StructureSettingsBuilder structureBuilder = StructureSettingsBuilder.copyOf(original.structureSettings());
return new Builder(structureBuilder);
}
private Builder(final StructureSettingsBuilder structureSettings)
{
this.structureSettings = structureSettings;
}
public StructureInfo build()
{
return new StructureInfo(this.structureSettings.build());
}
public StructureSettingsBuilder getStructureSettings()
{
return structureSettings;
}
}
}
}
@@ -0,0 +1,29 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
import com.mojang.serialization.Codec;
import net.minecraft.core.Holder;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo.Builder;
public class NoneStructureModifier implements StructureModifier
{
public static final NoneStructureModifier INSTANCE = new NoneStructureModifier();
@Override
public void modify(Holder<Structure> structure, Phase phase, Builder builder)
{
// NOOP - intended for datapack makers who want to disable a structure modifier
}
@Override
public Codec<? extends StructureModifier> codec()
{
return ForgeMod.NONE_STRUCTURE_MODIFIER_TYPE.get();
}
}
@@ -0,0 +1,94 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
import com.mojang.serialization.Codec;
import java.util.function.Function;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.RegistryCodecs;
import net.minecraft.resources.RegistryFileCodec;
import net.minecraft.resources.RegistryOps;
import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraftforge.common.world.ModifiableStructureInfo.StructureInfo;
import net.minecraftforge.registries.ForgeRegistries;
/**
* JSON-serializable structure modifier.
* Requires a {@link Codec} to deserialize structure modifiers from structure modifier jsons.
* <p>
* Structure modifier jsons have the following json format:
* <pre>
* {
* "type": "yourmod:yourserializer", // Indicates a registered structure modifier serializer
* // Additional fields can be specified here according to the codec
* }
* </pre>
* <p>
* Datapacks can also disable a structure modifier by overriding the json and using {@code "type": "forge:none"}.</p>
*/
public interface StructureModifier
{
/**
* Codec for (de)serializing structure modifiers inline.
* Mods can use this for data generation.
*/
Codec<StructureModifier> DIRECT_CODEC = ExtraCodecs.lazyInitializedCodec(() -> ForgeRegistries.STRUCTURE_MODIFIER_SERIALIZERS.get().getCodec())
.dispatch(StructureModifier::codec, Function.identity());
/**
* Codec for referring to structure modifiers by id in other datapack registry files.
* Can only be used with {@link RegistryOps}.
*/
Codec<Holder<StructureModifier>> REFERENCE_CODEC = RegistryFileCodec.create(ForgeRegistries.Keys.STRUCTURE_MODIFIERS, DIRECT_CODEC);
/**
* Codec for referring to structure modifiers by id, list of id, or tags.
* Can only be used with {@link RegistryOps}.
*/
Codec<HolderSet<StructureModifier>> LIST_CODEC = RegistryCodecs.homogeneousList(ForgeRegistries.Keys.STRUCTURE_MODIFIERS, DIRECT_CODEC);
/**
* Modifies the information via the provided structure builder.
* Allows mob spawns and world-gen features to be added or removed,
* and climate and client effects to be modified.
*
* @param structure the named structure being modified (with original data readable).
* @param phase structure modification phase. Structure modifiers apply in each phase in order of the enum constants.
* @param builder mutable structure info builder. Apply changes to this.
*/
void modify(Holder<Structure> structure, Phase phase, StructureInfo.Builder builder);
/**
* @return the codec which serializes and deserializes this structure modifier
*/
Codec<? extends StructureModifier> codec();
enum Phase
{
/**
* Catch-all for anything that needs to run before standard phases.
*/
BEFORE_EVERYTHING,
/**
* Additional mob spawns, etc.
*/
ADD,
/**
* Removal of mob spawns, etc.
*/
REMOVE,
/**
* Alteration of values.
*/
MODIFY,
/**
* Catch-all for anything that needs to run after standard phases.
*/
AFTER_EVERYTHING
}
}
@@ -0,0 +1,200 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import net.minecraft.core.HolderSet;
import net.minecraft.util.random.WeightedRandomList;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.structure.Structure.StructureSettings;
import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride;
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
import org.jetbrains.annotations.Nullable;
public class StructureSettingsBuilder
{
private HolderSet<Biome> biomes;
private final Map<MobCategory, StructureSpawnOverrideBuilder> spawnOverrides;
private GenerationStep.Decoration step;
private TerrainAdjustment terrainAdaptation;
/**
* @param settings Existing StructureSettings.
* @return A new builder with a copy of that StructureSettings's values.
*/
public static StructureSettingsBuilder copyOf(StructureSettings settings)
{
return new StructureSettingsBuilder(settings.biomes(), settings.spawnOverrides(), settings.step(), settings.terrainAdaptation());
}
private StructureSettingsBuilder(HolderSet<Biome> biomes, Map<MobCategory, StructureSpawnOverride> spawnOverrides, GenerationStep.Decoration step, TerrainAdjustment terrainAdaptation)
{
this.biomes = biomes;
this.spawnOverrides = spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> StructureSpawnOverrideBuilder.copyOf(entry.getValue())));
this.step = step;
this.terrainAdaptation = terrainAdaptation;
}
/**
* @return A new StructureSettings with the finalized values.
*/
public StructureSettings build()
{
Map<MobCategory, StructureSpawnOverride> overrides = Collections.unmodifiableMap(
this.spawnOverrides.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().build()))
);
return new StructureSettings(this.biomes, overrides, this.step, this.terrainAdaptation);
}
public HolderSet<Biome> getBiomes()
{
return biomes;
}
public void setBiomes(HolderSet<Biome> biomes)
{
this.biomes = biomes;
}
/**
* Gets a mutable builder for the spawn overrides of a given mob category or {@code null} if no overrides are defined for that category.
* @param category Mob category
*/
@Nullable
public StructureSpawnOverrideBuilder getSpawnOverrides(MobCategory category)
{
return spawnOverrides.get(category);
}
/**
* Gets or creates a mutable builder for the spawn overrides of a given mob category. If the override needed to be created it will default to piece bounding.
* @param category Mob category
*/
public StructureSpawnOverrideBuilder getOrAddSpawnOverrides(MobCategory category)
{
return spawnOverrides.computeIfAbsent(category, c -> new StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType.PIECE, Collections.emptyList()));
}
/**
* Removes the spawn overrides for the given mob category.
* @param category Mob category
*/
public void removeSpawnOverrides(MobCategory category)
{
this.spawnOverrides.remove(category);
}
/**
* Gets the world generation decoration step the structure spawns during.
*/
public GenerationStep.Decoration getDecorationStep()
{
return step;
}
/**
* Sets the world generation decoration step the structure spawns during.
*/
public void setDecorationStep(GenerationStep.Decoration step)
{
this.step = step;
}
/**
* Gets the way the structure adapts to the terrain during generation.
*/
public TerrainAdjustment getTerrainAdaptation()
{
return terrainAdaptation;
}
/**
* Sets the way the structure adapts to the terrain during generation.
* @param terrainAdaptation New terrain adjustment
*/
public void setTerrainAdaptation(TerrainAdjustment terrainAdaptation)
{
this.terrainAdaptation = terrainAdaptation;
}
public static class StructureSpawnOverrideBuilder
{
private StructureSpawnOverride.BoundingBoxType boundingBox;
private final List<MobSpawnSettings.SpawnerData> spawns;
private final List<MobSpawnSettings.SpawnerData> spawnsView;
/**
* @param override Existing spawn override data.
* @return A new builder with a copy of that StructureSpawnOverride's values.
*/
public static StructureSpawnOverrideBuilder copyOf(StructureSpawnOverride override)
{
return new StructureSpawnOverrideBuilder(override.boundingBox(), override.spawns().unwrap());
}
private StructureSpawnOverrideBuilder(StructureSpawnOverride.BoundingBoxType boundingBox, List<MobSpawnSettings.SpawnerData> spawns)
{
this.boundingBox = boundingBox;
this.spawns = new ArrayList<>(spawns);
this.spawnsView = Collections.unmodifiableList(this.spawns);
}
/**
* Gets the type of bounding box for this structures spawn overrides.
*/
public StructureSpawnOverride.BoundingBoxType getBoundingBox()
{
return boundingBox;
}
/**
* Sets the way the structure checks for spawn overrides. Whether it is on a piece by piece basis or within the bounds of the overall structure.
*/
public void setBoundingBox(StructureSpawnOverride.BoundingBoxType boundingBox)
{
this.boundingBox = boundingBox;
}
/**
* Unmodifiable view of the possible spawns.
*/
public List<MobSpawnSettings.SpawnerData> getSpawns()
{
return spawnsView;
}
/**
* Adds a spawn to the overrides.
*/
public void addSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.add(spawn);
}
/**
* Removes a given spawn from the list of overrides. Use {@link #getSpawns()} to get instances of spawn data to remove.
*/
public void removeSpawn(MobSpawnSettings.SpawnerData spawn)
{
this.spawns.remove(spawn);
}
/**
* @return A new StructureSpawnOverride with the finalized values.
*/
public StructureSpawnOverride build()
{
return new StructureSpawnOverride(boundingBox, WeightedRandomList.create(spawns));
}
}
}
@@ -1,112 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.common.world;
//TODO-PATCHING: Reengineer this with configured features in mind as those are what handle spawning right now.s
/**
* Class to help manage entity spawns inside of structures
* /
public class StructureSpawnManager
{
private static Map<StructureFeature<?>, StructureSpawnInfo> structuresWithSpawns = Collections.emptyMap();
/**
* Gathers potential entity spawns for all the different registered structures.
* @apiNote Internal
* /
public static void gatherEntitySpawns()
{
//We use a linked hash map to ensure that we check the structures in an order that if there are multiple structures a position satisfies
// then we have the same behavior as vanilla as vanilla checks, swamp huts, pillager outposts, ocean monuments, and nether fortresses in
// that order.
Map<StructureFeature<?>, StructureSpawnInfo> structuresWithSpawns = new LinkedHashMap<>();
gatherEntitySpawns(structuresWithSpawns, StructureFeature.SWAMP_HUT);
gatherEntitySpawns(structuresWithSpawns, StructureFeature.PILLAGER_OUTPOST);
gatherEntitySpawns(structuresWithSpawns, StructureFeature.OCEAN_MONUMENT);
gatherEntitySpawns(structuresWithSpawns, StructureFeature.NETHER_BRIDGE);
for (StructureFeature<?> structure : ForgeRegistries.STRUCTURE_FEATURES.getValues())
{
if (structure != StructureFeature.SWAMP_HUT && structure != StructureFeature.PILLAGER_OUTPOST && structure != StructureFeature.OCEAN_MONUMENT &&
structure != StructureFeature.NETHER_BRIDGE)
{
//If we didn't already gather the spawns already to ensure we do vanilla ones already
// gather the spawns for this structure
gatherEntitySpawns(structuresWithSpawns, structure);
}
}
StructureSpawnManager.structuresWithSpawns = structuresWithSpawns;
}
private static void gatherEntitySpawns(Map<StructureFeature<?>, StructureSpawnInfo> structuresWithSpawns, StructureFeature<?> structure)
{
StructureSpawnListGatherEvent event = new StructureSpawnListGatherEvent(structure);
MinecraftForge.EVENT_BUS.post(event);
ImmutableMap.Builder<net.minecraft.world.entity.MobCategory, WeightedRandomList<MobSpawnSettings.SpawnerData>> builder = ImmutableMap.builder();
event.getEntitySpawns().forEach((classification, spawns) -> {
if (!spawns.isEmpty())
builder.put(classification, WeightedRandomList.create(spawns));
});
ImmutableMap<MobCategory, WeightedRandomList<MobSpawnSettings.SpawnerData>> entitySpawns = builder.build();
if (!entitySpawns.isEmpty())
structuresWithSpawns.put(structure, new StructureSpawnInfo(entitySpawns, event.isInsideOnly()));
}
/**
* Looks up if a given position is within a structure and returns any entity spawns that structure has for the given classification, or null if
* none are found.
* @param structureManager Structure Manager, used to check if a position is within a structure.
* @param classification Entity classification
* @param pos Position to get entity spawns of
* /
@Nullable
public static WeightedRandomList<MobSpawnSettings.SpawnerData> getStructureSpawns(StructureFeatureManager structureManager, MobCategory classification, BlockPos pos)
{
for (Entry<StructureFeature<?>, StructureSpawnInfo> entry : structuresWithSpawns.entrySet())
{
StructureFeature<?> structure = entry.getKey();
StructureSpawnInfo spawnInfo = entry.getValue();
//Note: We check if the structure has spawns for a type first before looking at the world as it should be a cheaper check
if (spawnInfo.spawns.containsKey(classification))
{
boolean valid = spawnInfo.insideOnly
? structureManager.getStructureWithPieceAt(pos, structure).isValid()
: structureManager.getStructureAt(pos, structure).isValid();
if (valid)
return spawnInfo.spawns.get(classification);
}
}
return null;
}
/**
* Gets the entity spawn lists for entities of a given classification for a given structure.
* @param structure The Structure
* @param classification The classification to lookup
* /
public static WeightedRandomList<MobSpawnSettings.SpawnerData> getSpawnList(StructureFeature<?> structure, MobCategory classification)
{
StructureSpawnInfo info = structuresWithSpawns.get(structure);
if (info != null)
return info.spawns.getOrDefault(classification, WeightedRandomList.create());
return WeightedRandomList.create();
}
/**
* Helper class to keep track of spawns and if the spawns should be restricted to inside the structure pieces.
* /
private static class StructureSpawnInfo
{
private final Map<MobCategory, WeightedRandomList<MobSpawnSettings.SpawnerData>> spawns;
private final boolean insideOnly;
private StructureSpawnInfo(ImmutableMap<MobCategory, WeightedRandomList<MobSpawnSettings.SpawnerData>> spawns, boolean insideOnly)
{
this.spawns = spawns;
this.insideOnly = insideOnly;
}
}
}
*/
@@ -1,142 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.event.world;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.world.entity.MobCategory;
import net.minecraft.world.level.biome.MobSpawnSettings;
import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.EventPriority;
/**
* This event fires when a Structure is gathering what mobs/creatures can spawn in it.
*
* In order to maintain the most compatibility possible with other mods' modifications to a structure,
* the event should be assigned a {@link net.minecraftforge.eventbus.api.EventPriority} as follows:
*
* - Additions : {@link EventPriority#HIGH}
* - Removals : {@link EventPriority#NORMAL}
* - Any other modification : {@link EventPriority#LOW}
*
* Be aware that another mod could have done an operation beforehand, so an expected value out of a vanilla structure might not
* always be the same, depending on other mods.
*/
public class StructureSpawnListGatherEvent extends Event
{
private final Structure structure;
private final Map<MobCategory, List<MobSpawnSettings.SpawnerData>> entitySpawns = new HashMap<>();
private final Map<MobCategory, List<MobSpawnSettings.SpawnerData>> entitySpawnsUnmodifiableLists = new HashMap<>();
private final Map<MobCategory, List<MobSpawnSettings.SpawnerData>> entitySpawnsUnmodifiable = Collections.unmodifiableMap(entitySpawnsUnmodifiableLists);
private boolean insideOnly;
public StructureSpawnListGatherEvent(Structure structure)
{
this.structure = structure;
this.insideOnly = false;
/*this.insideOnly = this.structure.getDefaultRestrictsSpawnsToInside();
for (MobCategory cat : MobCategory.values()) {
List<SpawnerData> lst = this.structure.getDefaultSpawnList(cat);
if (!lst.isEmpty())
addEntitySpawns(cat, lst);
}*/
// TODO-PATCHING: follow how StructureSpawnManager is reengineered
}
/**
* @return Structure to add or remove spawns to/from.
*/
public Structure getStructure()
{
return structure;
}
/**
* Change if entity spawn location checks are done against the entire bounds of the structure or only the inside the pieces of the structure.
* @param insideOnly {@code true} to restrict the spawn checks to inside the pieces of the structure, {@code false} to allow spawns outside
*/
public void setInsideOnly(boolean insideOnly)
{
this.insideOnly = insideOnly;
}
/**
* Checks if spawns for the structure are restricted to being inside the individual pieces of the structure.
*/
public boolean isInsideOnly()
{
return insideOnly;
}
/**
* Gets an unmodifiable view of the the list representing the entity spawns for the given classification.
* @param classification Entity Classification
* @return The list of spawns for the given classification.
*/
public List<MobSpawnSettings.SpawnerData> getEntitySpawns(MobCategory classification)
{
return this.entitySpawnsUnmodifiableLists.getOrDefault(classification, Collections.emptyList());
}
/**
* Gets the internal spawn list for a given entity classification, or adds one if needed. (This includes adding it to the unmodifiable view)
*/
private List<MobSpawnSettings.SpawnerData> getOrCreateEntitySpawns(MobCategory classification)
{
return this.entitySpawns.computeIfAbsent(classification, c -> {
List<MobSpawnSettings.SpawnerData> spawners = new ArrayList<>();
//If the classification isn't in entitySpawns yet, also add an unmodifiable view of the list to
// the unmodifiable list spawn map
this.entitySpawnsUnmodifiableLists.put(c, Collections.unmodifiableList(spawners));
return spawners;
});
}
/**
* Adds a spawn to the list of spawns for the given classification.
* @param classification Entity Classification
* @param spawner Spawner
*/
public void addEntitySpawn(MobCategory classification, MobSpawnSettings.SpawnerData spawner)
{
getOrCreateEntitySpawns(classification).add(spawner);
}
/**
* Adds spawns to the list of spawns for the given classification.
* @param classification Entity Classification
* @param spawners Spawners to add
*/
public void addEntitySpawns(MobCategory classification, List<MobSpawnSettings.SpawnerData> spawners)
{
getOrCreateEntitySpawns(classification).addAll(spawners);
}
/**
* Removes a spawn from the list of spawns for the given classification.
* @param classification Entity Classification
* @param spawner Spawner
*/
public void removeEntitySpawn(MobCategory classification, MobSpawnSettings.SpawnerData spawner)
{
if (this.entitySpawns.containsKey(classification))
this.entitySpawns.get(classification).remove(spawner);
}
/**
* Gets an unmodifiable view of the map of spawns based on entity classification that is used to fill in the various spawn lists for the structure.
*/
public Map<MobCategory, List<MobSpawnSettings.SpawnerData>> getEntitySpawns()
{
return entitySpawnsUnmodifiable;
}
}
@@ -24,6 +24,8 @@ public class ForgeDeferredRegistriesSetup
ForgeRegistries.DEFERRED_WORLD_TYPES.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_BIOME_MODIFIERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.register(modEventBus);
ForgeRegistries.DEFERRED_STRUCTURE_MODIFIERS.register(modEventBus);
setup = true;
}
@@ -46,6 +46,7 @@ import net.minecraftforge.common.world.BiomeModifier;
import net.minecraftforge.common.world.ForgeWorldPreset;
import java.util.function.Supplier;
import net.minecraftforge.common.world.StructureModifier;
/**
* A class that exposes static references to all vanilla and Forge registries.
@@ -102,10 +103,14 @@ public class ForgeRegistries
public static final Supplier<IForgeRegistry<ForgeWorldPreset>> WORLD_TYPES = DEFERRED_WORLD_TYPES.makeRegistry(GameData::getWorldTypesRegistryBuilder);
static final DeferredRegister<Codec<? extends BiomeModifier>> DEFERRED_BIOME_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.BIOME_MODIFIER_SERIALIZERS, Keys.BIOME_MODIFIER_SERIALIZERS.location().getNamespace());
public static final Supplier<IForgeRegistry<Codec<? extends BiomeModifier>>> BIOME_MODIFIER_SERIALIZERS = DEFERRED_BIOME_MODIFIER_SERIALIZERS.makeRegistry(() -> new RegistryBuilder<Codec<? extends BiomeModifier>>().disableSaving().disableSync());
static final DeferredRegister<Codec<? extends StructureModifier>> DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS = DeferredRegister.create(Keys.STRUCTURE_MODIFIER_SERIALIZERS, Keys.STRUCTURE_MODIFIER_SERIALIZERS.location().getNamespace());
public static final Supplier<IForgeRegistry<Codec<? extends StructureModifier>>> STRUCTURE_MODIFIER_SERIALIZERS = DEFERRED_STRUCTURE_MODIFIER_SERIALIZERS.makeRegistry(() -> new RegistryBuilder<Codec<? extends StructureModifier>>().disableSaving().disableSync());
// Custom forge datapack registries
static final DeferredRegister<BiomeModifier> DEFERRED_BIOME_MODIFIERS = DeferredRegister.create(Keys.BIOME_MODIFIERS, "forge");
public static final Supplier<IForgeRegistry<BiomeModifier>> BIOME_MODIFIERS_BUILTIN = DEFERRED_BIOME_MODIFIERS.makeRegistry(() -> new RegistryBuilder<BiomeModifier>().disableSaving().dataPackRegistry(BiomeModifier.DIRECT_CODEC));
static final DeferredRegister<StructureModifier> DEFERRED_STRUCTURE_MODIFIERS = DeferredRegister.create(Keys.STRUCTURE_MODIFIERS, "forge");
public static final Supplier<IForgeRegistry<StructureModifier>> STRUCTURE_MODIFIERS_BUILTIN = DEFERRED_STRUCTURE_MODIFIERS.makeRegistry(() -> new RegistryBuilder<StructureModifier>().disableSaving().dataPackRegistry(StructureModifier.DIRECT_CODEC));
public static final class Keys {
//Vanilla
@@ -146,9 +151,11 @@ public class ForgeRegistries
public static final ResourceKey<Registry<GlobalLootModifierSerializer<?>>> LOOT_MODIFIER_SERIALIZERS = key("forge:loot_modifier_serializers");
public static final ResourceKey<Registry<ForgeWorldPreset>> WORLD_TYPES = key("forge:world_types");
public static final ResourceKey<Registry<Codec<? extends BiomeModifier>>> BIOME_MODIFIER_SERIALIZERS = key("forge:biome_modifier_serializers");
public static final ResourceKey<Registry<Codec<? extends StructureModifier>>> STRUCTURE_MODIFIER_SERIALIZERS = key("forge:structure_modifier_serializers");
// Forge Dynamic
public static final ResourceKey<Registry<BiomeModifier>> BIOME_MODIFIERS = key("forge:biome_modifier");
public static final ResourceKey<Registry<StructureModifier>> STRUCTURE_MODIFIERS = key("forge:structure_modifier");
private static <T> ResourceKey<Registry<T>> key(String name)
{
@@ -26,6 +26,7 @@ import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.server.packs.repository.RepositorySource;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraftforge.common.world.StructureModifier;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.common.util.LogicalSidedProvider;
import net.minecraftforge.common.world.BiomeModifier;
@@ -38,6 +39,7 @@ import net.minecraftforge.network.ServerStatusPing;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.network.NetworkRegistry;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.registries.ForgeRegistries.Keys;
import net.minecraftforge.resource.PathResourcePack;
import net.minecraftforge.server.permission.PermissionAPI;
import org.apache.logging.log4j.LogManager;
@@ -89,7 +91,7 @@ public class ServerLifecycleHooks
// on the dedi server we need to force the stuff to setup properly
LogicalSidedProvider.setServer(()->server);
ConfigTracker.INSTANCE.loadConfigs(ModConfig.Type.SERVER, getServerConfigPath(server));
runBiomeModifiers(server);
runModifiers(server);
return !MinecraftForge.EVENT_BUS.post(new ServerAboutToStartEvent(server));
}
@@ -211,20 +213,29 @@ public class ServerLifecycleHooks
}
}
private static void runBiomeModifiers(final MinecraftServer server)
private static void runModifiers(final MinecraftServer server)
{
final RegistryAccess registries = server.registryAccess();
// The order of holders() is the order modifiers were loaded in.
final List<BiomeModifier> modifiers = registries.registryOrThrow(ForgeRegistries.Keys.BIOME_MODIFIERS)
final List<BiomeModifier> biomeModifiers = registries.registryOrThrow(ForgeRegistries.Keys.BIOME_MODIFIERS)
.holders()
.map(Holder::value)
.toList();
final List<StructureModifier> structureModifiers = registries.registryOrThrow(Keys.STRUCTURE_MODIFIERS)
.holders()
.map(Holder::value)
.toList();
// Apply sorted biome modifiers to each biome.
registries.registryOrThrow(Registry.BIOME_REGISTRY).holders().forEach(biomeHolder ->
{
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, modifiers);
biomeHolder.value().modifiableBiomeInfo().applyBiomeModifiers(biomeHolder, biomeModifiers);
});
// Apply sorted structure modifiers to each structure.
registries.registryOrThrow(Registry.STRUCTURE_REGISTRY).holders().forEach(structureHolder ->
{
structureHolder.value().modifiableStructureInfo().applyStructureModifiers(structureHolder, structureModifiers);
});
}
}