Reformated

This commit is contained in:
Frank 2022-06-08 20:57:21 +02:00
parent 079b51e3f6
commit 852e5a6abc
385 changed files with 6924 additions and 5656 deletions

40
BetterX_CodeFormat.xml Normal file
View file

@ -0,0 +1,40 @@
<code_scheme name="BetterX" version="173">
<option name="ENABLE_SECOND_REFORMAT" value="true" />
<JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="org.betterx" withSubpackages="true" static="false" />
<emptyLine />
<package name="com.mojang" withSubpackages="true" static="false" />
<package name="net.minecraft" withSubpackages="true" static="false" />
<emptyLine />
<package name="net.fabricmc" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<package name="java" withSubpackages="true" static="false" />
<package name="org.jetbrains" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="true" />
</value>
</option>
</JavaCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="BLANK_LINES_AROUND_METHOD_IN_INTERFACE" value="0" />
<option name="ALIGN_MULTILINE_CHAINED_METHODS" value="true" />
<option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
<option name="CALL_PARAMETERS_WRAP" value="5" />
<option name="CALL_PARAMETERS_LPAREN_ON_NEXT_LINE" value="true" />
<option name="CALL_PARAMETERS_RPAREN_ON_NEXT_LINE" value="true" />
<option name="METHOD_PARAMETERS_WRAP" value="5" />
<option name="METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE" value="true" />
<option name="METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE" value="true" />
<option name="METHOD_CALL_CHAIN_WRAP" value="5" />
<option name="TERNARY_OPERATION_WRAP" value="5" />
<option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
<option name="ARRAY_INITIALIZER_WRAP" value="5" />
<option name="ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE" value="true" />
<option name="ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE" value="true" />
</codeStyleSettings>
</code_scheme>

View file

@ -8,4 +8,5 @@ import java.lang.annotation.Target;
// Included from "Inventory Profiles Next" (https://github.com/blackd/Inventory-Profiles) // Included from "Inventory Profiles Next" (https://github.com/blackd/Inventory-Profiles)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) @Target(ElementType.TYPE)
public @interface IPNIgnore {} public @interface IPNIgnore {
}

View file

@ -1,16 +1,5 @@
package org.betterx.bclib; package org.betterx.bclib;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
import net.minecraft.world.level.block.Blocks;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import org.betterx.bclib.api.v2.WorldDataAPI; import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.*; import org.betterx.bclib.api.v2.dataexchange.handler.autosync.*;
@ -31,6 +20,17 @@ import org.betterx.bclib.registry.BaseBlockEntities;
import org.betterx.bclib.registry.BaseRegistry; import org.betterx.bclib.registry.BaseRegistry;
import org.betterx.bclib.util.Logger; import org.betterx.bclib.util.Logger;
import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.ai.village.poi.PoiType;
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
import net.minecraft.world.level.block.Blocks;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -58,13 +58,13 @@ public class BCLib implements ModInitializer {
CommandRegistry.register(); CommandRegistry.register();
DataExchangeAPI.registerDescriptors(List.of( DataExchangeAPI.registerDescriptors(List.of(
HelloClient.DESCRIPTOR, HelloClient.DESCRIPTOR,
HelloServer.DESCRIPTOR, HelloServer.DESCRIPTOR,
RequestFiles.DESCRIPTOR, RequestFiles.DESCRIPTOR,
SendFiles.DESCRIPTOR, SendFiles.DESCRIPTOR,
Chunker.DESCRIPTOR Chunker.DESCRIPTOR
) )
); );
BCLibPatch.register(); BCLibPatch.register();
TemplatePiece.ensureStaticInitialization(); TemplatePiece.ensureStaticInitialization();

View file

@ -1,5 +1,14 @@
package org.betterx.bclib; package org.betterx.bclib;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.api.v2.datafixer.ForcedLevelPatch;
import org.betterx.bclib.api.v2.datafixer.MigrationProfile;
import org.betterx.bclib.api.v2.generator.GeneratorOptions;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.MHelper;
import com.mojang.serialization.Dynamic;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
@ -11,15 +20,6 @@ import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.levelgen.WorldGenSettings;
import com.mojang.serialization.Dynamic;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.api.v2.datafixer.ForcedLevelPatch;
import org.betterx.bclib.api.v2.datafixer.MigrationProfile;
import org.betterx.bclib.api.v2.generator.GeneratorOptions;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.MHelper;
import java.util.Optional; import java.util.Optional;
public final class BCLibPatch { public final class BCLibPatch {
@ -87,22 +87,23 @@ final class BiomeSourcePatch extends ForcedLevelPatch {
// return result; // return result;
} }
private boolean checkDimension(CompoundTag worldGenSettings, private boolean checkDimension(
CompoundTag dimensions, CompoundTag worldGenSettings,
RegistryAccess registryAccess, CompoundTag dimensions,
RegistryOps<Tag> registryOps, RegistryAccess registryAccess,
ResourceKey<LevelStem> dimensionKey RegistryOps<Tag> registryOps,
ResourceKey<LevelStem> dimensionKey
) { ) {
final long seed = worldGenSettings.contains("seed") final long seed = worldGenSettings.contains("seed")
? worldGenSettings.getLong("seed") ? worldGenSettings.getLong("seed")
: MHelper.RANDOM.nextLong(); : MHelper.RANDOM.nextLong();
final boolean genStructures = worldGenSettings.contains("generate_features") ? worldGenSettings.getBoolean( final boolean genStructures = !worldGenSettings.contains("generate_features") || worldGenSettings.getBoolean(
"generate_features") : true; "generate_features");
final boolean genBonusChest = worldGenSettings.contains("bonus_chest") ? worldGenSettings.getBoolean( final boolean genBonusChest = worldGenSettings.contains("bonus_chest") && worldGenSettings.getBoolean(
"bonus_chest") : false; "bonus_chest");
boolean result = false; boolean result = false;
CompoundTag dimensionTag = dimensions.getCompound(dimensionKey.location().toString()); CompoundTag dimensionTag = dimensions.getCompound(dimensionKey.location().toString());

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.util.BlocksHelper;
import org.betterx.bclib.util.WeightedList;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -8,8 +11,6 @@ import net.minecraft.world.level.block.Block;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.util.BlocksHelper;
import org.betterx.bclib.util.WeightedList;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -80,10 +81,12 @@ public class BonemealAPI {
addLandGrass(biome, makeConsumer(plant), terrain, chance); addLandGrass(biome, makeConsumer(plant), terrain, chance);
} }
public static void addLandGrass(ResourceLocation biome, public static void addLandGrass(
BiConsumer<Level, BlockPos> plant, ResourceLocation biome,
Block terrain, BiConsumer<Level, BlockPos> plant,
float chance) { Block terrain,
float chance
) {
Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = LAND_GRASS_BIOMES.get(biome); Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = LAND_GRASS_BIOMES.get(biome);
if (map == null) { if (map == null) {
map = Maps.newHashMap(); map = Maps.newHashMap();
@ -136,10 +139,12 @@ public class BonemealAPI {
addWaterGrass(biome, makeConsumer(plant), terrain, chance); addWaterGrass(biome, makeConsumer(plant), terrain, chance);
} }
public static void addWaterGrass(ResourceLocation biome, public static void addWaterGrass(
BiConsumer<Level, BlockPos> plant, ResourceLocation biome,
Block terrain, BiConsumer<Level, BlockPos> plant,
float chance) { Block terrain,
float chance
) {
Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = WATER_GRASS_BIOMES.get(biome); Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = WATER_GRASS_BIOMES.get(biome);
if (map == null) { if (map == null) {
map = Maps.newHashMap(); map = Maps.newHashMap();
@ -154,9 +159,11 @@ public class BonemealAPI {
list.add(plant, chance); list.add(plant, chance);
} }
public static BiConsumer<Level, BlockPos> getLandGrass(ResourceLocation biomeID, public static BiConsumer<Level, BlockPos> getLandGrass(
Block terrain, ResourceLocation biomeID,
RandomSource random) { Block terrain,
RandomSource random
) {
Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = LAND_GRASS_BIOMES.get(biomeID); Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = LAND_GRASS_BIOMES.get(biomeID);
WeightedList<BiConsumer<Level, BlockPos>> list; WeightedList<BiConsumer<Level, BlockPos>> list;
if (map != null) { if (map != null) {
@ -170,9 +177,11 @@ public class BonemealAPI {
return list == null ? null : list.get(random); return list == null ? null : list.get(random);
} }
public static BiConsumer<Level, BlockPos> getWaterGrass(ResourceLocation biomeID, public static BiConsumer<Level, BlockPos> getWaterGrass(
Block terrain, ResourceLocation biomeID,
RandomSource random) { Block terrain,
RandomSource random
) {
Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = WATER_GRASS_BIOMES.get(biomeID); Map<Block, WeightedList<BiConsumer<Level, BlockPos>>> map = WATER_GRASS_BIOMES.get(biomeID);
WeightedList<BiConsumer<Level, BlockPos>> list; WeightedList<BiConsumer<Level, BlockPos>> list;
if (map != null) { if (map != null) {

View file

@ -1,11 +1,11 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.mixin.common.ComposterBlockAccessor;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import org.betterx.bclib.mixin.common.ComposterBlockAccessor;
public class ComposterAPI { public class ComposterAPI {
public static Block allowCompost(float chance, Block block) { public static Block allowCompost(float chance, Block block) {
if (block != null) { if (block != null) {

View file

@ -1,5 +1,11 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.mixin.common.RegistryOpsAccessor;
import net.minecraft.client.gui.screens.worldselection.WorldGenSettingsComponent; import net.minecraft.client.gui.screens.worldselection.WorldGenSettingsComponent;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
@ -16,12 +22,6 @@ import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.level.storage.ServerLevelData;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.mixin.common.RegistryOpsAccessor;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -40,8 +40,10 @@ public class LifeCycleAPI {
InternalBiomeAPI.initRegistry(access); InternalBiomeAPI.initRegistry(access);
} }
public static void newWorldSetup(LevelStorageSource.LevelStorageAccess levelStorageAccess, public static void newWorldSetup(
WorldGenSettings settings) { LevelStorageSource.LevelStorageAccess levelStorageAccess,
WorldGenSettings settings
) {
DataExchangeAPI.prepareServerside(); DataExchangeAPI.prepareServerside();
InternalBiomeAPI.prepareNewLevel(); InternalBiomeAPI.prepareNewLevel();
@ -49,9 +51,11 @@ public class LifeCycleAPI {
_runBeforeLevelLoad(); _runBeforeLevelLoad();
} }
public static void newWorldSetup(String levelID, public static void newWorldSetup(
WorldGenSettings worldGenSettings, String levelID,
LevelStorageSource levelSource) { WorldGenSettings worldGenSettings,
LevelStorageSource levelSource
) {
DataExchangeAPI.prepareServerside(); DataExchangeAPI.prepareServerside();
InternalBiomeAPI.prepareNewLevel(); InternalBiomeAPI.prepareNewLevel();
@ -81,8 +85,10 @@ public class LifeCycleAPI {
} }
} }
public static void worldCreationStarted(Optional<LevelStorageSource.LevelStorageAccess> levelStorageAccess, public static void worldCreationStarted(
WorldGenSettingsComponent worldGenSettingsComponent) { Optional<LevelStorageSource.LevelStorageAccess> levelStorageAccess,
WorldGenSettingsComponent worldGenSettingsComponent
) {
worldCreationStarted(worldGenSettingsComponent.registryHolder()); worldCreationStarted(worldGenSettingsComponent.registryHolder());
if (levelStorageAccess.isPresent()) { if (levelStorageAccess.isPresent()) {
@ -142,18 +148,21 @@ public class LifeCycleAPI {
* @param list * @param list
* @param bl2 * @param bl2
*/ */
public static void _runLevelLoad(ServerLevel world, public static void _runLevelLoad(
MinecraftServer minecraftServer, ServerLevel world,
Executor executor, MinecraftServer minecraftServer,
LevelStorageSource.LevelStorageAccess levelStorageAccess, Executor executor,
ServerLevelData serverLevelData, LevelStorageSource.LevelStorageAccess levelStorageAccess,
ResourceKey<Level> resourceKey, ServerLevelData serverLevelData,
ChunkProgressListener chunkProgressListener, ResourceKey<Level> resourceKey,
boolean bl, ChunkProgressListener chunkProgressListener,
long l, boolean bl,
List<CustomSpawner> list, long l,
boolean bl2) { List<CustomSpawner> list,
onLoadLevel.forEach(c -> c.onLoad(world, boolean bl2
) {
onLoadLevel.forEach(c -> c.onLoad(
world,
minecraftServer, minecraftServer,
executor, executor,
levelStorageAccess, levelStorageAccess,
@ -163,7 +172,8 @@ public class LifeCycleAPI {
bl, bl,
l, l,
list, list,
bl2)); bl2
));
final long seed = world.getSeed(); final long seed = world.getSeed();
final Registry<Biome> biomeRegistry = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY); final Registry<Biome> biomeRegistry = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY);
@ -188,16 +198,18 @@ public class LifeCycleAPI {
* A callback function that is used for each new ServerLevel instance * A callback function that is used for each new ServerLevel instance
*/ */
public interface LevelLoadCall { public interface LevelLoadCall {
void onLoad(ServerLevel world, void onLoad(
MinecraftServer minecraftServer, ServerLevel world,
Executor executor, MinecraftServer minecraftServer,
LevelStorageSource.LevelStorageAccess levelStorageAccess, Executor executor,
ServerLevelData serverLevelData, LevelStorageSource.LevelStorageAccess levelStorageAccess,
ResourceKey<Level> resourceKey, ServerLevelData serverLevelData,
ChunkProgressListener chunkProgressListener, ResourceKey<Level> resourceKey,
boolean bl, ChunkProgressListener chunkProgressListener,
long l, boolean bl,
List<CustomSpawner> list, long l,
boolean bl2); List<CustomSpawner> list,
boolean bl2
);
} }
} }

View file

@ -1,9 +1,10 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.integration.ModIntegration;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.betterx.bclib.integration.ModIntegration;
import java.util.List; import java.util.List;

View file

@ -1,16 +1,5 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Registry;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import com.google.common.collect.Lists;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.api.v2.tag.NamedMineableTags; import org.betterx.bclib.api.v2.tag.NamedMineableTags;
@ -29,6 +18,18 @@ import org.betterx.bclib.interfaces.TagProvider;
import org.betterx.bclib.interfaces.tools.*; import org.betterx.bclib.interfaces.tools.*;
import org.betterx.bclib.registry.BaseBlockEntities; import org.betterx.bclib.registry.BaseBlockEntities;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.core.Registry;
import net.minecraft.tags.TagKey;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap;
import com.google.common.collect.Lists;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.mixin.common.ShovelItemAccessor;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import org.betterx.bclib.mixin.common.ShovelItemAccessor;
import java.util.Map; import java.util.Map;
public class ShovelAPI { public class ShovelAPI {

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2; package org.betterx.bclib.api.v2;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.util.ModUtil;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.NbtIo;
@ -10,9 +14,6 @@ import net.fabricmc.loader.api.ModContainer;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.datafixer.DataFixerAPI;
import org.betterx.bclib.util.ModUtil;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -135,7 +136,7 @@ public class WorldDataAPI {
tag.putString(TAG_MODIFIED, ModUtil.getModVersion(modID)); tag.putString(TAG_MODIFIED, ModUtil.getModVersion(modID));
final File tempFile =new File(dataDir, modID + "_temp.nbt"); final File tempFile = new File(dataDir, modID + "_temp.nbt");
NbtIo.writeCompressed(tag, tempFile); NbtIo.writeCompressed(tag, tempFile);
final File oldFile = new File(dataDir, modID + "_old.nbt"); final File oldFile = new File(dataDir, modID + "_old.nbt");

View file

@ -35,18 +35,22 @@ public abstract class BaseDataHandler {
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
abstract void receiveFromServer(Minecraft client, abstract void receiveFromServer(
ClientPacketListener handler, Minecraft client,
FriendlyByteBuf buf, ClientPacketListener handler,
PacketSender responseSender); FriendlyByteBuf buf,
PacketSender responseSender
);
private ServerPlayer lastMessageSender; private ServerPlayer lastMessageSender;
void receiveFromClient(MinecraftServer server, void receiveFromClient(
ServerPlayer player, MinecraftServer server,
ServerGamePacketListenerImpl handler, ServerPlayer player,
FriendlyByteBuf buf, ServerGamePacketListenerImpl handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
lastMessageSender = player; lastMessageSender = player;
} }

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
@ -9,9 +12,6 @@ import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
/** /**
* This is an internal class that handles a Clienetside players Connection to a Server * This is an internal class that handles a Clienetside players Connection to a Server
*/ */
@ -59,11 +59,13 @@ public class ConnectorClientside extends Connector {
} }
} }
void receiveFromServer(DataHandlerDescriptor desc, void receiveFromServer(
Minecraft client, DataHandlerDescriptor desc,
ClientPacketListener handler, Minecraft client,
FriendlyByteBuf buf, ClientPacketListener handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
BaseDataHandler h = desc.INSTANCE.get(); BaseDataHandler h = desc.INSTANCE.get();
h.receiveFromServer(client, handler, buf, responseSender); h.receiveFromServer(client, handler, buf, responseSender);
} }

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
@ -8,9 +11,6 @@ import net.minecraft.server.network.ServerGamePacketListenerImpl;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
/** /**
* This is an internal class that handles a Serverside Connection to a Client-Player * This is an internal class that handles a Serverside Connection to a Client-Player
*/ */
@ -33,16 +33,20 @@ public class ConnectorServerside extends Connector {
} }
this.server = server; this.server = server;
for (DataHandlerDescriptor desc : getDescriptors()) { for (DataHandlerDescriptor desc : getDescriptors()) {
ServerPlayNetworking.registerReceiver(handler, ServerPlayNetworking.registerReceiver(
desc.IDENTIFIER, handler,
(_server, _player, _handler, _buf, _responseSender) -> { desc.IDENTIFIER,
receiveFromClient(desc, (_server, _player, _handler, _buf, _responseSender) -> {
_server, receiveFromClient(
_player, desc,
_handler, _server,
_buf, _player,
_responseSender); _handler,
}); _buf,
_responseSender
);
}
);
} }
} }
@ -63,12 +67,14 @@ public class ConnectorServerside extends Connector {
} }
} }
void receiveFromClient(DataHandlerDescriptor desc, void receiveFromClient(
MinecraftServer server, DataHandlerDescriptor desc,
ServerPlayer player, MinecraftServer server,
ServerGamePacketListenerImpl handler, ServerPlayer player,
FriendlyByteBuf buf, ServerGamePacketListenerImpl handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
BaseDataHandler h = desc.INSTANCE.get(); BaseDataHandler h = desc.INSTANCE.get();
h.receiveFromClient(server, player, handler, buf, responseSender); h.receiveFromClient(server, player, handler, buf, responseSender);
} }

View file

@ -1,17 +1,18 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID;
import org.betterx.bclib.config.Config;
import org.betterx.bclib.util.ModUtil;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID;
import org.betterx.bclib.config.Config;
import org.betterx.bclib.util.ModUtil;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
@ -167,10 +168,12 @@ public class DataExchangeAPI extends DataExchange {
* @param fileName The name of the File * @param fileName The name of the File
* @param needTransfer If the predicate returns true, the file needs to get copied to the server. * @param needTransfer If the predicate returns true, the file needs to get copied to the server.
*/ */
public static void addAutoSyncFile(String modID, public static void addAutoSyncFile(
String uniqueID, String modID,
File fileName, String uniqueID,
AutoSync.NeedTransferPredicate needTransfer) { File fileName,
AutoSync.NeedTransferPredicate needTransfer
) {
AutoSync.addAutoSyncFileData(modID, uniqueID, fileName, true, needTransfer); AutoSync.addAutoSyncFileData(modID, uniqueID, fileName, true, needTransfer);
} }

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.Chunker;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientPacketListener; import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
@ -17,9 +20,6 @@ import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.PlayerLookup; import net.fabricmc.fabric.api.networking.v1.PlayerLookup;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.Chunker;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -60,10 +60,12 @@ public abstract class DataHandler extends BaseDataHandler {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
@Override @Override
void receiveFromServer(Minecraft client, void receiveFromServer(
ClientPacketListener handler, Minecraft client,
FriendlyByteBuf buf, ClientPacketListener handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
deserializeIncomingData(buf, responseSender, true); deserializeIncomingData(buf, responseSender, true);
final Runnable runner = () -> runOnGameThread(client, null, true); final Runnable runner = () -> runOnGameThread(client, null, true);
@ -72,11 +74,13 @@ public abstract class DataHandler extends BaseDataHandler {
} }
@Override @Override
void receiveFromClient(MinecraftServer server, void receiveFromClient(
ServerPlayer player, MinecraftServer server,
ServerGamePacketListenerImpl handler, ServerPlayer player,
FriendlyByteBuf buf, ServerGamePacketListenerImpl handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
super.receiveFromClient(server, player, handler, buf, responseSender); super.receiveFromClient(server, player, handler, buf, responseSender);
deserializeIncomingData(buf, responseSender, false); deserializeIncomingData(buf, responseSender, false);
@ -107,10 +111,12 @@ public abstract class DataHandler extends BaseDataHandler {
} }
public static void _sendToClient(ResourceLocation identifier, public static void _sendToClient(
MinecraftServer server, ResourceLocation identifier,
Collection<ServerPlayer> players, MinecraftServer server,
FriendlyByteBuf buf) { Collection<ServerPlayer> players,
FriendlyByteBuf buf
) {
if (buf.readableBytes() > Chunker.MAX_PACKET_SIZE) { if (buf.readableBytes() > Chunker.MAX_PACKET_SIZE) {
final Chunker.PacketChunkSender sender = new Chunker.PacketChunkSender(buf, identifier); final Chunker.PacketChunkSender sender = new Chunker.PacketChunkSender(buf, identifier);
sender.sendChunks(players); sender.sendChunks(players);
@ -150,9 +156,11 @@ public abstract class DataHandler extends BaseDataHandler {
} }
@Override @Override
protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, protected void deserializeIncomingDataOnServer(
Player player, FriendlyByteBuf buf,
PacketSender responseSender) { Player player,
PacketSender responseSender
) {
} }
} }
@ -168,26 +176,32 @@ public abstract class DataHandler extends BaseDataHandler {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
abstract protected void serializeDataOnClient(FriendlyByteBuf buf); abstract protected void serializeDataOnClient(FriendlyByteBuf buf);
protected abstract void deserializeIncomingDataOnServer(FriendlyByteBuf buf, protected abstract void deserializeIncomingDataOnServer(
Player player, FriendlyByteBuf buf,
PacketSender responseSender); Player player,
PacketSender responseSender
);
protected abstract void runOnServerGameThread(MinecraftServer server, Player player); protected abstract void runOnServerGameThread(MinecraftServer server, Player player);
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
@Override @Override
void receiveFromServer(Minecraft client, void receiveFromServer(
ClientPacketListener handler, Minecraft client,
FriendlyByteBuf buf, ClientPacketListener handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the client!"); BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the client!");
} }
@Override @Override
void receiveFromClient(MinecraftServer server, void receiveFromClient(
ServerPlayer player, MinecraftServer server,
ServerGamePacketListenerImpl handler, ServerPlayer player,
FriendlyByteBuf buf, ServerGamePacketListenerImpl handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
super.receiveFromClient(server, player, handler, buf, responseSender); super.receiveFromClient(server, player, handler, buf, responseSender);
deserializeIncomingDataOnServer(buf, player, responseSender); deserializeIncomingDataOnServer(buf, player, responseSender);
@ -260,10 +274,12 @@ public abstract class DataHandler extends BaseDataHandler {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
@Override @Override
final void receiveFromServer(Minecraft client, final void receiveFromServer(
ClientPacketListener handler, Minecraft client,
FriendlyByteBuf buf, ClientPacketListener handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
deserializeIncomingDataOnClient(buf, responseSender); deserializeIncomingDataOnClient(buf, responseSender);
final Runnable runner = () -> runOnClientGameThread(client); final Runnable runner = () -> runOnClientGameThread(client);
@ -272,11 +288,13 @@ public abstract class DataHandler extends BaseDataHandler {
} }
@Override @Override
final void receiveFromClient(MinecraftServer server, final void receiveFromClient(
ServerPlayer player, MinecraftServer server,
ServerGamePacketListenerImpl handler, ServerPlayer player,
FriendlyByteBuf buf, ServerGamePacketListenerImpl handler,
PacketSender responseSender) { FriendlyByteBuf buf,
PacketSender responseSender
) {
super.receiveFromClient(server, player, handler, buf, responseSender); super.receiveFromClient(server, player, handler, buf, responseSender);
BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the server!"); BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the server!");
} }

View file

@ -11,18 +11,22 @@ public class DataHandlerDescriptor {
this(identifier, instancer, instancer, false, false); this(identifier, instancer, instancer, false, false);
} }
public DataHandlerDescriptor(@NotNull ResourceLocation identifier, public DataHandlerDescriptor(
@NotNull Supplier<BaseDataHandler> instancer, @NotNull ResourceLocation identifier,
boolean sendOnJoin, @NotNull Supplier<BaseDataHandler> instancer,
boolean sendBeforeEnter) { boolean sendOnJoin,
boolean sendBeforeEnter
) {
this(identifier, instancer, instancer, sendOnJoin, sendBeforeEnter); this(identifier, instancer, instancer, sendOnJoin, sendBeforeEnter);
} }
public DataHandlerDescriptor(@NotNull ResourceLocation identifier, public DataHandlerDescriptor(
@NotNull Supplier<BaseDataHandler> receiv_instancer, @NotNull ResourceLocation identifier,
@NotNull Supplier<BaseDataHandler> join_instancer, @NotNull Supplier<BaseDataHandler> receiv_instancer,
boolean sendOnJoin, @NotNull Supplier<BaseDataHandler> join_instancer,
boolean sendBeforeEnter) { boolean sendOnJoin,
boolean sendBeforeEnter
) {
this.INSTANCE = receiv_instancer; this.INSTANCE = receiv_instancer;
this.JOIN_INSTANCE = join_instancer; this.JOIN_INSTANCE = join_instancer;
this.IDENTIFIER = identifier; this.IDENTIFIER = identifier;

View file

@ -1,9 +1,9 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import net.minecraft.network.FriendlyByteBuf;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import net.minecraft.network.FriendlyByteBuf;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.dataexchange; package org.betterx.bclib.api.v2.dataexchange;
import net.minecraft.network.FriendlyByteBuf;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync; import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync;
import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID; import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID;
import net.minecraft.network.FriendlyByteBuf;
import java.io.File; import java.io.File;
import java.util.Objects; import java.util.Objects;

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.dataexchange.handler; package org.betterx.bclib.api.v2.dataexchange.handler;
import org.betterx.bclib.api.v2.dataexchange.*;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
@ -7,8 +9,6 @@ import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import org.betterx.bclib.api.v2.dataexchange.*;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View file

@ -1,7 +1,5 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.minecraft.network.FriendlyByteBuf;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataHandler; import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.SyncFileHash; import org.betterx.bclib.api.v2.dataexchange.SyncFileHash;
@ -11,6 +9,8 @@ import org.betterx.bclib.util.Pair;
import org.betterx.bclib.util.PathUtil; import org.betterx.bclib.util.PathUtil;
import org.betterx.bclib.util.Triple; import org.betterx.bclib.util.Triple;
import net.minecraft.network.FriendlyByteBuf;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -39,11 +39,13 @@ class AutoFileSyncEntry extends AutoSyncID {
if (desc != null) { if (desc != null) {
//ensures that the file is not above the base-folder //ensures that the file is not above the base-folder
if (desc.acceptChildElements(desc.mapAbsolute(relFile))) { if (desc.acceptChildElements(desc.mapAbsolute(relFile))) {
return new AutoFileSyncEntry.ForDirectFileRequest(syncID, return new AutoFileSyncEntry.ForDirectFileRequest(
new File(relFile), syncID,
desc.localFolder.resolve(relFile) new File(relFile),
.normalize() desc.localFolder.resolve(relFile)
.toFile()); .normalize()
.toFile()
);
} }
} }
return null; return null;
@ -67,11 +69,13 @@ class AutoFileSyncEntry extends AutoSyncID {
public final String version; public final String version;
ForModFileRequest(String modID, boolean matchLocalVersion, String version) { ForModFileRequest(String modID, boolean matchLocalVersion, String version) {
super(modID, super(
AutoSyncID.ForModFileRequest.UNIQUE_ID, modID,
getLocalPathForID(modID, matchLocalVersion), AutoSyncID.ForModFileRequest.UNIQUE_ID,
false, getLocalPathForID(modID, matchLocalVersion),
(a, b, c) -> false); false,
(a, b, c) -> false
);
if (this.fileName == null && matchLocalVersion) { if (this.fileName == null && matchLocalVersion) {
BCLib.LOGGER.error("Unknown mod '" + modID + "'."); BCLib.LOGGER.error("Unknown mod '" + modID + "'.");
} }
@ -104,18 +108,22 @@ class AutoFileSyncEntry extends AutoSyncID {
public final boolean requestContent; public final boolean requestContent;
private SyncFileHash hash; private SyncFileHash hash;
AutoFileSyncEntry(String modID, AutoFileSyncEntry(
File fileName, String modID,
boolean requestContent, File fileName,
AutoSync.NeedTransferPredicate needTransfer) { boolean requestContent,
AutoSync.NeedTransferPredicate needTransfer
) {
this(modID, fileName.getName(), fileName, requestContent, needTransfer); this(modID, fileName.getName(), fileName, requestContent, needTransfer);
} }
AutoFileSyncEntry(String modID, AutoFileSyncEntry(
String uniqueID, String modID,
File fileName, String uniqueID,
boolean requestContent, File fileName,
AutoSync.NeedTransferPredicate needTransfer) { boolean requestContent,
AutoSync.NeedTransferPredicate needTransfer
) {
super(modID, uniqueID); super(modID, uniqueID);
this.needTransfer = needTransfer; this.needTransfer = needTransfer;
this.fileName = fileName; this.fileName = fileName;
@ -226,9 +234,11 @@ class AutoFileSyncEntry extends AutoSyncID {
final File absPath = desc.localFolder.resolve(subFile.relPath) final File absPath = desc.localFolder.resolve(subFile.relPath)
.normalize() .normalize()
.toFile(); .toFile();
return new AutoFileSyncEntry.ForDirectFileRequest(freq.uniqueID, return new AutoFileSyncEntry.ForDirectFileRequest(
new File(subFile.relPath), freq.uniqueID,
absPath); new File(subFile.relPath),
absPath
);
} }
} }
return null; return null;

View file

@ -1,7 +1,5 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.fabricmc.loader.api.FabricLoader;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.dataexchange.SyncFileHash; import org.betterx.bclib.api.v2.dataexchange.SyncFileHash;
@ -9,6 +7,8 @@ import org.betterx.bclib.config.Configs;
import org.betterx.bclib.config.ServerConfig; import org.betterx.bclib.config.ServerConfig;
import org.betterx.bclib.util.PathUtil; import org.betterx.bclib.util.PathUtil;
import net.fabricmc.loader.api.FabricLoader;
import java.io.File; import java.io.File;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@ -18,13 +18,15 @@ import java.util.function.BiConsumer;
public class AutoSync { public class AutoSync {
public static final String SYNC_CATEGORY = "auto_sync"; public static final String SYNC_CATEGORY = "auto_sync";
public final static SyncFolderDescriptor SYNC_FOLDER = new SyncFolderDescriptor("BCLIB-SYNC", public final static SyncFolderDescriptor SYNC_FOLDER = new SyncFolderDescriptor(
FabricLoader.getInstance() "BCLIB-SYNC",
.getGameDir() FabricLoader.getInstance()
.resolve("bclib-sync") .getGameDir()
.normalize() .resolve("bclib-sync")
.toAbsolutePath(), .normalize()
true); .toAbsolutePath(),
true
);
@FunctionalInterface @FunctionalInterface
public interface NeedTransferPredicate { public interface NeedTransferPredicate {
@ -83,10 +85,12 @@ public class AutoSync {
* If the File needs to be copied. Normally using the {@link SyncFileHash} * If the File needs to be copied. Normally using the {@link SyncFileHash}
* for comparison is sufficient. * for comparison is sufficient.
*/ */
public static void addAutoSyncFileData(String modID, public static void addAutoSyncFileData(
File fileName, String modID,
boolean requestContent, File fileName,
NeedTransferPredicate needTransfer) { boolean requestContent,
NeedTransferPredicate needTransfer
) {
if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) { if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) {
BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER); BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER);
} else { } else {
@ -109,11 +113,13 @@ public class AutoSync {
* If the File needs to be copied. Normally using the {@link SyncFileHash} * If the File needs to be copied. Normally using the {@link SyncFileHash}
* for comparison is sufficient. * for comparison is sufficient.
*/ */
public static void addAutoSyncFileData(String modID, public static void addAutoSyncFileData(
String uniqueID, String modID,
File fileName, String uniqueID,
boolean requestContent, File fileName,
NeedTransferPredicate needTransfer) { boolean requestContent,
NeedTransferPredicate needTransfer
) {
if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) { if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) {
BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER); BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER);
} else { } else {
@ -184,9 +190,11 @@ public class AutoSync {
public static void registerSyncFolder(String folderID, Path localBaseFolder, boolean removeAdditionalFiles) { public static void registerSyncFolder(String folderID, Path localBaseFolder, boolean removeAdditionalFiles) {
localBaseFolder = localBaseFolder.normalize(); localBaseFolder = localBaseFolder.normalize();
if (PathUtil.isChildOf(PathUtil.GAME_FOLDER, localBaseFolder)) { if (PathUtil.isChildOf(PathUtil.GAME_FOLDER, localBaseFolder)) {
final SyncFolderDescriptor desc = new SyncFolderDescriptor(folderID, final SyncFolderDescriptor desc = new SyncFolderDescriptor(
localBaseFolder, folderID,
removeAdditionalFiles); localBaseFolder,
removeAdditionalFiles
);
if (syncFolderDescriptions.contains(desc)) { if (syncFolderDescriptions.contains(desc)) {
BCLib.LOGGER.warning("Tried to override Folder Sync '" + folderID + "' again."); BCLib.LOGGER.warning("Tried to override Folder Sync '" + folderID + "' again.");
} else { } else {

View file

@ -1,11 +1,11 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.minecraft.network.FriendlyByteBuf;
import org.betterx.bclib.api.v2.dataexchange.DataHandler; import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.config.Config; import org.betterx.bclib.config.Config;
import org.betterx.bclib.util.ModUtil; import org.betterx.bclib.util.ModUtil;
import net.minecraft.network.FriendlyByteBuf;
import java.io.File; import java.io.File;
import java.util.Objects; import java.util.Objects;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View file

@ -1,5 +1,11 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.BaseDataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -10,12 +16,6 @@ import net.fabricmc.fabric.api.networking.v1.PacketByteBufs;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.BaseDataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange;
import java.util.*; import java.util.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -191,11 +191,15 @@ public class Chunker extends DataHandler.FromServer {
public static final int MAX_PACKET_SIZE = 1024 * 1024; public static final int MAX_PACKET_SIZE = 1024 * 1024;
private static final int MAX_PAYLOAD_SIZE = MAX_PACKET_SIZE - HEADER_SIZE; private static final int MAX_PAYLOAD_SIZE = MAX_PACKET_SIZE - HEADER_SIZE;
public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(
"chunker"), new ResourceLocation(
Chunker::new, BCLib.MOD_ID,
false, "chunker"
false); ),
Chunker::new,
false,
false
);
private int serialNo; private int serialNo;
private UUID uuid; private UUID uuid;

View file

@ -1,12 +1,12 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import org.betterx.bclib.client.gui.screens.ProgressScreen;
import net.minecraft.util.ProgressListener; import net.minecraft.util.ProgressListener;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import org.betterx.bclib.client.gui.screens.ProgressScreen;
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
public class ChunkerProgress { public class ChunkerProgress {
private static ProgressScreen progressScreen; private static ProgressScreen progressScreen;

View file

@ -1,16 +1,5 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.loader.api.metadata.ModEnvironment;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.dataexchange.DataHandler; import org.betterx.bclib.api.v2.dataexchange.DataHandler;
@ -25,6 +14,17 @@ import org.betterx.bclib.util.ModUtil;
import org.betterx.bclib.util.ModUtil.ModInfo; import org.betterx.bclib.util.ModUtil.ModInfo;
import org.betterx.bclib.util.PathUtil; import org.betterx.bclib.util.PathUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.loader.api.metadata.ModEnvironment;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -47,11 +47,15 @@ public class HelloClient extends DataHandler.FromServer {
public static class ServerModMap extends HashMap<String, OfferedModInfo> implements IServerModMap { public static class ServerModMap extends HashMap<String, OfferedModInfo> implements IServerModMap {
} }
public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(
"hello_client"), new ResourceLocation(
BCLib.MOD_ID,
"hello_client"
),
HelloClient::new, HelloClient::new,
false, false,
false); false
);
public HelloClient() { public HelloClient() {
super(DESCRIPTOR.IDENTIFIER); super(DESCRIPTOR.IDENTIFIER);
@ -217,8 +221,10 @@ public class HelloClient extends DataHandler.FromServer {
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
private void processAutoSyncFolder(final List<AutoSyncID> filesToRequest, private void processAutoSyncFolder(
final List<AutoSyncID.ForDirectFileRequest> filesToRemove) { final List<AutoSyncID> filesToRequest,
final List<AutoSyncID.ForDirectFileRequest> filesToRemove
) {
if (!Configs.CLIENT_CONFIG.isAcceptingFiles()) { if (!Configs.CLIENT_CONFIG.isAcceptingFiles()) {
return; return;
} }
@ -249,7 +255,8 @@ public class HelloClient extends DataHandler.FromServer {
.filter(desc::acceptChildElements) .filter(desc::acceptChildElements)
.map(absPath -> new AutoSyncID.ForDirectFileRequest( .map(absPath -> new AutoSyncID.ForDirectFileRequest(
desc.folderID, desc.folderID,
absPath.toFile())) absPath.toFile()
))
.collect(Collectors.toList()); .collect(Collectors.toList());
additionalFiles.forEach(aid -> BCLib.LOGGER.info(" * " + desc.localFolder.relativize(aid.relFile.toPath()) + " (missing on server)")); additionalFiles.forEach(aid -> BCLib.LOGGER.info(" * " + desc.localFolder.relativize(aid.relFile.toPath()) + " (missing on server)"));
@ -264,16 +271,20 @@ public class HelloClient extends DataHandler.FromServer {
//the file exists locally, check if the hashes match //the file exists locally, check if the hashes match
if (!localSubFile.hash.equals(subFile.hash)) { if (!localSubFile.hash.equals(subFile.hash)) {
BCLib.LOGGER.info(" * " + subFile.relPath + " (changed)"); BCLib.LOGGER.info(" * " + subFile.relPath + " (changed)");
filesToRequest.add(new AutoSyncID.ForDirectFileRequest(desc.folderID, filesToRequest.add(new AutoSyncID.ForDirectFileRequest(
new File(subFile.relPath))); desc.folderID,
new File(subFile.relPath)
));
} else { } else {
BCLib.LOGGER.info(" * " + subFile.relPath); BCLib.LOGGER.info(" * " + subFile.relPath);
} }
} else { } else {
//the file is missing locally //the file is missing locally
BCLib.LOGGER.info(" * " + subFile.relPath + " (missing on client)"); BCLib.LOGGER.info(" * " + subFile.relPath + " (missing on client)");
filesToRequest.add(new AutoSyncID.ForDirectFileRequest(desc.folderID, filesToRequest.add(new AutoSyncID.ForDirectFileRequest(
new File(subFile.relPath))); desc.folderID,
new File(subFile.relPath)
));
} }
}); });
@ -309,10 +320,12 @@ public class HelloClient extends DataHandler.FromServer {
if (contentWrapper.getRawContent() == null) { if (contentWrapper.getRawContent() == null) {
filesToRequest.add(new AutoSyncID(e.serverHash.modID, e.serverHash.uniqueID)); filesToRequest.add(new AutoSyncID(e.serverHash.modID, e.serverHash.uniqueID));
} else { } else {
filesToRequest.add(new AutoSyncID.WithContentOverride(e.serverHash.modID, filesToRequest.add(new AutoSyncID.WithContentOverride(
e.serverHash.modID,
e.serverHash.uniqueID, e.serverHash.uniqueID,
contentWrapper, contentWrapper,
e.localMatch.fileName)); e.localMatch.fileName
));
} }
} }
@ -389,12 +402,14 @@ public class HelloClient extends DataHandler.FromServer {
showSyncFilesScreen(client, filesToRequest, filesToRemove); showSyncFilesScreen(client, filesToRequest, filesToRemove);
return; return;
} else if (serverPublishedModInfo && mismatchingMods.size() > 0 && Configs.CLIENT_CONFIG.isShowingModInfo()) { } else if (serverPublishedModInfo && mismatchingMods.size() > 0 && Configs.CLIENT_CONFIG.isShowingModInfo()) {
client.setScreen(new ModListScreen(client.screen, client.setScreen(new ModListScreen(
client.screen,
Component.translatable("title.bclib.modmissmatch"), Component.translatable("title.bclib.modmissmatch"),
Component.translatable("message.bclib.modmissmatch"), Component.translatable("message.bclib.modmissmatch"),
CommonComponents.GUI_PROCEED, CommonComponents.GUI_PROCEED,
ModUtil.getMods(), ModUtil.getMods(),
modVersion)); modVersion
));
return; return;
} }
} }
@ -415,9 +430,11 @@ public class HelloClient extends DataHandler.FromServer {
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
protected void showSyncFilesScreen(Minecraft client, protected void showSyncFilesScreen(
List<AutoSyncID> files, Minecraft client,
final List<AutoSyncID.ForDirectFileRequest> filesToRemove) { List<AutoSyncID> files,
final List<AutoSyncID.ForDirectFileRequest> filesToRemove
) {
int configFiles = 0; int configFiles = 0;
int singleFiles = 0; int singleFiles = 0;
int folderFiles = 0; int folderFiles = 0;
@ -435,7 +452,8 @@ public class HelloClient extends DataHandler.FromServer {
} }
} }
client.setScreen(new SyncFilesScreen(modFiles, client.setScreen(new SyncFilesScreen(
modFiles,
configFiles, configFiles,
singleFiles, singleFiles,
folderFiles, folderFiles,
@ -468,7 +486,8 @@ public class HelloClient extends DataHandler.FromServer {
} }
this.onCloseSyncFilesScreen(); this.onCloseSyncFilesScreen();
})); }
));
} }
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
@ -498,9 +517,11 @@ public class HelloClient extends DataHandler.FromServer {
private void requestFileDownloads(List<AutoSyncID> files) { private void requestFileDownloads(List<AutoSyncID> files) {
BCLib.LOGGER.info("Starting download of Files:" + files.size()); BCLib.LOGGER.info("Starting download of Files:" + files.size());
final ProgressScreen progress = new ProgressScreen(null, final ProgressScreen progress = new ProgressScreen(
null,
Component.translatable("title.bclib.filesync.progress"), Component.translatable("title.bclib.filesync.progress"),
Component.translatable("message.bclib.filesync.progress")); Component.translatable("message.bclib.filesync.progress")
);
progress.progressStart(Component.translatable("message.bclib.filesync.progress.stage.empty")); progress.progressStart(Component.translatable("message.bclib.filesync.progress.stage.empty"));
ChunkerProgress.setProgressScreen(progress); ChunkerProgress.setProgressScreen(progress);

View file

@ -1,5 +1,12 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.ModUtil;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -9,13 +16,6 @@ import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.ModUtil;
import java.io.File; import java.io.File;
/** /**
@ -60,11 +60,15 @@ import java.io.File;
* </table> * </table>
*/ */
public class HelloServer extends DataHandler.FromClient { public class HelloServer extends DataHandler.FromClient {
public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(
"hello_server"), new ResourceLocation(
HelloServer::new, BCLib.MOD_ID,
true, "hello_server"
false); ),
HelloServer::new,
true,
false
);
protected String bclibVersion = "0.0.0"; protected String bclibVersion = "0.0.0";

View file

@ -1,5 +1,10 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.config.Configs;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -9,22 +14,21 @@ import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
import org.betterx.bclib.config.Configs;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class RequestFiles extends DataHandler.FromClient { public class RequestFiles extends DataHandler.FromClient {
public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(
"request_files"), new ResourceLocation(
RequestFiles::new, BCLib.MOD_ID,
false, "request_files"
false); ),
RequestFiles::new,
false,
false
);
static String currentToken = ""; static String currentToken = "";
protected List<AutoSyncID> files; protected List<AutoSyncID> files;

View file

@ -1,13 +1,5 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataHandler; import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor;
@ -17,6 +9,14 @@ import org.betterx.bclib.util.Pair;
import org.betterx.bclib.util.PathUtil; import org.betterx.bclib.util.PathUtil;
import org.betterx.bclib.util.Triple; import org.betterx.bclib.util.Triple;
import net.minecraft.client.Minecraft;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@ -26,11 +26,15 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class SendFiles extends DataHandler.FromServer { public class SendFiles extends DataHandler.FromServer {
public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(new ResourceLocation(BCLib.MOD_ID, public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor(
"send_files"), new ResourceLocation(
BCLib.MOD_ID,
"send_files"
),
SendFiles::new, SendFiles::new,
false, false,
false); false
);
protected List<AutoFileSyncEntry> files; protected List<AutoFileSyncEntry> files;
private String token; private String token;
@ -172,8 +176,10 @@ public class SendFiles extends DataHandler.FromServer {
path = PathUtil.MOD_FOLDER.resolve(name); path = PathUtil.MOD_FOLDER.resolve(name);
} }
count++; count++;
name = prefix + mase.modID + "_" + mase.version.replace(".", "_") + "__" + String.format("%03d", name = prefix + mase.modID + "_" + mase.version.replace(".", "_") + "__" + String.format(
count) + ".jar"; "%03d",
count
) + ".jar";
} while (path.toFile().exists()); } while (path.toFile().exists());
} }

View file

@ -1,7 +1,5 @@
package org.betterx.bclib.api.v2.dataexchange.handler.autosync; package org.betterx.bclib.api.v2.dataexchange.handler.autosync;
import net.minecraft.network.FriendlyByteBuf;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.dataexchange.DataHandler; import org.betterx.bclib.api.v2.dataexchange.DataHandler;
import org.betterx.bclib.api.v2.dataexchange.FileHash; import org.betterx.bclib.api.v2.dataexchange.FileHash;
@ -9,6 +7,8 @@ import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID.ForDire
import org.betterx.bclib.config.Configs; import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.PathUtil; import org.betterx.bclib.util.PathUtil;
import net.minecraft.network.FriendlyByteBuf;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -110,9 +110,11 @@ public class SyncFolderDescriptor {
public void loadCache() { public void loadCache() {
if (fileCache == null) { if (fileCache == null) {
fileCache = new ArrayList<>(8); fileCache = new ArrayList<>(8);
PathUtil.fileWalker(localFolder.toFile(), p -> fileCache.add(new SubFile(localFolder.relativize(p) PathUtil.fileWalker(localFolder.toFile(), p -> fileCache.add(new SubFile(
.toString(), localFolder.relativize(p)
FileHash.create(p.toFile())))); .toString(),
FileHash.create(p.toFile())
)));
/*//this tests if we can trick the system to load files that are not beneath the base-folder /*//this tests if we can trick the system to load files that are not beneath the base-folder
if (!BCLib.isClient()) { if (!BCLib.isClient()) {
@ -145,14 +147,16 @@ public class SyncFolderDescriptor {
final SyncFolderDescriptor desc; final SyncFolderDescriptor desc;
if (localDescriptor != null) { if (localDescriptor != null) {
desc = new SyncFolderDescriptor(folderID, desc = new SyncFolderDescriptor(
localDescriptor.localFolder, folderID,
localDescriptor.removeAdditionalFiles && remAddFiles); localDescriptor.localFolder,
localDescriptor.removeAdditionalFiles && remAddFiles
);
desc.fileCache = new ArrayList<>(count); desc.fileCache = new ArrayList<>(count);
} else { } else {
BCLib.LOGGER.warning(BCLib.isClient() BCLib.LOGGER.warning(BCLib.isClient()
? "Client" ? "Client"
: "Server" + " does not know Sync-Folder ID '" + folderID + "'"); : "Server" + " does not know Sync-Folder ID '" + folderID + "'");
desc = null; desc = null;
} }

View file

@ -1,5 +1,16 @@
package org.betterx.bclib.api.v2.datafixer; package org.betterx.bclib.api.v2.datafixer;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.client.gui.screens.AtomicProgressListener;
import org.betterx.bclib.client.gui.screens.ConfirmFixScreen;
import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen;
import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen.Listener;
import org.betterx.bclib.client.gui.screens.ProgressScreen;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.Logger;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.toasts.SystemToast; import net.minecraft.client.gui.components.toasts.SystemToast;
@ -16,17 +27,6 @@ import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment; import net.fabricmc.api.Environment;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.api.v2.levelgen.LevelGenUtil;
import org.betterx.bclib.client.gui.screens.AtomicProgressListener;
import org.betterx.bclib.client.gui.screens.ConfirmFixScreen;
import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen;
import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen.Listener;
import org.betterx.bclib.client.gui.screens.ProgressScreen;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.util.Logger;
import java.io.*; import java.io.*;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
@ -72,9 +72,11 @@ public class DataFixerAPI {
void call(); void call();
} }
private static boolean wrapCall(LevelStorageSource levelSource, private static boolean wrapCall(
String levelID, LevelStorageSource levelSource,
Function<LevelStorageAccess, Boolean> runWithLevel) { String levelID,
Function<LevelStorageAccess, Boolean> runWithLevel
) {
LevelStorageSource.LevelStorageAccess levelStorageAccess; LevelStorageSource.LevelStorageAccess levelStorageAccess;
try { try {
levelStorageAccess = levelSource.createAccess(levelID); levelStorageAccess = levelSource.createAccess(levelID);
@ -108,10 +110,12 @@ public class DataFixerAPI {
* @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and
* patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world.
*/ */
public static boolean fixData(LevelStorageSource levelSource, public static boolean fixData(
String levelID, LevelStorageSource levelSource,
boolean showUI, String levelID,
Consumer<Boolean> onResume) { boolean showUI,
Consumer<Boolean> onResume
) {
return wrapCall(levelSource, levelID, (levelStorageAccess) -> fixData(levelStorageAccess, showUI, onResume)); return wrapCall(levelSource, levelID, (levelStorageAccess) -> fixData(levelStorageAccess, showUI, onResume));
} }
@ -125,9 +129,11 @@ public class DataFixerAPI {
* @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and
* patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world.
*/ */
public static boolean fixData(LevelStorageSource.LevelStorageAccess levelStorageAccess, public static boolean fixData(
boolean showUI, LevelStorageSource.LevelStorageAccess levelStorageAccess,
Consumer<Boolean> onResume) { boolean showUI,
Consumer<Boolean> onResume
) {
File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(); File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile();
File levelDat = levelStorageAccess.getLevelPath(LevelResource.LEVEL_DATA_FILE).toFile(); File levelDat = levelStorageAccess.getLevelPath(LevelResource.LEVEL_DATA_FILE).toFile();
boolean newWorld = false; boolean newWorld = false;
@ -203,9 +209,11 @@ public class DataFixerAPI {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
private static AtomicProgressListener showProgressScreen() { private static AtomicProgressListener showProgressScreen() {
ProgressScreen ps = new ProgressScreen(Minecraft.getInstance().screen, ProgressScreen ps = new ProgressScreen(
Minecraft.getInstance().screen,
Component.translatable("title.bclib.datafixer.progress"), Component.translatable("title.bclib.datafixer.progress"),
Component.translatable("message.bclib.datafixer.progress")); Component.translatable("message.bclib.datafixer.progress")
);
Minecraft.getInstance().setScreen(ps); Minecraft.getInstance().setScreen(ps);
return ps; return ps;
} }
@ -311,9 +319,11 @@ public class DataFixerAPI {
@Environment(EnvType.CLIENT) @Environment(EnvType.CLIENT)
private static void showLevelFixErrorScreen(State state, Listener onContinue) { private static void showLevelFixErrorScreen(State state, Listener onContinue) {
Minecraft.getInstance() Minecraft.getInstance()
.setScreen(new LevelFixErrorScreen(Minecraft.getInstance().screen, .setScreen(new LevelFixErrorScreen(
Minecraft.getInstance().screen,
state.getErrorMessages(), state.getErrorMessages(),
onContinue)); onContinue
));
} }
private static MigrationProfile loadProfileIfNeeded(File levelBaseDir) { private static MigrationProfile loadProfileIfNeeded(File levelBaseDir) {
@ -524,9 +534,13 @@ public class DataFixerAPI {
}); });
try { try {
changed[0] |= data.patchBlockState(palette, changed[0] |= data.patchBlockState(
((CompoundTag) tag).getList("BlockStates", palette,
Tag.TAG_LONG)); ((CompoundTag) tag).getList(
"BlockStates",
Tag.TAG_LONG
)
);
} catch (PatchDidiFailException e) { } catch (PatchDidiFailException e) {
BCLib.LOGGER.error("Failed fixing BlockState in " + pos); BCLib.LOGGER.error("Failed fixing BlockState in " + pos);
state.addError("Failed fixing BlockState in " + pos + " (" + e.getMessage() + ")"); state.addError("Failed fixing BlockState in " + pos + " (" + e.getMessage() + ")");

View file

@ -1,11 +1,11 @@
package org.betterx.bclib.api.v2.datafixer; package org.betterx.bclib.api.v2.datafixer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import org.betterx.bclib.interfaces.PatchBiFunction; import org.betterx.bclib.interfaces.PatchBiFunction;
import org.betterx.bclib.interfaces.PatchFunction; import org.betterx.bclib.interfaces.PatchFunction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View file

@ -1,16 +1,16 @@
package org.betterx.bclib.api.v2.datafixer; package org.betterx.bclib.api.v2.datafixer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.Tag;
import org.betterx.bclib.BCLib; import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.WorldDataAPI; import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.interfaces.PatchBiFunction; import org.betterx.bclib.interfaces.PatchBiFunction;
import org.betterx.bclib.interfaces.PatchFunction; import org.betterx.bclib.interfaces.PatchFunction;
import org.betterx.bclib.util.ModUtil; import org.betterx.bclib.util.ModUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.Tag;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
@ -225,10 +225,12 @@ public class MigrationProfile {
final public void markApplied() { final public void markApplied() {
for (String modID : mods) { for (String modID : mods) {
DataFixerAPI.LOGGER.info("Updating Patch-Level for '{}' from {} to {}", DataFixerAPI.LOGGER.info(
modID, "Updating Patch-Level for '{}' from {} to {}",
ModUtil.convertModVersion(currentPatchLevel(modID)), modID,
ModUtil.convertModVersion(Patch.maxPatchLevel(modID))); ModUtil.convertModVersion(currentPatchLevel(modID)),
ModUtil.convertModVersion(Patch.maxPatchLevel(modID))
);
if (config != null) if (config != null)
config.putString(modID, Patch.maxPatchVersion(modID)); config.putString(modID, Patch.maxPatchVersion(modID));
} }

View file

@ -1,13 +1,13 @@
package org.betterx.bclib.api.v2.datafixer; package org.betterx.bclib.api.v2.datafixer;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import org.betterx.bclib.api.v2.WorldDataAPI; import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.interfaces.PatchBiFunction; import org.betterx.bclib.interfaces.PatchBiFunction;
import org.betterx.bclib.interfaces.PatchFunction; import org.betterx.bclib.interfaces.PatchFunction;
import org.betterx.bclib.util.ModUtil; import org.betterx.bclib.util.ModUtil;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -7,7 +9,6 @@ import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.BiomeSource;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@ -35,10 +36,12 @@ public abstract class BCLBiomeSource extends BiomeSource {
return biomes; return biomes;
} }
protected BCLBiomeSource(Registry<Biome> biomeRegistry, protected BCLBiomeSource(
List<Holder<Biome>> list, Registry<Biome> biomeRegistry,
long seed, List<Holder<Biome>> list,
Optional<Integer> biomeSourceVersion) { long seed,
Optional<Integer> biomeSourceVersion
) {
super(preInit(biomeRegistry, list)); super(preInit(biomeRegistry, list));
this.biomeRegistry = biomeRegistry; this.biomeRegistry = biomeRegistry;
@ -88,10 +91,12 @@ public abstract class BCLBiomeSource extends BiomeSource {
boolean isValid(Holder<Biome> biome, ResourceLocation location); boolean isValid(Holder<Biome> biome, ResourceLocation location);
} }
protected static List<Holder<Biome>> getBiomes(Registry<Biome> biomeRegistry, protected static List<Holder<Biome>> getBiomes(
List<String> exclude, Registry<Biome> biomeRegistry,
List<String> include, List<String> exclude,
BCLibNetherBiomeSource.ValidBiomePredicate test) { List<String> include,
BCLibNetherBiomeSource.ValidBiomePredicate test
) {
return biomeRegistry.stream() return biomeRegistry.stream()
.filter(biome -> biomeRegistry.getResourceKey(biome).isPresent()) .filter(biome -> biomeRegistry.getResourceKey(biome).isPresent())

View file

@ -1,5 +1,13 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleUtil;
import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider;
import org.betterx.bclib.interfaces.SurfaceRuleProvider;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryOps; import net.minecraft.resources.RegistryOps;
@ -15,14 +23,6 @@ import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureSet;
import net.minecraft.world.level.levelgen.synth.NormalNoise; import net.minecraft.world.level.levelgen.synth.NormalNoise;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleUtil;
import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider;
import org.betterx.bclib.interfaces.SurfaceRuleProvider;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.Predicate; import java.util.function.Predicate;
@ -53,10 +53,12 @@ public class BCLChunkGenerator extends NoiseBasedChunkGenerator {
}); });
public BCLChunkGenerator(Registry<StructureSet> registry, public BCLChunkGenerator(
Registry<NormalNoise.NoiseParameters> registry2, Registry<StructureSet> registry,
BiomeSource biomeSource, Registry<NormalNoise.NoiseParameters> registry2,
Holder<NoiseGeneratorSettings> holder) { BiomeSource biomeSource,
Holder<NoiseGeneratorSettings> holder
) {
super(registry, registry2, biomeSource, holder); super(registry, registry2, biomeSource, holder);
System.out.println("Chunk Generator: " + this); System.out.println("Chunk Generator: " + this);
} }
@ -65,8 +67,10 @@ public class BCLChunkGenerator extends NoiseBasedChunkGenerator {
BCLChunkGenerator.injectNoiseSettings(settings, BCLChunkGenerator.ALL_DIMENSIONS); BCLChunkGenerator.injectNoiseSettings(settings, BCLChunkGenerator.ALL_DIMENSIONS);
} }
public static void injectNoiseSettings(ResourceKey<LevelStem> dimensionKey, public static void injectNoiseSettings(
ChunkGenerator loadedChunkGenerator) { ResourceKey<LevelStem> dimensionKey,
ChunkGenerator loadedChunkGenerator
) {
BCLib.LOGGER.debug("Checking Noise Settings for " + dimensionKey.location().toString()); BCLib.LOGGER.debug("Checking Noise Settings for " + dimensionKey.location().toString());
final BiomeSource loadedBiomeSource = loadedChunkGenerator.getBiomeSource(); final BiomeSource loadedBiomeSource = loadedChunkGenerator.getBiomeSource();
InternalBiomeAPI.applyModifications(loadedBiomeSource, dimensionKey); InternalBiomeAPI.applyModifications(loadedBiomeSource, dimensionKey);
@ -121,9 +125,11 @@ public class BCLChunkGenerator extends NoiseBasedChunkGenerator {
public static RandomState createRandomState(ServerLevel level, ChunkGenerator generator) { public static RandomState createRandomState(ServerLevel level, ChunkGenerator generator) {
if (generator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { if (generator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) {
return RandomState.create(noiseBasedChunkGenerator.generatorSettings().value(), return RandomState.create(
noiseBasedChunkGenerator.generatorSettings().value(),
level.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY), level.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY),
level.getSeed()); level.getSeed()
);
} else { } else {
return RandomState.create(level.registryAccess(), NoiseGeneratorSettings.OVERWORLD, level.getSeed()); return RandomState.create(level.registryAccess(), NoiseGeneratorSettings.OVERWORLD, level.getSeed());
} }

View file

@ -1,5 +1,18 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap;
import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.config.ConfigKeeper.StringArrayEntry;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.interfaces.BiomeMap;
import org.betterx.bclib.interfaces.TheEndBiomeDataAccessor;
import org.betterx.bclib.noise.OpenSimplexNoise;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryOps; import net.minecraft.resources.RegistryOps;
@ -16,19 +29,6 @@ import net.minecraft.world.level.levelgen.synth.SimplexNoise;
import net.fabricmc.fabric.impl.biome.TheEndBiomeData; import net.fabricmc.fabric.impl.biome.TheEndBiomeData;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap;
import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.config.ConfigKeeper.StringArrayEntry;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.interfaces.BiomeMap;
import org.betterx.bclib.interfaces.TheEndBiomeDataAccessor;
import org.betterx.bclib.noise.OpenSimplexNoise;
import java.awt.*; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -52,8 +52,10 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
.INT .INT
.optionalFieldOf("version") .optionalFieldOf("version")
.stable() .stable()
.forGetter(source -> Optional.of(source.biomeSourceVersion))) .forGetter(source -> Optional.of(source.biomeSourceVersion))
.apply(instance, )
.apply(
instance,
instance.stable(BCLibEndBiomeSource::new) instance.stable(BCLibEndBiomeSource::new)
) )
); );
@ -80,23 +82,29 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
this(biomeRegistry, getBiomes(biomeRegistry), seed, version, initMaps); this(biomeRegistry, getBiomes(biomeRegistry), seed, version, initMaps);
} }
private BCLibEndBiomeSource(Registry<Biome> biomeRegistry, private BCLibEndBiomeSource(
List<Holder<Biome>> list, Registry<Biome> biomeRegistry,
long seed, List<Holder<Biome>> list,
Optional<Integer> version, long seed,
boolean initMaps) { Optional<Integer> version,
boolean initMaps
) {
super(biomeRegistry, list, seed, version); super(biomeRegistry, list, seed, version);
endLandBiomePicker = new BiomePicker(biomeRegistry); endLandBiomePicker = new BiomePicker(biomeRegistry);
endVoidBiomePicker = new BiomePicker(biomeRegistry); endVoidBiomePicker = new BiomePicker(biomeRegistry);
List<String> includeVoid = Configs.BIOMES_CONFIG.getEntry("force_include", List<String> includeVoid = Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_void_biomes", "end_void_biomes",
StringArrayEntry.class).getValue(); StringArrayEntry.class
).getValue();
List<String> includeLand = Configs.BIOMES_CONFIG.getEntry("force_include", List<String> includeLand = Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_land_biomes", "end_land_biomes",
StringArrayEntry.class).getValue(); StringArrayEntry.class
).getValue();
this.possibleBiomes().forEach(biome -> { this.possibleBiomes().forEach(biome -> {
ResourceLocation key = biome.unwrapKey().orElseThrow().location(); ResourceLocation key = biome.unwrapKey().orElseThrow().location();
String group = key.getNamespace() + "." + key.getPath(); String group = key.getNamespace() + "." + key.getPath();
@ -115,7 +123,7 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
if (bclBiome.getParentBiome() == null) { if (bclBiome.getParentBiome() == null) {
if (BiomeAPI.wasRegisteredAsEndVoidBiome(key) || includeVoid.contains(key.toString())) { if (BiomeAPI.wasRegisteredAsEndVoidBiome(key) || includeVoid.contains(key.toString())) {
endVoidBiomePicker.addBiome(bclBiome); endVoidBiomePicker.addBiome(bclBiome);
} else if (BiomeAPI.wasRegisteredAsEndLandBiome(key) || includeLand.contains(key.toString()) ){ } else if (BiomeAPI.wasRegisteredAsEndLandBiome(key) || includeLand.contains(key.toString())) {
endLandBiomePicker.addBiome(bclBiome); endLandBiomePicker.addBiome(bclBiome);
} }
} }
@ -141,22 +149,29 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
protected BCLBiomeSource cloneForDatapack(Set<Holder<Biome>> datapackBiomes) { protected BCLBiomeSource cloneForDatapack(Set<Holder<Biome>> datapackBiomes) {
datapackBiomes.addAll(getBclBiomes(this.biomeRegistry)); datapackBiomes.addAll(getBclBiomes(this.biomeRegistry));
return new BCLibEndBiomeSource(this.biomeRegistry, return new BCLibEndBiomeSource(
this.biomeRegistry,
datapackBiomes.stream().toList(), datapackBiomes.stream().toList(),
this.currentSeed, this.currentSeed,
Optional.of(biomeSourceVersion), Optional.of(biomeSourceVersion),
true); true
);
} }
private static List<Holder<Biome>> getBclBiomes(Registry<Biome> biomeRegistry) { private static List<Holder<Biome>> getBclBiomes(Registry<Biome> biomeRegistry) {
List<String> include = Configs.BIOMES_CONFIG.getEntry("force_include", List<String> include = Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_land_biomes", "end_land_biomes",
StringArrayEntry.class).getValue(); StringArrayEntry.class
include.addAll(Configs.BIOMES_CONFIG.getEntry("force_include", ).getValue();
include.addAll(Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_void_biomes", "end_void_biomes",
StringArrayEntry.class).getValue()); StringArrayEntry.class
).getValue());
if (TheEndBiomeData.createOverrides(biomeRegistry) instanceof TheEndBiomeDataAccessor acc) { if (TheEndBiomeData.createOverrides(biomeRegistry) instanceof TheEndBiomeDataAccessor acc) {
return getBiomes(biomeRegistry, return getBiomes(
biomeRegistry,
new ArrayList<>(0), new ArrayList<>(0),
include, include,
(biome, location) -> (biome, location) ->
@ -165,23 +180,30 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
); );
} else { } else {
return getBiomes(biomeRegistry, return getBiomes(
biomeRegistry,
new ArrayList<>(0), new ArrayList<>(0),
include, include,
BCLibEndBiomeSource::isValidNonVanillaEndBiome); BCLibEndBiomeSource::isValidNonVanillaEndBiome
);
} }
} }
private static List<Holder<Biome>> getBiomes(Registry<Biome> biomeRegistry) { private static List<Holder<Biome>> getBiomes(Registry<Biome> biomeRegistry) {
List<String> include = Configs.BIOMES_CONFIG.getEntry("force_include", List<String> include = Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_land_biomes", "end_land_biomes",
StringArrayEntry.class).getValue(); StringArrayEntry.class
include.addAll(Configs.BIOMES_CONFIG.getEntry("force_include", ).getValue();
include.addAll(Configs.BIOMES_CONFIG.getEntry(
"force_include",
"end_void_biomes", "end_void_biomes",
StringArrayEntry.class).getValue()); StringArrayEntry.class
).getValue());
if (TheEndBiomeData.createOverrides(biomeRegistry) instanceof TheEndBiomeDataAccessor acc) { if (TheEndBiomeData.createOverrides(biomeRegistry) instanceof TheEndBiomeDataAccessor acc) {
return getBiomes(biomeRegistry, return getBiomes(
biomeRegistry,
new ArrayList<>(0), new ArrayList<>(0),
include, include,
(biome, location) -> (biome, location) ->
@ -236,19 +258,27 @@ public class BCLibEndBiomeSource extends BCLBiomeSource {
@Override @Override
protected void onInitMap(long seed) { protected void onInitMap(long seed) {
if ((biomeSourceVersion != BIOME_SOURCE_VERSION_HEX)) { if ((biomeSourceVersion != BIOME_SOURCE_VERSION_HEX)) {
this.mapLand = new SquareBiomeMap(seed, this.mapLand = new SquareBiomeMap(
seed,
GeneratorOptions.getBiomeSizeEndLand(), GeneratorOptions.getBiomeSizeEndLand(),
endLandBiomePicker); endLandBiomePicker
this.mapVoid = new SquareBiomeMap(seed, );
this.mapVoid = new SquareBiomeMap(
seed,
GeneratorOptions.getBiomeSizeEndVoid(), GeneratorOptions.getBiomeSizeEndVoid(),
endVoidBiomePicker); endVoidBiomePicker
);
} else { } else {
this.mapLand = new HexBiomeMap(seed, this.mapLand = new HexBiomeMap(
seed,
GeneratorOptions.getBiomeSizeEndLand(), GeneratorOptions.getBiomeSizeEndLand(),
endLandBiomePicker); endLandBiomePicker
this.mapVoid = new HexBiomeMap(seed, );
this.mapVoid = new HexBiomeMap(
seed,
GeneratorOptions.getBiomeSizeEndVoid(), GeneratorOptions.getBiomeSizeEndVoid(),
endVoidBiomePicker); endVoidBiomePicker
);
} }
WorldgenRandom chunkRandom = new WorldgenRandom(new LegacyRandomSource(seed)); WorldgenRandom chunkRandom = new WorldgenRandom(new LegacyRandomSource(seed));

View file

@ -1,5 +1,17 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.generator.map.MapStack;
import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap;
import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.config.ConfigKeeper.StringArrayEntry;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.interfaces.BiomeMap;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryOps; import net.minecraft.resources.RegistryOps;
@ -11,18 +23,7 @@ import net.minecraft.world.level.biome.Climate;
import net.fabricmc.fabric.impl.biome.NetherBiomeData; import net.fabricmc.fabric.impl.biome.NetherBiomeData;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.apache.commons.lang3.function.TriFunction; import org.apache.commons.lang3.function.TriFunction;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.generator.map.MapStack;
import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap;
import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.config.ConfigKeeper.StringArrayEntry;
import org.betterx.bclib.config.Configs;
import org.betterx.bclib.interfaces.BiomeMap;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -33,7 +34,8 @@ public class BCLibNetherBiomeSource extends BCLBiomeSource {
private static int worldHeight; private static int worldHeight;
public static final Codec<BCLibNetherBiomeSource> CODEC = RecordCodecBuilder public static final Codec<BCLibNetherBiomeSource> CODEC = RecordCodecBuilder
.create(instance -> instance .create(instance -> instance
.group(RegistryOps .group(
RegistryOps
.retrieveRegistry(Registry.BIOME_REGISTRY) .retrieveRegistry(Registry.BIOME_REGISTRY)
.forGetter(source -> source.biomeRegistry), .forGetter(source -> source.biomeRegistry),
Codec Codec
@ -62,18 +64,22 @@ public class BCLibNetherBiomeSource extends BCLBiomeSource {
this(biomeRegistry, seed, version, true); this(biomeRegistry, seed, version, true);
} }
private BCLibNetherBiomeSource(Registry<Biome> biomeRegistry, private BCLibNetherBiomeSource(
long seed, Registry<Biome> biomeRegistry,
Optional<Integer> version, long seed,
boolean initMaps) { Optional<Integer> version,
boolean initMaps
) {
this(biomeRegistry, getBiomes(biomeRegistry), seed, version, initMaps); this(biomeRegistry, getBiomes(biomeRegistry), seed, version, initMaps);
} }
private BCLibNetherBiomeSource(Registry<Biome> biomeRegistry, private BCLibNetherBiomeSource(
List<Holder<Biome>> list, Registry<Biome> biomeRegistry,
long seed, List<Holder<Biome>> list,
Optional<Integer> version, long seed,
boolean initMaps) { Optional<Integer> version,
boolean initMaps
) {
super(biomeRegistry, list, seed, version); super(biomeRegistry, list, seed, version);
biomePicker = new BiomePicker(biomeRegistry); biomePicker = new BiomePicker(biomeRegistry);
@ -103,11 +109,13 @@ public class BCLibNetherBiomeSource extends BCLBiomeSource {
protected BCLBiomeSource cloneForDatapack(Set<Holder<Biome>> datapackBiomes) { protected BCLBiomeSource cloneForDatapack(Set<Holder<Biome>> datapackBiomes) {
datapackBiomes.addAll(getBclBiomes(this.biomeRegistry)); datapackBiomes.addAll(getBclBiomes(this.biomeRegistry));
return new BCLibNetherBiomeSource(this.biomeRegistry, return new BCLibNetherBiomeSource(
this.biomeRegistry,
datapackBiomes.stream().toList(), datapackBiomes.stream().toList(),
this.currentSeed, this.currentSeed,
Optional.of(biomeSourceVersion), Optional.of(biomeSourceVersion),
true); true
);
} }
/** /**
@ -196,9 +204,11 @@ public class BCLibNetherBiomeSource extends BCLBiomeSource {
mapConstructor mapConstructor
); );
} else { } else {
this.biomeMap = mapConstructor.apply(seed, this.biomeMap = mapConstructor.apply(
seed,
GeneratorOptions.getBiomeSizeNether(), GeneratorOptions.getBiomeSizeNether(),
biomePicker); biomePicker
);
} }
} }

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.util.WeighTree;
import org.betterx.bclib.util.WeightedList;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
@ -7,9 +11,6 @@ import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.levelgen.WorldgenRandom; import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome;
import org.betterx.bclib.util.WeighTree;
import org.betterx.bclib.util.WeightedList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;

View file

@ -1,9 +1,9 @@
package org.betterx.bclib.api.v2.generator; package org.betterx.bclib.api.v2.generator;
import net.minecraft.util.Mth;
import org.betterx.bclib.config.Configs; import org.betterx.bclib.config.Configs;
import net.minecraft.util.Mth;
import java.awt.*; import java.awt.*;
import java.util.function.Function; import java.util.function.Function;
@ -22,9 +22,11 @@ public class GeneratorOptions {
public static void init() { public static void init() {
biomeSizeNether = Configs.GENERATOR_CONFIG.getInt("nether.biomeMap", "biomeSize", 256); biomeSizeNether = Configs.GENERATOR_CONFIG.getInt("nether.biomeMap", "biomeSize", 256);
biomeVSizeNether = Configs.GENERATOR_CONFIG.getInt("nether.biomeMap", biomeVSizeNether = Configs.GENERATOR_CONFIG.getInt(
"nether.biomeMap",
"biomeVerticalSize(onlyInTallNether)", "biomeVerticalSize(onlyInTallNether)",
86); 86
);
biomeSizeEndLand = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeLand", 256); biomeSizeEndLand = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeLand", 256);
biomeSizeEndVoid = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeVoid", 256); biomeSizeEndVoid = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeVoid", 256);
customNetherBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options", "customNetherBiomeSource", true); customNetherBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options", "customNetherBiomeSource", true);

View file

@ -1,14 +1,15 @@
package org.betterx.bclib.api.v2.generator.map; package org.betterx.bclib.api.v2.generator.map;
import net.minecraft.util.Mth;
import org.apache.commons.lang3.function.TriFunction;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.interfaces.BiomeChunk; import org.betterx.bclib.interfaces.BiomeChunk;
import org.betterx.bclib.interfaces.BiomeMap; import org.betterx.bclib.interfaces.BiomeMap;
import org.betterx.bclib.interfaces.TriConsumer; import org.betterx.bclib.interfaces.TriConsumer;
import org.betterx.bclib.noise.OpenSimplexNoise; import org.betterx.bclib.noise.OpenSimplexNoise;
import net.minecraft.util.Mth;
import org.apache.commons.lang3.function.TriFunction;
import java.util.Random; import java.util.Random;
public class MapStack implements BiomeMap { public class MapStack implements BiomeMap {
@ -20,12 +21,14 @@ public class MapStack implements BiomeMap {
private final int maxValue; private final int maxValue;
private final int maxIndex; private final int maxIndex;
public MapStack(long seed, public MapStack(
int size, long seed,
BiomePicker picker, int size,
int mapHeight, BiomePicker picker,
int worldHeight, int mapHeight,
TriFunction<Long, Integer, BiomePicker, BiomeMap> mapConstructor) { int worldHeight,
TriFunction<Long, Integer, BiomePicker, BiomeMap> mapConstructor
) {
final int mapCount = Mth.ceil((float) worldHeight / mapHeight); final int mapCount = Mth.ceil((float) worldHeight / mapHeight);
this.maxIndex = mapCount - 1; this.maxIndex = mapCount - 1;
this.worldHeight = worldHeight; this.worldHeight = worldHeight;
@ -66,8 +69,10 @@ public class MapStack implements BiomeMap {
} else if (y > maxValue) { } else if (y > maxValue) {
mapIndex = maxIndex; mapIndex = maxIndex;
} else { } else {
mapIndex = Mth.floor((y + noise.eval(x * 0.03, mapIndex = Mth.floor((y + noise.eval(
z * 0.03) * layerDistortion) / worldHeight * maxIndex + 0.5F); x * 0.03,
z * 0.03
) * layerDistortion) / worldHeight * maxIndex + 0.5F);
mapIndex = Mth.clamp(mapIndex, 0, maxIndex); mapIndex = Mth.clamp(mapIndex, 0, maxIndex);
} }

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.generator.map.hex; package org.betterx.bclib.api.v2.generator.map.hex;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.interfaces.BiomeChunk; import org.betterx.bclib.interfaces.BiomeChunk;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import java.util.Arrays; import java.util.Arrays;
public class HexBiomeChunk implements BiomeChunk { public class HexBiomeChunk implements BiomeChunk {
@ -83,10 +83,12 @@ public class HexBiomeChunk implements BiomeChunk {
System.arraycopy(outBuffer, 0, this.biomes, 0, SIZE); System.arraycopy(outBuffer, 0, this.biomes, 0, SIZE);
} }
private void circle(BiomePicker.ActualBiome[] buffer, private void circle(
short center, BiomePicker.ActualBiome[] buffer,
BiomePicker.ActualBiome biome, short center,
BiomePicker.ActualBiome mask) { BiomePicker.ActualBiome biome,
BiomePicker.ActualBiome mask
) {
if (buffer[center] == mask) { if (buffer[center] == mask) {
buffer[center] = biome; buffer[center] = biome;
} }

View file

@ -1,10 +1,5 @@
package org.betterx.bclib.api.v2.generator.map.hex; package org.betterx.bclib.api.v2.generator.map.hex;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Maps;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.interfaces.BiomeChunk; import org.betterx.bclib.interfaces.BiomeChunk;
import org.betterx.bclib.interfaces.BiomeMap; import org.betterx.bclib.interfaces.BiomeMap;
@ -12,6 +7,12 @@ import org.betterx.bclib.interfaces.TriConsumer;
import org.betterx.bclib.noise.OpenSimplexNoise; import org.betterx.bclib.noise.OpenSimplexNoise;
import org.betterx.bclib.util.MHelper; import org.betterx.bclib.util.MHelper;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Maps;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.generator.map.square; package org.betterx.bclib.api.v2.generator.map.square;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.interfaces.BiomeChunk; import org.betterx.bclib.interfaces.BiomeChunk;
import net.minecraft.world.level.levelgen.WorldgenRandom;
public class SquareBiomeChunk implements BiomeChunk { public class SquareBiomeChunk implements BiomeChunk {
private static final int BIT_OFFSET = 4; private static final int BIT_OFFSET = 4;
protected static final int WIDTH = 1 << BIT_OFFSET; protected static final int WIDTH = 1 << BIT_OFFSET;

View file

@ -1,10 +1,5 @@
package org.betterx.bclib.api.v2.generator.map.square; package org.betterx.bclib.api.v2.generator.map.square;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Maps;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.interfaces.BiomeChunk; import org.betterx.bclib.interfaces.BiomeChunk;
import org.betterx.bclib.interfaces.BiomeMap; import org.betterx.bclib.interfaces.BiomeMap;
@ -12,6 +7,12 @@ import org.betterx.bclib.interfaces.TriConsumer;
import org.betterx.bclib.noise.OpenSimplexNoise; import org.betterx.bclib.noise.OpenSimplexNoise;
import org.betterx.bclib.util.MHelper; import org.betterx.bclib.util.MHelper;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Maps;
import java.util.Map; import java.util.Map;
public class SquareBiomeMap implements BiomeMap { public class SquareBiomeMap implements BiomeMap {
@ -124,8 +125,10 @@ public class SquareBiomeMap implements BiomeMap {
z += (ix / 2) & 1; z += (ix / 2) & 1;
} }
ChunkPos cpos = new ChunkPos(MHelper.floor(x / SquareBiomeChunk.WIDTH), ChunkPos cpos = new ChunkPos(
MHelper.floor(z / SquareBiomeChunk.WIDTH)); MHelper.floor(x / SquareBiomeChunk.WIDTH),
MHelper.floor(z / SquareBiomeChunk.WIDTH)
);
SquareBiomeChunk chunk = maps.get(cpos); SquareBiomeChunk chunk = maps.get(cpos);
if (chunk == null) { if (chunk == null) {
synchronized (random) { synchronized (random) {

View file

@ -1,5 +1,20 @@
package org.betterx.bclib.api.v2.levelgen; package org.betterx.bclib.api.v2.levelgen;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.api.v2.generator.BCLBiomeSource;
import org.betterx.bclib.api.v2.generator.BCLChunkGenerator;
import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource;
import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource;
import org.betterx.bclib.mixin.common.RegistryOpsAccessor;
import org.betterx.bclib.presets.worldgen.BCLWorldPresetSettings;
import org.betterx.bclib.presets.worldgen.BCLWorldPresets;
import org.betterx.bclib.presets.worldgen.WorldPresetSettings;
import org.betterx.bclib.util.ModUtil;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.MappedRegistry; import net.minecraft.core.MappedRegistry;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
@ -21,21 +36,6 @@ import net.minecraft.world.level.levelgen.presets.WorldPreset;
import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.StructureSet;
import net.minecraft.world.level.levelgen.synth.NormalNoise; import net.minecraft.world.level.levelgen.synth.NormalNoise;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.WorldDataAPI;
import org.betterx.bclib.api.v2.generator.BCLBiomeSource;
import org.betterx.bclib.api.v2.generator.BCLChunkGenerator;
import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource;
import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource;
import org.betterx.bclib.mixin.common.RegistryOpsAccessor;
import org.betterx.bclib.presets.worldgen.BCLWorldPresetSettings;
import org.betterx.bclib.presets.worldgen.BCLWorldPresets;
import org.betterx.bclib.presets.worldgen.WorldPresetSettings;
import org.betterx.bclib.util.ModUtil;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -43,7 +43,7 @@ import org.jetbrains.annotations.NotNull;
public class LevelGenUtil { public class LevelGenUtil {
private static final String TAG_VERSION = "version"; private static final String TAG_VERSION = "version";
private static final String TAG_BN_GEN_VERSION = "generator_version"; private static final String TAG_BN_GEN_VERSION = "generator_version";
private static String TAG_GENERATOR = "generator"; private static final String TAG_GENERATOR = "generator";
@NotNull @NotNull
public static LevelStem getBCLNetherLevelStem(Context context, Optional<Integer> version) { public static LevelStem getBCLNetherLevelStem(Context context, Optional<Integer> version) {
@ -58,7 +58,8 @@ public class LevelGenUtil {
context.structureSets, context.structureSets,
context.noiseParameters, context.noiseParameters,
biomeSource, biomeSource,
context.generatorSettings) context.generatorSettings
)
); );
} }
@ -70,7 +71,8 @@ public class LevelGenUtil {
context.structureSets, context.structureSets,
context.noiseParameters, context.noiseParameters,
biomeSource, biomeSource,
context.generatorSettings) context.generatorSettings
)
); );
} }
@ -88,8 +90,10 @@ public class LevelGenUtil {
* @see BCLChunkGenerator#injectNoiseSettings(WorldGenSettings) for the correcponding behaviour * @see BCLChunkGenerator#injectNoiseSettings(WorldGenSettings) for the correcponding behaviour
* for new worlds * for new worlds
*/ */
public static WorldGenSettings fixSettingsInCurrentWorld(Optional<RegistryOps<Tag>> registryOps, public static WorldGenSettings fixSettingsInCurrentWorld(
WorldGenSettings settings) { Optional<RegistryOps<Tag>> registryOps,
WorldGenSettings settings
) {
if (registryOps.orElse(null) instanceof RegistryOpsAccessor acc) { if (registryOps.orElse(null) instanceof RegistryOpsAccessor acc) {
return getWorldSettings().repairSettingsOnLoad(acc.bcl_getRegistryAccess(), settings); return getWorldSettings().repairSettingsOnLoad(acc.bcl_getRegistryAccess(), settings);
} else { } else {
@ -98,11 +102,13 @@ public class LevelGenUtil {
return settings; return settings;
} }
public static WorldGenSettings createWorldFromPreset(ResourceKey<WorldPreset> preset, public static WorldGenSettings createWorldFromPreset(
RegistryAccess registryAccess, ResourceKey<WorldPreset> preset,
long seed, RegistryAccess registryAccess,
boolean generateStructures, long seed,
boolean generateBonusChest) { boolean generateStructures,
boolean generateBonusChest
) {
WorldGenSettings settings = registryAccess WorldGenSettings settings = registryAccess
.registryOrThrow(Registry.WORLD_PRESET_REGISTRY) .registryOrThrow(Registry.WORLD_PRESET_REGISTRY)
.getHolderOrThrow(preset) .getHolderOrThrow(preset)
@ -118,15 +124,19 @@ public class LevelGenUtil {
return settings; return settings;
} }
public static WorldGenSettings createDefaultWorldFromPreset(RegistryAccess registryAccess, public static WorldGenSettings createDefaultWorldFromPreset(
long seed, RegistryAccess registryAccess,
boolean generateStructures, long seed,
boolean generateBonusChest) { boolean generateStructures,
return createWorldFromPreset(BCLWorldPresets.DEFAULT.orElseThrow(), boolean generateBonusChest
) {
return createWorldFromPreset(
BCLWorldPresets.DEFAULT.orElseThrow(),
registryAccess, registryAccess,
seed, seed,
generateStructures, generateStructures,
generateBonusChest); generateBonusChest
);
} }
public static Pair<WorldGenSettings, RegistryAccess.Frozen> defaultWorldDataSupplier(RegistryAccess.Frozen frozen) { public static Pair<WorldGenSettings, RegistryAccess.Frozen> defaultWorldDataSupplier(RegistryAccess.Frozen frozen) {
@ -157,11 +167,13 @@ public class LevelGenUtil {
worldGenSettings.generateStructures(), worldGenSettings.generateStructures(),
worldGenSettings.generateStructures() worldGenSettings.generateStructures()
); );
return replaceGenerator(dimensionKey, return replaceGenerator(
dimensionKey,
dimensionTypeKey, dimensionTypeKey,
registryAccess, registryAccess,
worldGenSettings, worldGenSettings,
oLevelStem.map(l -> l.value().generator()).orElseThrow()); oLevelStem.map(l -> l.value().generator()).orElseThrow()
);
} }
public static WorldGenSettings replaceGenerator( public static WorldGenSettings replaceGenerator(
@ -172,15 +184,19 @@ public class LevelGenUtil {
ChunkGenerator generator ChunkGenerator generator
) { ) {
Registry<DimensionType> dimensionTypeRegistry = registryAccess.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY); Registry<DimensionType> dimensionTypeRegistry = registryAccess.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY);
Registry<LevelStem> newDimensions = withDimension(dimensionKey, Registry<LevelStem> newDimensions = withDimension(
dimensionKey,
dimensionTypeKey, dimensionTypeKey,
dimensionTypeRegistry, dimensionTypeRegistry,
worldGenSettings.dimensions(), worldGenSettings.dimensions(),
generator); generator
return new WorldGenSettings(worldGenSettings.seed(), );
return new WorldGenSettings(
worldGenSettings.seed(),
worldGenSettings.generateStructures(), worldGenSettings.generateStructures(),
worldGenSettings.generateBonusChest(), worldGenSettings.generateBonusChest(),
newDimensions); newDimensions
);
} }
public static WorldGenSettings replaceStem( public static WorldGenSettings replaceStem(
@ -188,20 +204,26 @@ public class LevelGenUtil {
WorldGenSettings worldGenSettings, WorldGenSettings worldGenSettings,
LevelStem levelStem LevelStem levelStem
) { ) {
Registry<LevelStem> newDimensions = withDimension(dimensionKey, Registry<LevelStem> newDimensions = withDimension(
dimensionKey,
worldGenSettings.dimensions(), worldGenSettings.dimensions(),
levelStem); levelStem
return new WorldGenSettings(worldGenSettings.seed(), );
return new WorldGenSettings(
worldGenSettings.seed(),
worldGenSettings.generateStructures(), worldGenSettings.generateStructures(),
worldGenSettings.generateBonusChest(), worldGenSettings.generateBonusChest(),
newDimensions); newDimensions
);
} }
public static Registry<LevelStem> withDimension(ResourceKey<LevelStem> dimensionKey, public static Registry<LevelStem> withDimension(
ResourceKey<DimensionType> dimensionTypeKey, ResourceKey<LevelStem> dimensionKey,
Registry<DimensionType> dimensionTypeRegistry, ResourceKey<DimensionType> dimensionTypeKey,
Registry<LevelStem> inputDimensions, Registry<DimensionType> dimensionTypeRegistry,
ChunkGenerator generator) { Registry<LevelStem> inputDimensions,
ChunkGenerator generator
) {
LevelStem levelStem = inputDimensions.get(dimensionKey); LevelStem levelStem = inputDimensions.get(dimensionKey);
Holder<DimensionType> dimensionType = levelStem == null Holder<DimensionType> dimensionType = levelStem == null
@ -210,21 +232,29 @@ public class LevelGenUtil {
return withDimension(dimensionKey, inputDimensions, new LevelStem(dimensionType, generator)); return withDimension(dimensionKey, inputDimensions, new LevelStem(dimensionType, generator));
} }
public static Registry<LevelStem> withDimension(ResourceKey<LevelStem> dimensionKey, public static Registry<LevelStem> withDimension(
Registry<LevelStem> inputDimensions, ResourceKey<LevelStem> dimensionKey,
LevelStem levelStem) { Registry<LevelStem> inputDimensions,
MappedRegistry<LevelStem> writableRegistry = new MappedRegistry<>(Registry.LEVEL_STEM_REGISTRY, LevelStem levelStem
) {
MappedRegistry<LevelStem> writableRegistry = new MappedRegistry<>(
Registry.LEVEL_STEM_REGISTRY,
Lifecycle.experimental(), Lifecycle.experimental(),
null); null
writableRegistry.register(dimensionKey, );
writableRegistry.register(
dimensionKey,
levelStem, levelStem,
Lifecycle.stable()); Lifecycle.stable()
);
for (Map.Entry<ResourceKey<LevelStem>, LevelStem> entry : inputDimensions.entrySet()) { for (Map.Entry<ResourceKey<LevelStem>, LevelStem> entry : inputDimensions.entrySet()) {
ResourceKey<LevelStem> resourceKey = entry.getKey(); ResourceKey<LevelStem> resourceKey = entry.getKey();
if (resourceKey == dimensionKey) continue; if (resourceKey == dimensionKey) continue;
writableRegistry.register(resourceKey, writableRegistry.register(
resourceKey,
entry.getValue(), entry.getValue(),
inputDimensions.lifecycle(entry.getValue())); inputDimensions.lifecycle(entry.getValue())
);
} }
return writableRegistry; return writableRegistry;
} }
@ -248,20 +278,23 @@ public class LevelGenUtil {
registryAccess, registryAccess,
seed, seed,
generateStructures, generateStructures,
generateBonusChest); generateBonusChest
);
} else if (biomeSourceVersion == BCLBiomeSource.BIOME_SOURCE_VERSION_SQUARE) { } else if (biomeSourceVersion == BCLBiomeSource.BIOME_SOURCE_VERSION_SQUARE) {
referenceSettings = createWorldFromPreset( referenceSettings = createWorldFromPreset(
BCLWorldPresets.BCL_WORLD_17, BCLWorldPresets.BCL_WORLD_17,
registryAccess, registryAccess,
seed, seed,
generateStructures, generateStructures,
generateBonusChest); generateBonusChest
);
} else { } else {
referenceSettings = createDefaultWorldFromPreset( referenceSettings = createDefaultWorldFromPreset(
registryAccess, registryAccess,
seed, seed,
generateStructures, generateStructures,
generateBonusChest); generateBonusChest
);
} }
return referenceSettings.dimensions().getHolder(dimensionKey); return referenceSettings.dimensions().getHolder(dimensionKey);
} }
@ -272,8 +305,10 @@ public class LevelGenUtil {
return settingsNbt.getInt(key.location().toString()); return settingsNbt.getInt(key.location().toString());
} }
private static int getDimensionVersion(WorldGenSettings settings, private static int getDimensionVersion(
ResourceKey<LevelStem> key) { WorldGenSettings settings,
ResourceKey<LevelStem> key
) {
var dimension = settings.dimensions().getHolder(key); var dimension = settings.dimensions().getHolder(key);
if (dimension.isPresent()) { if (dimension.isPresent()) {
return getBiomeVersionForGenerator(dimension.get().value().generator()); return getBiomeVersionForGenerator(dimension.get().value().generator());
@ -282,9 +317,11 @@ public class LevelGenUtil {
} }
} }
private static void writeDimensionVersion(WorldGenSettings settings, private static void writeDimensionVersion(
CompoundTag generatorSettings, WorldGenSettings settings,
ResourceKey<LevelStem> key) { CompoundTag generatorSettings,
ResourceKey<LevelStem> key
) {
generatorSettings.putInt(key.location().toString(), getDimensionVersion(settings, key)); generatorSettings.putInt(key.location().toString(), getDimensionVersion(settings, key));
} }
@ -363,10 +400,12 @@ public class LevelGenUtil {
public final Registry<NormalNoise.NoiseParameters> noiseParameters; public final Registry<NormalNoise.NoiseParameters> noiseParameters;
public final Holder<NoiseGeneratorSettings> generatorSettings; public final Holder<NoiseGeneratorSettings> generatorSettings;
public StemContext(Holder<DimensionType> dimension, public StemContext(
Registry<StructureSet> structureSets, Holder<DimensionType> dimension,
Registry<NormalNoise.NoiseParameters> noiseParameters, Registry<StructureSet> structureSets,
Holder<NoiseGeneratorSettings> generatorSettings) { Registry<NormalNoise.NoiseParameters> noiseParameters,
Holder<NoiseGeneratorSettings> generatorSettings
) {
this.dimension = dimension; this.dimension = dimension;
this.structureSets = structureSets; this.structureSets = structureSets;
this.noiseParameters = noiseParameters; this.noiseParameters = noiseParameters;
@ -377,10 +416,12 @@ public class LevelGenUtil {
public static class Context extends StemContext { public static class Context extends StemContext {
public final Registry<Biome> biomes; public final Registry<Biome> biomes;
public Context(Registry<Biome> biomes, Holder<DimensionType> dimension, public Context(
Registry<StructureSet> structureSets, Registry<Biome> biomes, Holder<DimensionType> dimension,
Registry<NormalNoise.NoiseParameters> noiseParameters, Registry<StructureSet> structureSets,
Holder<NoiseGeneratorSettings> generatorSettings) { Registry<NormalNoise.NoiseParameters> noiseParameters,
Holder<NoiseGeneratorSettings> generatorSettings
) {
super(dimension, structureSets, noiseParameters, generatorSettings); super(dimension, structureSets, noiseParameters, generatorSettings);
this.biomes = biomes; this.biomes = biomes;
} }

View file

@ -1,5 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.biomes; package org.betterx.bclib.api.v2.levelgen.biomes;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleUtil;
import org.betterx.bclib.api.v2.tag.TagAPI;
import org.betterx.bclib.util.WeightedList;
import net.minecraft.data.BuiltinRegistries; import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -13,10 +18,6 @@ import net.minecraft.world.level.levelgen.WorldgenRandom;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleUtil;
import org.betterx.bclib.api.v2.tag.TagAPI;
import org.betterx.bclib.util.WeightedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View file

@ -1,5 +1,15 @@
package org.betterx.bclib.api.v2.levelgen.biomes; package org.betterx.bclib.api.v2.levelgen.biomes;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import org.betterx.bclib.api.v2.levelgen.structures.BCLStructure;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleBuilder;
import org.betterx.bclib.entity.BCLEntityWrapper;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import org.betterx.bclib.util.CollectionsUtil;
import org.betterx.bclib.util.ColorUtil;
import org.betterx.bclib.util.Pair;
import org.betterx.bclib.util.TriFunction;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet; import net.minecraft.core.HolderSet;
import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleOptions;
@ -29,15 +39,6 @@ import net.fabricmc.fabric.api.biome.v1.BiomeModifications;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import org.betterx.bclib.api.v2.levelgen.structures.BCLStructure;
import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleBuilder;
import org.betterx.bclib.entity.BCLEntityWrapper;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import org.betterx.bclib.util.CollectionsUtil;
import org.betterx.bclib.util.ColorUtil;
import org.betterx.bclib.util.Pair;
import org.betterx.bclib.util.TriFunction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -52,8 +53,10 @@ public class BCLBiomeBuilder {
} }
private static final BCLBiomeBuilder INSTANCE = new BCLBiomeBuilder(); private static final BCLBiomeBuilder INSTANCE = new BCLBiomeBuilder();
private static final SurfaceRules.ConditionSource SURFACE_NOISE = SurfaceRules.noiseCondition(Noises.SOUL_SAND_LAYER, private static final SurfaceRules.ConditionSource SURFACE_NOISE = SurfaceRules.noiseCondition(
-0.012); Noises.SOUL_SAND_LAYER,
-0.012
);
private final List<Pair<GenerationStep.Carving, Holder<? extends ConfiguredWorldCarver<?>>>> carvers = new ArrayList<>( private final List<Pair<GenerationStep.Carving, Holder<? extends ConfiguredWorldCarver<?>>>> carvers = new ArrayList<>(
1); 1);
@ -64,7 +67,7 @@ public class BCLBiomeBuilder {
private Precipitation precipitation; private Precipitation precipitation;
private ResourceLocation biomeID; private ResourceLocation biomeID;
private Set<TagKey<Biome>> tags = Sets.newHashSet(); private final Set<TagKey<Biome>> tags = Sets.newHashSet();
private final List<Climate.ParameterPoint> parameters = Lists.newArrayList(); private final List<Climate.ParameterPoint> parameters = Lists.newArrayList();
@ -152,12 +155,16 @@ public class BCLBiomeBuilder {
* @param maxGroupCount maximum mobs in group. * @param maxGroupCount maximum mobs in group.
* @return same {@link BCLBiomeBuilder} instance. * @return same {@link BCLBiomeBuilder} instance.
*/ */
public <M extends Mob> BCLBiomeBuilder spawn(EntityType<M> entityType, public <M extends Mob> BCLBiomeBuilder spawn(
int weight, EntityType<M> entityType,
int minGroupCount, int weight,
int maxGroupCount) { int minGroupCount,
getSpawns().addSpawn(entityType.getCategory(), int maxGroupCount
new SpawnerData(entityType, weight, minGroupCount, maxGroupCount)); ) {
getSpawns().addSpawn(
entityType.getCategory(),
new SpawnerData(entityType, weight, minGroupCount, maxGroupCount)
);
return this; return this;
} }
@ -170,10 +177,12 @@ public class BCLBiomeBuilder {
* @param maxGroupCount maximum mobs in group. * @param maxGroupCount maximum mobs in group.
* @return same {@link BCLBiomeBuilder} instance. * @return same {@link BCLBiomeBuilder} instance.
*/ */
public <M extends Mob> BCLBiomeBuilder spawn(BCLEntityWrapper<M> wrapper, public <M extends Mob> BCLBiomeBuilder spawn(
int weight, BCLEntityWrapper<M> wrapper,
int minGroupCount, int weight,
int maxGroupCount) { int minGroupCount,
int maxGroupCount
) {
if (wrapper.canSpawn()) { if (wrapper.canSpawn()) {
return spawn(wrapper.type(), weight, minGroupCount, maxGroupCount); return spawn(wrapper.type(), weight, minGroupCount, maxGroupCount);
} }
@ -618,9 +627,11 @@ public class BCLBiomeBuilder {
final ResourceLocation immutableID = biomeID; final ResourceLocation immutableID = biomeID;
var oKey = carver.unwrapKey(); var oKey = carver.unwrapKey();
if (oKey.isPresent()) { if (oKey.isPresent()) {
BiomeModifications.addCarver(ctx -> ctx.getBiomeKey().location().equals(immutableID), BiomeModifications.addCarver(
ctx -> ctx.getBiomeKey().location().equals(immutableID),
step, step,
(ResourceKey<ConfiguredWorldCarver<?>>) oKey.get()); (ResourceKey<ConfiguredWorldCarver<?>>) oKey.get()
);
} }
//carvers.add(new Pair<>(step, carver)); //carvers.add(new Pair<>(step, carver));
return this; return this;

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.biomes; package org.betterx.bclib.api.v2.levelgen.biomes;
import net.minecraft.world.level.biome.Biome;
import org.betterx.bclib.api.v2.generator.BiomePicker; import org.betterx.bclib.api.v2.generator.BiomePicker;
import org.betterx.bclib.config.Configs; import org.betterx.bclib.config.Configs;
import net.minecraft.world.level.biome.Biome;
public class BCLBiomeSettings { public class BCLBiomeSettings {
public static Builder createBCL() { public static Builder createBCL() {
return new Builder(); return new Builder();

View file

@ -1,5 +1,14 @@
package org.betterx.bclib.api.v2.levelgen.biomes; package org.betterx.bclib.api.v2.levelgen.biomes;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import org.betterx.bclib.api.v2.tag.CommonBiomeTags;
import org.betterx.bclib.api.v2.tag.TagAPI;
import org.betterx.bclib.interfaces.SurfaceMaterialProvider;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import org.betterx.bclib.mixin.common.MobSpawnSettingsAccessor;
import org.betterx.bclib.util.CollectionsUtil;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
@ -40,14 +49,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import org.betterx.bclib.api.v2.tag.CommonBiomeTags;
import org.betterx.bclib.api.v2.tag.TagAPI;
import org.betterx.bclib.interfaces.SurfaceMaterialProvider;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import org.betterx.bclib.mixin.common.MobSpawnSettingsAccessor;
import org.betterx.bclib.util.CollectionsUtil;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -95,7 +96,7 @@ public class BiomeAPI {
@Override @Override
public String toString() { public String toString() {
String str = debugName; String str = debugName;
if (parentOrNull != null) str += " -> " + parentOrNull.toString(); if (parentOrNull != null) str += " -> " + parentOrNull;
return str; return str;
} }
} }
@ -115,12 +116,16 @@ public class BiomeAPI {
public static final BCLBiome BASALT_DELTAS_BIOME = registerNetherBiome(getFromRegistry(Biomes.BASALT_DELTAS).value()); public static final BCLBiome BASALT_DELTAS_BIOME = registerNetherBiome(getFromRegistry(Biomes.BASALT_DELTAS).value());
public static final BCLBiome THE_END = registerEndLandBiome(getFromRegistry(Biomes.THE_END)); public static final BCLBiome THE_END = registerEndLandBiome(getFromRegistry(Biomes.THE_END));
public static final BCLBiome END_MIDLANDS = registerSubBiome(THE_END, public static final BCLBiome END_MIDLANDS = registerSubBiome(
THE_END,
getFromRegistry(Biomes.END_MIDLANDS).value(), getFromRegistry(Biomes.END_MIDLANDS).value(),
0.5F); 0.5F
public static final BCLBiome END_HIGHLANDS = registerSubBiome(THE_END, );
public static final BCLBiome END_HIGHLANDS = registerSubBiome(
THE_END,
getFromRegistry(Biomes.END_HIGHLANDS).value(), getFromRegistry(Biomes.END_HIGHLANDS).value(),
0.5F); 0.5F
);
public static final BCLBiome END_BARRENS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("end_barrens"))); public static final BCLBiome END_BARRENS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("end_barrens")));
public static final BCLBiome SMALL_END_ISLANDS = registerEndVoidBiome(getFromRegistry(new ResourceLocation( public static final BCLBiome SMALL_END_ISLANDS = registerEndVoidBiome(getFromRegistry(new ResourceLocation(
@ -155,16 +160,20 @@ public class BiomeAPI {
} }
public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome) { public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome) {
return registerSubBiome(parent, return registerSubBiome(
parent,
subBiome, subBiome,
BiomeType.BIOME_TYPE_MAP.getOrDefault(parent.getID(), BiomeType.NONE)); BiomeType.BIOME_TYPE_MAP.getOrDefault(parent.getID(), BiomeType.NONE)
);
} }
public static BCLBiome registerSubBiome(BCLBiome parent, Biome subBiome, float genChance) { public static BCLBiome registerSubBiome(BCLBiome parent, Biome subBiome, float genChance) {
return registerSubBiome(parent, return registerSubBiome(
parent,
subBiome, subBiome,
genChance, genChance,
BiomeType.BIOME_TYPE_MAP.getOrDefault(parent.getID(), BiomeType.NONE)); BiomeType.BIOME_TYPE_MAP.getOrDefault(parent.getID(), BiomeType.NONE)
);
} }
public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome, BiomeType dim) { public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome, BiomeType dim) {
@ -251,8 +260,10 @@ public class BiomeAPI {
* @return {@link BCLBiome} * @return {@link BCLBiome}
*/ */
public static BCLBiome registerEndLandBiome(Holder<Biome> biome, float genChance) { public static BCLBiome registerEndLandBiome(Holder<Biome> biome, float genChance) {
BCLBiome bclBiome = new BCLBiome(biome.value(), BCLBiome bclBiome = new BCLBiome(
VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); biome.value(),
VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()
);
registerBiome(bclBiome, BiomeType.OTHER_END_LAND); registerBiome(bclBiome, BiomeType.OTHER_END_LAND);
return bclBiome; return bclBiome;
@ -299,8 +310,10 @@ public class BiomeAPI {
* @return {@link BCLBiome} * @return {@link BCLBiome}
*/ */
public static BCLBiome registerEndVoidBiome(Holder<Biome> biome, float genChance) { public static BCLBiome registerEndVoidBiome(Holder<Biome> biome, float genChance) {
BCLBiome bclBiome = new BCLBiome(biome.value(), BCLBiome bclBiome = new BCLBiome(
VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); biome.value(),
VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()
);
registerBiome(bclBiome, BiomeType.END_VOID); registerBiome(bclBiome, BiomeType.END_VOID);
return bclBiome; return bclBiome;
@ -506,11 +519,14 @@ public class BiomeAPI {
* @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld". * @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld".
* @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters. * @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters.
*/ */
public static void registerBiomeModification(ResourceKey<LevelStem> dimensionID, public static void registerBiomeModification(
BiConsumer<ResourceLocation, Holder<Biome>> modification) { ResourceKey<LevelStem> dimensionID,
BiConsumer<ResourceLocation, Holder<Biome>> modification
) {
List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications = InternalBiomeAPI.MODIFICATIONS.computeIfAbsent( List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications = InternalBiomeAPI.MODIFICATIONS.computeIfAbsent(
dimensionID, dimensionID,
k -> Lists.newArrayList()); k -> Lists.newArrayList()
);
modifications.add(modification); modifications.add(modification);
} }
@ -549,11 +565,14 @@ public class BiomeAPI {
* @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld". * @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld".
* @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters. * @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters.
*/ */
public static void onFinishingBiomeTags(ResourceKey dimensionID, public static void onFinishingBiomeTags(
BiConsumer<ResourceLocation, Holder<Biome>> modification) { ResourceKey dimensionID,
BiConsumer<ResourceLocation, Holder<Biome>> modification
) {
List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications = InternalBiomeAPI.TAG_ADDERS.computeIfAbsent( List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications = InternalBiomeAPI.TAG_ADDERS.computeIfAbsent(
dimensionID, dimensionID,
k -> Lists.newArrayList()); k -> Lists.newArrayList()
);
modifications.add(modification); modifications.add(modification);
} }
@ -627,9 +646,11 @@ public class BiomeAPI {
* @param step a {@link Decoration} step for the feature. * @param step a {@link Decoration} step for the feature.
* @param additionalFeatures List of {@link ConfiguredFeature} to add. * @param additionalFeatures List of {@link ConfiguredFeature} to add.
*/ */
private static void addBiomeFeature(Holder<Biome> biome, private static void addBiomeFeature(
Decoration step, Holder<Biome> biome,
List<Holder<PlacedFeature>> additionalFeatures) { Decoration step,
List<Holder<PlacedFeature>> additionalFeatures
) {
BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.value() BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.value()
.getGenerationSettings(); .getGenerationSettings();
List<HolderSet<PlacedFeature>> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); List<HolderSet<PlacedFeature>> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures());
@ -670,11 +691,13 @@ public class BiomeAPI {
* @param minGroupCount minimum mobs in group. * @param minGroupCount minimum mobs in group.
* @param maxGroupCount maximum mobs in group. * @param maxGroupCount maximum mobs in group.
*/ */
public static <M extends Mob> void addBiomeMobSpawn(Holder<Biome> biome, public static <M extends Mob> void addBiomeMobSpawn(
EntityType<M> entityType, Holder<Biome> biome,
int weight, EntityType<M> entityType,
int minGroupCount, int weight,
int maxGroupCount) { int minGroupCount,
int maxGroupCount
) {
final MobCategory category = entityType.getCategory(); final MobCategory category = entityType.getCategory();
MobSpawnSettingsAccessor accessor = (MobSpawnSettingsAccessor) biome.value().getMobSettings(); MobSpawnSettingsAccessor accessor = (MobSpawnSettingsAccessor) biome.value().getMobSettings();
Map<MobCategory, WeightedRandomList<SpawnerData>> spawners = CollectionsUtil.getMutable(accessor.bcl_getSpawners()); Map<MobCategory, WeightedRandomList<SpawnerData>> spawners = CollectionsUtil.getMutable(accessor.bcl_getSpawners());
@ -759,8 +782,10 @@ public class BiomeAPI {
} }
features.forEach(feature -> { features.forEach(feature -> {
InternalBiomeAPI.FEATURE_ORDER.computeIfAbsent(feature, InternalBiomeAPI.FEATURE_ORDER.computeIfAbsent(
f -> InternalBiomeAPI.FEATURE_ORDER_ID.getAndIncrement()); feature,
f -> InternalBiomeAPI.FEATURE_ORDER_ID.getAndIncrement()
);
}); });
features.sort((f1, f2) -> { features.sort((f1, f2) -> {
@ -771,8 +796,10 @@ public class BiomeAPI {
} }
private static List<Holder<PlacedFeature>> getFeaturesListCopy(List<HolderSet<PlacedFeature>> features, private static List<Holder<PlacedFeature>> getFeaturesListCopy(
Decoration step) { List<HolderSet<PlacedFeature>> features,
Decoration step
) {
return getFeaturesListCopy(features, step.ordinal()); return getFeaturesListCopy(features, step.ordinal());
} }

View file

@ -1,5 +1,11 @@
package org.betterx.bclib.api.v2.levelgen.biomes; package org.betterx.bclib.api.v2.levelgen.biomes;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.interfaces.BiomeSourceAccessor;
import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider;
import org.betterx.bclib.interfaces.SurfaceRuleProvider;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess; import net.minecraft.core.RegistryAccess;
@ -17,11 +23,6 @@ import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import org.apache.commons.lang3.mutable.MutableInt; import org.apache.commons.lang3.mutable.MutableInt;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.interfaces.BiomeSourceAccessor;
import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider;
import org.betterx.bclib.interfaces.SurfaceRuleProvider;
import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -215,8 +216,10 @@ public class InternalBiomeAPI {
} }
} }
private static void applyModificationsAndUpdateFeatures(List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications, private static void applyModificationsAndUpdateFeatures(
Holder<Biome> biome) { List<BiConsumer<ResourceLocation, Holder<Biome>>> modifications,
Holder<Biome> biome
) {
ResourceLocation biomeID = BiomeAPI.getBiomeID(biome); ResourceLocation biomeID = BiomeAPI.getBiomeID(biome);
if (modifications != null) { if (modifications != null) {
modifications.forEach(consumer -> { modifications.forEach(consumer -> {

View file

@ -18,9 +18,11 @@ public class BCLCommonFeatures {
* @param density iterations per chunk. * @param density iterations per chunk.
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeVegetationFeature(ResourceLocation id, public static BCLFeature makeVegetationFeature(
Feature<NoneFeatureConfiguration> feature, ResourceLocation id,
int density) { Feature<NoneFeatureConfiguration> feature,
int density
) {
return makeVegetationFeature(id, feature, density, false); return makeVegetationFeature(id, feature, density, false);
} }
@ -33,10 +35,12 @@ public class BCLCommonFeatures {
* @param allHeight if {@code true} will generate plant on all layers, if {@code false} - only on surface. * @param allHeight if {@code true} will generate plant on all layers, if {@code false} - only on surface.
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeVegetationFeature(ResourceLocation id, public static BCLFeature makeVegetationFeature(
Feature<NoneFeatureConfiguration> feature, ResourceLocation id,
int density, Feature<NoneFeatureConfiguration> feature,
boolean allHeight) { int density,
boolean allHeight
) {
if (allHeight) { if (allHeight) {
return BCLFeatureBuilder return BCLFeatureBuilder
.start(id, feature) .start(id, feature)
@ -63,9 +67,11 @@ public class BCLCommonFeatures {
* @param feature {@link Feature} with {@link NoneFeatureConfiguration} config. * @param feature {@link Feature} with {@link NoneFeatureConfiguration} config.
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeChunkFeature(ResourceLocation id, public static BCLFeature makeChunkFeature(
Decoration decoration, ResourceLocation id,
Feature<NoneFeatureConfiguration> feature) { Decoration decoration,
Feature<NoneFeatureConfiguration> feature
) {
return BCLFeatureBuilder.start(id, feature).decoration(decoration).count(1).onlyInBiome().buildAndRegister(); return BCLFeatureBuilder.start(id, feature).decoration(decoration).count(1).onlyInBiome().buildAndRegister();
} }
@ -78,10 +84,12 @@ public class BCLCommonFeatures {
* @param chance chance for feature to be generated in. * @param chance chance for feature to be generated in.
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeChancedFeature(ResourceLocation id, public static BCLFeature makeChancedFeature(
Decoration decoration, ResourceLocation id,
Feature<NoneFeatureConfiguration> feature, Decoration decoration,
int chance) { Feature<NoneFeatureConfiguration> feature,
int chance
) {
return BCLFeatureBuilder.start(id, feature) return BCLFeatureBuilder.start(id, feature)
.decoration(decoration) .decoration(decoration)
.onceEvery(chance) .onceEvery(chance)
@ -99,10 +107,12 @@ public class BCLCommonFeatures {
* @param count iterations steps. * @param count iterations steps.
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeCountFeature(ResourceLocation id, public static BCLFeature makeCountFeature(
Decoration decoration, ResourceLocation id,
Feature<NoneFeatureConfiguration> feature, Decoration decoration,
int count) { Feature<NoneFeatureConfiguration> feature,
int count
) {
return BCLFeatureBuilder.start(id, feature) return BCLFeatureBuilder.start(id, feature)
.decoration(decoration) .decoration(decoration)
.count(count) .count(count)
@ -125,14 +135,16 @@ public class BCLCommonFeatures {
* @param rare when true, this is placed as a rare resource * @param rare when true, this is placed as a rare resource
* @return new BCLFeature instance. * @return new BCLFeature instance.
*/ */
public static BCLFeature makeOreFeature(ResourceLocation id, public static BCLFeature makeOreFeature(
Block blockOre, ResourceLocation id,
Block hostBlock, Block blockOre,
int veins, Block hostBlock,
int veinSize, int veins,
float airDiscardChance, int veinSize,
PlacementModifier placement, float airDiscardChance,
boolean rare) { PlacementModifier placement,
boolean rare
) {
BCLFeatureBuilder builder = BCLFeatureBuilder.start(id, Feature.ORE).decoration(Decoration.UNDERGROUND_ORES); BCLFeatureBuilder builder = BCLFeatureBuilder.start(id, Feature.ORE).decoration(Decoration.UNDERGROUND_ORES);
if (rare) { if (rare) {

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features; package org.betterx.bclib.api.v2.levelgen.features;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.features.config.*;
import org.betterx.bclib.api.v2.levelgen.features.features.*;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
@ -21,45 +25,54 @@ import net.minecraft.world.level.levelgen.feature.configurations.RandomPatchConf
import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.api.v2.levelgen.features.config.*;
import org.betterx.bclib.api.v2.levelgen.features.features.*;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Optional; import java.util.Optional;
public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration> { public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration> {
public static final Feature<PlaceFacingBlockConfig> PLACE_BLOCK = register( public static final Feature<PlaceFacingBlockConfig> PLACE_BLOCK = register(
BCLib.makeID("place_block"), BCLib.makeID("place_block"),
new PlaceBlockFeature<>(PlaceFacingBlockConfig.CODEC)); new PlaceBlockFeature<>(PlaceFacingBlockConfig.CODEC)
);
public static final Feature<ScatterFeatureConfig.OnSolid> SCATTER_ON_SOLID = register( public static final Feature<ScatterFeatureConfig.OnSolid> SCATTER_ON_SOLID = register(
BCLib.makeID("scatter_on_solid"), BCLib.makeID("scatter_on_solid"),
new ScatterFeature<>(ScatterFeatureConfig.OnSolid.CODEC)); new ScatterFeature<>(ScatterFeatureConfig.OnSolid.CODEC)
);
public static final Feature<ScatterFeatureConfig.ExtendTop> SCATTER_EXTEND_TOP = register( public static final Feature<ScatterFeatureConfig.ExtendTop> SCATTER_EXTEND_TOP = register(
BCLib.makeID("scatter_extend_top"), BCLib.makeID("scatter_extend_top"),
new ScatterFeature<>(ScatterFeatureConfig.ExtendTop.CODEC)); new ScatterFeature<>(ScatterFeatureConfig.ExtendTop.CODEC)
);
public static final Feature<ScatterFeatureConfig.ExtendBottom> SCATTER_EXTEND_BOTTOM = register( public static final Feature<ScatterFeatureConfig.ExtendBottom> SCATTER_EXTEND_BOTTOM = register(
BCLib.makeID("scatter_extend_bottom"), BCLib.makeID("scatter_extend_bottom"),
new ScatterFeature<>(ScatterFeatureConfig.ExtendBottom.CODEC)); new ScatterFeature<>(ScatterFeatureConfig.ExtendBottom.CODEC)
);
public static final Feature<RandomFeatureConfiguration> RANDOM_SELECTOR = register( public static final Feature<RandomFeatureConfiguration> RANDOM_SELECTOR = register(
BCLib.makeID("random_select"), BCLib.makeID("random_select"),
new WeightedRandomSelectorFeature()); new WeightedRandomSelectorFeature()
public static final Feature<TemplateFeatureConfig> TEMPLATE = register(BCLib.makeID("template"), );
public static final Feature<TemplateFeatureConfig> TEMPLATE = register(
BCLib.makeID("template"),
new TemplateFeature( new TemplateFeature(
TemplateFeatureConfig.CODEC)); TemplateFeatureConfig.CODEC)
);
public static final Feature<NoneFeatureConfiguration> MARK_POSTPROCESSING = register(BCLib.makeID( public static final Feature<NoneFeatureConfiguration> MARK_POSTPROCESSING = register(
BCLib.makeID(
"mark_postprocessing"), "mark_postprocessing"),
new MarkPostProcessingFeature()); new MarkPostProcessingFeature()
);
public static final Feature<SequenceFeatureConfig> SEQUENCE = register(BCLib.makeID("sequence"), public static final Feature<SequenceFeatureConfig> SEQUENCE = register(
new SequenceFeature()); BCLib.makeID("sequence"),
new SequenceFeature()
);
public static final Feature<ConditionFeatureConfig> CONDITION = register(BCLib.makeID("condition"), public static final Feature<ConditionFeatureConfig> CONDITION = register(
new ConditionFeature()); BCLib.makeID("condition"),
new ConditionFeature()
);
private final Holder<PlacedFeature> placedFeature; private final Holder<PlacedFeature> placedFeature;
private final Decoration featureStep; private final Decoration featureStep;
private final F feature; private final F feature;
@ -67,19 +80,23 @@ public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration>
public final ResourceLocation id; public final ResourceLocation id;
public BCLFeature(ResourceLocation id, public BCLFeature(
F feature, ResourceLocation id,
Decoration featureStep, F feature,
FC configuration, Decoration featureStep,
PlacementModifier[] modifiers) { FC configuration,
PlacementModifier[] modifiers
) {
this(id, feature, featureStep, configuration, buildPlacedFeature(id, feature, configuration, modifiers)); this(id, feature, featureStep, configuration, buildPlacedFeature(id, feature, configuration, modifiers));
} }
public BCLFeature(ResourceLocation id, public BCLFeature(
F feature, ResourceLocation id,
Decoration featureStep, F feature,
FC configuration, Decoration featureStep,
Holder<PlacedFeature> placedFeature) { FC configuration,
Holder<PlacedFeature> placedFeature
) {
this.placedFeature = placedFeature; this.placedFeature = placedFeature;
this.featureStep = featureStep; this.featureStep = featureStep;
this.feature = feature; this.feature = feature;
@ -98,24 +115,31 @@ public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration>
ResourceLocation id, ResourceLocation id,
F feature, F feature,
FC configuration, FC configuration,
PlacementModifier[] modifiers) { PlacementModifier[] modifiers
) {
Holder<ConfiguredFeature<?, ?>> configuredFeature; Holder<ConfiguredFeature<?, ?>> configuredFeature;
if (!BuiltinRegistries.CONFIGURED_FEATURE.containsKey(id)) { if (!BuiltinRegistries.CONFIGURED_FEATURE.containsKey(id)) {
configuredFeature = (Holder<ConfiguredFeature<?, ?>>) (Object) FeatureUtils.register(id.toString(), configuredFeature = (Holder<ConfiguredFeature<?, ?>>) (Object) FeatureUtils.register(
id.toString(),
feature, feature,
configuration); configuration
);
} else { } else {
configuredFeature = BuiltinRegistries.CONFIGURED_FEATURE configuredFeature = BuiltinRegistries.CONFIGURED_FEATURE
.getHolder(ResourceKey.create(BuiltinRegistries.CONFIGURED_FEATURE.key(), .getHolder(ResourceKey.create(
id)) BuiltinRegistries.CONFIGURED_FEATURE.key(),
id
))
.orElseThrow(); .orElseThrow();
} }
if (!BuiltinRegistries.PLACED_FEATURE.containsKey(id)) { if (!BuiltinRegistries.PLACED_FEATURE.containsKey(id)) {
return PlacementUtils.register(id.toString(), configuredFeature, modifiers); return PlacementUtils.register(id.toString(), configuredFeature, modifiers);
} else { } else {
return BuiltinRegistries.PLACED_FEATURE.getHolder(ResourceKey.create(BuiltinRegistries.PLACED_FEATURE.key(), return BuiltinRegistries.PLACED_FEATURE.getHolder(ResourceKey.create(
id)).orElseThrow(); BuiltinRegistries.PLACED_FEATURE.key(),
id
)).orElseThrow();
} }
} }
@ -128,8 +152,10 @@ public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration>
return optional.isPresent(); return optional.isPresent();
} }
public static <C extends FeatureConfiguration, F extends Feature<C>> F register(ResourceLocation string, public static <C extends FeatureConfiguration, F extends Feature<C>> F register(
F feature) { ResourceLocation string,
F feature
) {
return Registry.register(Registry.FEATURE, string, feature); return Registry.register(Registry.FEATURE, string, feature);
} }
@ -168,11 +194,13 @@ public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration>
return place(this.getFeature(), this.getConfiguration(), level, pos, random); return place(this.getFeature(), this.getConfiguration(), level, pos, random);
} }
private static boolean placeUnbound(Feature<?> feature, private static boolean placeUnbound(
FeatureConfiguration config, Feature<?> feature,
ServerLevel level, FeatureConfiguration config,
BlockPos pos, ServerLevel level,
RandomSource random) { BlockPos pos,
RandomSource random
) {
if (config instanceof RandomPatchConfiguration rnd) { if (config instanceof RandomPatchConfiguration rnd) {
var configured = rnd.feature().value().feature().value(); var configured = rnd.feature().value().feature().value();
feature = configured.feature(); feature = configured.feature();
@ -194,18 +222,22 @@ public class BCLFeature<F extends Feature<FC>, FC extends FeatureConfiguration>
return feature.place(context); return feature.place(context);
} }
public static boolean place(Feature<NoneFeatureConfiguration> feature, public static boolean place(
ServerLevel level, Feature<NoneFeatureConfiguration> feature,
BlockPos pos, ServerLevel level,
RandomSource random) { BlockPos pos,
RandomSource random
) {
return placeUnbound(feature, FeatureConfiguration.NONE, level, pos, random); return placeUnbound(feature, FeatureConfiguration.NONE, level, pos, random);
} }
public static <FC extends FeatureConfiguration> boolean place(Feature<FC> feature, public static <FC extends FeatureConfiguration> boolean place(
FC config, Feature<FC> feature,
ServerLevel level, FC config,
BlockPos pos, ServerLevel level,
RandomSource random) { BlockPos pos,
RandomSource random
) {
return placeUnbound(feature, config, level, pos, random); return placeUnbound(feature, config, level, pos, random);
} }
} }

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.levelgen.features; package org.betterx.bclib.api.v2.levelgen.features;
import org.betterx.bclib.api.v2.levelgen.features.placement.*;
import org.betterx.bclib.api.v2.tag.CommonBlockTags;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.data.worldgen.placement.PlacementUtils;
@ -18,16 +21,13 @@ import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvi
import net.minecraft.world.level.levelgen.placement.*; import net.minecraft.world.level.levelgen.placement.*;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import org.betterx.bclib.api.v2.levelgen.features.placement.*;
import org.betterx.bclib.api.v2.tag.CommonBlockTags;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
public class BCLFeatureBuilder<FC extends FeatureConfiguration, F extends Feature<FC>> { public class BCLFeatureBuilder<FC extends FeatureConfiguration, F extends Feature<FC>> {
private final List<PlacementModifier> modifications = new ArrayList<>(5); private final List<PlacementModifier> modifications = new ArrayList<>(5);
private ResourceLocation featureID; private final ResourceLocation featureID;
private Decoration decoration = Decoration.VEGETAL_DECORATION; private Decoration decoration = Decoration.VEGETAL_DECORATION;
private final F feature; private final F feature;
private BlockStateProvider provider; private BlockStateProvider provider;
@ -48,18 +48,24 @@ public class BCLFeatureBuilder<FC extends FeatureConfiguration, F extends Featur
return new BCLFeatureBuilder(featureID, feature); return new BCLFeatureBuilder(featureID, feature);
} }
public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(ResourceLocation featureID, public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(
Block block) { ResourceLocation featureID,
Block block
) {
return start(featureID, BlockStateProvider.simple(block)); return start(featureID, BlockStateProvider.simple(block));
} }
public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(ResourceLocation featureID, public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(
BlockState state) { ResourceLocation featureID,
BlockState state
) {
return start(featureID, BlockStateProvider.simple(state)); return start(featureID, BlockStateProvider.simple(state));
} }
public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(ResourceLocation featureID, public static BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> start(
BlockStateProvider provider) { ResourceLocation featureID,
BlockStateProvider provider
) {
BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> builder = new BCLFeatureBuilder( BCLFeatureBuilder<SimpleBlockConfiguration, SimpleBlockFeature> builder = new BCLFeatureBuilder(
featureID, featureID,
Feature.SIMPLE_BLOCK Feature.SIMPLE_BLOCK

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features; package org.betterx.bclib.api.v2.levelgen.features;
import org.betterx.bclib.api.v2.levelgen.features.config.PlaceFacingBlockConfig;
import org.betterx.bclib.api.v2.levelgen.features.config.ScatterFeatureConfig;
import org.betterx.bclib.api.v2.levelgen.features.features.ScatterFeature;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.util.valueproviders.UniformInt;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
@ -14,10 +18,6 @@ import net.minecraft.world.level.levelgen.feature.configurations.SimpleBlockConf
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.level.levelgen.feature.stateproviders.RandomizedIntStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.RandomizedIntStateProvider;
import org.betterx.bclib.api.v2.levelgen.features.config.PlaceFacingBlockConfig;
import org.betterx.bclib.api.v2.levelgen.features.config.ScatterFeatureConfig;
import org.betterx.bclib.api.v2.levelgen.features.features.ScatterFeature;
public class FastFeatures { public class FastFeatures {
@ -25,15 +25,17 @@ public class FastFeatures {
ResourceLocation location, ResourceLocation location,
boolean onFloor, boolean onFloor,
boolean sparse, boolean sparse,
ScatterFeatureConfig.Builder builder) { ScatterFeatureConfig.Builder builder
) {
return scatter(location, onFloor, sparse, builder, BCLFeature.SCATTER_ON_SOLID); return scatter(location, onFloor, sparse, builder, BCLFeature.SCATTER_ON_SOLID);
} }
public static BCLFeature scatter(ResourceLocation location, public static BCLFeature scatter(
boolean onFloor, ResourceLocation location,
boolean sparse, boolean onFloor,
ScatterFeatureConfig.Builder builder, boolean sparse,
Feature scatterFeature ScatterFeatureConfig.Builder builder,
Feature scatterFeature
) { ) {
BCLFeatureBuilder fBuilder = BCLFeatureBuilder.start(location, scatterFeature); BCLFeatureBuilder fBuilder = BCLFeatureBuilder.start(location, scatterFeature);
if (onFloor) { if (onFloor) {
@ -58,22 +60,26 @@ public class FastFeatures {
public static BCLFeature public static BCLFeature
patch(ResourceLocation location, Block block, int attempts, int xzSpread, int ySpread) { patch(ResourceLocation location, Block block, int attempts, int xzSpread, int ySpread) {
return patch(location, return patch(
location,
attempts, attempts,
xzSpread, xzSpread,
ySpread, ySpread,
Feature.SIMPLE_BLOCK, Feature.SIMPLE_BLOCK,
new SimpleBlockConfiguration(BlockStateProvider.simple(block))); new SimpleBlockConfiguration(BlockStateProvider.simple(block))
);
} }
public static BCLFeature public static BCLFeature
patch(ResourceLocation location, BlockStateProvider provider, int attempts, int xzSpread, int ySpread) { patch(ResourceLocation location, BlockStateProvider provider, int attempts, int xzSpread, int ySpread) {
return patch(location, return patch(
location,
attempts, attempts,
xzSpread, xzSpread,
ySpread, ySpread,
Feature.SIMPLE_BLOCK, Feature.SIMPLE_BLOCK,
new SimpleBlockConfiguration(provider)); new SimpleBlockConfiguration(provider)
);
} }
public static BCLFeature patchWitRandomInt(ResourceLocation location, Block block, IntegerProperty prop) { public static BCLFeature patchWitRandomInt(ResourceLocation location, Block block, IntegerProperty prop) {
@ -81,24 +87,30 @@ public class FastFeatures {
} }
public static BCLFeature public static BCLFeature
patchWitRandomInt(ResourceLocation location, patchWitRandomInt(
Block block, ResourceLocation location,
IntegerProperty prop, Block block,
int attempts, IntegerProperty prop,
int xzSpread, int attempts,
int ySpread) { int xzSpread,
return patch(location, int ySpread
) {
return patch(
location,
attempts, attempts,
xzSpread, xzSpread,
ySpread, ySpread,
simple(location, ySpread, false, block.defaultBlockState(), prop)); simple(location, ySpread, false, block.defaultBlockState(), prop)
);
} }
public static BCLFeature public static BCLFeature
simple(ResourceLocation location, simple(
int searchDist, ResourceLocation location,
boolean rare, int searchDist,
Feature<NoneFeatureConfiguration> feature) { boolean rare,
Feature<NoneFeatureConfiguration> feature
) {
return simple(location, searchDist, rare, feature, NoneFeatureConfiguration.NONE); return simple(location, searchDist, rare, feature, NoneFeatureConfiguration.NONE);
} }
@ -123,11 +135,13 @@ public class FastFeatures {
} }
public static BCLFeature public static BCLFeature
simple(ResourceLocation location, simple(
int searchDist, ResourceLocation location,
boolean rare, int searchDist,
BlockState baseState, boolean rare,
IntegerProperty property) { BlockState baseState,
IntegerProperty property
) {
int min = Integer.MAX_VALUE; int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE; int max = Integer.MIN_VALUE;
@ -136,7 +150,8 @@ public class FastFeatures {
if (i > max) max = i; if (i > max) max = i;
} }
return simple(location, return simple(
location,
searchDist, searchDist,
rare, rare,
Feature.SIMPLE_BLOCK, Feature.SIMPLE_BLOCK,
@ -144,16 +159,19 @@ public class FastFeatures {
BlockStateProvider.simple(baseState), BlockStateProvider.simple(baseState),
property, property,
UniformInt.of(min, max) UniformInt.of(min, max)
))); ))
);
} }
public static <FC extends FeatureConfiguration> BCLFeature<Feature<FC>, FC> public static <FC extends FeatureConfiguration> BCLFeature<Feature<FC>, FC>
simple(ResourceLocation location, simple(
int searchDist, ResourceLocation location,
boolean rare, int searchDist,
Feature<FC> feature, boolean rare,
FC config) { Feature<FC> feature,
FC config
) {
BCLFeatureBuilder builder = BCLFeatureBuilder BCLFeatureBuilder builder = BCLFeatureBuilder
.start(location, feature) .start(location, feature)
.findSolidFloor(Math.min(12, searchDist)) .findSolidFloor(Math.min(12, searchDist))
@ -171,43 +189,52 @@ public class FastFeatures {
public static BCLFeature public static BCLFeature
patch(ResourceLocation location, patch(
int attempts, ResourceLocation location,
int xzSpread, int attempts,
int ySpread, int xzSpread,
Feature<NoneFeatureConfiguration> feature) { int ySpread,
Feature<NoneFeatureConfiguration> feature
) {
return patch(location, attempts, xzSpread, ySpread, feature, FeatureConfiguration.NONE); return patch(location, attempts, xzSpread, ySpread, feature, FeatureConfiguration.NONE);
} }
public static <FC extends FeatureConfiguration> BCLFeature public static <FC extends FeatureConfiguration> BCLFeature
patch(ResourceLocation location, patch(
int attempts, ResourceLocation location,
int xzSpread, int attempts,
int ySpread, int xzSpread,
Feature<FC> feature, int ySpread,
FC config) { Feature<FC> feature,
FC config
) {
final BCLFeature SINGLE = simple(location, ySpread, false, feature, config); final BCLFeature SINGLE = simple(location, ySpread, false, feature, config);
return patch(location, attempts, xzSpread, ySpread, SINGLE); return patch(location, attempts, xzSpread, ySpread, SINGLE);
} }
public static BCLFeature public static BCLFeature
wallPatch(ResourceLocation location, wallPatch(
Block block, ResourceLocation location,
int attempts, Block block,
int xzSpread, int attempts,
int ySpread) { int xzSpread,
int ySpread
) {
final BCLFeature SINGLE = simple(location, ySpread, false, BCLFeature.PLACE_BLOCK, final BCLFeature SINGLE = simple(location, ySpread, false, BCLFeature.PLACE_BLOCK,
new PlaceFacingBlockConfig(block, PlaceFacingBlockConfig.HORIZONTAL)); new PlaceFacingBlockConfig(block, PlaceFacingBlockConfig.HORIZONTAL)
);
return patch(location, attempts, xzSpread, ySpread, SINGLE); return patch(location, attempts, xzSpread, ySpread, SINGLE);
} }
public static BCLFeature public static BCLFeature
patch(ResourceLocation location, patch(
int attempts, ResourceLocation location,
int xzSpread, int attempts,
int ySpread, int xzSpread,
BCLFeature single) { int ySpread,
BCLFeature single
) {
ResourceLocation patchLocation = new ResourceLocation(location.getNamespace(), location.getPath() + "_patch"); ResourceLocation patchLocation = new ResourceLocation(location.getNamespace(), location.getPath() + "_patch");
return BCLFeatureBuilder return BCLFeatureBuilder

View file

@ -6,8 +6,10 @@ import net.minecraft.world.level.ServerLevelAccessor;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
public interface UserGrowableFeature<FC extends FeatureConfiguration> { public interface UserGrowableFeature<FC extends FeatureConfiguration> {
boolean grow(ServerLevelAccessor level, boolean grow(
BlockPos pos, ServerLevelAccessor level,
RandomSource random, BlockPos pos,
FC configuration); RandomSource random,
FC configuration
);
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.blockpredicates; package org.betterx.bclib.api.v2.levelgen.features.blockpredicates;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.WorldGenLevel;
@ -7,9 +9,6 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate;
import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType; import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
public class IsFullShape implements BlockPredicate { public class IsFullShape implements BlockPredicate {
public static final IsFullShape HERE = new IsFullShape(); public static final IsFullShape HERE = new IsFullShape();
public static final Codec<IsFullShape> CODEC = RecordCodecBuilder.create( public static final Codec<IsFullShape> CODEC = RecordCodecBuilder.create(

View file

@ -1,16 +1,18 @@
package org.betterx.bclib.api.v2.levelgen.features.blockpredicates; package org.betterx.bclib.api.v2.levelgen.features.blockpredicates;
import org.betterx.bclib.BCLib;
import com.mojang.serialization.Codec;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate;
import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType; import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType;
import com.mojang.serialization.Codec;
import org.betterx.bclib.BCLib;
public class Types { public class Types {
public static final BlockPredicateType<IsFullShape> FULL_SHAPE = register(BCLib.makeID("full_shape"), public static final BlockPredicateType<IsFullShape> FULL_SHAPE = register(
IsFullShape.CODEC); BCLib.makeID("full_shape"),
IsFullShape.CODEC
);
public static <P extends BlockPredicate> BlockPredicateType<P> register(ResourceLocation location, Codec<P> codec) { public static <P extends BlockPredicate> BlockPredicateType<P> register(ResourceLocation location, Codec<P> codec) {
return Registry.register(Registry.BLOCK_PREDICATE_TYPES, location, () -> codec); return Registry.register(Registry.BLOCK_PREDICATE_TYPES, location, () -> codec);

View file

@ -1,15 +1,15 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import net.minecraft.world.level.levelgen.placement.PlacementFilter; import net.minecraft.world.level.levelgen.placement.PlacementFilter;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import java.util.Optional; import java.util.Optional;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -26,33 +26,43 @@ public class ConditionFeatureConfig implements FeatureConfiguration {
public final Holder<PlacedFeature> okFeature; public final Holder<PlacedFeature> okFeature;
public final Optional<Holder<PlacedFeature>> failFeature; public final Optional<Holder<PlacedFeature>> failFeature;
public ConditionFeatureConfig(@NotNull PlacementFilter filter, public ConditionFeatureConfig(
@NotNull BCLFeature okFeature) { @NotNull PlacementFilter filter,
@NotNull BCLFeature okFeature
) {
this(filter, okFeature.getPlacedFeature(), Optional.empty()); this(filter, okFeature.getPlacedFeature(), Optional.empty());
} }
public ConditionFeatureConfig(@NotNull PlacementFilter filter, public ConditionFeatureConfig(
@NotNull BCLFeature okFeature, @NotNull PlacementFilter filter,
@NotNull BCLFeature failFeature) { @NotNull BCLFeature okFeature,
@NotNull BCLFeature failFeature
) {
this(filter, okFeature.getPlacedFeature(), Optional.of(failFeature.getPlacedFeature())); this(filter, okFeature.getPlacedFeature(), Optional.of(failFeature.getPlacedFeature()));
} }
public ConditionFeatureConfig(@NotNull PlacementFilter filter, public ConditionFeatureConfig(
@NotNull Holder<PlacedFeature> okFeature) { @NotNull PlacementFilter filter,
@NotNull Holder<PlacedFeature> okFeature
) {
this(filter, okFeature, Optional.empty()); this(filter, okFeature, Optional.empty());
} }
public ConditionFeatureConfig(@NotNull PlacementFilter filter, public ConditionFeatureConfig(
@NotNull Holder<PlacedFeature> okFeature, @NotNull PlacementFilter filter,
@NotNull Holder<PlacedFeature> failFeature) { @NotNull Holder<PlacedFeature> okFeature,
@NotNull Holder<PlacedFeature> failFeature
) {
this(filter, okFeature, Optional.of(failFeature)); this(filter, okFeature, Optional.of(failFeature));
} }
protected ConditionFeatureConfig(@NotNull PlacementModifier filter, protected ConditionFeatureConfig(
@NotNull Holder<PlacedFeature> okFeature, @NotNull PlacementModifier filter,
@NotNull Optional<Holder<PlacedFeature>> failFeature) { @NotNull Holder<PlacedFeature> okFeature,
@NotNull Optional<Holder<PlacedFeature>> failFeature
) {
this.filter = filter; this.filter = filter;
this.okFeature = okFeature; this.okFeature = okFeature;
this.failFeature = failFeature; this.failFeature = failFeature;

View file

@ -1,5 +1,6 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.util.random.SimpleWeightedRandomList; import net.minecraft.util.random.SimpleWeightedRandomList;
@ -11,8 +12,6 @@ import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfigur
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.List; import java.util.List;
public abstract class PlaceBlockFeatureConfig implements FeatureConfiguration { public abstract class PlaceBlockFeatureConfig implements FeatureConfiguration {
@ -70,8 +69,10 @@ public abstract class PlaceBlockFeatureConfig implements FeatureConfiguration {
} }
protected abstract boolean placeBlock(FeaturePlaceContext<? extends PlaceBlockFeatureConfig> ctx, protected abstract boolean placeBlock(
WorldGenLevel level, FeaturePlaceContext<? extends PlaceBlockFeatureConfig> ctx,
BlockPos pos, WorldGenLevel level,
BlockState targetState); BlockPos pos,
BlockState targetState
);
} }

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.util.ExtraCodecs; import net.minecraft.util.ExtraCodecs;
@ -12,10 +16,6 @@ import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
import java.util.List; import java.util.List;
public class PlaceFacingBlockConfig extends PlaceBlockFeatureConfig { public class PlaceFacingBlockConfig extends PlaceBlockFeatureConfig {
@ -28,17 +28,21 @@ public class PlaceFacingBlockConfig extends PlaceBlockFeatureConfig {
.forGetter(a -> a.directions) .forGetter(a -> a.directions)
).apply(instance, PlaceFacingBlockConfig::new) ).apply(instance, PlaceFacingBlockConfig::new)
); );
public static final List<Direction> HORIZONTAL = List.of(Direction.NORTH, public static final List<Direction> HORIZONTAL = List.of(
Direction.NORTH,
Direction.EAST, Direction.EAST,
Direction.WEST, Direction.WEST,
Direction.SOUTH); Direction.SOUTH
);
public static final List<Direction> VERTICAL = List.of(Direction.UP, Direction.DOWN); public static final List<Direction> VERTICAL = List.of(Direction.UP, Direction.DOWN);
public static final List<Direction> ALL = List.of(Direction.NORTH, public static final List<Direction> ALL = List.of(
Direction.NORTH,
Direction.EAST, Direction.EAST,
Direction.SOUTH, Direction.SOUTH,
Direction.WEST, Direction.WEST,
Direction.UP, Direction.UP,
Direction.DOWN); Direction.DOWN
);
private final List<Direction> directions; private final List<Direction> directions;
@ -65,10 +69,12 @@ public class PlaceFacingBlockConfig extends PlaceBlockFeatureConfig {
@Override @Override
public boolean placeBlock(FeaturePlaceContext<? extends PlaceBlockFeatureConfig> ctx, public boolean placeBlock(
WorldGenLevel level, FeaturePlaceContext<? extends PlaceBlockFeatureConfig> ctx,
BlockPos pos, WorldGenLevel level,
BlockState targetState) { BlockPos pos,
BlockState targetState
) {
BlockState lookupState; BlockState lookupState;
for (Direction dir : directions) { for (Direction dir : directions) {
lookupState = targetState.setValue(HorizontalDirectionalBlock.FACING, dir); lookupState = targetState.setValue(HorizontalDirectionalBlock.FACING, dir);

View file

@ -1,5 +1,12 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.blocks.BlockProperties;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.datafixers.util.Function15;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.util.valueproviders.ConstantInt; import net.minecraft.util.valueproviders.ConstantInt;
@ -10,13 +17,6 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider;
import com.mojang.datafixers.util.Function15;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.blocks.BlockProperties;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Optional; import java.util.Optional;
public abstract class ScatterFeatureConfig implements FeatureConfiguration { public abstract class ScatterFeatureConfig implements FeatureConfiguration {
@ -41,21 +41,23 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
public final boolean growWhileFree; public final boolean growWhileFree;
public ScatterFeatureConfig(BlockStateProvider clusterBlock, public ScatterFeatureConfig(
Optional<BlockStateProvider> tipBlock, BlockStateProvider clusterBlock,
Optional<BlockStateProvider> bottomBlock, Optional<BlockStateProvider> tipBlock,
Optional<BlockState> baseState, Optional<BlockStateProvider> bottomBlock,
float baseReplaceChance, Optional<BlockState> baseState,
float chanceOfDirectionalSpread, float baseReplaceChance,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3, float chanceOfSpreadRadius2,
int minHeight, float chanceOfSpreadRadius3,
int maxHeight, int minHeight,
float maxSpread, int maxHeight,
float sizeVariation, float maxSpread,
float floorChance, float sizeVariation,
boolean growWhileFree, float floorChance,
IntProvider spreadCount) { boolean growWhileFree,
IntProvider spreadCount
) {
this.clusterBlock = clusterBlock; this.clusterBlock = clusterBlock;
this.tipBlock = tipBlock.orElse(clusterBlock); this.tipBlock = tipBlock.orElse(clusterBlock);
this.bottomBlock = bottomBlock.orElse(clusterBlock); this.bottomBlock = bottomBlock.orElse(clusterBlock);
@ -84,7 +86,8 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
public static <T extends ScatterFeatureConfig> Codec<T> buildCodec(Instancer<T> instancer) { public static <T extends ScatterFeatureConfig> Codec<T> buildCodec(Instancer<T> instancer) {
return RecordCodecBuilder.create((instance) -> instance return RecordCodecBuilder.create((instance) -> instance
.group(BlockStateProvider.CODEC .group(
BlockStateProvider.CODEC
.fieldOf("cluster_block") .fieldOf("cluster_block")
.forGetter((T cfg) -> cfg.clusterBlock), .forGetter((T cfg) -> cfg.clusterBlock),
BlockStateProvider.CODEC BlockStateProvider.CODEC
@ -281,22 +284,28 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
} }
public Builder<T> generateBaseBlock(BlockState baseState, public Builder<T> generateBaseBlock(
float chanceOfDirectionalSpread, BlockState baseState,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3) { float chanceOfSpreadRadius2,
return generateBaseBlock(baseState, float chanceOfSpreadRadius3
) {
return generateBaseBlock(
baseState,
1, 1,
chanceOfDirectionalSpread, chanceOfDirectionalSpread,
chanceOfSpreadRadius2, chanceOfSpreadRadius2,
chanceOfSpreadRadius3); chanceOfSpreadRadius3
);
} }
public Builder<T> generateBaseBlock(BlockState baseState, public Builder<T> generateBaseBlock(
float baseReplaceChance, BlockState baseState,
float chanceOfDirectionalSpread, float baseReplaceChance,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3) { float chanceOfSpreadRadius2,
float chanceOfSpreadRadius3
) {
if (this.baseState.isPresent() && this.baseReplaceChance == 0) { if (this.baseState.isPresent() && this.baseReplaceChance == 0) {
BCLib.LOGGER.error("Base generation was already selected."); BCLib.LOGGER.error("Base generation was already selected.");
} }
@ -367,22 +376,25 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
public static class OnSolid extends ScatterFeatureConfig { public static class OnSolid extends ScatterFeatureConfig {
public static final Codec<OnSolid> CODEC = buildCodec(OnSolid::new); public static final Codec<OnSolid> CODEC = buildCodec(OnSolid::new);
protected OnSolid(BlockStateProvider clusterBlock, protected OnSolid(
Optional<BlockStateProvider> tipBlock, BlockStateProvider clusterBlock,
Optional<BlockStateProvider> bottomBlock, Optional<BlockStateProvider> tipBlock,
Optional<BlockState> baseState, Optional<BlockStateProvider> bottomBlock,
float baseReplaceChance, Optional<BlockState> baseState,
float chanceOfDirectionalSpread, float baseReplaceChance,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3, float chanceOfSpreadRadius2,
int minHeight, float chanceOfSpreadRadius3,
int maxHeight, int minHeight,
float maxSpread, int maxHeight,
float sizeVariation, float maxSpread,
float floorChance, float sizeVariation,
boolean growWhileFree, float floorChance,
IntProvider spreadCount) { boolean growWhileFree,
super(clusterBlock, IntProvider spreadCount
) {
super(
clusterBlock,
tipBlock, tipBlock,
bottomBlock, bottomBlock,
baseState, baseState,
@ -396,7 +408,8 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
sizeVariation, sizeVariation,
floorChance, floorChance,
growWhileFree, growWhileFree,
spreadCount); spreadCount
);
} }
@ -423,22 +436,25 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
public static class ExtendTop extends ScatterFeatureConfig { public static class ExtendTop extends ScatterFeatureConfig {
public static final Codec<ExtendTop> CODEC = buildCodec(ExtendTop::new); public static final Codec<ExtendTop> CODEC = buildCodec(ExtendTop::new);
protected ExtendTop(BlockStateProvider clusterBlock, protected ExtendTop(
Optional<BlockStateProvider> tipBlock, BlockStateProvider clusterBlock,
Optional<BlockStateProvider> bottomBlock, Optional<BlockStateProvider> tipBlock,
Optional<BlockState> baseState, Optional<BlockStateProvider> bottomBlock,
float baseReplaceChance, Optional<BlockState> baseState,
float chanceOfDirectionalSpread, float baseReplaceChance,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3, float chanceOfSpreadRadius2,
int minHeight, float chanceOfSpreadRadius3,
int maxHeight, int minHeight,
float maxSpread, int maxHeight,
float sizeVariation, float maxSpread,
float floorChance, float sizeVariation,
boolean growWhileFree, float floorChance,
IntProvider spreadCount) { boolean growWhileFree,
super(clusterBlock, IntProvider spreadCount
) {
super(
clusterBlock,
tipBlock, tipBlock,
bottomBlock, bottomBlock,
baseState, baseState,
@ -452,7 +468,8 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
sizeVariation, sizeVariation,
floorChance, floorChance,
growWhileFree, growWhileFree,
spreadCount); spreadCount
);
} }
@ -477,22 +494,25 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
public static class ExtendBottom extends ScatterFeatureConfig { public static class ExtendBottom extends ScatterFeatureConfig {
public static final Codec<ExtendBottom> CODEC = buildCodec(ExtendBottom::new); public static final Codec<ExtendBottom> CODEC = buildCodec(ExtendBottom::new);
protected ExtendBottom(BlockStateProvider clusterBlock, protected ExtendBottom(
Optional<BlockStateProvider> tipBlock, BlockStateProvider clusterBlock,
Optional<BlockStateProvider> bottomBlock, Optional<BlockStateProvider> tipBlock,
Optional<BlockState> baseState, Optional<BlockStateProvider> bottomBlock,
float baseReplaceChance, Optional<BlockState> baseState,
float chanceOfDirectionalSpread, float baseReplaceChance,
float chanceOfSpreadRadius2, float chanceOfDirectionalSpread,
float chanceOfSpreadRadius3, float chanceOfSpreadRadius2,
int minHeight, float chanceOfSpreadRadius3,
int maxHeight, int minHeight,
float maxSpread, int maxHeight,
float sizeVariation, float maxSpread,
float floorChance, float sizeVariation,
boolean growWhileFree, float floorChance,
IntProvider spreadCount) { boolean growWhileFree,
super(clusterBlock, IntProvider spreadCount
) {
super(
clusterBlock,
tipBlock, tipBlock,
bottomBlock, bottomBlock,
baseState, baseState,
@ -506,7 +526,8 @@ public abstract class ScatterFeatureConfig implements FeatureConfiguration {
sizeVariation, sizeVariation,
floorChance, floorChance,
growWhileFree, growWhileFree,
spreadCount); spreadCount
);
} }

View file

@ -1,15 +1,15 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.util.ExtraCodecs; import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import java.util.List; import java.util.List;
public class SequenceFeatureConfig implements FeatureConfiguration { public class SequenceFeatureConfig implements FeatureConfiguration {

View file

@ -1,13 +1,13 @@
package org.betterx.bclib.api.v2.levelgen.features.config; package org.betterx.bclib.api.v2.levelgen.features.config;
import net.minecraft.resources.ResourceLocation; import org.betterx.bclib.api.v2.levelgen.structures.StructurePlacementType;
import net.minecraft.util.ExtraCodecs; import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.api.v2.levelgen.structures.StructurePlacementType; import net.minecraft.resources.ResourceLocation;
import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT; import net.minecraft.util.ExtraCodecs;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import java.util.List; import java.util.List;
@ -23,10 +23,12 @@ public class TemplateFeatureConfig implements FeatureConfiguration {
public final List<StructureWorldNBT> structures; public final List<StructureWorldNBT> structures;
public static StructureWorldNBT cfg(ResourceLocation location, public static StructureWorldNBT cfg(
int offsetY, ResourceLocation location,
StructurePlacementType type, int offsetY,
float chance) { StructurePlacementType type,
float chance
) {
return StructureWorldNBT.create(location, offsetY, type, chance); return StructureWorldNBT.create(location, offsetY, type, chance);
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import org.betterx.bclib.api.v2.levelgen.features.config.ConditionFeatureConfig;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -9,8 +11,6 @@ import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature;
import net.minecraft.world.level.levelgen.placement.PlacementContext; import net.minecraft.world.level.levelgen.placement.PlacementContext;
import org.betterx.bclib.api.v2.levelgen.features.config.ConditionFeatureConfig;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream; import java.util.stream.Stream;

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import org.betterx.bclib.util.BlocksHelper;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.WorldGenLevel;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@ -8,8 +10,6 @@ import net.minecraft.world.level.levelgen.Heightmap.Types;
import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration;
import org.betterx.bclib.util.BlocksHelper;
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public abstract class DefaultFeature extends Feature<NoneFeatureConfiguration> { public abstract class DefaultFeature extends Feature<NoneFeatureConfiguration> {
protected static final BlockState AIR = Blocks.AIR.defaultBlockState(); protected static final BlockState AIR = Blocks.AIR.defaultBlockState();

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import net.minecraft.world.level.levelgen.feature.Feature; import org.betterx.bclib.api.v2.levelgen.features.config.PlaceBlockFeatureConfig;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import org.betterx.bclib.api.v2.levelgen.features.config.PlaceBlockFeatureConfig; import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
public class PlaceBlockFeature<FC extends PlaceBlockFeatureConfig> extends Feature<FC> { public class PlaceBlockFeature<FC extends PlaceBlockFeatureConfig> extends Feature<FC> {
public PlaceBlockFeature(Codec<FC> codec) { public PlaceBlockFeature(Codec<FC> codec) {

View file

@ -1,5 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import org.betterx.bclib.api.v2.levelgen.features.UserGrowableFeature;
import org.betterx.bclib.api.v2.levelgen.features.config.ScatterFeatureConfig;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -10,11 +15,6 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import com.mojang.serialization.Codec;
import org.betterx.bclib.api.v2.levelgen.features.UserGrowableFeature;
import org.betterx.bclib.api.v2.levelgen.features.config.ScatterFeatureConfig;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Optional; import java.util.Optional;
public class ScatterFeature<FC extends ScatterFeatureConfig> public class ScatterFeature<FC extends ScatterFeatureConfig>
@ -44,13 +44,15 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
} }
protected void growCenterPillar(LevelAccessor level, protected void growCenterPillar(
BlockPos origin, LevelAccessor level,
BlockPos basePos, BlockPos origin,
Direction direction, BlockPos basePos,
int centerHeight, Direction direction,
ScatterFeatureConfig config, int centerHeight,
RandomSource random) { ScatterFeatureConfig config,
RandomSource random
) {
if (config.isValidBase(level.getBlockState(basePos))) { if (config.isValidBase(level.getBlockState(basePos))) {
final Direction surfaceDirection = direction.getOpposite(); final Direction surfaceDirection = direction.getOpposite();
BlockPos.MutableBlockPos POS = new BlockPos.MutableBlockPos(); BlockPos.MutableBlockPos POS = new BlockPos.MutableBlockPos();
@ -65,11 +67,13 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
POS.set(x, basePos.getY(), z); POS.set(x, basePos.getY(), z);
if (BlocksHelper.findSurroundingSurface(level, POS, surfaceDirection, 4, config::isValidBase)) { if (BlocksHelper.findSurroundingSurface(level, POS, surfaceDirection, 4, config::isValidBase)) {
int myHeight = freeHeight(level, int myHeight = freeHeight(
level,
direction, direction,
centerHeight, centerHeight,
config, config,
POS); POS
);
int dx = x - POS.getX(); int dx = x - POS.getX();
int dz = z - POS.getZ(); int dz = z - POS.getZ();
@ -90,20 +94,24 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
direction, direction,
myHeight, myHeight,
config, config,
random, false); random, false
);
} }
} }
} }
} }
private int freeHeight(LevelAccessor level, private int freeHeight(
Direction direction, LevelAccessor level,
int defaultHeight, Direction direction,
ScatterFeatureConfig config, int defaultHeight,
BlockPos POS) { ScatterFeatureConfig config,
BlockPos POS
) {
int myHeight; int myHeight;
if (config.growWhileFree) { if (config.growWhileFree) {
myHeight = BlocksHelper.blockCount(level, myHeight = BlocksHelper.blockCount(
level,
POS, POS,
direction, direction,
config.maxHeight, config.maxHeight,
@ -115,14 +123,16 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
return Math.max(config.minHeight, myHeight); return Math.max(config.minHeight, myHeight);
} }
private void buildPillarWithBase(LevelAccessor level, private void buildPillarWithBase(
BlockPos origin, LevelAccessor level,
BlockPos basePos, BlockPos origin,
Direction direction, BlockPos basePos,
int height, Direction direction,
ScatterFeatureConfig config, int height,
RandomSource random, ScatterFeatureConfig config,
boolean force) { RandomSource random,
boolean force
) {
if (force || BlocksHelper.isFreeSpace(level, origin, direction, height, BlocksHelper::isFree)) { if (force || BlocksHelper.isFreeSpace(level, origin, direction, height, BlocksHelper::isFree)) {
createPatchOfBaseBlocks(level, random, basePos, config); createPatchOfBaseBlocks(level, random, basePos, config);
BlockState bottom = config.bottomBlock.getState(random, origin); BlockState bottom = config.bottomBlock.getState(random, origin);
@ -132,12 +142,14 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
} }
} }
private void buildPillar(LevelAccessor level, private void buildPillar(
BlockPos origin, LevelAccessor level,
Direction direction, BlockPos origin,
int height, Direction direction,
ScatterFeatureConfig config, int height,
RandomSource random) { ScatterFeatureConfig config,
RandomSource random
) {
final BlockPos.MutableBlockPos POS = origin.mutable(); final BlockPos.MutableBlockPos POS = origin.mutable();
for (int size = 0; size < height; size++) { for (int size = 0; size < height; size++) {
@ -147,10 +159,12 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
} }
} }
private Optional<Direction> getTipDirection(LevelAccessor levelAccessor, private Optional<Direction> getTipDirection(
BlockPos blockPos, LevelAccessor levelAccessor,
RandomSource randomSource, BlockPos blockPos,
ScatterFeatureConfig config) { RandomSource randomSource,
ScatterFeatureConfig config
) {
boolean onCeil = config.floorChance < 1 && config.isValidBase(levelAccessor.getBlockState(blockPos.above())); boolean onCeil = config.floorChance < 1 && config.isValidBase(levelAccessor.getBlockState(blockPos.above()));
boolean onFloor = config.floorChance > 0 && config.isValidBase(levelAccessor.getBlockState(blockPos.below())); boolean onFloor = config.floorChance > 0 && config.isValidBase(levelAccessor.getBlockState(blockPos.below()));
@ -166,10 +180,12 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
return Optional.empty(); return Optional.empty();
} }
private void createPatchOfBaseBlocks(LevelAccessor levelAccessor, private void createPatchOfBaseBlocks(
RandomSource randomSource, LevelAccessor levelAccessor,
BlockPos blockPos, RandomSource randomSource,
ScatterFeatureConfig config) { BlockPos blockPos,
ScatterFeatureConfig config
) {
if (config.baseState.isPresent() && config.baseReplaceChance > 0 && randomSource.nextFloat() < config.baseReplaceChance) { if (config.baseState.isPresent() && config.baseReplaceChance > 0 && randomSource.nextFloat() < config.baseReplaceChance) {
final BlockState baseState = config.baseState.get(); final BlockState baseState = config.baseState.get();
BlockPos pos; BlockPos pos;
@ -190,9 +206,11 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
} }
} }
protected void placeBaseBlockIfPossible(LevelAccessor levelAccessor, protected void placeBaseBlockIfPossible(
BlockPos blockPos, LevelAccessor levelAccessor,
BlockState baseState) { BlockPos blockPos,
BlockState baseState
) {
BlockState blockState = levelAccessor.getBlockState(blockPos); BlockState blockState = levelAccessor.getBlockState(blockPos);
if (BlocksHelper.isTerrain(blockState)) { if (BlocksHelper.isTerrain(blockState)) {
levelAccessor.setBlock(blockPos, baseState, 2); levelAccessor.setBlock(blockPos, baseState, 2);
@ -200,10 +218,12 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
} }
@Override @Override
public boolean grow(ServerLevelAccessor level, public boolean grow(
BlockPos origin, ServerLevelAccessor level,
RandomSource random, BlockPos origin,
FC config) { RandomSource random,
FC config
) {
Optional<Direction> oDirection = getTipDirection(level, origin, random, config); Optional<Direction> oDirection = getTipDirection(level, origin, random, config);
if (oDirection.isEmpty()) { if (oDirection.isEmpty()) {
return false; return false;
@ -213,11 +233,13 @@ public class ScatterFeature<FC extends ScatterFeatureConfig>
if (config.isValidBase(level.getBlockState(basePos))) { if (config.isValidBase(level.getBlockState(basePos))) {
int centerHeight = (int) (random.nextFloat() * (1 + config.maxHeight - config.minHeight) + config.minHeight); int centerHeight = (int) (random.nextFloat() * (1 + config.maxHeight - config.minHeight) + config.minHeight);
centerHeight = freeHeight(level, centerHeight = freeHeight(
level,
direction, direction,
centerHeight, centerHeight,
config, config,
origin.relative(direction, 1)) + 1; origin.relative(direction, 1)
) + 1;
buildPillarWithBase(level, origin, basePos, direction, centerHeight, config, random, true); buildPillarWithBase(level, origin, basePos, direction, centerHeight, config, random, true);
} }
return false; return false;

View file

@ -1,10 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import org.betterx.bclib.api.v2.levelgen.features.config.SequenceFeatureConfig;
import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import org.betterx.bclib.api.v2.levelgen.features.config.SequenceFeatureConfig;
public class SequenceFeature extends Feature<SequenceFeatureConfig> { public class SequenceFeature extends Feature<SequenceFeatureConfig> {
public SequenceFeature() { public SequenceFeature() {
super(SequenceFeatureConfig.CODEC); super(SequenceFeatureConfig.CODEC);

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.Feature;
@ -7,9 +10,6 @@ import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration;
import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration;
import com.mojang.serialization.Codec;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Optional; import java.util.Optional;
public abstract class SurfaceFeature<T extends FeatureConfiguration> extends Feature<T> { public abstract class SurfaceFeature<T extends FeatureConfiguration> extends Feature<T> {
@ -31,10 +31,12 @@ public abstract class SurfaceFeature<T extends FeatureConfiguration> extends Fea
@Override @Override
public boolean place(FeaturePlaceContext<T> ctx) { public boolean place(FeaturePlaceContext<T> ctx) {
Optional<BlockPos> pos = BlocksHelper.findSurfaceBelow(ctx.level(), Optional<BlockPos> pos = BlocksHelper.findSurfaceBelow(
ctx.level(),
ctx.origin(), ctx.origin(),
minHeight(ctx), minHeight(ctx),
this::isValidSurface); this::isValidSurface
);
if (pos.isPresent()) { if (pos.isPresent()) {
generate(pos.get(), ctx); generate(pos.get(), ctx);
return true; return true;

View file

@ -1,23 +1,25 @@
package org.betterx.bclib.api.v2.levelgen.features.features; package org.betterx.bclib.api.v2.levelgen.features.features;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
import com.mojang.serialization.Codec;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeature; import org.betterx.bclib.api.v2.levelgen.features.BCLFeature;
import org.betterx.bclib.api.v2.levelgen.features.BCLFeatureBuilder; import org.betterx.bclib.api.v2.levelgen.features.BCLFeatureBuilder;
import org.betterx.bclib.api.v2.levelgen.features.config.TemplateFeatureConfig; import org.betterx.bclib.api.v2.levelgen.features.config.TemplateFeatureConfig;
import org.betterx.bclib.api.v2.levelgen.structures.StructureNBT; import org.betterx.bclib.api.v2.levelgen.structures.StructureNBT;
import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT; import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT;
import com.mojang.serialization.Codec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.feature.Feature;
import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext;
public class TemplateFeature<FC extends TemplateFeatureConfig> extends Feature<FC> { public class TemplateFeature<FC extends TemplateFeatureConfig> extends Feature<FC> {
public static <T extends TemplateFeatureConfig> BCLFeature createAndRegisterRare(ResourceLocation location, public static <T extends TemplateFeatureConfig> BCLFeature createAndRegisterRare(
TemplateFeatureConfig configuration, ResourceLocation location,
int onceEveryChunk) { TemplateFeatureConfig configuration,
int onceEveryChunk
) {
return BCLFeatureBuilder return BCLFeatureBuilder
@ -34,9 +36,11 @@ public class TemplateFeature<FC extends TemplateFeatureConfig> extends Feature<F
.buildAndRegister(configuration); .buildAndRegister(configuration);
} }
public static <T extends TemplateFeatureConfig> BCLFeature createAndRegister(ResourceLocation location, public static <T extends TemplateFeatureConfig> BCLFeature createAndRegister(
TemplateFeatureConfig configuration, ResourceLocation location,
int count) { TemplateFeatureConfig configuration,
int count
) {
return BCLFeatureBuilder return BCLFeatureBuilder
.start(location, BCLFeature.TEMPLATE) .start(location, BCLFeature.TEMPLATE)
.decoration(GenerationStep.Decoration.SURFACE_STRUCTURES) .decoration(GenerationStep.Decoration.SURFACE_STRUCTURES)
@ -73,7 +77,8 @@ public class TemplateFeature<FC extends TemplateFeatureConfig> extends Feature<F
@Override @Override
public boolean place(FeaturePlaceContext<FC> ctx) { public boolean place(FeaturePlaceContext<FC> ctx) {
StructureWorldNBT structure = randomStructure(ctx.config(), ctx.random()); StructureWorldNBT structure = randomStructure(ctx.config(), ctx.random());
return structure.generateIfPlaceable(ctx.level(), return structure.generateIfPlaceable(
ctx.level(),
ctx.origin(), ctx.origin(),
StructureNBT.getRandomRotation(ctx.random()), StructureNBT.getRandomRotation(ctx.random()),
StructureNBT.getRandomMirror(ctx.random()) StructureNBT.getRandomMirror(ctx.random())

View file

@ -1,13 +1,12 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.world.level.levelgen.placement.PlacementContext; import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -16,9 +15,11 @@ public class All extends PlacementModifier {
public static final Codec<All> CODEC = Codec.unit(All::new); public static final Codec<All> CODEC = Codec.unit(All::new);
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext placementContext, public Stream<BlockPos> getPositions(
RandomSource randomSource, PlacementContext placementContext,
BlockPos blockPos) { RandomSource randomSource,
BlockPos blockPos
) {
return IntStream.range(0, 16 * 16 - 1).mapToObj(i -> blockPos.offset(i & 0xF, 0, i >> 4)); return IntStream.range(0, 16 * 16 - 1).mapToObj(i -> blockPos.offset(i & 0xF, 0, i >> 4));
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -9,9 +11,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.stream.Stream; import java.util.stream.Stream;
public class Extend extends PlacementModifier { public class Extend extends PlacementModifier {
@ -37,9 +36,11 @@ public class Extend extends PlacementModifier {
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext placementContext, public Stream<BlockPos> getPositions(
RandomSource random, PlacementContext placementContext,
BlockPos blockPos) { RandomSource random,
BlockPos blockPos
) {
var builder = Stream.<BlockPos>builder(); var builder = Stream.<BlockPos>builder();
final int count = length.sample(random); final int count = length.sample(random);
builder.add(blockPos); builder.add(blockPos);

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.util.ExtraCodecs; import net.minecraft.util.ExtraCodecs;
@ -10,10 +14,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -28,8 +28,10 @@ public class FindSolidInDirection extends PlacementModifier {
Codec.intRange(1, 32).fieldOf("dist").orElse(12).forGetter((p) -> p.maxSearchDistance), Codec.intRange(1, 32).fieldOf("dist").orElse(12).forGetter((p) -> p.maxSearchDistance),
Codec.BOOL.fieldOf("random:select").orElse(true).forGetter(p -> p.randomSelect) Codec.BOOL.fieldOf("random:select").orElse(true).forGetter(p -> p.randomSelect)
) )
.apply(instance, .apply(
FindSolidInDirection::new)); instance,
FindSolidInDirection::new
));
protected static final FindSolidInDirection DOWN = new FindSolidInDirection(Direction.DOWN, 6); protected static final FindSolidInDirection DOWN = new FindSolidInDirection(Direction.DOWN, 6);
protected static final FindSolidInDirection UP = new FindSolidInDirection(Direction.UP, 6); protected static final FindSolidInDirection UP = new FindSolidInDirection(Direction.UP, 6);
private final List<Direction> direction; private final List<Direction> direction;
@ -77,9 +79,11 @@ public class FindSolidInDirection extends PlacementModifier {
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext placementContext, public Stream<BlockPos> getPositions(
RandomSource randomSource, PlacementContext placementContext,
BlockPos blockPos) { RandomSource randomSource,
BlockPos blockPos
) {
var builder = Stream.<BlockPos>builder(); var builder = Stream.<BlockPos>builder();
if (randomSelect) { if (randomSelect) {
submitSingle(placementContext, blockPos, builder, randomDirection(randomSource)); submitSingle(placementContext, blockPos, builder, randomDirection(randomSource));
@ -92,16 +96,20 @@ public class FindSolidInDirection extends PlacementModifier {
return builder.build(); return builder.build();
} }
private void submitSingle(PlacementContext placementContext, private void submitSingle(
BlockPos blockPos, PlacementContext placementContext,
Stream.Builder<BlockPos> builder, BlockPos blockPos,
Direction d) { Stream.Builder<BlockPos> builder,
Direction d
) {
BlockPos.MutableBlockPos POS = blockPos.mutable(); BlockPos.MutableBlockPos POS = blockPos.mutable();
if (BlocksHelper.findOnSurroundingSurface(placementContext.getLevel(), if (BlocksHelper.findOnSurroundingSurface(
placementContext.getLevel(),
POS, POS,
d, d,
maxSearchDistance, maxSearchDistance,
BlocksHelper::isTerrain)) { BlocksHelper::isTerrain
)) {
builder.add(POS); builder.add(POS);
} }
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
@ -10,9 +12,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementFilter; import net.minecraft.world.level.levelgen.placement.PlacementFilter;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Optional; import java.util.Optional;
public class Is extends PlacementFilter { public class Is extends PlacementFilter {

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.WorldGenLevel;
@ -8,9 +10,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementFilter; import net.minecraft.world.level.levelgen.placement.PlacementFilter;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Optional; import java.util.Optional;
public class IsBasin extends PlacementFilter { public class IsBasin extends PlacementFilter {

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.WorldGenLevel;
@ -7,9 +9,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementFilter; import net.minecraft.world.level.levelgen.placement.PlacementFilter;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
/** /**
* Tests if there is air at two locations above the tested block position * Tests if there is air at two locations above the tested block position
*/ */
@ -64,11 +63,8 @@ public class IsEmptyAboveSampledFilter extends PlacementFilter {
@Override @Override
protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) { protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) {
WorldGenLevel level = ctx.getLevel(); WorldGenLevel level = ctx.getLevel();
if (level.isEmptyBlock(pos.above(distance1)) return level.isEmptyBlock(pos.above(distance1))
&& (distance1 == distance2 || level.isEmptyBlock(pos.above(distance2)))) { && (distance1 == distance2 || level.isEmptyBlock(pos.above(distance2)));
return true;
}
return false;
} }
@Override @Override

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -8,13 +12,9 @@ import net.minecraft.world.level.levelgen.placement.PlacementFilter;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
public class MinEmptyFilter extends PlacementFilter { public class MinEmptyFilter extends PlacementFilter {
private static MinEmptyFilter DOWN = new MinEmptyFilter(Direction.DOWN, 2); private static final MinEmptyFilter DOWN = new MinEmptyFilter(Direction.DOWN, 2);
private static MinEmptyFilter UP = new MinEmptyFilter(Direction.UP, 2); private static final MinEmptyFilter UP = new MinEmptyFilter(Direction.UP, 2);
public static final Codec<MinEmptyFilter> CODEC = RecordCodecBuilder.create((instance) -> instance public static final Codec<MinEmptyFilter> CODEC = RecordCodecBuilder.create((instance) -> instance
.group( .group(
Direction.CODEC.fieldOf("dir").orElse(Direction.DOWN).forGetter((p) -> p.direction), Direction.CODEC.fieldOf("dir").orElse(Direction.DOWN).forGetter((p) -> p.direction),

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
@ -9,14 +11,12 @@ import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream; import java.util.stream.Stream;
public class Offset extends PlacementModifier { public class Offset extends PlacementModifier {
private static Map<Direction, Offset> DIRECTIONS = Maps.newHashMap(); private static final Map<Direction, Offset> DIRECTIONS = Maps.newHashMap();
public static final Codec<Offset> CODEC = RecordCodecBuilder.create((instance) -> instance public static final Codec<Offset> CODEC = RecordCodecBuilder.create((instance) -> instance
.group( .group(
Vec3i.CODEC Vec3i.CODEC
@ -36,9 +36,11 @@ public class Offset extends PlacementModifier {
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext placementContext, public Stream<BlockPos> getPositions(
RandomSource randomSource, PlacementContext placementContext,
BlockPos blockPos) { RandomSource randomSource,
BlockPos blockPos
) {
return Stream.of(blockPos.offset(offset)); return Stream.of(blockPos.offset(offset));
} }

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@ -9,17 +13,13 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream; import java.util.stream.Stream;
public class OnEveryLayer public class OnEveryLayer
extends PlacementModifier { extends PlacementModifier {
private static OnEveryLayer INSTANCE = new OnEveryLayer(Optional.empty(), Optional.empty()); private static final OnEveryLayer INSTANCE = new OnEveryLayer(Optional.empty(), Optional.empty());
private static OnEveryLayer INSTANCE_MIN_4 = new OnEveryLayer(Optional.of(4), Optional.empty()); private static final OnEveryLayer INSTANCE_MIN_4 = new OnEveryLayer(Optional.of(4), Optional.empty());
public static final Codec<OnEveryLayer> CODEC = RecordCodecBuilder.create(instance -> instance public static final Codec<OnEveryLayer> CODEC = RecordCodecBuilder.create(instance -> instance
.group( .group(
Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight), Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight),
@ -45,9 +45,11 @@ public class OnEveryLayer
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext ctx, public Stream<BlockPos> getPositions(
RandomSource random, PlacementContext ctx,
BlockPos pos) { RandomSource random,
BlockPos pos
) {
Stream.Builder<BlockPos> builder = Stream.builder(); Stream.Builder<BlockPos> builder = Stream.builder();

View file

@ -1,65 +1,78 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import org.betterx.bclib.BCLib;
import com.mojang.serialization.Codec;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import org.betterx.bclib.BCLib;
public class PlacementModifiers { public class PlacementModifiers {
public static final PlacementModifierType<IsEmptyAboveSampledFilter> IS_EMPTY_ABOVE_SAMPLED_FILTER = register( public static final PlacementModifierType<IsEmptyAboveSampledFilter> IS_EMPTY_ABOVE_SAMPLED_FILTER = register(
"is_empty_above_sampled_filter", "is_empty_above_sampled_filter",
IsEmptyAboveSampledFilter.CODEC); IsEmptyAboveSampledFilter.CODEC
);
public static final PlacementModifierType<MinEmptyFilter> MIN_EMPTY_FILTER = register( public static final PlacementModifierType<MinEmptyFilter> MIN_EMPTY_FILTER = register(
"min_empty_filter", "min_empty_filter",
MinEmptyFilter.CODEC); MinEmptyFilter.CODEC
);
public static final PlacementModifierType<FindSolidInDirection> SOLID_IN_DIR = register( public static final PlacementModifierType<FindSolidInDirection> SOLID_IN_DIR = register(
"solid_in_dir", "solid_in_dir",
FindSolidInDirection.CODEC); FindSolidInDirection.CODEC
);
public static final PlacementModifierType<Stencil> STENCIL = register( public static final PlacementModifierType<Stencil> STENCIL = register(
"stencil", "stencil",
Stencil.CODEC); Stencil.CODEC
);
public static final PlacementModifierType<All> ALL = register( public static final PlacementModifierType<All> ALL = register(
"all", "all",
All.CODEC); All.CODEC
);
public static final PlacementModifierType<IsBasin> IS_BASIN = register( public static final PlacementModifierType<IsBasin> IS_BASIN = register(
"is_basin", "is_basin",
IsBasin.CODEC); IsBasin.CODEC
);
public static final PlacementModifierType<Is> IS = register( public static final PlacementModifierType<Is> IS = register(
"is", "is",
Is.CODEC); Is.CODEC
);
public static final PlacementModifierType<Offset> OFFSET = register( public static final PlacementModifierType<Offset> OFFSET = register(
"offset", "offset",
Offset.CODEC); Offset.CODEC
);
public static final PlacementModifierType<Extend> EXTEND = register( public static final PlacementModifierType<Extend> EXTEND = register(
"extend", "extend",
Extend.CODEC); Extend.CODEC
);
public static final PlacementModifierType<OnEveryLayer> ON_EVERY_LAYER = register( public static final PlacementModifierType<OnEveryLayer> ON_EVERY_LAYER = register(
"on_every_layer", "on_every_layer",
OnEveryLayer.CODEC); OnEveryLayer.CODEC
);
public static final PlacementModifierType<UnderEveryLayer> UNDER_EVERY_LAYER = register( public static final PlacementModifierType<UnderEveryLayer> UNDER_EVERY_LAYER = register(
"under_every_layer", "under_every_layer",
UnderEveryLayer.CODEC); UnderEveryLayer.CODEC
);
private static <P extends PlacementModifier> PlacementModifierType<P> register(String path, Codec<P> codec) { private static <P extends PlacementModifier> PlacementModifierType<P> register(String path, Codec<P> codec) {
return register(BCLib.makeID(path), codec); return register(BCLib.makeID(path), codec);
} }
public static <P extends PlacementModifier> PlacementModifierType<P> register(ResourceLocation location, public static <P extends PlacementModifier> PlacementModifierType<P> register(
Codec<P> codec) { ResourceLocation location,
Codec<P> codec
) {
return Registry.register(Registry.PLACEMENT_MODIFIERS, location, () -> codec); return Registry.register(Registry.PLACEMENT_MODIFIERS, location, () -> codec);
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.ExtraCodecs; import net.minecraft.util.ExtraCodecs;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
@ -7,9 +9,6 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -45,9 +44,11 @@ public class Stencil extends PlacementModifier {
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext placementContext, public Stream<BlockPos> getPositions(
RandomSource randomSource, PlacementContext placementContext,
BlockPos blockPos) { RandomSource randomSource,
BlockPos blockPos
) {
List<BlockPos> pos = new ArrayList<>(16 * 16); List<BlockPos> pos = new ArrayList<>(16 * 16);
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int y = 0; y < 16; y++) { for (int y = 0; y < 16; y++) {

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.features.placement; package org.betterx.bclib.api.v2.levelgen.features.placement;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.util.RandomSource; import net.minecraft.util.RandomSource;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@ -9,17 +13,13 @@ import net.minecraft.world.level.levelgen.placement.PlacementContext;
import net.minecraft.world.level.levelgen.placement.PlacementModifier; import net.minecraft.world.level.levelgen.placement.PlacementModifier;
import net.minecraft.world.level.levelgen.placement.PlacementModifierType; import net.minecraft.world.level.levelgen.placement.PlacementModifierType;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream; import java.util.stream.Stream;
public class UnderEveryLayer public class UnderEveryLayer
extends PlacementModifier { extends PlacementModifier {
private static UnderEveryLayer INSTANCE = new UnderEveryLayer(Optional.empty(), Optional.empty()); private static final UnderEveryLayer INSTANCE = new UnderEveryLayer(Optional.empty(), Optional.empty());
private static UnderEveryLayer INSTANCE_MIN_4 = new UnderEveryLayer(Optional.of(4), Optional.empty()); private static final UnderEveryLayer INSTANCE_MIN_4 = new UnderEveryLayer(Optional.of(4), Optional.empty());
public static final Codec<UnderEveryLayer> CODEC = RecordCodecBuilder.create(instance -> instance public static final Codec<UnderEveryLayer> CODEC = RecordCodecBuilder.create(instance -> instance
.group( .group(
Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight), Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight),
@ -45,9 +45,11 @@ public class UnderEveryLayer
} }
@Override @Override
public Stream<BlockPos> getPositions(PlacementContext ctx, public Stream<BlockPos> getPositions(
RandomSource random, PlacementContext ctx,
BlockPos pos) { RandomSource random,
BlockPos pos
) {
Stream.Builder<BlockPos> builder = Stream.builder(); Stream.Builder<BlockPos> builder = Stream.builder();

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeBuilder;
import org.betterx.bclib.mixin.common.StructuresAccessor;
import com.mojang.serialization.Codec;
import net.minecraft.core.*; import net.minecraft.core.*;
import net.minecraft.data.BuiltinRegistries; import net.minecraft.data.BuiltinRegistries;
import net.minecraft.data.worldgen.StructureSets; import net.minecraft.data.worldgen.StructureSets;
@ -13,9 +17,6 @@ import net.minecraft.world.level.levelgen.structure.*;
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.mojang.serialization.Codec;
import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeBuilder;
import org.betterx.bclib.mixin.common.StructuresAccessor;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -42,31 +43,39 @@ public class BCLStructure<S extends Structure> {
return BuiltinRegistries.BIOME.getOrCreateTag(tagKey); return BuiltinRegistries.BIOME.getOrCreateTag(tagKey);
} }
private static Structure.StructureSettings structure(TagKey<Biome> tagKey, private static Structure.StructureSettings structure(
Map<MobCategory, StructureSpawnOverride> map, TagKey<Biome> tagKey,
GenerationStep.Decoration decoration, Map<MobCategory, StructureSpawnOverride> map,
TerrainAdjustment terrainAdjustment) { GenerationStep.Decoration decoration,
TerrainAdjustment terrainAdjustment
) {
return new Structure.StructureSettings(biomes(tagKey), map, decoration, terrainAdjustment); return new Structure.StructureSettings(biomes(tagKey), map, decoration, terrainAdjustment);
} }
private static Structure.StructureSettings structure(TagKey<Biome> tagKey, private static Structure.StructureSettings structure(
GenerationStep.Decoration decoration, TagKey<Biome> tagKey,
TerrainAdjustment terrainAdjustment) { GenerationStep.Decoration decoration,
TerrainAdjustment terrainAdjustment
) {
return structure(tagKey, Map.of(), decoration, terrainAdjustment); return structure(tagKey, Map.of(), decoration, terrainAdjustment);
} }
private static <S extends Structure> StructureType<S> registerStructureType(ResourceLocation id, private static <S extends Structure> StructureType<S> registerStructureType(
Codec<S> codec) { ResourceLocation id,
Codec<S> codec
) {
return Registry.register(Registry.STRUCTURE_TYPES, id, () -> codec); return Registry.register(Registry.STRUCTURE_TYPES, id, () -> codec);
} }
protected BCLStructure(@NotNull ResourceLocation id, protected BCLStructure(
@NotNull Function<Structure.StructureSettings, S> structureBuilder, @NotNull ResourceLocation id,
GenerationStep.Decoration step, @NotNull Function<Structure.StructureSettings, S> structureBuilder,
@NotNull StructurePlacement placement, GenerationStep.Decoration step,
@NotNull Codec<S> codec, @NotNull StructurePlacement placement,
@NotNull TagKey<Biome> biomeTag, @NotNull Codec<S> codec,
@NotNull TerrainAdjustment terrainAdjustment) { @NotNull TagKey<Biome> biomeTag,
@NotNull TerrainAdjustment terrainAdjustment
) {
this.id = id; this.id = id;
this.featureStep = step; this.featureStep = step;
this.STRUCTURE_CODEC = codec; this.STRUCTURE_CODEC = codec;

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import org.betterx.bclib.api.v2.tag.TagAPI;
import com.mojang.serialization.Codec;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey; import net.minecraft.tags.TagKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
@ -10,9 +13,6 @@ import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStruct
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadType; import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadType;
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
import com.mojang.serialization.Codec;
import org.betterx.bclib.api.v2.tag.TagAPI;
import java.util.function.Function; import java.util.function.Function;
public class BCLStructureBuilder<S extends Structure> { public class BCLStructureBuilder<S extends Structure> {
@ -34,8 +34,10 @@ public class BCLStructureBuilder<S extends Structure> {
private BCLStructureBuilder() { private BCLStructureBuilder() {
} }
public static <S extends Structure> BCLStructureBuilder<S> start(ResourceLocation structureID, public static <S extends Structure> BCLStructureBuilder<S> start(
Function<Structure.StructureSettings, S> structureBuilder) { ResourceLocation structureID,
Function<Structure.StructureSettings, S> structureBuilder
) {
INSTANCE.structureID = structureID; INSTANCE.structureID = structureID;
INSTANCE.structureBuilder = structureBuilder; INSTANCE.structureBuilder = structureBuilder;
@ -69,12 +71,12 @@ public class BCLStructureBuilder<S extends Structure> {
} }
public BCLStructureBuilder<S> randomPlacement(int spacing, int separation) { public BCLStructureBuilder<S> randomPlacement(int spacing, int separation) {
this.placement = new RandomSpreadStructurePlacement(spacing, this.placement = new RandomSpreadStructurePlacement(
spacing,
separation, separation,
RandomSpreadType.LINEAR, RandomSpreadType.LINEAR,
13323129 + spacing + separation + structureID.toString().hashCode() % 10000 13323129 + spacing + separation + structureID.toString().hashCode() % 10000
); );
;
return this; return this;
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import org.betterx.bclib.BCLib;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.BlockPos.MutableBlockPos;
import net.minecraft.core.Vec3i; import net.minecraft.core.Vec3i;
@ -17,7 +19,6 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlac
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import org.betterx.bclib.BCLib;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;

View file

@ -1,8 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import net.minecraft.util.StringRepresentable;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import net.minecraft.util.StringRepresentable;
public enum StructurePlacementType implements StringRepresentable { public enum StructurePlacementType implements StringRepresentable {
FLOOR, WALL, CEIL, LAVA, UNDER; FLOOR, WALL, CEIL, LAVA, UNDER;

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import org.betterx.bclib.util.BlocksHelper;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.BlockPos.MutableBlockPos;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
@ -12,9 +16,6 @@ import net.minecraft.world.level.block.Rotation;
import net.minecraft.world.level.levelgen.structure.BoundingBox; import net.minecraft.world.level.levelgen.structure.BoundingBox;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.util.BlocksHelper;
import java.util.Map; import java.util.Map;
@ -62,29 +63,35 @@ public class StructureWorldNBT extends StructureNBT {
return create(location, offsetY, type, 1.0f); return create(location, offsetY, type, 1.0f);
} }
public static StructureWorldNBT create(ResourceLocation location, public static StructureWorldNBT create(
int offsetY, ResourceLocation location,
StructurePlacementType type, int offsetY,
float chance) { StructurePlacementType type,
float chance
) {
String key = location.toString() + "::" + offsetY + "::" + type.getSerializedName(); String key = location.toString() + "::" + offsetY + "::" + type.getSerializedName();
return READER_CACHE.computeIfAbsent(key, r -> new StructureWorldNBT(location, offsetY, type, chance)); return READER_CACHE.computeIfAbsent(key, r -> new StructureWorldNBT(location, offsetY, type, chance));
} }
public boolean generateIfPlaceable(ServerLevelAccessor level, public boolean generateIfPlaceable(
BlockPos pos, ServerLevelAccessor level,
RandomSource random BlockPos pos,
RandomSource random
) { ) {
return generateIfPlaceable(level, return generateIfPlaceable(
level,
pos, pos,
getRandomRotation(random), getRandomRotation(random),
getRandomMirror(random) getRandomMirror(random)
); );
} }
public boolean generateIfPlaceable(ServerLevelAccessor level, public boolean generateIfPlaceable(
BlockPos pos, ServerLevelAccessor level,
Rotation r, BlockPos pos,
Mirror m) { Rotation r,
Mirror m
) {
if (canGenerate(level, pos, r)) { if (canGenerate(level, pos, r)) {
return generate(level, pos, r, m); return generate(level, pos, r, m);
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import org.betterx.bclib.BCLib;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
@ -17,19 +19,21 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlac
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import org.betterx.bclib.BCLib;
public class TemplatePiece extends TemplateStructurePiece { public class TemplatePiece extends TemplateStructurePiece {
public static final StructurePieceType INSTANCE = setTemplatePieceId(TemplatePiece::new, public static final StructurePieceType INSTANCE = setTemplatePieceId(
"template_piece"); TemplatePiece::new,
"template_piece"
);
private static StructurePieceType setFullContextPieceId(StructurePieceType structurePieceType, String id) { private static StructurePieceType setFullContextPieceId(StructurePieceType structurePieceType, String id) {
return Registry.register(Registry.STRUCTURE_PIECE, BCLib.makeID(id), structurePieceType); return Registry.register(Registry.STRUCTURE_PIECE, BCLib.makeID(id), structurePieceType);
} }
private static StructurePieceType setTemplatePieceId(StructurePieceType.StructureTemplateType structureTemplateType, private static StructurePieceType setTemplatePieceId(
String string) { StructurePieceType.StructureTemplateType structureTemplateType,
String string
) {
return setFullContextPieceId(structureTemplateType, string); return setFullContextPieceId(structureTemplateType, string);
} }
@ -38,32 +42,40 @@ public class TemplatePiece extends TemplateStructurePiece {
} }
public TemplatePiece(StructureTemplateManager structureTemplateManager, public TemplatePiece(
ResourceLocation resourceLocation, StructureTemplateManager structureTemplateManager,
BlockPos centerPos, ResourceLocation resourceLocation,
Rotation rotation, BlockPos centerPos,
Mirror mirror, Rotation rotation,
BlockPos halfSize) { Mirror mirror,
super(INSTANCE, BlockPos halfSize
) {
super(
INSTANCE,
0, 0,
structureTemplateManager, structureTemplateManager,
resourceLocation, resourceLocation,
resourceLocation.toString(), resourceLocation.toString(),
makeSettings(rotation, mirror, halfSize), makeSettings(rotation, mirror, halfSize),
shiftPos(rotation, mirror, halfSize, centerPos)); shiftPos(rotation, mirror, halfSize, centerPos)
);
} }
public TemplatePiece(StructureTemplateManager structureTemplateManager, CompoundTag compoundTag) { public TemplatePiece(StructureTemplateManager structureTemplateManager, CompoundTag compoundTag) {
super(INSTANCE, super(
INSTANCE,
compoundTag, compoundTag,
structureTemplateManager, structureTemplateManager,
(ResourceLocation resourceLocation) -> makeSettings(compoundTag)); (ResourceLocation resourceLocation) -> makeSettings(compoundTag)
);
} }
private static BlockPos shiftPos(Rotation rotation, private static BlockPos shiftPos(
Mirror mirror, Rotation rotation,
BlockPos halfSize, Mirror mirror,
BlockPos pos) { BlockPos halfSize,
BlockPos pos
) {
halfSize = StructureTemplate.transform(halfSize, mirror, rotation, halfSize); halfSize = StructureTemplate.transform(halfSize, mirror, rotation, halfSize);
return pos.offset(-halfSize.getX(), 0, -halfSize.getZ()); return pos.offset(-halfSize.getX(), 0, -halfSize.getZ());
} }
@ -72,7 +84,8 @@ public class TemplatePiece extends TemplateStructurePiece {
return makeSettings( return makeSettings(
Rotation.valueOf(compoundTag.getString("R")), Rotation.valueOf(compoundTag.getString("R")),
Mirror.valueOf(compoundTag.getString("M")), Mirror.valueOf(compoundTag.getString("M")),
new BlockPos(compoundTag.getInt("RX"), compoundTag.getInt("RY"), compoundTag.getInt("RZ"))); new BlockPos(compoundTag.getInt("RX"), compoundTag.getInt("RY"), compoundTag.getInt("RZ"))
);
} }
@ -84,8 +97,10 @@ public class TemplatePiece extends TemplateStructurePiece {
} }
@Override @Override
protected void addAdditionalSaveData(StructurePieceSerializationContext structurePieceSerializationContext, protected void addAdditionalSaveData(
CompoundTag tag) { StructurePieceSerializationContext structurePieceSerializationContext,
CompoundTag tag
) {
super.addAdditionalSaveData(structurePieceSerializationContext, tag); super.addAdditionalSaveData(structurePieceSerializationContext, tag);
tag.putString("R", this.placeSettings.getRotation().name()); tag.putString("R", this.placeSettings.getRotation().name());
tag.putString("M", this.placeSettings.getMirror().name()); tag.putString("M", this.placeSettings.getMirror().name());
@ -95,11 +110,13 @@ public class TemplatePiece extends TemplateStructurePiece {
} }
@Override @Override
protected void handleDataMarker(String string, protected void handleDataMarker(
BlockPos blockPos, String string,
ServerLevelAccessor serverLevelAccessor, BlockPos blockPos,
RandomSource randomSource, ServerLevelAccessor serverLevelAccessor,
BoundingBox boundingBox) { RandomSource randomSource,
BoundingBox boundingBox
) {
} }
} }

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.structures; package org.betterx.bclib.api.v2.levelgen.structures;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.ExtraCodecs; import net.minecraft.util.ExtraCodecs;
@ -15,9 +17,6 @@ import net.minecraft.world.level.levelgen.structure.BoundingBox;
import net.minecraft.world.level.levelgen.structure.Structure; import net.minecraft.world.level.levelgen.structure.Structure;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.function.BiFunction; import java.util.function.BiFunction;
@ -39,16 +38,20 @@ public abstract class TemplateStructure extends Structure {
} }
protected TemplateStructure(StructureSettings structureSettings, protected TemplateStructure(
ResourceLocation location, StructureSettings structureSettings,
int offsetY, ResourceLocation location,
StructurePlacementType type, int offsetY,
float chance) { StructurePlacementType type,
float chance
) {
this(structureSettings, List.of(new Config(location, offsetY, type, chance))); this(structureSettings, List.of(new Config(location, offsetY, type, chance)));
} }
protected TemplateStructure(StructureSettings structureSettings, protected TemplateStructure(
List<Config> configs) { StructureSettings structureSettings,
List<Config> configs
) {
super(structureSettings); super(structureSettings);
this.configs = configs; this.configs = configs;
} }
@ -80,8 +83,10 @@ public abstract class TemplateStructure extends Structure {
@Override @Override
public Optional<GenerationStub> findGenerationPoint(GenerationContext ctx) { public Optional<GenerationStub> findGenerationPoint(GenerationContext ctx) {
WorldGenerationContext worldGenerationContext = new WorldGenerationContext(ctx.chunkGenerator(), WorldGenerationContext worldGenerationContext = new WorldGenerationContext(
ctx.heightAccessor()); ctx.chunkGenerator(),
ctx.heightAccessor()
);
final Config config = randomConfig(ctx.random()); final Config config = randomConfig(ctx.random());
if (config == null) return Optional.empty(); if (config == null) return Optional.empty();
ChunkPos chunkPos = ctx.chunkPos(); ChunkPos chunkPos = ctx.chunkPos();
@ -123,30 +128,38 @@ public abstract class TemplateStructure extends Structure {
if (y >= maxHeight || y < seaLevel) return Optional.empty(); if (y >= maxHeight || y < seaLevel) return Optional.empty();
if (!BCLStructure.isValidBiome(ctx, y)) return Optional.empty(); if (!BCLStructure.isValidBiome(ctx, y)) return Optional.empty();
BlockPos halfSize = new BlockPos(structureTemplate.getSize().getX() / 2, BlockPos halfSize = new BlockPos(
structureTemplate.getSize().getX() / 2,
0, 0,
structureTemplate.getSize().getZ() / 2); structureTemplate.getSize().getZ() / 2
);
Rotation rotation = StructureNBT.getRandomRotation(ctx.random()); Rotation rotation = StructureNBT.getRandomRotation(ctx.random());
Mirror mirror = StructureNBT.getRandomMirror(ctx.random()); Mirror mirror = StructureNBT.getRandomMirror(ctx.random());
BlockPos centerPos = new BlockPos(x, BlockPos centerPos = new BlockPos(
x,
y - (searchStep == 1 ? 0 : (structureTemplate.getSize(Rotation.NONE).getY())), y - (searchStep == 1 ? 0 : (structureTemplate.getSize(Rotation.NONE).getY())),
z); z
);
BoundingBox boundingBox = structureTemplate.getBoundingBox(centerPos, rotation, halfSize, mirror); BoundingBox boundingBox = structureTemplate.getBoundingBox(centerPos, rotation, halfSize, mirror);
// if (!structure.canGenerate(ctx.chunkGenerator()., centerPos)) // if (!structure.canGenerate(ctx.chunkGenerator()., centerPos))
return Optional.of(new GenerationStub(centerPos, return Optional.of(new GenerationStub(
centerPos,
structurePiecesBuilder -> structurePiecesBuilder ->
structurePiecesBuilder.addPiece( structurePiecesBuilder.addPiece(
new TemplatePiece(ctx.structureTemplateManager(), new TemplatePiece(
ctx.structureTemplateManager(),
config.location, config.location,
centerPos.offset( centerPos.offset(
0, 0,
config.offsetY, config.offsetY,
0), 0
),
rotation, rotation,
mirror, mirror,
halfSize)) halfSize
))
)); ));
} }

View file

@ -1,5 +1,8 @@
package org.betterx.bclib.api.v2.levelgen.structures.templatesystem; package org.betterx.bclib.api.v2.levelgen.structures.templatesystem;
import org.betterx.bclib.util.BlocksHelper;
import org.betterx.bclib.util.MHelper;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
@ -7,9 +10,6 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProc
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo;
import org.betterx.bclib.util.BlocksHelper;
import org.betterx.bclib.util.MHelper;
public class DestructionStructureProcessor extends StructureProcessor { public class DestructionStructureProcessor extends StructureProcessor {
private int chance = 4; private int chance = 4;
@ -18,12 +18,14 @@ public class DestructionStructureProcessor extends StructureProcessor {
} }
@Override @Override
public StructureBlockInfo processBlock(LevelReader worldView, public StructureBlockInfo processBlock(
BlockPos pos, LevelReader worldView,
BlockPos blockPos, BlockPos pos,
StructureBlockInfo structureBlockInfo, BlockPos blockPos,
StructureBlockInfo structureBlockInfo2, StructureBlockInfo structureBlockInfo,
StructurePlaceSettings structurePlacementData) { StructureBlockInfo structureBlockInfo2,
StructurePlaceSettings structurePlacementData
) {
if (!BlocksHelper.isInvulnerable( if (!BlocksHelper.isInvulnerable(
structureBlockInfo2.state, structureBlockInfo2.state,
worldView, worldView,

View file

@ -1,5 +1,7 @@
package org.betterx.bclib.api.v2.levelgen.structures.templatesystem; package org.betterx.bclib.api.v2.levelgen.structures.templatesystem;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
@ -9,8 +11,6 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProc
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
public class TerrainStructureProcessor extends StructureProcessor { public class TerrainStructureProcessor extends StructureProcessor {
private final Block defaultBlock; private final Block defaultBlock;
@ -19,12 +19,14 @@ public class TerrainStructureProcessor extends StructureProcessor {
} }
@Override @Override
public StructureBlockInfo processBlock(LevelReader worldView, public StructureBlockInfo processBlock(
BlockPos pos, LevelReader worldView,
BlockPos blockPos, BlockPos pos,
StructureBlockInfo structureBlockInfo, BlockPos blockPos,
StructureBlockInfo structureBlockInfo2, StructureBlockInfo structureBlockInfo,
StructurePlaceSettings structurePlacementData) { StructureBlockInfo structureBlockInfo2,
StructurePlaceSettings structurePlacementData
) {
BlockPos bpos = structureBlockInfo2.pos; BlockPos bpos = structureBlockInfo2.pos;
if (structureBlockInfo2.state.is(defaultBlock) && worldView.isEmptyBlock(bpos.above())) { if (structureBlockInfo2.state.is(defaultBlock) && worldView.isEmptyBlock(bpos.above())) {
final BlockState top = BiomeAPI.findTopMaterial(worldView.getBiome(pos)) final BlockState top = BiomeAPI.findTopMaterial(worldView.getBiome(pos))

View file

@ -1,5 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.surface; package org.betterx.bclib.api.v2.levelgen.surface;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.api.v2.levelgen.surface.rules.Conditions;
import org.betterx.bclib.api.v2.levelgen.surface.rules.DoubleBlockSurfaceNoiseCondition;
import org.betterx.bclib.api.v2.levelgen.surface.rules.NoiseCondition;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -9,10 +14,6 @@ import net.minecraft.world.level.levelgen.placement.CaveSurface;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import org.betterx.bclib.api.v2.levelgen.surface.rules.DoubleBlockSurfaceNoiseCondition;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.api.v2.levelgen.surface.rules.Conditions;
import org.betterx.bclib.api.v2.levelgen.surface.rules.NoiseCondition;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -96,8 +97,10 @@ public class SurfaceRuleBuilder {
* @return same {@link SurfaceRuleBuilder} instance. * @return same {@link SurfaceRuleBuilder} instance.
*/ */
public SurfaceRuleBuilder filler(BlockState state) { public SurfaceRuleBuilder filler(BlockState state) {
entryInstance = getFromCache("fill_" + state.toString(), entryInstance = getFromCache(
() -> new SurfaceRuleEntry(10, SurfaceRules.state(state))); "fill_" + state.toString(),
() -> new SurfaceRuleEntry(10, SurfaceRules.state(state))
);
rules.add(entryInstance); rules.add(entryInstance);
return this; return this;
} }
@ -126,16 +129,22 @@ public class SurfaceRuleBuilder {
* @return same {@link SurfaceRuleBuilder} instance. * @return same {@link SurfaceRuleBuilder} instance.
*/ */
public SurfaceRuleBuilder belowFloor(BlockState state, int height, NoiseCondition noise) { public SurfaceRuleBuilder belowFloor(BlockState state, int height, NoiseCondition noise) {
entryInstance = getFromCache("below_floor_" + height + "_" + state.toString() + "_" + noise.getClass() entryInstance = getFromCache(
.getSimpleName(), "below_floor_" + height + "_" + state.toString() + "_" + noise.getClass()
.getSimpleName(),
() -> { () -> {
RuleSource rule = SurfaceRules.state(state); RuleSource rule = SurfaceRules.state(state);
rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, rule = SurfaceRules.ifTrue(
SurfaceRules.stoneDepthCheck(
height,
false, false,
CaveSurface.FLOOR), CaveSurface.FLOOR
SurfaceRules.ifTrue(noise, rule)); ),
SurfaceRules.ifTrue(noise, rule)
);
return new SurfaceRuleEntry(3, rule); return new SurfaceRuleEntry(3, rule);
}); }
);
rules.add(entryInstance); rules.add(entryInstance);
return this; return this;
} }
@ -250,39 +259,49 @@ public class SurfaceRuleBuilder {
* @return same {@link SurfaceRuleBuilder} instance. * @return same {@link SurfaceRuleBuilder} instance.
*/ */
public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, BlockState surfaceBlockB, NoiseCondition noise) { public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, BlockState surfaceBlockB, NoiseCondition noise) {
entryInstance = getFromCache("chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass() entryInstance = getFromCache(
.getSimpleName(), "chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass()
.getSimpleName(),
() -> { () -> {
RuleSource rule = RuleSource rule =
SurfaceRules.ifTrue(SurfaceRules.ON_FLOOR, SurfaceRules.ifTrue(
SurfaceRules.ON_FLOOR,
SurfaceRules.sequence( SurfaceRules.sequence(
SurfaceRules.ifTrue(noise, SurfaceRules.ifTrue(
noise,
SurfaceRules.state( SurfaceRules.state(
surfaceBlockA)), surfaceBlockA)
),
SurfaceRules.state(surfaceBlockB) SurfaceRules.state(surfaceBlockB)
) )
); );
return new SurfaceRuleEntry(4, rule); return new SurfaceRuleEntry(4, rule);
}); }
);
rules.add(entryInstance); rules.add(entryInstance);
return this; return this;
} }
public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, RuleSource surfaceBlockB, NoiseCondition noise) { public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, RuleSource surfaceBlockB, NoiseCondition noise) {
entryInstance = getFromCache("chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass() entryInstance = getFromCache(
.getSimpleName(), "chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass()
.getSimpleName(),
() -> { () -> {
RuleSource rule = RuleSource rule =
SurfaceRules.ifTrue(SurfaceRules.ON_FLOOR, SurfaceRules.ifTrue(
SurfaceRules.ON_FLOOR,
SurfaceRules.sequence( SurfaceRules.sequence(
SurfaceRules.ifTrue(noise, SurfaceRules.ifTrue(
noise,
SurfaceRules.state( SurfaceRules.state(
surfaceBlockA)), surfaceBlockA)
),
surfaceBlockB surfaceBlockB
) )
); );
return new SurfaceRuleEntry(4, rule); return new SurfaceRuleEntry(4, rule);
}); }
);
rules.add(entryInstance); rules.add(entryInstance);
return this; return this;
} }

View file

@ -1,5 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.surface; package org.betterx.bclib.api.v2.levelgen.surface;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.mixin.common.NoiseGeneratorSettingsMixin;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
@ -11,9 +15,6 @@ import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI;
import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI;
import org.betterx.bclib.mixin.common.NoiseGeneratorSettingsMixin;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;

View file

@ -1,58 +1,72 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.interfaces.NumericProvider;
import com.mojang.serialization.Codec;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.valueproviders.UniformFloat; import net.minecraft.util.valueproviders.UniformFloat;
import net.minecraft.world.level.levelgen.SurfaceRules; import net.minecraft.world.level.levelgen.SurfaceRules;
import com.mojang.serialization.Codec;
import org.betterx.bclib.BCLib;
import org.betterx.bclib.interfaces.NumericProvider;
public class Conditions { public class Conditions {
public static final ThresholdCondition DOUBLE_BLOCK_SURFACE_NOISE = new ThresholdCondition(4141, public static final ThresholdCondition DOUBLE_BLOCK_SURFACE_NOISE = new ThresholdCondition(
4141,
0, 0,
UniformFloat.of(-0.4f, 0.4f), UniformFloat.of(-0.4f, 0.4f),
0.1, 0.1,
0.1); 0.1
);
public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_A = new ThresholdCondition(614, public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_A = new ThresholdCondition(
614,
0, 0,
UniformFloat.of(-0.2f, 0f), UniformFloat.of(-0.2f, 0f),
0.1, 0.1,
0.1); 0.1
);
public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_B = new ThresholdCondition(614, public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_B = new ThresholdCondition(
614,
0, 0,
UniformFloat.of(-0.7f, -0.5f), UniformFloat.of(-0.7f, -0.5f),
0.1, 0.1,
0.1); 0.1
);
public static final ThresholdCondition NETHER_SURFACE_NOISE = new ThresholdCondition(245, public static final ThresholdCondition NETHER_SURFACE_NOISE = new ThresholdCondition(
245,
0, 0,
UniformFloat.of(-0.7f, -0.5f), UniformFloat.of(-0.7f, -0.5f),
0.05, 0.05,
0.05); 0.05
);
public static final ThresholdCondition NETHER_SURFACE_NOISE_LARGE = new ThresholdCondition(523, public static final ThresholdCondition NETHER_SURFACE_NOISE_LARGE = new ThresholdCondition(
523,
0, 0,
UniformFloat.of(-0.4f, -0.3f), UniformFloat.of(-0.4f, -0.3f),
0.5, 0.5,
0.5); 0.5
);
public static final VolumeThresholdCondition NETHER_VOLUME_NOISE = new VolumeThresholdCondition(245, public static final VolumeThresholdCondition NETHER_VOLUME_NOISE = new VolumeThresholdCondition(
245,
0, 0,
UniformFloat.of(-0.1f, 0.2f), UniformFloat.of(-0.1f, 0.2f),
0.1, 0.1,
0.2, 0.2,
0.1); 0.1
);
public static final VolumeThresholdCondition NETHER_VOLUME_NOISE_LARGE = new VolumeThresholdCondition(523, public static final VolumeThresholdCondition NETHER_VOLUME_NOISE_LARGE = new VolumeThresholdCondition(
523,
0, 0,
UniformFloat.of(-0.1f, 0.4f), UniformFloat.of(-0.1f, 0.4f),
0.2, 0.2,
0.2, 0.2,
0.2); 0.2
);
public static final NumericProvider NETHER_NOISE = new NetherNoiseCondition(); public static final NumericProvider NETHER_NOISE = new NetherNoiseCondition();

View file

@ -1,14 +1,17 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import com.mojang.serialization.Codec;
import org.betterx.bclib.interfaces.NumericProvider; import org.betterx.bclib.interfaces.NumericProvider;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import org.betterx.bclib.util.MHelper; import org.betterx.bclib.util.MHelper;
import com.mojang.serialization.Codec;
public class NetherNoiseCondition implements NumericProvider { public class NetherNoiseCondition implements NumericProvider {
public static final Codec<NetherNoiseCondition> CODEC = Codec.BYTE.fieldOf("nether_noise") public static final Codec<NetherNoiseCondition> CODEC = Codec.BYTE.fieldOf("nether_noise")
.xmap((obj) -> (NetherNoiseCondition) Conditions.NETHER_NOISE, .xmap(
obj -> (byte) 0) (obj) -> (NetherNoiseCondition) Conditions.NETHER_NOISE,
obj -> (byte) 0
)
.codec(); .codec();
@ -26,9 +29,11 @@ public class NetherNoiseCondition implements NumericProvider {
final int x = context.getBlockX(); final int x = context.getBlockX();
final int y = context.getBlockY(); final int y = context.getBlockY();
final int z = context.getBlockZ(); final int z = context.getBlockZ();
double value = Conditions.NETHER_VOLUME_NOISE.noiseContext.noise.eval(x * Conditions.NETHER_VOLUME_NOISE.scaleX, double value = Conditions.NETHER_VOLUME_NOISE.noiseContext.noise.eval(
x * Conditions.NETHER_VOLUME_NOISE.scaleX,
y * Conditions.NETHER_VOLUME_NOISE.scaleY, y * Conditions.NETHER_VOLUME_NOISE.scaleY,
z * Conditions.NETHER_VOLUME_NOISE.scaleZ); z * Conditions.NETHER_VOLUME_NOISE.scaleZ
);
int offset = Conditions.NETHER_VOLUME_NOISE.noiseContext.random.nextInt(20) == 0 ? 3 : 0; int offset = Conditions.NETHER_VOLUME_NOISE.noiseContext.random.nextInt(20) == 0 ? 3 : 0;

View file

@ -1,9 +1,9 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import net.minecraft.world.level.levelgen.SurfaceRules;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import net.minecraft.world.level.levelgen.SurfaceRules;
public interface NoiseCondition extends SurfaceRules.ConditionSource { public interface NoiseCondition extends SurfaceRules.ConditionSource {
boolean test(SurfaceRulesContextAccessor context); boolean test(SurfaceRulesContextAccessor context);
} }

View file

@ -1,10 +1,11 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import com.mojang.serialization.Codec;
import org.betterx.bclib.interfaces.NumericProvider; import org.betterx.bclib.interfaces.NumericProvider;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import org.betterx.bclib.util.MHelper; import org.betterx.bclib.util.MHelper;
import com.mojang.serialization.Codec;
public record RandomIntProvider(int range) implements NumericProvider { public record RandomIntProvider(int range) implements NumericProvider {
public static final Codec<RandomIntProvider> CODEC = Codec.INT.fieldOf("range") public static final Codec<RandomIntProvider> CODEC = Codec.INT.fieldOf("range")
.xmap(RandomIntProvider::new, obj -> obj.range) .xmap(RandomIntProvider::new, obj -> obj.range)

View file

@ -1,11 +1,11 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import net.minecraft.world.level.levelgen.SurfaceRules.Condition; import net.minecraft.world.level.levelgen.SurfaceRules.Condition;
import net.minecraft.world.level.levelgen.SurfaceRules.Context; import net.minecraft.world.level.levelgen.SurfaceRules.Context;
import net.minecraft.world.level.levelgen.SurfaceRules.LazyXZCondition; import net.minecraft.world.level.levelgen.SurfaceRules.LazyXZCondition;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
public abstract class SurfaceNoiseCondition implements NoiseCondition { public abstract class SurfaceNoiseCondition implements NoiseCondition {
@Override @Override
public final Condition apply(Context context2) { public final Condition apply(Context context2) {

View file

@ -1,5 +1,10 @@
package org.betterx.bclib.api.v2.levelgen.surface.rules; package org.betterx.bclib.api.v2.levelgen.surface.rules;
import org.betterx.bclib.interfaces.NumericProvider;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.util.KeyDispatchDataCodec; import net.minecraft.util.KeyDispatchDataCodec;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -7,11 +12,6 @@ import net.minecraft.world.level.levelgen.SurfaceRules.Context;
import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource; import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource;
import net.minecraft.world.level.levelgen.SurfaceRules.SurfaceRule; import net.minecraft.world.level.levelgen.SurfaceRules.SurfaceRule;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.betterx.bclib.interfaces.NumericProvider;
import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor;
import java.util.List; import java.util.List;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@ -20,9 +20,11 @@ public record SwitchRuleSource(NumericProvider selector, List<RuleSource> collec
public static final Codec<SwitchRuleSource> CODEC = RecordCodecBuilder.create(instance -> instance.group( public static final Codec<SwitchRuleSource> CODEC = RecordCodecBuilder.create(instance -> instance.group(
NumericProvider.CODEC.fieldOf("selector").forGetter(SwitchRuleSource::selector), NumericProvider.CODEC.fieldOf("selector").forGetter(SwitchRuleSource::selector),
RuleSource.CODEC.listOf().fieldOf("collection").forGetter(SwitchRuleSource::collection) RuleSource.CODEC.listOf().fieldOf("collection").forGetter(SwitchRuleSource::collection)
) )
.apply(instance, .apply(
SwitchRuleSource::new)); instance,
SwitchRuleSource::new
));
private static final KeyDispatchDataCodec<? extends RuleSource> KEY_CODEC = KeyDispatchDataCodec.of(SwitchRuleSource.CODEC); private static final KeyDispatchDataCodec<? extends RuleSource> KEY_CODEC = KeyDispatchDataCodec.of(SwitchRuleSource.CODEC);

Some files were not shown because too many files have changed in this diff Show more