diff --git a/gradle.properties b/gradle.properties index 9f36e135..8b1454fd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,15 +6,15 @@ loom_version=0.10-SNAPSHOT # Fabric Properties # check these on https://fabricmc.net/versions.html -minecraft_version= 1.18.1 -loader_version= 0.12.12 -fabric_version = 0.46.2+1.18 +minecraft_version= 1.18.2 +loader_version= 0.13.3 +fabric_version = 0.48.0+1.18.2 # Mod Properties -mod_version = 1.3.5 +mod_version = 1.4.2 maven_group = ru.bclib archives_base_name = bclib # Dependencies patchouli_version = 50-FABRIC -modmenu_version=3.0.1 \ No newline at end of file +modmenu_version=3.1.0 \ No newline at end of file diff --git a/src/main/java/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index f80d8a0d..afc2ace1 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -13,6 +13,7 @@ import ru.bclib.api.dataexchange.handler.autosync.SendFiles; import ru.bclib.api.tag.TagAPI; import ru.bclib.config.Configs; +import ru.bclib.recipes.AnvilRecipe; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; import ru.bclib.registry.BaseRegistry; @@ -38,6 +39,7 @@ public void onInitialize() { CraftingRecipes.init(); WorldDataAPI.registerModCache(MOD_ID); DataExchangeAPI.registerMod(MOD_ID); + AnvilRecipe.register(); DataExchangeAPI.registerDescriptors(List.of( HelloClient.DESCRIPTOR, diff --git a/src/main/java/ru/bclib/api/LifeCycleAPI.java b/src/main/java/ru/bclib/api/LifeCycleAPI.java index c6afcb20..cf403cd0 100644 --- a/src/main/java/ru/bclib/api/LifeCycleAPI.java +++ b/src/main/java/ru/bclib/api/LifeCycleAPI.java @@ -1,5 +1,6 @@ package ru.bclib.api; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; @@ -49,7 +50,7 @@ void onLoad( LevelStorageSource.LevelStorageAccess levelStorageAccess, ServerLevelData serverLevelData, ResourceKey resourceKey, - DimensionType dimensionType, + Holder dimensionType, ChunkProgressListener chunkProgressListener, ChunkGenerator chunkGenerator, boolean bl, @@ -114,7 +115,7 @@ public static void _runLevelLoad(ServerLevel world, LevelStorageSource.LevelStorageAccess levelStorageAccess, ServerLevelData serverLevelData, ResourceKey resourceKey, - DimensionType dimensionType, + Holder dimensionType, ChunkProgressListener chunkProgressListener, ChunkGenerator chunkGenerator, boolean bl, diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java index c0066245..ea2ceb3b 100644 --- a/src/main/java/ru/bclib/api/PostInitAPI.java +++ b/src/main/java/ru/bclib/api/PostInitAPI.java @@ -10,6 +10,7 @@ import net.minecraft.world.level.block.Block; import ru.bclib.BCLib; import ru.bclib.api.biomes.BiomeAPI; +import ru.bclib.api.tag.NamedMineableTags; import ru.bclib.api.tag.TagAPI; import ru.bclib.api.tag.TagAPI.TagLocation; import ru.bclib.blocks.BaseBarrelBlock; @@ -23,6 +24,7 @@ import ru.bclib.interfaces.PostInitable; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.*; import ru.bclib.registry.BaseBlockEntities; import java.util.List; @@ -111,6 +113,29 @@ else if (block instanceof BaseBarrelBlock) { else if (block instanceof BaseFurnaceBlock) { BaseBlockEntities.FURNACE.registerBlock(block); } + if (!(block instanceof PreventMineableAdd)) { + if (block instanceof AddMineableShears) { + TagAPI.addBlockTags(block, NamedMineableTags.SHEARS); + } + if (block instanceof AddMineableAxe) { + TagAPI.addBlockTags(block, NamedMineableTags.AXE); + } + if (block instanceof AddMineablePickaxe) { + TagAPI.addBlockTags(block, NamedMineableTags.PICKAXE); + } + if (block instanceof AddMineableShovel) { + TagAPI.addBlockTags(block, NamedMineableTags.SHOVEL); + } + if (block instanceof AddMineableHoe) { + TagAPI.addBlockTags(block, NamedMineableTags.HOE); + } + if (block instanceof AddMineableSword) { + TagAPI.addBlockTags(block, NamedMineableTags.SWORD); + } + if (block instanceof AddMineableHammer) { + TagAPI.addBlockTags(block, NamedMineableTags.HAMMER); + } + } if (block instanceof TagProvider) { TagProvider.class.cast(block).addTags(blockTags, itemTags); blockTags.forEach(tag -> TagAPI.addBlockTag(tag, block)); diff --git a/src/main/java/ru/bclib/api/biomes/BCLBiomeBuilder.java b/src/main/java/ru/bclib/api/biomes/BCLBiomeBuilder.java index a2ac6d70..87b18ddc 100644 --- a/src/main/java/ru/bclib/api/biomes/BCLBiomeBuilder.java +++ b/src/main/java/ru/bclib/api/biomes/BCLBiomeBuilder.java @@ -1,25 +1,24 @@ package ru.bclib.api.biomes; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import net.fabricmc.fabric.api.biome.v1.BiomeModifications; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.data.BuiltinRegistries; import net.minecraft.data.worldgen.BiomeDefaultFeatures; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.Music; import net.minecraft.sounds.SoundEvent; +import net.minecraft.tags.TagKey; import net.minecraft.util.Mth; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; -import net.minecraft.world.level.biome.AmbientAdditionsSettings; -import net.minecraft.world.level.biome.AmbientMoodSettings; -import net.minecraft.world.level.biome.AmbientParticleSettings; -import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.*; import net.minecraft.world.level.biome.Biome.BiomeBuilder; import net.minecraft.world.level.biome.Biome.BiomeCategory; import net.minecraft.world.level.biome.Biome.Precipitation; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSpecialEffects; -import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; @@ -28,12 +27,13 @@ import net.minecraft.world.level.levelgen.Noises; import net.minecraft.world.level.levelgen.SurfaceRules; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; -import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import ru.bclib.api.surface.SurfaceRuleBuilder; import ru.bclib.entity.BCLEntityWrapper; import ru.bclib.mixin.common.BiomeGenerationSettingsAccessor; +import ru.bclib.util.CollectionsUtil; import ru.bclib.util.ColorUtil; +import ru.bclib.util.Pair; import ru.bclib.util.TriFunction; import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.biomes.BCLBiomeSettings; @@ -41,12 +41,10 @@ import ru.bclib.world.structures.BCLStructureFeature; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Consumer; -import java.util.function.Supplier; import java.util.stream.Collectors; public class BCLBiomeBuilder { @@ -57,7 +55,8 @@ public interface BiomeSupplier extends TriFunction structures = new ArrayList<>(16); + private List> structureTags = new ArrayList<>(8); + private List>>> carvers = new ArrayList<>(1); private BiomeGenerationSettings.Builder generationSettings; private BiomeSpecialEffects.Builder effectsBuilder; private MobSpawnSettings.Builder spawnSettings; @@ -87,7 +86,7 @@ public static BCLBiomeBuilder start(ResourceLocation biomeID) { INSTANCE.generationSettings = null; INSTANCE.effectsBuilder = null; INSTANCE.spawnSettings = null; - INSTANCE.structures.clear(); + INSTANCE.structureTags.clear(); INSTANCE.temperature = 1.0F; INSTANCE.fogDensity = 1.0F; INSTANCE.edgeSize = 0; @@ -96,6 +95,7 @@ public static BCLBiomeBuilder start(ResourceLocation biomeID) { INSTANCE.height = 0.1F; INSTANCE.vertical = false; INSTANCE.edge = null; + INSTANCE.carvers.clear(); return INSTANCE; } @@ -500,7 +500,7 @@ public BCLBiomeBuilder additions(SoundEvent additions) { * @param feature {@link PlacedFeature}. * @return same {@link BCLBiomeBuilder} instance. */ - public BCLBiomeBuilder feature(Decoration decoration, PlacedFeature feature) { + public BCLBiomeBuilder feature(Decoration decoration, Holder feature) { getGeneration().addFeature(decoration, feature); return this; } @@ -542,11 +542,11 @@ public BCLBiomeBuilder feature(BCLFeature feature) { /** * Adds new structure feature into the biome. - * @param structure {@link ConfiguredStructureFeature} to add. + * @param structureTag {@link TagKey} to add. * @return same {@link BCLBiomeBuilder} instance. */ - public BCLBiomeBuilder structure(ConfiguredStructureFeature structure) { - structures.add(structure); + public BCLBiomeBuilder structure(TagKey structureTag) { + structureTags.add(structureTag); return this; } @@ -557,7 +557,7 @@ public BCLBiomeBuilder structure(ConfiguredStructureFeature structure) { */ public BCLBiomeBuilder structure(BCLStructureFeature structure) { structure.addInternalBiome(biomeID); - return structure(structure.getFeatureConfigured()); + return structure(structure.biomeTag); } /** @@ -565,11 +565,13 @@ public BCLBiomeBuilder structure(BCLStructureFeature structure) { * @param carver {@link ConfiguredWorldCarver} to add. * @return same {@link BCLBiomeBuilder} instance. */ - public BCLBiomeBuilder carver(GenerationStep.Carving step, ConfiguredWorldCarver carver) { + public BCLBiomeBuilder carver(GenerationStep.Carving step, Holder> carver) { final ResourceLocation immutableID = biomeID; - BuiltinRegistries.CONFIGURED_CARVER - .getResourceKey(carver) - .ifPresent(key -> BiomeModifications.addCarver(ctx -> ctx.getBiomeKey().location().equals(immutableID), step, key)); + var oKey = carver.unwrapKey(); + if (oKey.isPresent()) { + BiomeModifications.addCarver(ctx -> ctx.getBiomeKey().location().equals(immutableID), step, (ResourceKey>) oKey.get()); + } + //carvers.add(new Pair<>(step, carver)); return this; } @@ -625,8 +627,8 @@ public BCLBiomeBuilder terrainHeight(float height) { this.height = height; return this; } - - + + /** * Make this a vertical Biome @@ -645,7 +647,7 @@ public BCLBiomeBuilder vertical() { public BCLBiome build() { return build((BiomeSupplier)BCLBiome::new); } - + /** * Finalize biome creation. * @param biomeConstructor {@link BiFunction} biome constructor. @@ -655,7 +657,22 @@ public BCLBiome build() { public T build(BiFunction biomeConstructor) { return build((id, biome, settings)->biomeConstructor.apply(id, biome)); } - + + private static BiomeGenerationSettings fixGenerationSettings(BiomeGenerationSettings settings){ + //Fabric Biome Modification API can not handle an empty carver map, thus we will create one with + //an empty HolderSet for every possible step: + //https://github.com/FabricMC/fabric/issues/2079 + //TODO: Remove, once fabric gets fixed + if (settings instanceof BiomeGenerationSettingsAccessor acc){ + Map>> carvers = CollectionsUtil.getMutable(acc.bclib_getCarvers()); + for (GenerationStep.Carving step : GenerationStep.Carving.values()){ + carvers.computeIfAbsent(step, __->HolderSet.direct(Lists.newArrayList())); + } + acc.bclib_setCarvers(carvers); + } + return settings; + } + /** * Finalize biome creation. * @param biomeConstructor {@link BiomeSupplier} biome constructor. @@ -670,26 +687,8 @@ public T build(BiomeSupplier biomeConstructor) { builder.mobSpawnSettings(getSpawns().build()); builder.specialEffects(getEffects().build()); - - Map>> defferedFeatures = new HashMap<>(); - BiomeGenerationSettingsAccessor acc = BiomeGenerationSettingsAccessor.class.cast(getGeneration().build()); - if (acc != null) { - builder.generationSettings(new BiomeGenerationSettings.Builder().build()); - var decorations = acc.bclib_getFeatures(); - for (Decoration d : Decoration.values()) { - int i = d.ordinal(); - if (i >= 0 && i < decorations.size()) { - var features = decorations.get(i); - defferedFeatures.put(d, features.stream().collect(Collectors.toList())); - } - else { - defferedFeatures.put(d, new ArrayList<>(0)); - } - } - } - else { - builder.generationSettings(getGeneration().build()); - } + + builder.generationSettings(fixGenerationSettings(getGeneration().build())); BCLBiomeSettings settings = BCLBiomeSettings.createBCL() .setTerrainHeight(height) @@ -699,11 +698,13 @@ public T build(BiomeSupplier biomeConstructor) { .setEdge(edge) .setVertical(vertical) .build(); - - final T res = biomeConstructor.apply(biomeID, builder.build(), settings); - res.attachStructures(structures); + + final Biome biome = builder.build(); + final T res = biomeConstructor.apply(biomeID, biome, settings); + res.attachStructures(structureTags); res.setSurface(surfaceRule); - res.setFeatures(defferedFeatures); + + //carvers.forEach(cfg -> BiomeAPI.addBiomeCarver(biome, cfg.second, cfg.first)); return res; } diff --git a/src/main/java/ru/bclib/api/biomes/BiomeAPI.java b/src/main/java/ru/bclib/api/biomes/BiomeAPI.java index 686cf96c..24787fde 100644 --- a/src/main/java/ru/bclib/api/biomes/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/biomes/BiomeAPI.java @@ -1,19 +1,18 @@ package ru.bclib.api.biomes; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.biome.NetherBiomeData; import net.fabricmc.fabric.impl.biome.TheEndBiomeData; -import net.fabricmc.fabric.impl.structure.FabricStructureImpl; import net.minecraft.client.Minecraft; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; +import net.minecraft.core.HolderSet; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceKey; @@ -26,11 +25,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.Biomes; -import net.minecraft.world.level.biome.Climate; +import net.minecraft.world.level.biome.*; import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; @@ -41,27 +36,21 @@ import net.minecraft.world.level.levelgen.GenerationStep.Decoration; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.StructureSettings; import net.minecraft.world.level.levelgen.SurfaceRules; import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; -import net.minecraft.world.level.levelgen.feature.StructureFeature; -import net.minecraft.world.level.levelgen.feature.configurations.StructureFeatureConfiguration; +import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; +import net.minecraft.world.level.levelgen.structure.StructureSet; import org.apache.commons.lang3.mutable.MutableInt; import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; import ru.bclib.entity.BCLEntityWrapper; -import ru.bclib.interfaces.BiomeSourceAccessor; -import ru.bclib.interfaces.NoiseGeneratorSettingsProvider; -import ru.bclib.interfaces.SurfaceMaterialProvider; -import ru.bclib.interfaces.SurfaceProvider; -import ru.bclib.interfaces.SurfaceRuleProvider; +import ru.bclib.interfaces.*; import ru.bclib.mixin.common.BiomeGenerationSettingsAccessor; import ru.bclib.mixin.common.MobSpawnSettingsAccessor; -import ru.bclib.mixin.common.StructureSettingsAccessor; import ru.bclib.util.CollectionsUtil; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; @@ -69,18 +58,9 @@ import ru.bclib.world.biomes.VanillaBiomeSettings; import ru.bclib.world.features.BCLFeature; import ru.bclib.world.generator.BiomePicker; -import ru.bclib.world.structures.BCLStructureFeature; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; -import java.util.Random; -import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -100,27 +80,26 @@ public class BiomeAPI { private static final Map CLIENT = Maps.newHashMap(); private static Registry biomeRegistry; - private static final Map FEATURE_ORDER = Maps.newHashMap(); + private static final Map, Integer> FEATURE_ORDER = Maps.newHashMap(); private static final MutableInt FEATURE_ORDER_ID = new MutableInt(0); - - private final static Map, Multimap, ResourceKey>>, Map, StructureFeatureConfiguration>>> STRUCTURE_STARTS = new HashMap<>(); - private static final Map>> MODIFICATIONS = Maps.newHashMap(); + + private static final Map>>> MODIFICATIONS = Maps.newHashMap(); private static final Map SURFACE_RULES = Maps.newHashMap(); private static final Set MODIFIED_SURFACE_PROVIDERS = new HashSet<>(8); - public static final BCLBiome NETHER_WASTES_BIOME = registerNetherBiome(getFromRegistry(Biomes.NETHER_WASTES)); - public static final BCLBiome CRIMSON_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.CRIMSON_FOREST)); - public static final BCLBiome WARPED_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.WARPED_FOREST)); - public static final BCLBiome SOUL_SAND_VALLEY_BIOME = registerNetherBiome(getFromRegistry(Biomes.SOUL_SAND_VALLEY)); - public static final BCLBiome BASALT_DELTAS_BIOME = registerNetherBiome(getFromRegistry(Biomes.BASALT_DELTAS)); + public static final BCLBiome NETHER_WASTES_BIOME = registerNetherBiome(getFromRegistry(Biomes.NETHER_WASTES).value()); + public static final BCLBiome CRIMSON_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.CRIMSON_FOREST).value()); + public static final BCLBiome WARPED_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.WARPED_FOREST).value()); + public static final BCLBiome SOUL_SAND_VALLEY_BIOME = registerNetherBiome(getFromRegistry(Biomes.SOUL_SAND_VALLEY).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 END_MIDLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_MIDLANDS), 0.5F); - public static final BCLBiome END_HIGHLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_HIGHLANDS), 0.5F); + public static final BCLBiome END_MIDLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_MIDLANDS).value(), 0.5F); + public static final BCLBiome END_HIGHLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_HIGHLANDS).value(), 0.5F); public static final BCLBiome END_BARRENS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("end_barrens"))); public static final BCLBiome SMALL_END_ISLANDS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("small_end_islands"))); - + private static void initFeatureOrder() { if (!FEATURE_ORDER.isEmpty()) { return; @@ -137,8 +116,7 @@ private static void initFeatureOrder() { .map(Entry::getValue) .map(biome -> (BiomeGenerationSettingsAccessor) biome.getGenerationSettings()) .map(BiomeGenerationSettingsAccessor::bclib_getFeatures) - .forEach(stepFeatureSuppliers -> stepFeatureSuppliers.forEach(step -> step.forEach(featureSupplier -> { - PlacedFeature feature = featureSupplier.get(); + .forEach(stepFeatureSuppliers -> stepFeatureSuppliers.forEach(step -> step.forEach(feature -> { FEATURE_ORDER.computeIfAbsent(feature, f -> FEATURE_ORDER_ID.getAndIncrement()); }))); } @@ -161,23 +139,23 @@ public static void initRegistry(Registry biomeRegistry) { * called from {@link ru.bclib.mixin.client.MinecraftMixin} */ public static void prepareNewLevel(){ - STRUCTURE_STARTS.clear(); - MODIFIED_SURFACE_PROVIDERS.forEach(p->p.bclib_clearBiomeSources()); MODIFIED_SURFACE_PROVIDERS.clear(); } /** * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * @param biome {@link BCLBiome} + * @param bclbiome {@link BCLBiome} * @return {@link BCLBiome} */ - public static BCLBiome registerBiome(BCLBiome biome) { - if (BuiltinRegistries.BIOME.get(biome.getID()) == null) { - Registry.register(BuiltinRegistries.BIOME, biome.getID(), biome.getBiome()); + public static BCLBiome registerBiome(BCLBiome bclbiome) { + if (BuiltinRegistries.BIOME.get(bclbiome.getID()) == null) { + final Biome biome = bclbiome.getBiome(); + ResourceLocation loc = bclbiome.getID(); + Registry.register(BuiltinRegistries.BIOME, loc, biome); } - ID_MAP.put(biome.getID(), biome); - return biome; + ID_MAP.put(bclbiome.getID(), bclbiome); + return bclbiome; } public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome) { @@ -212,7 +190,7 @@ public static BCLBiome registerNetherBiome(BCLBiome biome) { MHelper.randRange(-1.5F, 1.5F, random), random.nextFloat() ); - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).orElseThrow(); + ResourceKey key = BiomeAPI.getBiomeKeyOrThrow(biome.getBiomeHolder()); NetherBiomeData.addNetherBiome(key, parameters); return biome; } @@ -242,7 +220,7 @@ public static BCLBiome registerEndLandBiome(BCLBiome biome) { END_LAND_BIOME_PICKER.addBiome(biome); float weight = biome.getGenChance(); - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).orElseThrow(); + ResourceKey key = BiomeAPI.getBiomeKey(biome.getBiome()); TheEndBiomeData.addEndBiomeReplacement(Biomes.END_HIGHLANDS, key, weight); TheEndBiomeData.addEndBiomeReplacement(Biomes.END_MIDLANDS, key, weight); return biome; @@ -254,8 +232,8 @@ public static BCLBiome registerEndLandBiome(BCLBiome biome) { * @param biome {@link BCLBiome} * @return {@link BCLBiome} */ - public static BCLBiome registerEndLandBiome(Biome biome) { - BCLBiome bclBiome = new BCLBiome(biome, null); + public static BCLBiome registerEndLandBiome(Holder biome) { + BCLBiome bclBiome = new BCLBiome(biome.value(), null); END_LAND_BIOME_PICKER.addBiome(bclBiome); registerBiome(bclBiome); @@ -269,8 +247,8 @@ public static BCLBiome registerEndLandBiome(Biome biome) { * @param genChance float generation chance. * @return {@link BCLBiome} */ - public static BCLBiome registerEndLandBiome(Biome biome, float genChance) { - BCLBiome bclBiome = new BCLBiome(biome, VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); + public static BCLBiome registerEndLandBiome(Holder biome, float genChance) { + BCLBiome bclBiome = new BCLBiome(biome.value(), VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); END_LAND_BIOME_PICKER.addBiome(bclBiome); registerBiome(bclBiome); @@ -288,7 +266,7 @@ public static BCLBiome registerEndVoidBiome(BCLBiome biome) { END_VOID_BIOME_PICKER.addBiome(biome); float weight = biome.getGenChance(); - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).orElseThrow(); + ResourceKey key = BiomeAPI.getBiomeKeyOrThrow(biome.getBiomeHolder()); TheEndBiomeData.addEndBiomeReplacement(Biomes.SMALL_END_ISLANDS, key, weight); return biome; } @@ -299,8 +277,8 @@ public static BCLBiome registerEndVoidBiome(BCLBiome biome) { * @param biome {@link BCLBiome} * @return {@link BCLBiome} */ - public static BCLBiome registerEndVoidBiome(Biome biome) { - BCLBiome bclBiome = new BCLBiome(biome, null); + public static BCLBiome registerEndVoidBiome(Holder biome) { + BCLBiome bclBiome = new BCLBiome(biome.value(), null); END_VOID_BIOME_PICKER.addBiome(bclBiome); registerBiome(bclBiome); @@ -314,8 +292,8 @@ public static BCLBiome registerEndVoidBiome(Biome biome) { * @param genChance float generation chance. * @return {@link BCLBiome} */ - public static BCLBiome registerEndVoidBiome(Biome biome, float genChance) { - BCLBiome bclBiome = new BCLBiome(biome, VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); + public static BCLBiome registerEndVoidBiome(Holder biome, float genChance) { + BCLBiome bclBiome = new BCLBiome(biome.value(), VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); END_VOID_BIOME_PICKER.addBiome(bclBiome); registerBiome(bclBiome); @@ -324,14 +302,14 @@ public static BCLBiome registerEndVoidBiome(Biome biome, float genChance) { /** * Get {@link BCLBiome} from {@link Biome} instance on server. Used to convert world biomes to BCLBiomes. - * @param biome - {@link Biome} from world. + * @param biome - {@link Holder} from world. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ - public static BCLBiome getFromBiome(Biome biome) { + public static BCLBiome getFromBiome(Holder biome) { if (biomeRegistry == null) { return EMPTY_BIOME; } - return ID_MAP.getOrDefault(biomeRegistry.getKey(biome), EMPTY_BIOME); + return ID_MAP.getOrDefault(biome.unwrapKey().orElseThrow().location(), EMPTY_BIOME); } /** @@ -375,6 +353,27 @@ public static ResourceLocation getBiomeID(Biome biome) { } return id == null ? EMPTY_BIOME.getID() : id; } + + /** + * Get biome {@link ResourceLocation} from given {@link Biome}. + * @param biome - {@link Holder} from server world. + * @return biome {@link ResourceLocation}. + */ + public static ResourceLocation getBiomeID(Holder biome) { + var oKey = biome.unwrapKey(); + if (oKey.isPresent()){ + return oKey.get().location(); + } + return null; + } + + public static ResourceKey getBiomeKey(Holder biome) { + return biome.unwrapKey().orElse(null); + } + + public static ResourceKey getBiomeKeyOrThrow(Holder biome) { + return biome.unwrapKey().orElseThrow(); + } /** * Get {@link BCLBiome} from given {@link ResourceLocation}. @@ -393,6 +392,15 @@ public static BCLBiome getBiome(ResourceLocation biomeID) { public static BCLBiome getBiome(Biome biome) { return getBiome(BiomeAPI.getBiomeID(biome)); } + + /** + * Get {@link BCLBiome} from given {@link Biome}. + * @param biome - biome {@link Biome}. + * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. + */ + public static BCLBiome getBiome(Holder biome) { + return getBiome(BiomeAPI.getBiomeID(biome)); + } /** * Check if biome with {@link ResourceLocation} exists in API registry. @@ -409,31 +417,31 @@ public static boolean hasBiome(ResourceLocation biomeID) { public static void loadFabricAPIBiomes() { FabricBiomesData.NETHER_BIOMES.forEach((key) -> { if (!hasBiome(key.location())) { - registerNetherBiome(BuiltinRegistries.BIOME.get(key.location())); + registerNetherBiome(BuiltinRegistries.BIOME.get(key)); } }); FabricBiomesData.END_LAND_BIOMES.forEach((key, weight) -> { if (!hasBiome(key.location())) { - registerEndLandBiome(BuiltinRegistries.BIOME.get(key.location()), weight); + registerEndLandBiome(BuiltinRegistries.BIOME.getHolder(key).orElseThrow(), weight); } }); FabricBiomesData.END_VOID_BIOMES.forEach((key, weight) -> { if (!hasBiome(key.location())) { - registerEndVoidBiome(BuiltinRegistries.BIOME.get(key.location()), weight); + registerEndVoidBiome(BuiltinRegistries.BIOME.getOrCreateHolder(key), weight); } }); } @Nullable - public static Biome getFromRegistry(ResourceLocation key) { - return BuiltinRegistries.BIOME.get(key); + public static Holder getFromRegistry(ResourceLocation key) { + return BuiltinRegistries.BIOME.getHolder(ResourceKey.create(Registry.BIOME_REGISTRY, key)).orElseThrow(); } @Nullable - public static Biome getFromRegistry(ResourceKey key) { - return BuiltinRegistries.BIOME.get(key); + public static Holder getFromRegistry(ResourceKey key) { + return BuiltinRegistries.BIOME.getOrCreateHolder(key); } public static boolean isDatapackBiome(ResourceLocation biomeID) { @@ -457,8 +465,8 @@ private static boolean pickerHasBiome(BiomePicker picker, ResourceLocation key) * @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. */ - public static void registerBiomeModification(ResourceKey dimensionID, BiConsumer modification) { - List> modifications = MODIFICATIONS.computeIfAbsent(dimensionID, k -> Lists.newArrayList()); + public static void registerBiomeModification(ResourceKey dimensionID, BiConsumer> modification) { + List>> modifications = MODIFICATIONS.computeIfAbsent(dimensionID, k -> Lists.newArrayList()); modifications.add(modification); } @@ -466,7 +474,7 @@ public static void registerBiomeModification(ResourceKey dimensionID, BiConsumer * Registers new biome modification for the Overworld. Will work both for mod and datapack biomes. * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. */ - public static void registerOverworldBiomeModification(BiConsumer modification) { + public static void registerOverworldBiomeModification(BiConsumer> modification) { registerBiomeModification(Level.OVERWORLD, modification); } @@ -474,7 +482,7 @@ public static void registerOverworldBiomeModification(BiConsumer modification) { + public static void registerNetherBiomeModification(BiConsumer> modification) { registerBiomeModification(Level.NETHER, modification); } @@ -482,7 +490,7 @@ public static void registerNetherBiomeModification(BiConsumer modification) { + public static void registerEndBiomeModification(BiConsumer> modification) { registerBiomeModification(Level.END, modification); } @@ -491,40 +499,54 @@ public static void registerEndBiomeModification(BiConsumer biomes = source.possibleBiomes(); + NoiseGeneratorSettings noiseGeneratorSettings = null; + final ChunkGenerator chunkGenerator = level.getChunkSource().getGenerator(); + final BiomeSource source = chunkGenerator.getBiomeSource(); + final Set> biomes = source.possibleBiomes(); - NoiseGeneratorSettings generator = level + if (chunkGenerator instanceof NoiseGeneratorSettingsProvider gen) + noiseGeneratorSettings = gen.bclib_getNoiseGeneratorSettings(); + /*final Registry structureSetRegistry; + if (chunkGenerator instanceof ChunkGeneratorAccessor acc) { + structureSetRegistry = acc.bclib_getStructureSetsRegistry(); + } else { + structureSetRegistry = null; + } + + + noiseGeneratorSettings = level .getServer() .getWorldData() .worldGenSettings() .dimensions() .stream() .map(dim->dim.generator()) - .filter(gen->(gen instanceof NoiseGeneratorSettingsProvider) && gen.getSettings()==settings) + .filter(gen-> structureSetRegistry!=null && (gen instanceof NoiseGeneratorSettingsProvider) && (gen instanceof ChunkGeneratorAccessor) && ((ChunkGeneratorAccessor)gen).bclib_getStructureSetsRegistry()==structureSetRegistry) .map(gen->((NoiseGeneratorSettingsProvider)gen).bclib_getNoiseGeneratorSettings()) .findFirst() - .orElse(null); + .orElse(null);*/ + // Datapacks (like Amplified Nether)will change the GeneratorSettings upon load, so we will // only use the default Setting for Nether/End if we were unable to find a settings object - if (generator==null){ + if (noiseGeneratorSettings==null){ if (level.dimension() == Level.NETHER) { - generator = BuiltinRegistries.NOISE_GENERATOR_SETTINGS.get(NoiseGeneratorSettings.NETHER); + noiseGeneratorSettings = BuiltinRegistries.NOISE_GENERATOR_SETTINGS.get(NoiseGeneratorSettings.NETHER); } else if (level.dimension() == Level.END) { - generator = BuiltinRegistries.NOISE_GENERATOR_SETTINGS.get(NoiseGeneratorSettings.END); + noiseGeneratorSettings = BuiltinRegistries.NOISE_GENERATOR_SETTINGS.get(NoiseGeneratorSettings.END); } } - List> modifications = MODIFICATIONS.get(level.dimension()); - for (Biome biome : biomes) { - applyModificationsAndUpdateFeatures(modifications, biome); + List>> modifications = MODIFICATIONS.get(level.dimension()); + for (Holder biomeHolder : biomes) { + if (biomeHolder.isBound()) { + applyModificationsAndUpdateFeatures(modifications, biomeHolder); + } } - if (generator != null) { - final SurfaceRuleProvider provider = SurfaceRuleProvider.class.cast(generator); + if (noiseGeneratorSettings != null) { + final SurfaceRuleProvider provider = SurfaceRuleProvider.class.cast(noiseGeneratorSettings); // Multiple Biomes can use the same generator. So we need to keep track of all Biomes that are // Provided by all the BiomeSources that use the same generator. // This happens for example when using the MiningDimensions, which reuses the generator for the @@ -535,20 +557,10 @@ public static void applyModifications(ServerLevel level) { BCLib.LOGGER.warning("No generator for " + source); } - if (settings!=null){ - final StructureSettingsAccessor settingsAccessor = (StructureSettingsAccessor)settings; - final Set biomeIDs = biomes.stream().map(BiomeAPI::getBiomeID).collect(Collectors.toSet()); - for (Entry, Multimap, ResourceKey>>, Map, StructureFeatureConfiguration>>> e : STRUCTURE_STARTS.entrySet()) { - if (biomeIDs.contains(e.getKey().biomeID)) { - applyStructureStarts(settingsAccessor, e.getValue()); - } - } - } - ((BiomeSourceAccessor) source).bclRebuildFeatures(); } - private static void applyModificationsAndUpdateFeatures(List> modifications, Biome biome) { + private static void applyModificationsAndUpdateFeatures(List>> modifications, Holder biome) { ResourceLocation biomeID = getBiomeID(biome); if (modifications!=null) { modifications.forEach(consumer -> { @@ -556,11 +568,6 @@ private static void applyModificationsAndUpdateFeatures(List biome) { + BiomeGenerationSettings settings = biome.value().getGenerationSettings(); BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) settings; - List>> featureList = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); + List> featureList = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); final int size = featureList.size(); for (int i = 0; i < size; i++) { - List> features = CollectionsUtil.getMutable(featureList.get(i)); + List> features = getFeaturesListCopy(featureList, i); sortFeatures(features); - featureList.set(i, features); + featureList.set(i, HolderSet.direct(features)); } accessor.bclib_setFeatures(featureList); } - private static List getRuleSourcesForBiomes(Set biomes) { + private static List getRuleSourcesForBiomes(Set> biomes) { Set biomeIDs = biomes .stream() .map(biome -> getBiomeID(biome)) @@ -600,7 +607,7 @@ private static List getRuleSourcesForBiomes(Set * @return A list of {@link RuleSource}-Objects that are needed to create those Biomes */ public static List getRuleSources(Set sources) { - final Set biomes = new HashSet<>(); + final Set> biomes = new HashSet<>(); for (BiomeSource s : sources) { biomes.addAll(s.possibleBiomes()); } @@ -624,7 +631,7 @@ private static List getRuleSourcesFromIDs(Set biome, BCLFeature feature) { addBiomeFeature(biome, feature.getDecoration(), feature.getPlacedFeature()); } @@ -634,7 +641,7 @@ public static void addBiomeFeature(Biome biome, BCLFeature feature) { * @param step a {@link Decoration} step for the feature. * @param featureList {@link ConfiguredFeature} to add. */ - public static void addBiomeFeature(Biome biome, Decoration step, PlacedFeature... featureList) { + public static void addBiomeFeature(Holder biome, Decoration step, Holder... featureList) { addBiomeFeature(biome, step, List.of(featureList)); } @@ -642,107 +649,25 @@ public static void addBiomeFeature(Biome biome, Decoration step, PlacedFeature.. * Adds new features to existing biome. * @param biome {@link Biome} to add features in. * @param step a {@link Decoration} step for the feature. - * @param featureList List of {@link ConfiguredFeature} to add. + * @param additionalFeatures List of {@link ConfiguredFeature} to add. */ - private static void addBiomeFeature(Biome biome, Decoration step, List featureList) { - BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.getGenerationSettings(); - List>> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); - Set set = CollectionsUtil.getMutable(accessor.bclib_getFeatureSet()); - List> features = getFeaturesList(allFeatures, step); - for (var feature : featureList) { - features.add(() -> feature); - set.add(feature); - } - accessor.bclib_setFeatures(allFeatures); - accessor.bclib_setFeatureSet(set); - } - - /** - * For internal use only! - * - * Adds new features to existing biome. Called from {@link #applyModificationsAndUpdateFeatures(List, Biome)} when the Biome is - * present in any {@link BiomeSource} - * @param biome {@link Biome} to add features in. - * @param featureMap Map of {@link ConfiguredFeature} to add. - */ - private static void addStepFeaturesToBiome(Biome biome, Map>> featureMap) { - BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.getGenerationSettings(); - List>> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); - Set set = CollectionsUtil.getMutable(accessor.bclib_getFeatureSet()); - - for (Decoration step: featureMap.keySet()) { - List> features = getFeaturesList(allFeatures, step); - List> featureList = featureMap.get(step); - - for (Supplier feature : featureList) { + private static void addBiomeFeature(Holder biome, Decoration step, List> additionalFeatures) { + BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.value().getGenerationSettings(); + List> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); + List> features = getFeaturesListCopy(allFeatures, step); + + for (var feature : additionalFeatures) { + if (!features.contains(feature)) features.add(feature); - set.add(feature.get()); - } } - accessor.bclib_setFeatures(allFeatures); - accessor.bclib_setFeatureSet(set); - } - - /** - * Adds new structure feature to existing biome. - * @param biomeKey {@link ResourceKey} for the {@link Biome} to add structure feature in. - * @param structure {@link ConfiguredStructureFeature} to add. - */ - public static void addBiomeStructure(ResourceKey biomeKey, ConfiguredStructureFeature structure) { - if (biomeKey == null){ - BCLib.LOGGER.error("null is not a valid biomeKey for " + structure); - return; - } - changeStructureStarts(biomeKey.location(), structure, (structureMap, configMap) -> { - Multimap, ResourceKey> configuredMap = structureMap.computeIfAbsent(structure.feature, k -> HashMultimap.create()); - configuredMap.put(structure, biomeKey); - - StructureFeatureConfiguration config = FabricStructureImpl.STRUCTURE_TO_CONFIG_MAP.get(structure.feature); - if (config != null){ - configMap.put(structure.feature, config); - } - }); - } - /** - * Add an existing StructureFeature to a Biome - * @param biome The {@link Biome} you want to add teh feature to - * @param structure The {@link ConfiguredStructureFeature} to add - */ - public static void addBiomeStructure(Biome biome, ConfiguredStructureFeature structure) { - changeStructureStarts(BiomeAPI.getBiomeID(biome), structure, (structureMap, configMap) -> { - Multimap, ResourceKey> configuredMap = structureMap.computeIfAbsent(structure.feature, k -> HashMultimap.create()); - var key = getBiomeKey(biome); - if (key != null) { - StructureFeatureConfiguration config = FabricStructureImpl.STRUCTURE_TO_CONFIG_MAP.get(structure.feature); - if (config != null) { - configMap.put(structure.feature, config); - } - configuredMap.put(structure, key); - } else { - BCLib.LOGGER.warning("Unable to find Biome " + getBiomeID(biome)); - } - }); - } - - /** - * Adds new structure feature to existing biome. - * @param biomeKey {@link ResourceKey} for the {@link Biome} to add structure feature in. - * @param structure {@link BCLStructureFeature} to add. - */ - public static void addBiomeStructure(ResourceKey biomeKey, BCLStructureFeature structure) { - addBiomeStructure(biomeKey, structure.getFeatureConfigured()); - } + allFeatures.set(step.ordinal(), HolderSet.direct(features)); + final Supplier>> flowerFeatures = Suppliers.memoize(() -> allFeatures.stream().flatMap(HolderSet::stream).map(Holder::value).flatMap(PlacedFeature::getFeatures).filter(configuredFeature -> configuredFeature.feature() == Feature.FLOWER).collect(ImmutableList.toImmutableList())); + final Supplier> featureSet = Suppliers.memoize(() -> allFeatures.stream().flatMap(HolderSet::stream).map(Holder::value).collect(Collectors.toSet())); - /** - * Adds new structure features to existing biome. - * @param biomeKey {@link ResourceKey} for the {@link Biome} to add structure features in. - * @param structures array of {@link BCLStructureFeature} to add. - */ - public static void addBiomeStructures(ResourceKey biomeKey, BCLStructureFeature... structures) { - for (BCLStructureFeature structure: structures) { - addBiomeStructure(biomeKey, structure.getFeatureConfigured()); - } + accessor.bclib_setFeatures(allFeatures); + accessor.bclib_setFeatureSet(featureSet); + accessor.bclib_setFlowerFeatures(flowerFeatures); } /** @@ -751,13 +676,20 @@ public static void addBiomeStructures(ResourceKey biomeKey, BCLStructureFeature. * @param carver {@link ConfiguredWorldCarver} to add. * @param stage {@link Carving} stage. */ - public static void addBiomeCarver(Biome biome, ConfiguredWorldCarver carver, Carving stage) { + public static void addBiomeCarver(Biome biome, Holder> carver, Carving stage) { BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.getGenerationSettings(); - Map>>> carvers = CollectionsUtil.getMutable(accessor.bclib_getCarvers()); - List>> carverList = CollectionsUtil.getMutable(carvers.getOrDefault(stage, new ArrayList<>())); - carvers.put(stage, carverList); - carverList.add(() -> carver); - accessor.bclib_setCarvers(carvers); + Map>> carverMap = CollectionsUtil.getMutable(accessor.bclib_getCarvers()); + HolderSet> carvers = carverMap.get(stage); + + List>> carverList; + if (carvers==null) { + carverList = Lists.newArrayList(); + } else { + carverList = carvers.stream().toList(); + } + carverList.add((Holder>)carver); + carverMap.put(stage, HolderSet.direct(carverList)); + accessor.bclib_setCarvers(carverMap); } /** @@ -788,7 +720,7 @@ public static SurfaceRules.RuleSource getSurfaceRule(ResourceLocation biomeID) { * @param minGroupCount minimum mobs in group. * @param maxGroupCount maximum mobs in group. */ - public static void addBiomeMobSpawn(Biome biome, BCLEntityWrapper entityType, int weight, int minGroupCount, int maxGroupCount) { + public static void addBiomeMobSpawn(Holder biome, BCLEntityWrapper entityType, int weight, int minGroupCount, int maxGroupCount) { if (entityType.canSpawn()){ addBiomeMobSpawn(biome, entityType.type(), weight, minGroupCount, maxGroupCount); } @@ -802,9 +734,9 @@ public static void addBiomeMobSpawn(Biome biome, BCLEntityWrappe * @param minGroupCount minimum mobs in group. * @param maxGroupCount maximum mobs in group. */ - public static void addBiomeMobSpawn(Biome biome, EntityType entityType, int weight, int minGroupCount, int maxGroupCount) { + public static void addBiomeMobSpawn(Holder biome, EntityType entityType, int weight, int minGroupCount, int maxGroupCount) { final MobCategory category = entityType.getCategory(); - MobSpawnSettingsAccessor accessor = (MobSpawnSettingsAccessor) biome.getMobSettings(); + MobSpawnSettingsAccessor accessor = (MobSpawnSettingsAccessor) biome.value().getMobSettings(); Map> spawners = CollectionsUtil.getMutable(accessor.bcl_getSpawners()); List mobs = spawners.containsKey(category) ? CollectionsUtil.getMutable(spawners.get(category).unwrap()) : Lists.newArrayList(); mobs.add(new SpawnerData(entityType, weight, minGroupCount, maxGroupCount)); @@ -815,11 +747,11 @@ public static void addBiomeMobSpawn(Biome biome, EntityType e /** * Get biome surface block. Can be used to get terrain material for features or other things. * @param pos {@link BlockPos} position to get block. - * @param biome {@link Biome} to get block from. + * @param biome {@link Holder} to get block from. * @param level {@link ServerLevel} current server level. * @return {@link BlockState} with the biome surface or AIR if it fails. */ - public static BlockState getBiomeSurfaceBlock(BlockPos pos, Biome biome, ServerLevel level) { + public static BlockState getBiomeSurfaceBlock(BlockPos pos, Holder biome, ServerLevel level) { ChunkGenerator generator = level.getChunkSource().getGenerator(); if (generator instanceof NoiseBasedChunkGenerator) { SurfaceProvider provider = SurfaceProvider.class.cast(generator); @@ -832,6 +764,10 @@ public static Optional findTopMaterial(WorldGenLevel world, BlockPos return findTopMaterial(getBiome(world.getBiome(pos))); } + public static Optional findTopMaterial(Holder biome){ + return findTopMaterial(getBiome(biome.value())); + } + public static Optional findTopMaterial(Biome biome){ return findTopMaterial(getBiome(biome)); } @@ -847,6 +783,10 @@ public static Optional findUnderMaterial(WorldGenLevel world, BlockP return findUnderMaterial(getBiome(world.getBiome(pos))); } + public static Optional findUnderMaterial(Holder biome){ + return findUnderMaterial(getBiome(biome.value())); + } + public static Optional findUnderMaterial(Biome biome){ return findUnderMaterial(getBiome(biome)); } @@ -862,11 +802,11 @@ public static Optional findUnderMaterial(BCLBiome biome){ * Set biome in chunk at specified position. * @param chunk {@link ChunkAccess} chunk to set biome in. * @param pos {@link BlockPos} biome position. - * @param biome {@link Biome} instance. Should be biome from world. + * @param biome {@link Holder} instance. Should be biome from world. */ - public static void setBiome(ChunkAccess chunk, BlockPos pos, Biome biome) { + public static void setBiome(ChunkAccess chunk, BlockPos pos, Holder biome) { int sectionY = (pos.getY() - chunk.getMinBuildHeight()) >> 4; - PalettedContainer biomes = chunk.getSection(sectionY).getBiomes(); + PalettedContainer> biomes = chunk.getSection(sectionY).getBiomes(); biomes.set((pos.getX() & 15) >> 2, (pos.getY() & 15) >> 2, (pos.getZ() & 15) >> 2, biome); } @@ -874,9 +814,9 @@ public static void setBiome(ChunkAccess chunk, BlockPos pos, Biome biome) { * Set biome in world at specified position. * @param level {@link LevelAccessor} world to set biome in. * @param pos {@link BlockPos} biome position. - * @param biome {@link Biome} instance. Should be biome from world. + * @param biome {@link Holder} instance. Should be biome from world. */ - public static void setBiome(LevelAccessor level, BlockPos pos, Biome biome) { + public static void setBiome(LevelAccessor level, BlockPos pos, Holder biome) { ChunkAccess chunk = level.getChunk(pos); setBiome(chunk, pos, biome); } @@ -909,42 +849,24 @@ public int hashCode() { } } - private static void changeStructureStarts(ResourceLocation biomeID, ConfiguredStructureFeature structure, BiConsumer, Multimap, ResourceKey>>, Map, StructureFeatureConfiguration>> modifier) { - STRUCTURE_STARTS.put(new StructureID(biomeID, structure), modifier); - } - - private static void applyStructureStarts(StructureSettingsAccessor access, BiConsumer, Multimap, ResourceKey>>, Map, StructureFeatureConfiguration>> modifier) { - Map, Multimap, ResourceKey>> structureMap; - Map, StructureFeatureConfiguration> configMap; - - structureMap = getMutableConfiguredStructures(access); - configMap = getMutableStructureConfig(access); - - modifier.accept(structureMap, configMap); - - setMutableConfiguredStructures(access, structureMap); - setMutableStructureConfig(access, configMap); - } - - private static void sortFeatures(List> features) { + private static void sortFeatures(List> features) { initFeatureOrder(); - Set featuresWithoutDuplicates = Sets.newHashSet(); - features.forEach(provider -> featuresWithoutDuplicates.add(provider.get())); + Set> featuresWithoutDuplicates = Sets.newHashSet(); + features.forEach(holder -> featuresWithoutDuplicates.add(holder)); if (featuresWithoutDuplicates.size() != features.size()) { features.clear(); - featuresWithoutDuplicates.forEach(feature -> features.add(() -> feature)); + featuresWithoutDuplicates.forEach(feature -> features.add(feature)); } - features.forEach(provider -> { - PlacedFeature feature = provider.get(); + features.forEach(feature -> { FEATURE_ORDER.computeIfAbsent(feature, f -> FEATURE_ORDER_ID.getAndIncrement()); }); features.sort((f1, f2) -> { - int v1 = FEATURE_ORDER.getOrDefault(f1.get(), 70000); - int v2 = FEATURE_ORDER.getOrDefault(f2.get(), 70000); + int v1 = FEATURE_ORDER.getOrDefault(f1, 70000); + int v2 = FEATURE_ORDER.getOrDefault(f2, 70000); return Integer.compare(v1, v2); }); } @@ -966,44 +888,15 @@ private static List> getList(Decoration step, List> getFeaturesList(List>> features, Decoration step) { - int index = step.ordinal(); - while (features.size() <= index) { - features.add(Lists.newArrayList()); - } - List> mutable = CollectionsUtil.getMutable(features.get(index)); - features.set(index, mutable); - return mutable; + + private static List> getFeaturesListCopy(List> features, Decoration step) { + return getFeaturesListCopy(features, step.ordinal()); } - //inspired by net.fabricmc.fabric.impl.biome.modification.BiomeStructureStartsImpl - private static Map, Multimap, ResourceKey>> getMutableConfiguredStructures(StructureSettingsAccessor access) { - ImmutableMap, ImmutableMultimap, ResourceKey>> configuredStructures = access.bcl_getConfiguredStructures(); - Map, Multimap, ResourceKey>> result = new HashMap<>(configuredStructures.size()); - - for (Map.Entry, ImmutableMultimap, ResourceKey>> entry : configuredStructures.entrySet()) { - result.put(entry.getKey(), HashMultimap.create(entry.getValue())); + private static List> getFeaturesListCopy(List> features, int index) { + while (features.size() <= index) { + features.add(HolderSet.direct(Lists.newArrayList())); } - - return result; - } - - //inspired by net.fabricmc.fabric.impl.biome.modification.BiomeStructureStartsImpl - private static void setMutableConfiguredStructures(StructureSettingsAccessor access, Map, Multimap, ResourceKey>> structureStarts) { - access.bcl_setConfiguredStructures( - structureStarts - .entrySet() - .stream() - .collect(ImmutableMap.toImmutableMap(Map.Entry::getKey, e -> ImmutableMultimap.copyOf(e.getValue()))) - ); - } - - private static Map, StructureFeatureConfiguration> getMutableStructureConfig(StructureSettingsAccessor access) { - return CollectionsUtil.getMutable(access.bcl_getStructureConfig()); - } - - private static void setMutableStructureConfig(StructureSettingsAccessor access, Map, StructureFeatureConfiguration> structureConfig) { - access.bcl_setStructureConfig(structureConfig); + return features.get(index).stream().collect(Collectors.toList()); } } diff --git a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java index 9f47278c..30492bed 100644 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java +++ b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java @@ -147,24 +147,8 @@ protected FromClient(ResourceLocation identifier) { @Environment(EnvType.CLIENT) abstract protected void serializeDataOnClient(FriendlyByteBuf buf); - @Deprecated(forRemoval = true) - protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, PacketSender responseSender){ } - - //TODO: should be abstract once deserializeIncomingDataOnServer(FriendlyByteBuf buf, PacketSender responseSender) was removed - - protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, Player player, PacketSender responseSender) { - deserializeIncomingDataOnServer(buf, responseSender); - } - - @Deprecated(forRemoval = true) - protected void runOnServerGameThread(MinecraftServer server){ } - - - //TODO: should be abstract once runOnServerGameThread(MinecraftServer server) was removed - protected void runOnServerGameThread(MinecraftServer server, Player player){ - runOnServerGameThread(server); - } - + protected abstract void deserializeIncomingDataOnServer(FriendlyByteBuf buf, Player player, PacketSender responseSender); + protected abstract void runOnServerGameThread(MinecraftServer server, Player player); @Environment(EnvType.CLIENT) @Override diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java index ef52b214..cd1e21de 100644 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java +++ b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java @@ -127,7 +127,6 @@ protected void runOnClientGameThread(Minecraft client) { if ( Configs.CLIENT_CONFIG.isAcceptingConfigs() || Configs.CLIENT_CONFIG.isAcceptingFiles() || Configs.CLIENT_CONFIG.isAcceptingMods()) { BCLib.LOGGER.info("Writing Files:"); - //TODO: Reject files that were not in the last RequestFiles. for (Pair entry : receivedFiles) { final AutoFileSyncEntry e = entry.first; final byte[] data = entry.second; diff --git a/src/main/java/ru/bclib/api/features/BCLFeatureBuilder.java b/src/main/java/ru/bclib/api/features/BCLFeatureBuilder.java index 3aa49a0d..d0b39889 100644 --- a/src/main/java/ru/bclib/api/features/BCLFeatureBuilder.java +++ b/src/main/java/ru/bclib/api/features/BCLFeatureBuilder.java @@ -4,6 +4,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.level.levelgen.GenerationStep.Decoration; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.placement.BiomeFilter; @@ -18,12 +19,12 @@ import java.util.ArrayList; import java.util.List; -public class BCLFeatureBuilder { +public class BCLFeatureBuilder >{ private static final BCLFeatureBuilder INSTANCE = new BCLFeatureBuilder(); private List modifications = new ArrayList<>(16); private ResourceLocation featureID; private Decoration decoration; - private Feature feature; + private F feature; private BCLFeatureBuilder() {} @@ -60,6 +61,11 @@ public BCLFeatureBuilder modifier(PlacementModifier modifier) { modifications.add(modifier); return this; } + + public BCLFeatureBuilder modifier(List modifiers) { + modifications.addAll(modifiers); + return this; + } /** * Generate feature in certain iterations (per chunk). @@ -134,10 +140,9 @@ public BCLFeatureBuilder heightmap() { * @param configuration any {@link FeatureConfiguration} for provided {@link Feature}. * @return created {@link BCLFeature} instance. */ - public BCLFeature build(FC configuration) { + public BCLFeature build(FC configuration) { PlacementModifier [] modifiers = modifications.toArray(new PlacementModifier [modifications.size()]); - PlacedFeature configured = ((Feature) feature).configured(configuration).placed(modifiers); - return new BCLFeature(featureID, feature, decoration, configured); + return new BCLFeature(featureID, feature, decoration, configuration, modifiers); } /** @@ -146,6 +151,6 @@ public BCLFeature build(FC configuration) { * @return created {@link BCLFeature} instance. */ public BCLFeature build() { - return build(FeatureConfiguration.NONE); + return build((FC)FeatureConfiguration.NONE); } } diff --git a/src/main/java/ru/bclib/api/surface/SurfaceRuleBuilder.java b/src/main/java/ru/bclib/api/surface/SurfaceRuleBuilder.java index bd88f2c1..2e6a14c5 100644 --- a/src/main/java/ru/bclib/api/surface/SurfaceRuleBuilder.java +++ b/src/main/java/ru/bclib/api/surface/SurfaceRuleBuilder.java @@ -75,7 +75,7 @@ public SurfaceRuleBuilder surface(BlockState state) { public SurfaceRuleBuilder subsurface(BlockState state, int depth) { entryInstance = getFromCache("subsurface_" + depth + "_" + state.toString(), () -> { RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, false, CaveSurface.FLOOR), rule); + rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, CaveSurface.FLOOR), rule); return new SurfaceRuleEntry(3, rule); }); rules.add(entryInstance); @@ -117,7 +117,7 @@ public SurfaceRuleBuilder floor(BlockState state) { public SurfaceRuleBuilder belowFloor(BlockState state, int height, NoiseCondition noise) { entryInstance = getFromCache("below_floor_" + height + "_" + state.toString() + "_" + noise.getClass().getSimpleName(), () -> { RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, false, CaveSurface.FLOOR), SurfaceRules.ifTrue(noise, rule)); + rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, CaveSurface.FLOOR), SurfaceRules.ifTrue(noise, rule)); return new SurfaceRuleEntry(3, rule); }); rules.add(entryInstance); @@ -133,7 +133,7 @@ public SurfaceRuleBuilder belowFloor(BlockState state, int height, NoiseConditio public SurfaceRuleBuilder belowFloor(BlockState state, int height) { entryInstance = getFromCache("below_floor_" + height + "_" + state.toString(), () -> { RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, false, CaveSurface.FLOOR), rule); + rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, CaveSurface.FLOOR), rule); return new SurfaceRuleEntry(3, rule); }); rules.add(entryInstance); @@ -163,7 +163,7 @@ public SurfaceRuleBuilder ceil(BlockState state) { public SurfaceRuleBuilder aboveCeil(BlockState state, int height) { entryInstance = getFromCache("above_ceil_" + height + "_" + state.toString(), () -> { RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, false, CaveSurface.CEILING), rule); + rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, CaveSurface.CEILING), rule); return new SurfaceRuleEntry(3, rule); }); rules.add(entryInstance); @@ -179,7 +179,7 @@ public SurfaceRuleBuilder aboveCeil(BlockState state, int height) { public SurfaceRuleBuilder steep(BlockState state, int depth) { entryInstance = getFromCache("steep_" + depth + "_" + state.toString(), () -> { RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, false, CaveSurface.FLOOR), rule); + rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, CaveSurface.FLOOR), rule); rule = SurfaceRules.ifTrue(SurfaceRules.steep(), rule); int priority = depth < 1 ? 0 : 1; return new SurfaceRuleEntry(priority, rule); diff --git a/src/main/java/ru/bclib/api/tag/CommonBlockTags.java b/src/main/java/ru/bclib/api/tag/CommonBlockTags.java index 1f18172d..6401a0d8 100644 --- a/src/main/java/ru/bclib/api/tag/CommonBlockTags.java +++ b/src/main/java/ru/bclib/api/tag/CommonBlockTags.java @@ -1,23 +1,26 @@ package ru.bclib.api.tag; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; -import ru.bclib.api.tag.TagAPI.TagNamed; public class CommonBlockTags { - public static final TagNamed BARREL = TagAPI.makeCommonBlockTag("barrel"); - public static final TagNamed BOOKSHELVES = TagAPI.makeCommonBlockTag("bookshelves"); - public static final TagNamed CHEST = TagAPI.makeCommonBlockTag("chest"); - public static final TagNamed END_STONES = TagAPI.makeCommonBlockTag("end_stones"); - public static final TagNamed GEN_END_STONES = END_STONES; - public static final TagNamed IMMOBILE = TagAPI.makeCommonBlockTag("immobile"); - public static final TagNamed LEAVES = TagAPI.makeCommonBlockTag("leaves"); - public static final TagNamed NETHERRACK = TagAPI.makeCommonBlockTag("netherrack"); - public static final TagNamed NETHER_MYCELIUM = TagAPI.makeCommonBlockTag("nether_mycelium"); - public static final TagNamed NETHER_PORTAL_FRAME = TagAPI.makeCommonBlockTag("nether_pframe"); - public static final TagNamed NETHER_STONES = TagAPI.makeCommonBlockTag("nether_stones"); - public static final TagNamed SAPLINGS = TagAPI.makeCommonBlockTag("saplings"); - public static final TagNamed SOUL_GROUND = TagAPI.makeCommonBlockTag("soul_ground"); - public static final TagNamed WOODEN_BARREL = TagAPI.makeCommonBlockTag("wooden_barrels"); - public static final TagNamed WOODEN_CHEST = TagAPI.makeCommonBlockTag("wooden_chests"); - public static final TagNamed WORKBENCHES = TagAPI.makeCommonBlockTag("workbench"); + public static final TagKey BARREL = TagAPI.makeCommonBlockTag("barrel"); + public static final TagKey BOOKSHELVES = TagAPI.makeCommonBlockTag("bookshelves"); + public static final TagKey CHEST = TagAPI.makeCommonBlockTag("chest"); + public static final TagKey END_STONES = TagAPI.makeCommonBlockTag("end_stones"); + public static final TagKey GEN_END_STONES = END_STONES; + public static final TagKey IMMOBILE = TagAPI.makeCommonBlockTag("immobile"); + public static final TagKey LEAVES = TagAPI.makeCommonBlockTag("leaves"); + public static final TagKey NETHERRACK = TagAPI.makeCommonBlockTag("netherrack"); + public static final TagKey NETHER_MYCELIUM = TagAPI.makeCommonBlockTag("nether_mycelium"); + public static final TagKey NETHER_PORTAL_FRAME = TagAPI.makeCommonBlockTag("nether_pframe"); + public static final TagKey NETHER_STONES = TagAPI.makeCommonBlockTag("nether_stones"); + public static final TagKey SAPLINGS = TagAPI.makeCommonBlockTag("saplings"); + public static final TagKey SOUL_GROUND = TagAPI.makeCommonBlockTag("soul_ground"); + public static final TagKey WOODEN_BARREL = TagAPI.makeCommonBlockTag("wooden_barrels"); + public static final TagKey WOODEN_CHEST = TagAPI.makeCommonBlockTag("wooden_chests"); + public static final TagKey WORKBENCHES = TagAPI.makeCommonBlockTag("workbench"); + + public static final TagKey MINABLE_WITH_HAMMER = TagAPI.makeCommonBlockTag("mineable/hammer"); } diff --git a/src/main/java/ru/bclib/api/tag/CommonItemTags.java b/src/main/java/ru/bclib/api/tag/CommonItemTags.java index 9fb7bfd4..eb96d373 100644 --- a/src/main/java/ru/bclib/api/tag/CommonItemTags.java +++ b/src/main/java/ru/bclib/api/tag/CommonItemTags.java @@ -1,19 +1,19 @@ package ru.bclib.api.tag; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; -import ru.bclib.api.tag.TagAPI.TagNamed; public class CommonItemTags { - public final static TagNamed HAMMERS = TagAPI.makeCommonItemTag("hammers"); - public static final TagNamed BARREL = TagAPI.makeCommonItemTag("barrel"); - public static final TagNamed CHEST = TagAPI.makeCommonItemTag("chest"); - public static final TagNamed SHEARS = TagAPI.makeCommonItemTag("shears"); - public static final TagNamed FURNACES = TagAPI.makeCommonItemTag("furnaces"); - public static final TagNamed IRON_INGOTS = TagAPI.makeCommonItemTag("iron_ingots"); - public static final TagNamed LEAVES = TagAPI.makeCommonItemTag("leaves"); - public static final TagNamed SAPLINGS = TagAPI.makeCommonItemTag("saplings"); - public static final TagNamed SOUL_GROUND = TagAPI.makeCommonItemTag("soul_ground"); - public static final TagNamed WOODEN_BARREL = TagAPI.makeCommonItemTag("wooden_barrels"); - public static final TagNamed WOODEN_CHEST = TagAPI.makeCommonItemTag("wooden_chests"); - public static final TagNamed WORKBENCHES = TagAPI.makeCommonItemTag("workbench"); + public final static TagKey HAMMERS = TagAPI.makeCommonItemTag("hammers"); + public static final TagKey BARREL = TagAPI.makeCommonItemTag("barrel"); + public static final TagKey CHEST = TagAPI.makeCommonItemTag("chest"); + public static final TagKey SHEARS = TagAPI.makeCommonItemTag("shears"); + public static final TagKey FURNACES = TagAPI.makeCommonItemTag("furnaces"); + public static final TagKey IRON_INGOTS = TagAPI.makeCommonItemTag("iron_ingots"); + public static final TagKey LEAVES = TagAPI.makeCommonItemTag("leaves"); + public static final TagKey SAPLINGS = TagAPI.makeCommonItemTag("saplings"); + public static final TagKey SOUL_GROUND = TagAPI.makeCommonItemTag("soul_ground"); + public static final TagKey WOODEN_BARREL = TagAPI.makeCommonItemTag("wooden_barrels"); + public static final TagKey WOODEN_CHEST = TagAPI.makeCommonItemTag("wooden_chests"); + public static final TagKey WORKBENCHES = TagAPI.makeCommonItemTag("workbench"); } diff --git a/src/main/java/ru/bclib/api/tag/NamedMineableTags.java b/src/main/java/ru/bclib/api/tag/NamedMineableTags.java index 78a2c97a..b78e0a16 100644 --- a/src/main/java/ru/bclib/api/tag/NamedMineableTags.java +++ b/src/main/java/ru/bclib/api/tag/NamedMineableTags.java @@ -10,4 +10,5 @@ public class NamedMineableTags { public static final TagLocation SHEARS = new TagLocation<>("fabric", "mineable/shears"); public static final TagLocation SHOVEL = new TagLocation<>("mineable/shovel"); public static final TagLocation SWORD = new TagLocation<>("fabric", "mineable/sword"); + public static final TagLocation HAMMER = new TagLocation<>("c", "mineable/hammer"); } diff --git a/src/main/java/ru/bclib/api/tag/TagAPI.java b/src/main/java/ru/bclib/api/tag/TagAPI.java index 3c055087..98d08a9f 100644 --- a/src/main/java/ru/bclib/api/tag/TagAPI.java +++ b/src/main/java/ru/bclib/api/tag/TagAPI.java @@ -2,112 +2,178 @@ import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import net.fabricmc.fabric.api.tag.TagFactory; -import net.fabricmc.fabric.impl.tag.extension.TagDelegate; import net.minecraft.core.Registry; +import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; -import net.minecraft.tags.Tag.Named; -import net.minecraft.tags.TagCollection; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; +import ru.bclib.api.biomes.BiomeAPI; +import ru.bclib.mixin.common.DiggerItemAccessor; -import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; -import java.util.function.Supplier; +import java.util.function.BiConsumer; public class TagAPI { private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); + private static final Map> TAGS_BIOME = Maps.newConcurrentMap(); /** - * Get or create {@link Tag.Named}. + * Get or create {@link TagKey}. * - * @param containerSupplier - {@link TagCollection} {@link Supplier} tag collection; + * @param registry - {@link Registry} tag collection; * @param id - {@link ResourceLocation} tag id. - * @return {@link Tag.Named}. + * @return {@link TagKey}. */ - public static TagNamed makeTag(Supplier> containerSupplier, TagLocation id) { - Tag tag = containerSupplier.get().getTag(id); - return tag == null ? new Delegate<>(id, containerSupplier) : CommonDelegate.proxy((Named) tag); + public static TagKey makeTag(Registry registry, TagLocation id) { + return registry + .getTagNames() + .filter(tagKey -> tagKey.location().equals(id)) + .findAny() + .orElse(TagKey.create(registry.key(), id)); } - + /** - * Get or create {@link Block} {@link Tag.Named} with mod namespace. + * Get or create {@link Block} {@link TagKey} with mod namespace. * * @param modID - {@link String} mod namespace (mod id); * @param name - {@link String} tag name. - * @return {@link Block} {@link Tag.Named}. + * @return {@link Block} {@link TagKey}. */ - public static TagNamed makeBlockTag(String modID, String name) { - return makeTag(BlockTags::getAllTags, new TagLocation<>(modID, name)); + public static TagKey makeBiomeTag(String modID, String name) { + return TagKey.create(Registry.BIOME_REGISTRY, new ResourceLocation(modID, name)); } + /** - * Get or create {@link Item} {@link Tag.Named} with mod namespace. + * Get or create {@link Block} {@link TagKey} with mod namespace. * * @param modID - {@link String} mod namespace (mod id); * @param name - {@link String} tag name. - * @return {@link Item} {@link Tag.Named}. + * @return {@link Block} {@link TagKey}. + */ + public static TagKey makeBlockTag(String modID, String name) { + return makeTag(Registry.BLOCK, new TagLocation<>(modID, name)); + } + + /** + * Get or create {@link Block} {@link TagKey} with mod namespace. + * + * @param id - {@link String} id for the tag; + * @return {@link Block} {@link TagKey}. */ - public static TagNamed makeItemTag(String modID, String name) { - return makeTag(ItemTags::getAllTags, new TagLocation<>(modID, name)); + public static TagKey makeBlockTag(ResourceLocation id) { + return makeTag(Registry.BLOCK, new TagLocation<>(id)); } /** - * Get or create {@link Block} {@link Tag.Named}. + * Get or create {@link Item} {@link TagKey} with mod namespace. * - * @param name - {@link String} tag name. - * @return {@link Block} {@link Tag.Named}. - * @see Fabric Wiki (Tags) + * @param modID - {@link String} mod namespace (mod id); + * @param name - {@link String} tag name. + * @return {@link Item} {@link TagKey}. + */ + public static TagKey makeItemTag(String modID, String name) { + return makeTag(Registry.ITEM, new TagLocation<>(modID, name)); + } + + /** + * Get or create {@link Item} {@link TagKey} with mod namespace. + * + * @param id - {@link String} id for the tag; + * @return {@link Item} {@link TagKey}. */ - public static TagNamed makeCommonBlockTag(String name) { - return makeTag(BlockTags::getAllTags, new TagLocation<>("c", name)); + public static TagKey makeItemTag(ResourceLocation id) { + return makeTag(Registry.ITEM, new TagLocation<>(id)); } /** - * Get or create {@link Item} {@link Tag.Named}. + * Get or create {@link Block} {@link TagKey}. * * @param name - {@link String} tag name. - * @return {@link Item} {@link Tag.Named}. + * @return {@link Block} {@link TagKey}. * @see Fabric Wiki (Tags) */ - public static TagNamed makeCommonItemTag(String name) { - return makeTag(ItemTags::getAllTags, new TagLocation<>("c", name)); + public static TagKey makeCommonBlockTag(String name) { + return makeTag(Registry.BLOCK, new TagLocation<>("c", name)); } /** - * Get or create Minecraft {@link Block} {@link Tag.Named}. + * Get or create {@link Item} {@link TagKey}. * * @param name - {@link String} tag name. - * @return {@link Block} {@link Tag.Named}. + * @return {@link Item} {@link TagKey}. + * @see Fabric Wiki (Tags) */ - @Deprecated(forRemoval = true) - public static TagNamed getMCBlockTag(String name) { - ResourceLocation id = new ResourceLocation(name); - Tag tag = BlockTags.getAllTags().getTag(id); - return CommonDelegate.proxy(tag == null ? (Named) TagFactory.BLOCK.create(id): (Named) tag); + public static TagKey makeCommonItemTag(String name) { + return makeTag(Registry.ITEM, new TagLocation<>("c", name)); } /** * Initializes basic tags. Should be called only in BCLib main class. */ public static void init() { - addBlockTag(CommonBlockTags.BOOKSHELVES.getName(), Blocks.BOOKSHELF); - addBlockTag(CommonBlockTags.CHEST.getName(), Blocks.CHEST); - addItemTag(CommonItemTags.CHEST.getName(), Items.CHEST); - addItemTag(CommonItemTags.IRON_INGOTS.getName(), Items.IRON_INGOT); - addItemTag(CommonItemTags.FURNACES.getName(), Blocks.FURNACE); + addBlockTag(CommonBlockTags.BOOKSHELVES, Blocks.BOOKSHELF); + addBlockTag(CommonBlockTags.CHEST, Blocks.CHEST); + addItemTag(CommonItemTags.CHEST, Items.CHEST); + addItemTag(CommonItemTags.IRON_INGOTS, Items.IRON_INGOT); + addItemTag(CommonItemTags.FURNACES, Blocks.FURNACE); } - + + /** + * Adds multiple Tags to one Biome. + * @param tagIDs array of {@link TagLocation} tag IDs. + * @param biome The {@link Biome} to add tag. + */ + @SafeVarargs + public static void addBiomeTags(Biome biome, TagLocation... tagIDs) { + for (TagLocation tagID : tagIDs) { + addBiomeTagUntyped(tagID, biome); + } + } + + /** + * Adds one Tag to multiple Biomes. + * @param tagID {@link TagLocation} tag ID. + * @param biomes array of {@link Biome} to add into tag. + */ + public static void addBiomeTag(TagLocation tagID, Biome... biomes) { + addBiomeTagUntyped(tagID, biomes); + } + + /** + * Adds one Tag to multiple Biomes. + * @param tagID {@link TagKey} tag ID. + * @param biomes array of {@link Biome} to add into tag. + */ + public static void addBiomeTag(TagKey tagID, Biome... biomes) { + addBiomeTagUntyped(tagID.location(), biomes); + } + /** + * Adds one Tag to multiple Biomes. + * @param tagID {@link ResourceLocation} tag ID. + * @param biomes array of {@link Biome} to add into tag. + */ + protected static void addBiomeTagUntyped(ResourceLocation tagID, Biome... biomes) { + Set set = TAGS_BIOME.computeIfAbsent(tagID, k -> Sets.newHashSet()); + for (Biome biome : biomes) { + ResourceLocation id = BiomeAPI.getBiomeID(biome); + if (id != null) { + set.add(id); + } + } + } + + /** * Adds multiple Tags to one Block. * @param tagIDs array of {@link TagLocation} tag IDs. @@ -128,6 +194,15 @@ public static void addBlockTags(Block block, TagLocation... tagIDs) { public static void addBlockTag(TagLocation tagID, Block... blocks) { addBlockTagUntyped(tagID, blocks); } + + /** + * Adds one Tag to multiple Blocks. + * @param tagID {@link TagKey} tag ID. + * @param blocks array of {@link Block} to add into tag. + */ + public static void addBlockTag(TagKey tagID, Block... blocks) { + addBlockTagUntyped(tagID.location(), blocks); + } /** * Adds one Tag to multiple Blocks. @@ -164,6 +239,15 @@ public static void addItemTags(ItemLike item, TagLocation... tagIDs) { public static void addItemTag(TagLocation tagID, ItemLike... items) { addItemTagUntyped(tagID, items); } + + /** + * Adds one Tag to multiple Items. + * @param tagID {@link TagKey} tag ID. + * @param items array of {@link ItemLike} to add into tag. + */ + public static void addItemTag(TagKey tagID, ItemLike... items) { + addItemTagUntyped(tagID.location(), items); + } /** * Adds one Tag to multiple Items. @@ -190,16 +274,17 @@ protected static void addItemTagUntyped(ResourceLocation tagID, ItemLike... item * @param tagsMap The map that will hold the registered Tags * @return The {@code tagsMap} Parameter. */ - public static Map apply(String directory, Map tagsMap) { - Map> tagMap = null; + public static Map apply(String directory, Map tagsMap) { + final BiConsumer> consumer; + consumer = (id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids); if ("tags/blocks".equals(directory)) { - tagMap = TAGS_BLOCK; + TAGS_BLOCK.forEach(consumer); } else if ("tags/items".equals(directory)) { - tagMap = TAGS_ITEM; + TAGS_ITEM.forEach(consumer); } - if (tagMap != null) { - tagMap.forEach((id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids)); + else if ("tags/worldgen/biome".equals(directory)) { + TAGS_BIOME.forEach(consumer); } return tagsMap; } @@ -215,16 +300,8 @@ public static Tag.Builder apply(Tag.Builder builder, Set ids) ids.forEach(value -> builder.addElement(value, "BCLib Code")); return builder; } - - /** - * Extends {@link Tag.Named} to return a type safe {@link TagLocation}. This Type was introduced to - * allow type-safe definition of Tags using their ResourceLocation. - * @param The Type of the underlying {@link Tag} - */ - public interface TagNamed extends Tag.Named{ - TagLocation getName(); - } - + + /** * Extends (without changing) {@link ResourceLocation}. This Type was introduced to allow type-safe definition af * Tags using their ResourceLocation. @@ -234,68 +311,32 @@ public static class TagLocation extends ResourceLocation { public TagLocation(String string) { super(string); } - + public TagLocation(String string, String string2) { super(string, string2); } - + public TagLocation(ResourceLocation location) { super(location.getNamespace(), location.getPath()); } - public static TagLocation of(Tag.Named tag){ - return new TagLocation(tag.getName()); + public static TagLocation of(TagKey tag){ + return new TagLocation(tag.location()); } } - - private abstract static class CommonDelegate implements TagNamed { - protected final Tag.Named delegate; - protected CommonDelegate(Tag.Named source){ - this.delegate = source; - } - - public static TagNamed proxy(Tag.Named source){ - if (source instanceof TagNamed typed) return typed; - return new ProxyDelegate<>(source); - } - - @Override - public boolean contains(T object) { - return delegate.contains(object); - } - - @Override - public List getValues() { - return delegate.getValues(); - } - - @Override - public T getRandomElement(Random random) { - return delegate.getRandomElement(random); - } + + public static boolean isToolWithMineableTag(ItemStack stack, TagKey tag){ + return isToolWithUntypedMineableTag(stack, tag.location()); } - - private static final class ProxyDelegate extends CommonDelegate{ - private final TagLocation id; - private ProxyDelegate(Tag.Named source) { - super( source); - id = new TagLocation<>(source.getName() - .getNamespace(), source.getName() - .getPath()); - } - @Override - public TagLocation getName(){ - return id; - } + + public static boolean isToolWithMineableTag(ItemStack stack, TagLocation tag){ + return isToolWithUntypedMineableTag(stack, tag); } - - private static final class Delegate extends CommonDelegate{ - public Delegate(TagLocation id, Supplier> containerSupplier) { - super( new TagDelegate<>(id, containerSupplier)); - } - @Override - public TagLocation getName(){ - return (TagLocation)delegate.getName(); + + private static boolean isToolWithUntypedMineableTag(ItemStack stack, ResourceLocation tag){ + if (stack.getItem() instanceof DiggerItemAccessor dig){ + return dig.bclib_getBlockTag().location().equals(tag); } + return false; } } diff --git a/src/main/java/ru/bclib/blocks/BaseCropBlock.java b/src/main/java/ru/bclib/blocks/BaseCropBlock.java index 72f7f20a..cea2121a 100644 --- a/src/main/java/ru/bclib/blocks/BaseCropBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCropBlock.java @@ -39,7 +39,6 @@ public class BaseCropBlock extends BasePlantBlock { public BaseCropBlock(Item drop, Block... terrain) { this( FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .randomTicks() .noCollission(), diff --git a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index 7c80d49e..0d96dc59 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -2,7 +2,6 @@ import com.google.common.collect.Lists; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -32,6 +31,7 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.items.tool.BaseShearsItem; import ru.bclib.util.BlocksHelper; import java.util.List; @@ -45,7 +45,6 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements R public BaseDoublePlantBlock() { this( FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .noCollission() ); @@ -54,7 +53,6 @@ public BaseDoublePlantBlock() { public BaseDoublePlantBlock(int light) { this( FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .lightLevel((state) -> state.getValue(TOP) ? light : 0) .noCollission() @@ -117,7 +115,8 @@ public List getDrops(BlockState state, LootContext.Builder builder) { } ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + //TODO: 1.18.2 Test if shearing still works + if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( Enchantments.SILK_TOUCH, tool ) > 0) { diff --git a/src/main/java/ru/bclib/blocks/BaseGlassBlock.java b/src/main/java/ru/bclib/blocks/BaseGlassBlock.java new file mode 100644 index 00000000..a7766e36 --- /dev/null +++ b/src/main/java/ru/bclib/blocks/BaseGlassBlock.java @@ -0,0 +1,63 @@ +package ru.bclib.blocks; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.enchantment.EnchantmentHelper; +import net.minecraft.world.item.enchantment.Enchantments; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.tools.AddMineablePickaxe; + +import java.util.Collections; +import java.util.List; + +public class BaseGlassBlock extends BaseBlockNotFull implements AddMineablePickaxe, RenderLayerProvider { + public BaseGlassBlock(Block block) { + this(block, 0.3f); + } + public BaseGlassBlock(Block block, float resistance) { + super(FabricBlockSettings.copyOf(block) + .resistance(resistance) + .nonOpaque() + .isSuffocating((arg1, arg2, arg3) -> false) + .isViewBlocking((arg1, arg2, arg3) -> false)); + } + + @Environment(EnvType.CLIENT) + public float getShadeBrightness(BlockState state, BlockGetter view, BlockPos pos) { + return 1.0F; + } + + @Override + public boolean propagatesSkylightDown(BlockState state, BlockGetter view, BlockPos pos) { + return true; + } + + @Environment(EnvType.CLIENT) + public boolean skipRendering(BlockState state, BlockState neighbor, Direction facing) { + return neighbor.getBlock() == this ? true : super.skipRendering(state, neighbor, facing); + } + + @Override + public List getDrops(BlockState state, LootContext.Builder builder) { + ItemStack tool = builder.getParameter(LootContextParams.TOOL); + if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + return Collections.singletonList(new ItemStack(this)); + } + return Collections.emptyList(); + } + + @Override + public BCLRenderLayer getRenderLayer() { + return BCLRenderLayer.TRANSLUCENT; + } +} diff --git a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 9955fbad..8daaee2f 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -24,6 +24,8 @@ import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.AddMineableHoe; +import ru.bclib.interfaces.tools.AddMineableShears; import ru.bclib.items.tool.BaseShearsItem; import ru.bclib.util.MHelper; @@ -31,7 +33,7 @@ import java.util.List; import java.util.function.Consumer; -public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider, TagProvider { +public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider, TagProvider, AddMineableShears, AddMineableHoe { protected final Block sapling; private static FabricBlockSettings makeLeaves(MaterialColor color) { @@ -100,8 +102,6 @@ public BlockModel getItemModel(ResourceLocation resourceLocation) { @Override public void addTags(List> blockTags, List> itemTags) { - blockTags.add(NamedMineableTags.SHEARS); - blockTags.add(NamedMineableTags.HOE); blockTags.add(NamedBlockTags.LEAVES); itemTags.add(NamedItemTags.LEAVES); } diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index abe61807..ceb8fe03 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -1,17 +1,17 @@ package ru.bclib.blocks; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -import net.fabricmc.fabric.impl.object.builder.FabricBlockInternals; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TieredItem; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.OreBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; @@ -19,7 +19,11 @@ import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import ru.bclib.api.tag.NamedCommonBlockTags; +import ru.bclib.api.tag.NamedMineableTags; +import ru.bclib.api.tag.TagAPI; import ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.interfaces.TagProvider; import ru.bclib.util.LootUtil; import ru.bclib.util.MHelper; @@ -31,6 +35,7 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final Supplier dropItem; private final int minCount; private final int maxCount; + private final int miningLevel; public BaseOreBlock(Supplier drop, int minCount, int maxCount, int experience) { this(drop, minCount, maxCount, experience, 0); @@ -53,15 +58,11 @@ public BaseOreBlock(Properties properties, Supplier drop, int minCount, in } public BaseOreBlock(Properties properties, Supplier drop, int minCount, int maxCount, int experience, int miningLevel) { - super(makeProps(properties, miningLevel), UniformInt.of(experience>0?1:0, experience)); + super(properties, UniformInt.of(experience>0?1:0, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; - } - - private static Properties makeProps(Properties properties, int level){ - FabricBlockInternals.computeExtraData(properties).addMiningLevel(FabricToolTags.PICKAXES, level); - return properties; + this.miningLevel = miningLevel; } @Override @@ -70,30 +71,35 @@ public List getDrops(BlockState state, LootContext.Builder builder) { return LootUtil .getDrops(this, state, builder) .orElseGet( - ()->BaseOreBlock.getDroppedItems(this, dropItem.get(), maxCount, minCount, state, builder) + ()->BaseOreBlock.getDroppedItems(this, dropItem.get(), maxCount, minCount, miningLevel, state, builder) ); } - public static List getDroppedItems(ItemLike block, Item dropItem, int maxCount, int minCount, BlockState state, LootContext.Builder builder) { + public static List getDroppedItems(ItemLike block, Item dropItem, int maxCount, int minCount, int miningLevel, BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null && tool.isCorrectToolForDrops(state)) { - if (EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(block)); + boolean canMine = miningLevel==0; + if (tool.getItem() instanceof TieredItem tired) { + canMine = tired.getTier().getLevel()>=miningLevel; } - int count; - int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); - if (enchantment > 0) { - int min = Mth.clamp(minCount + enchantment, minCount, maxCount); - int max = maxCount + (enchantment / Enchantments.BLOCK_FORTUNE.getMaxLevel()); - if (min == max) { - return Collections.singletonList(new ItemStack(dropItem, max)); + if (canMine) { + if (EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { + return Collections.singletonList(new ItemStack(block)); } - count = MHelper.randRange(min, max, MHelper.RANDOM); - } - else { - count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM); + int count; + int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); + if (enchantment > 0) { + int min = Mth.clamp(minCount + enchantment, minCount, maxCount); + int max = maxCount + (enchantment / Enchantments.BLOCK_FORTUNE.getMaxLevel()); + if (min == max) { + return Collections.singletonList(new ItemStack(dropItem, max)); + } + count = MHelper.randRange(min, max, MHelper.RANDOM); + } else { + count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM); + } + return Collections.singletonList(new ItemStack(dropItem, count)); } - return Collections.singletonList(new ItemStack(dropItem, count)); } return Collections.emptyList(); } diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index e469ccd7..ca88ba50 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -4,7 +4,6 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; @@ -40,12 +39,15 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.AddMineableHoe; +import ru.bclib.interfaces.tools.AddMineableShears; +import ru.bclib.items.tool.BaseShearsItem; import java.util.List; import java.util.Optional; import java.util.Random; -public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, TagProvider { +public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock{ private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public BasePlantBlock() { @@ -60,7 +62,6 @@ public BasePlantBlock(boolean replaceable) { this( FabricBlockSettings .of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .noCollission() ); @@ -70,7 +71,6 @@ public BasePlantBlock(boolean replaceable, int light) { this( FabricBlockSettings .of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByHand(true) .luminance(light) .sound(SoundType.GRASS) .noCollission() @@ -116,7 +116,8 @@ public BlockState updateShape(BlockState state, Direction facing, BlockState nei @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + //TODO: 1.18.2 Test if shearing still works + if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( Enchantments.SILK_TOUCH, tool ) > 0) { @@ -167,10 +168,4 @@ public BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState bl Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); return ModelsHelper.fromPattern(pattern); } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(NamedMineableTags.SHEARS); - blockTags.add(NamedMineableTags.HOE); - } } diff --git a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java index 3beb20d8..ae0baf4a 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java @@ -20,7 +20,6 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public BasePlantWithAgeBlock() { this( FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .randomTicks() .noCollission() diff --git a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java index 28127de4..9d2b9d46 100644 --- a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java @@ -1,7 +1,6 @@ package ru.bclib.blocks; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; @@ -15,6 +14,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.phys.BlockHitResult; +import ru.bclib.api.tag.NamedMineableTags; +import ru.bclib.api.tag.TagAPI; public class BaseStripableLogBlock extends BaseRotatedPillarBlock { private final Block striped; @@ -27,7 +28,7 @@ public BaseStripableLogBlock(MaterialColor color, Block striped) { @Override @SuppressWarnings("deprecation") public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { + if (TagAPI.isToolWithMineableTag(player.getMainHandItem(), NamedMineableTags.AXE)){ world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlock(pos, diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index 96b77c0e..aa98e969 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -3,8 +3,8 @@ import com.google.common.collect.Maps; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.resources.model.UnbakedModel; import net.minecraft.core.BlockPos; @@ -33,6 +33,8 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.BlockHitResult; import org.jetbrains.annotations.Nullable; +import ru.bclib.api.tag.NamedMineableTags; +import ru.bclib.api.tag.TagAPI; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; @@ -69,7 +71,9 @@ public Block getBaseBlock() { @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (pathBlock != null && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) { + //TODO: 1.18.2 check + if (pathBlock != null && TagAPI.isToolWithMineableTag(player.getMainHandItem(), NamedMineableTags.SHOVEL)){ + //if (pathBlock != null && FabricTagProvider.SHOVELS.contains(player.getMainHandItem().getItem())) { world.playSound(player, pos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlockAndUpdate(pos, pathBlock.defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java index e8fc1233..c6351c6a 100644 --- a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java @@ -18,7 +18,6 @@ public BaseUnderwaterWallPlantBlock() { this( FabricBlockSettings .of(Material.WATER_PLANT) - .breakByHand(true) .sound(SoundType.WET_GRASS) .noCollission() ); @@ -28,7 +27,6 @@ public BaseUnderwaterWallPlantBlock(int light) { this( FabricBlockSettings .of(Material.WATER_PLANT) - .breakByHand(true) .luminance(light) .sound(SoundType.WET_GRASS) .noCollission() diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 6e156b43..77c515cc 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -2,7 +2,6 @@ import com.google.common.collect.Lists; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -31,6 +30,7 @@ import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.items.tool.BaseShearsItem; import ru.bclib.util.BlocksHelper; import java.util.List; @@ -53,7 +53,6 @@ public BaseVineBlock(int light, boolean bottomOnly) { this( FabricBlockSettings .of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light) .noCollission() @@ -110,7 +109,7 @@ public BlockState updateShape(BlockState state, Direction facing, BlockState nei @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( Enchantments.SILK_TOUCH, tool ) > 0) { diff --git a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java index 54e8dbd3..9e100860 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java @@ -39,7 +39,6 @@ public BaseWallPlantBlock() { this( FabricBlockSettings .of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .noCollission() ); @@ -49,7 +48,6 @@ public BaseWallPlantBlock(int light) { this( FabricBlockSettings .of(Material.PLANT) - .breakByHand(true) .luminance(light) .sound(SoundType.GRASS) .noCollission() diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index dfee5df8..eb646024 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -44,7 +44,6 @@ public class FeatureSaplingBlock extends SaplingBlock implements RenderLayerProv public FeatureSaplingBlock(Function> featureSupplier) { this(FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .collidable(false) .instabreak() .sound(SoundType.GRASS) @@ -55,7 +54,6 @@ public FeatureSaplingBlock(Function> featureSupplier) { public FeatureSaplingBlock(int light, Function> featureSupplier) { this(FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) .collidable(false) .luminance(light) .instabreak() diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 1862427f..7aca9c59 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -14,10 +14,12 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.AddMineableHoe; +import ru.bclib.interfaces.tools.AddMineableShears; import java.util.List; -public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerProvider, TagProvider { +public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerProvider, TagProvider, AddMineableShears, AddMineableHoe { public SimpleLeavesBlock(MaterialColor color) { this( FabricBlockSettings @@ -58,8 +60,6 @@ public BCLRenderLayer getRenderLayer() { @Override public void addTags(List> blockTags, List> itemTags) { - blockTags.add(NamedMineableTags.SHEARS); - blockTags.add(NamedMineableTags.HOE); blockTags.add(NamedBlockTags.LEAVES); itemTags.add(NamedItemTags.LEAVES); } diff --git a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java index 328c6f1d..d04bcf59 100644 --- a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java @@ -1,7 +1,6 @@ package ru.bclib.blocks; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerPlayer; import net.minecraft.sounds.SoundEvents; @@ -15,6 +14,8 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.phys.BlockHitResult; +import ru.bclib.api.tag.NamedMineableTags; +import ru.bclib.api.tag.TagAPI; public class StripableBarkBlock extends BaseBarkBlock { private final Block striped; @@ -27,7 +28,7 @@ public StripableBarkBlock(MaterialColor color, Block striped) { @Override @SuppressWarnings("deprecation") public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { - if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { + if (TagAPI.isToolWithMineableTag(player.getMainHandItem(), NamedMineableTags.AXE)){ world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); if (!world.isClientSide) { world.setBlock(pos, diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index 486b96ac..a85a92be 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -2,7 +2,6 @@ import com.google.common.collect.Lists; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.server.level.ServerLevel; @@ -36,18 +35,20 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.AddMineableHoe; +import ru.bclib.interfaces.tools.AddMineableShears; +import ru.bclib.items.tool.BaseShearsItem; import java.util.List; import java.util.Random; -public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, LiquidBlockContainer, TagProvider { +public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public UnderwaterPlantBlock() { this( FabricBlockSettings .of(Material.WATER_PLANT) - .breakByHand(true) .sound(SoundType.WET_GRASS) .noCollission() ); @@ -57,7 +58,6 @@ public UnderwaterPlantBlock(int light) { this( FabricBlockSettings .of(Material.WATER_PLANT) - .breakByHand(true) .luminance(light) .sound(SoundType.WET_GRASS) .noCollission() @@ -105,7 +105,7 @@ public BlockState updateShape(BlockState state, Direction facing, BlockState nei @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( Enchantments.SILK_TOUCH, tool ) > 0) { @@ -158,10 +158,5 @@ public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, public FluidState getFluidState(BlockState state) { return Fluids.WATER.getSource(false); } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(NamedMineableTags.SHEARS); - blockTags.add(NamedMineableTags.HOE); - } + } diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java index e5ba1b6b..255f74fb 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java @@ -20,7 +20,6 @@ public UnderwaterPlantWithAgeBlock() { super( FabricBlockSettings .of(Material.WATER_PLANT) - .breakByHand(true) .sound(SoundType.WET_GRASS) .randomTicks() .noCollission() diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index f58e5526..34cf92f3 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -2,7 +2,6 @@ import com.google.common.collect.Lists; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.entity.player.Player; @@ -30,16 +29,18 @@ import ru.bclib.client.render.BCLRenderLayer; import ru.bclib.interfaces.RenderLayerProvider; import ru.bclib.interfaces.TagProvider; +import ru.bclib.interfaces.tools.AddMineableHoe; +import ru.bclib.interfaces.tools.AddMineableShears; +import ru.bclib.items.tool.BaseShearsItem; import java.util.List; -public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, TagProvider { +public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, AddMineableShears, AddMineableHoe { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); public UpDownPlantBlock() { this(FabricBlockSettings .of(Material.PLANT) - .breakByHand(true) .sound(SoundType.GRASS) .noCollission() ); @@ -83,7 +84,7 @@ public BlockState updateShape(BlockState state, Direction facing, BlockState nei @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( + if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( Enchantments.SILK_TOUCH, tool ) > 0) { @@ -104,10 +105,4 @@ public void playerDestroy(Level world, Player player, BlockPos pos, BlockState s super.playerDestroy(world, player, pos, state, blockEntity, stack); world.neighborChanged(pos, Blocks.AIR, pos.below()); } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(NamedMineableTags.SHEARS); - blockTags.add(NamedMineableTags.HOE); - } } diff --git a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java index 6c3379a0..ff6e6c5a 100644 --- a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java +++ b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java @@ -19,7 +19,6 @@ public WallMushroomBlock(int light) { this( FabricBlockSettings .of(Material.PLANT) - .breakByHand(true) .luminance(light) .destroyTime(0.2F) .sound(SoundType.GRASS) diff --git a/src/main/java/ru/bclib/client/render/CustomFogRenderer.java b/src/main/java/ru/bclib/client/render/CustomFogRenderer.java index 39291fe9..76a72637 100644 --- a/src/main/java/ru/bclib/client/render/CustomFogRenderer.java +++ b/src/main/java/ru/bclib/client/render/CustomFogRenderer.java @@ -108,12 +108,12 @@ private static boolean shouldIgnoreArea(Level level, int x, int y, int z) { } private static boolean shouldIgnore(Level level, int x, int y, int z) { - Biome biome = level.getBiome(MUT_POS.set(x, y, z)); + Biome biome = level.getBiome(MUT_POS.set(x, y, z)).value(); return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; } private static float getFogDensityI(Level level, int x, int y, int z) { - Biome biome = level.getBiome(MUT_POS.set(x, y, z)); + Biome biome = level.getBiome(MUT_POS.set(x, y, z)).value(); BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); return renderBiome.getFogDensity(); } diff --git a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java index 022e5eaf..2fc08408 100644 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java @@ -6,7 +6,7 @@ import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import org.jetbrains.annotations.Nullable; @@ -32,8 +32,8 @@ public abstract class ComplexMaterial { private final List defaultBlockEntries = Lists.newArrayList(); private final List defaultItemEntries = Lists.newArrayList(); - private final Map> blockTags = Maps.newHashMap(); - private final Map> itemTags = Maps.newHashMap(); + private final Map> blockTags = Maps.newHashMap(); + private final Map> itemTags = Maps.newHashMap(); private final Map blocks = Maps.newHashMap(); private final Map items = Maps.newHashMap(); @@ -105,39 +105,39 @@ protected void initFlammable(FlammableBlockRegistry registry) {} /** * Adds custom block tag for this {@link ComplexMaterial}, tag can be created with {@link TagAPI} or you can use one of already created tags. - * @param tag {@link Tag.Named} for {@link Block} + * @param tag {@link TagKey} for {@link Block} */ - protected void addBlockTag(Tag.Named tag) { - String key = tag.getName().getPath().replace(getBaseName() + "_", ""); + protected void addBlockTag(TagKey tag) { + String key = tag.location().getPath().replace(getBaseName() + "_", ""); blockTags.put(key, tag); } /** - * Adds custom iten tag for this {@link ComplexMaterial}, tag can be created with {@link TagAPI} or you can use one of already created tags. - * @param tag {@link Tag.Named} for {@link Item} + * Adds custom item tag for this {@link ComplexMaterial}, tag can be created with {@link TagAPI} or you can use one of already created tags. + * @param tag {@link TagKey} for {@link Item} */ - protected void addItemTag(Tag.Named tag) { - String key = tag.getName().getPath().replace(getBaseName() + "_", ""); + protected void addItemTag(TagKey tag) { + String key = tag.location().getPath().replace(getBaseName() + "_", ""); itemTags.put(key, tag); } /** - * Get custom {@link Block} {@link Tag.Named} from this {@link ComplexMaterial}. + * Get custom {@link Block} {@link TagKey} from this {@link ComplexMaterial}. * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. - * @return {@link Tag.Named} for {@link Block} or {@code null} if nothing is stored. + * @return {@link TagKey} for {@link Block} or {@code null} if nothing is stored. */ @Nullable - public Tag.Named getBlockTag(String key) { + public TagKey getBlockTag(String key) { return blockTags.get(key); } /** - * Get custom {@link Item} {@link Tag.Named} from this {@link ComplexMaterial}. + * Get custom {@link Item} {@link TagKey} from this {@link ComplexMaterial}. * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. - * @return {@link Tag.Named} for {@link Item} or {@code null} if nothing is stored. + * @return {@link TagKey} for {@link Item} or {@code null} if nothing is stored. */ @Nullable - public Tag.Named getItemTag(String key) { + public TagKey getItemTag(String key) { return itemTags.get(key); } diff --git a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java index 7d99b3d2..c405ef4b 100644 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java @@ -100,8 +100,8 @@ protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings } final protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - TagLocation tagBlockLog = new TagLocation<>(getBlockTag(TAG_LOGS).getName()); - TagLocation tagItemLog = new TagLocation<>(getItemTag(TAG_LOGS).getName()); + TagLocation tagBlockLog = TagLocation.of(getBlockTag(TAG_LOGS)); + TagLocation tagItemLog = TagLocation.of(getItemTag(TAG_LOGS)); addBlockEntry( new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> new BaseRotatedPillarBlock(settings)) diff --git a/src/main/java/ru/bclib/integration/ModIntegration.java b/src/main/java/ru/bclib/integration/ModIntegration.java index e1d93576..77838b24 100644 --- a/src/main/java/ru/bclib/integration/ModIntegration.java +++ b/src/main/java/ru/bclib/integration/ModIntegration.java @@ -1,7 +1,7 @@ package ru.bclib.integration; -import net.fabricmc.fabric.api.tag.TagFactory; import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceKey; @@ -9,7 +9,7 @@ import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; -import net.minecraft.tags.Tag.Named; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; @@ -19,6 +19,7 @@ import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import ru.bclib.BCLib; +import ru.bclib.api.tag.TagAPI; import ru.bclib.world.features.BCLFeature; import java.lang.reflect.Constructor; @@ -38,6 +39,10 @@ public ModIntegration(String modID) { public ResourceLocation getID(String name) { return new ResourceLocation(modID, name); } + + public ResourceKey getFeatureKey(String name) { + return ResourceKey.create(Registry.PLACED_FEATURE_REGISTRY, getID(name)); + } public Block getBlock(String name) { return Registry.BLOCK.get(getID(name)); @@ -62,8 +67,8 @@ public boolean modIsInstalled() { public BCLFeature getFeature(String featureID, String placedFeatureID, GenerationStep.Decoration featureStep) { ResourceLocation id = getID(featureID); Feature feature = Registry.FEATURE.get(id); - PlacedFeature featureConfigured = BuiltinRegistries.PLACED_FEATURE.get(getID(placedFeatureID)); - return new BCLFeature(id, feature, featureStep, featureConfigured); + Holder featurePlaced = BuiltinRegistries.PLACED_FEATURE.getHolder(getFeatureKey(placedFeatureID)).orElse(null); + return new BCLFeature(id, feature, featureStep, featurePlaced); } public BCLFeature getFeature(String name, GenerationStep.Decoration featureStep) { @@ -74,8 +79,8 @@ public BCLFeature getFeature(String name, GenerationStep.Decoration featureStep) return BuiltinRegistries.CONFIGURED_FEATURE.get(getID(name)); } - public Biome getBiome(String name) { - return BuiltinRegistries.BIOME.get(getID(name)); + public Holder getBiome(String name) { + return BuiltinRegistries.BIOME.getHolder(getKey(name)).orElseThrow(); } public Class getClass(String path) { @@ -197,18 +202,13 @@ public Object newInstance(Class cl, Object... args) { return null; } - public Tag.Named getItemTag(String name) { + public TagKey getItemTag(String name) { ResourceLocation id = getID(name); - Tag tag = ItemTags.getAllTags().getTag(id); - - //return tag == null ? (Named) TagRegistry.item(id) : (Named) tag; - return tag == null ? (Named) TagFactory.ITEM.create(id) : (Named) tag; + return TagAPI.makeItemTag(id); } - public Tag.Named getBlockTag(String name) { + public TagKey getBlockTag(String name) { ResourceLocation id = getID(name); - Tag tag = BlockTags.getAllTags().getTag(id); - //return tag == null ? (Named) TagRegistry.block(id) : (Named) tag; - return tag == null ? (Named) TagFactory.BLOCK.create(id) : (Named) tag; + return TagAPI.makeBlockTag(id); } } diff --git a/src/main/java/ru/bclib/interfaces/ChunkGeneratorAccessor.java b/src/main/java/ru/bclib/interfaces/ChunkGeneratorAccessor.java new file mode 100644 index 00000000..cb20ad10 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/ChunkGeneratorAccessor.java @@ -0,0 +1,8 @@ +package ru.bclib.interfaces; + +import net.minecraft.core.Registry; +import net.minecraft.world.level.levelgen.structure.StructureSet; + +public interface ChunkGeneratorAccessor { + Registry bclib_getStructureSetsRegistry(); +} diff --git a/src/main/java/ru/bclib/interfaces/NumericProvider.java b/src/main/java/ru/bclib/interfaces/NumericProvider.java index b24d305e..8bd76b02 100644 --- a/src/main/java/ru/bclib/interfaces/NumericProvider.java +++ b/src/main/java/ru/bclib/interfaces/NumericProvider.java @@ -12,7 +12,7 @@ public interface NumericProvider { ResourceKey>> NUMERIC_PROVIDER_REGISTRY = ResourceKey.createRegistryKey(BCLib.makeID("worldgen/numeric_provider")); - Registry> NUMERIC_PROVIDER = new MappedRegistry<>(NUMERIC_PROVIDER_REGISTRY, Lifecycle.experimental()); + Registry> NUMERIC_PROVIDER = new MappedRegistry<>(NUMERIC_PROVIDER_REGISTRY, Lifecycle.experimental(), null); Codec CODEC = NUMERIC_PROVIDER.byNameCodec().dispatch(NumericProvider::pcodec, Function.identity()); int getNumber(SurfaceRulesContextAccessor context); diff --git a/src/main/java/ru/bclib/interfaces/SurfaceProvider.java b/src/main/java/ru/bclib/interfaces/SurfaceProvider.java index 143e6499..26426edf 100644 --- a/src/main/java/ru/bclib/interfaces/SurfaceProvider.java +++ b/src/main/java/ru/bclib/interfaces/SurfaceProvider.java @@ -1,10 +1,11 @@ package ru.bclib.interfaces; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.state.BlockState; public interface SurfaceProvider { - public BlockState bclib_getSurface(BlockPos pos, Biome biome, ServerLevel level); + public BlockState bclib_getSurface(BlockPos pos, Holder biome, ServerLevel level); } diff --git a/src/main/java/ru/bclib/interfaces/SurvivesOnBlocks.java b/src/main/java/ru/bclib/interfaces/SurvivesOnBlocks.java new file mode 100644 index 00000000..148606c6 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/SurvivesOnBlocks.java @@ -0,0 +1,33 @@ +package ru.bclib.interfaces; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +public interface SurvivesOnBlocks extends SurvivesOnSpecialGround{ + List getSurvivableBlocks(); + + @Override + default String getSurvivableBlocksString(){ + return getSurvivableBlocks() + .stream() + .filter(block -> block!= Blocks.AIR && block!=null) + .map(block -> { + ItemStack stack = new ItemStack(block); + if (stack.hasCustomHoverName()) return stack.getHoverName().getString(); + else return block.getName().getString(); + }) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.joining(", ")); + } + + @Override + default boolean isSurvivable(BlockState state){ + return getSurvivableBlocks().contains(state.getBlock()); + } +} diff --git a/src/main/java/ru/bclib/interfaces/SurvivesOnSpecialGround.java b/src/main/java/ru/bclib/interfaces/SurvivesOnSpecialGround.java new file mode 100644 index 00000000..de1dae4c --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/SurvivesOnSpecialGround.java @@ -0,0 +1,63 @@ +package ru.bclib.interfaces; + +import com.google.common.collect.Lists; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.minecraft.ChatFormatting; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.world.level.LevelReader; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.List; + +public interface SurvivesOnSpecialGround { + String getSurvivableBlocksString(); + + @Environment(EnvType.CLIENT) + static List splitLines(String input) { + final int MAX_LEN = 45; + List lines = Lists.newArrayList(); + + while (input.length()>MAX_LEN){ + int idx = input.lastIndexOf(",", MAX_LEN); + if (idx>=0) { + lines.add( input.substring(0, idx+1).trim()); + input = input.substring(idx+1).trim(); + } else { + break; + } + } + lines.add(input.trim()); + + return lines; + } + + @Environment(EnvType.CLIENT) + static void appendHoverText(List list, String description) { + final int MAX_LINES = 7; + List lines = splitLines(description); + if (lines.size()==1) { + list.add(new TranslatableComponent("tooltip.bclib.place_on", lines.get(0)).withStyle(ChatFormatting.GREEN)); + } else if (lines.size()>1) { + list.add(new TranslatableComponent("tooltip.bclib.place_on", "").withStyle(ChatFormatting.GREEN)); + for (int i = 0; i < Math.min(lines.size(), MAX_LINES); i++) { + String line = lines.get(i); + if (i == MAX_LINES - 1 && i < lines.size() - 1) line += " ..."; + list.add(new TextComponent(" " + line).withStyle(ChatFormatting.GREEN)); + } + } + } + + boolean isSurvivable(BlockState state); + + default boolean canSurviveOnTop(BlockState state, LevelReader world, BlockPos pos) { + return isSurvivable(world.getBlockState(pos.below())); + } + + default boolean canSurviveOnBottom(BlockState state, LevelReader world, BlockPos pos) { + return isSurvivable(world.getBlockState(pos.above())); + } +} \ No newline at end of file diff --git a/src/main/java/ru/bclib/interfaces/SurvivesOnTags.java b/src/main/java/ru/bclib/interfaces/SurvivesOnTags.java new file mode 100644 index 00000000..fbd9d614 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/SurvivesOnTags.java @@ -0,0 +1,40 @@ +package ru.bclib.interfaces; + +import net.minecraft.core.Registry; +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.NetherrackBlock; +import net.minecraft.world.level.block.state.BlockState; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +public interface SurvivesOnTags extends SurvivesOnSpecialGround{ + List> getSurvivableTags(); + + @Override + default String getSurvivableBlocksString(){ + return getSurvivableTags() + .stream() + .map(tag -> Registry.BLOCK.getTag(tag)) + .filter(named->named.isPresent()) + .map(named->named.get()) + .flatMap(named->named.stream()) + .filter(block -> block != Blocks.AIR && block != null) + .map(block -> { + ItemStack stack = new ItemStack(block.value()); + if (stack.hasCustomHoverName()) return stack.getHoverName().getString(); + else return block.value().getName().getString(); + }) + .sorted(Comparator.naturalOrder()) + .collect(Collectors.joining(", ")); + } + + @Override + default boolean isSurvivable(BlockState state){ + return getSurvivableTags().stream().anyMatch(tag->state.is(tag)); + } +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableAxe.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableAxe.java new file mode 100644 index 00000000..e82ee451 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableAxe.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableAxe { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableHammer.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableHammer.java new file mode 100644 index 00000000..a88997bd --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableHammer.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableHammer { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableHoe.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableHoe.java new file mode 100644 index 00000000..3bd60291 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableHoe.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableHoe { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineablePickaxe.java b/src/main/java/ru/bclib/interfaces/tools/AddMineablePickaxe.java new file mode 100644 index 00000000..92fda1ea --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineablePickaxe.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineablePickaxe { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableShears.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableShears.java new file mode 100644 index 00000000..5a42b295 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableShears.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableShears { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableShovel.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableShovel.java new file mode 100644 index 00000000..cdd601f7 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableShovel.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableShovel { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/AddMineableSword.java b/src/main/java/ru/bclib/interfaces/tools/AddMineableSword.java new file mode 100644 index 00000000..f68e4500 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/AddMineableSword.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface AddMineableSword { +} diff --git a/src/main/java/ru/bclib/interfaces/tools/PreventMineableAdd.java b/src/main/java/ru/bclib/interfaces/tools/PreventMineableAdd.java new file mode 100644 index 00000000..a6f30fef --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/tools/PreventMineableAdd.java @@ -0,0 +1,4 @@ +package ru.bclib.interfaces.tools; + +public interface PreventMineableAdd { +} diff --git a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java index f0543c0f..bcac32bd 100644 --- a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java @@ -2,33 +2,18 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.tool.attribute.v1.DynamicAttributeTool; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.item.AxeItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Tier; -import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ItemModelProvider; -public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseAxeItem extends AxeItem implements ItemModelProvider { public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } - @Override - public int getMiningLevel(Tag tag, BlockState state, ItemStack stack, LivingEntity user) { - if (tag.equals(FabricToolTags.AXES)) { - return this.getTier().getLevel(); - } - return 0; - } - @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { diff --git a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java index 53be6e2d..5c458249 100644 --- a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java @@ -2,44 +2,18 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.tool.attribute.v1.DynamicAttributeTool; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -import net.fabricmc.fabric.impl.tool.attribute.ToolManagerImpl; -import net.fabricmc.fabric.impl.tool.attribute.ToolManagerImpl.Entry; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.Tier; -import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ItemModelProvider; -public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelProvider { +public class BasePickaxeItem extends PickaxeItem implements ItemModelProvider { public BasePickaxeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } - @Override - public int getMiningLevel(Tag tag, BlockState state, ItemStack stack, LivingEntity user) { - if (tag.equals(FabricToolTags.PICKAXES)) { - return getTier().getLevel(); - } - return 0; - } - - @Override - public float getDestroySpeed(ItemStack stack, BlockState state) { - Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.PICKAXES) >= 0) ? speed : super.getDestroySpeed( - stack, - state - ); - } - @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { diff --git a/src/main/java/ru/bclib/items/tool/BaseShearsItem.java b/src/main/java/ru/bclib/items/tool/BaseShearsItem.java index 002b46bf..61a29fab 100644 --- a/src/main/java/ru/bclib/items/tool/BaseShearsItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseShearsItem.java @@ -1,11 +1,13 @@ package ru.bclib.items.tool; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; + +import net.fabricmc.fabric.api.mininglevel.v1.FabricMineableTags; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.ShearsItem; import ru.bclib.api.tag.CommonItemTags; +import ru.bclib.api.tag.TagAPI; public class BaseShearsItem extends ShearsItem { public BaseShearsItem(Properties properties) { @@ -13,12 +15,12 @@ public BaseShearsItem(Properties properties) { } public static boolean isShear(ItemStack tool){ - return tool.is(Items.SHEARS) | tool.is(CommonItemTags.SHEARS) || tool.is(FabricToolTags.SHEARS); + return tool.is(Items.SHEARS) | tool.is(CommonItemTags.SHEARS) || TagAPI.isToolWithMineableTag(tool, FabricMineableTags.SHEARS_MINEABLE); } public static boolean isShear(ItemStack itemStack, Item item){ if (item == Items.SHEARS){ - return itemStack.is(item) | itemStack.is(CommonItemTags.SHEARS) || itemStack.is(FabricToolTags.SHEARS); + return itemStack.is(item) | itemStack.is(CommonItemTags.SHEARS); } else { return itemStack.is(item); } diff --git a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java index a987b68b..5c92008b 100644 --- a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java @@ -2,44 +2,18 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.tool.attribute.v1.DynamicAttributeTool; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -import net.fabricmc.fabric.impl.tool.attribute.ToolManagerImpl; -import net.fabricmc.fabric.impl.tool.attribute.ToolManagerImpl.Entry; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.Tier; -import net.minecraft.world.level.block.state.BlockState; import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ItemModelProvider; -public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseShovelItem extends ShovelItem implements ItemModelProvider { public BaseShovelItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } - @Override - public int getMiningLevel(Tag tag, BlockState state, ItemStack stack, LivingEntity user) { - if (tag.equals(FabricToolTags.SHOVELS)) { - return this.getTier().getLevel(); - } - return 0; - } - - @Override - public float getDestroySpeed(ItemStack stack, BlockState state) { - Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.SHOVELS) >= 0) ? speed : super.getDestroySpeed( - stack, - state - ); - } - @Override @Environment(EnvType.CLIENT) public BlockModel getItemModel(ResourceLocation resourceLocation) { diff --git a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java index c32addac..18aed8f7 100644 --- a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java @@ -2,7 +2,6 @@ import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.tool.attribute.v1.DynamicAttributeTool; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.SwordItem; @@ -10,7 +9,7 @@ import ru.bclib.client.models.ModelsHelper; import ru.bclib.interfaces.ItemModelProvider; -public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelProvider { +public class BaseSwordItem extends SwordItem implements ItemModelProvider { public BaseSwordItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } diff --git a/src/main/java/ru/bclib/mixin/client/BlockMixin.java b/src/main/java/ru/bclib/mixin/client/BlockMixin.java new file mode 100644 index 00000000..d4f92437 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/client/BlockMixin.java @@ -0,0 +1,25 @@ +package ru.bclib.mixin.client; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.BlockGetter; +import net.minecraft.world.level.block.Block; +import org.jetbrains.annotations.Nullable; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import ru.bclib.interfaces.SurvivesOnSpecialGround; + +import java.util.List; + +@Mixin(Block.class) +public class BlockMixin { + @Inject(method="appendHoverText", at=@At("HEAD")) + void bclib_appendSurvivalBlock(ItemStack itemStack, @Nullable BlockGetter blockGetter, List list, TooltipFlag tooltipFlag, CallbackInfo ci){ + if (this instanceof SurvivesOnSpecialGround surv){ + SurvivesOnSpecialGround.appendHoverText(list, surv.getSurvivableBlocksString()); + } + } +} diff --git a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java index 9ac56d2e..db8ddd23 100644 --- a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java @@ -15,13 +15,13 @@ public EnchantingTableBlockMixin(Properties settings) { super(settings); } - @Redirect(method = "animateTick", at = @At( + @Redirect(method = "isValidBookShelf", at = @At( value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/world/level/block/Block;)Z"), require = -1, expect = -1 ) - private boolean bclib_isBookshelf(BlockState state, Block block) { + private static boolean bclib_isBookshelf(BlockState state, Block block) { return block == Blocks.BOOKSHELF ? state.is(CommonBlockTags.BOOKSHELVES) : state.is(block); } } diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java index 87bce5f6..9ae7e755 100644 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java @@ -1,6 +1,5 @@ package ru.bclib.mixin.client; -import com.mojang.datafixers.util.Function4; import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft.ExperimentalDialogType; import net.minecraft.client.color.block.BlockColors; @@ -8,14 +7,11 @@ import net.minecraft.client.main.GameConfig; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; -import net.minecraft.core.RegistryAccess.RegistryHolder; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.level.DataPackConfig; +import net.minecraft.server.WorldStem; import net.minecraft.world.level.LevelSettings; import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; -import net.minecraft.world.level.storage.WorldData; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -44,17 +40,15 @@ public abstract class MinecraftMixin { @Inject(method = "*", at = @At("TAIL")) private void bclib_onMCInit(GameConfig args, CallbackInfo info) { Registry.BLOCK.forEach(block -> { - if (block instanceof CustomColorProvider) { - CustomColorProvider provider = (CustomColorProvider) block; + if (block instanceof CustomColorProvider provider) { blockColors.register(provider.getProvider(), block); itemColors.register(provider.getItemProvider(), block.asItem()); } }); } - - @Shadow - protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); - + + @Shadow protected abstract void doLoadLevel(String string, Function function, Function function2, boolean bl, ExperimentalDialogType experimentalDialogType); + @Shadow @Final private LevelStorageSource levelSource; @@ -66,7 +60,7 @@ private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { if (DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes) -> { LifeCycleAPI._runBeforeLevelLoad(); - this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, appliedFixes ? ExperimentalDialogType.NONE : ExperimentalDialogType.BACKUP); + this.doLoadLevel(levelID, WorldStem.DataPackConfigSupplier::loadFromWorld, WorldStem.WorldDataSupplier::loadFromWorld, false, appliedFixes ? ExperimentalDialogType.NONE : ExperimentalDialogType.BACKUP); })) { //cancle call when fix-screen is presented ci.cancel(); @@ -74,7 +68,7 @@ private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { else { LifeCycleAPI._runBeforeLevelLoad(); if (Configs.CLIENT_CONFIG.suppressExperimentalDialog()) { - this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, ExperimentalDialogType.NONE); + this.doLoadLevel(levelID, WorldStem.DataPackConfigSupplier::loadFromWorld, WorldStem.WorldDataSupplier::loadFromWorld, false, ExperimentalDialogType.NONE); //cancle call as we manually start the level load here ci.cancel(); } @@ -82,7 +76,7 @@ private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { } @Inject(method = "createLevel", at = @At("HEAD")) - private void bclib_initPatchData(String levelID, LevelSettings levelSettings, RegistryHolder registryHolder, WorldGenSettings worldGenSettings, CallbackInfo ci) { + private void bclib_initPatchData(String levelID, LevelSettings levelSettings, RegistryAccess registryAccess, WorldGenSettings worldGenSettings, CallbackInfo ci) { DataExchangeAPI.prepareServerside(); BiomeAPI.prepareNewLevel(); diff --git a/src/main/java/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java b/src/main/java/ru/bclib/mixin/client/MultiPackResourceManagerMixin.java similarity index 83% rename from src/main/java/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java rename to src/main/java/ru/bclib/mixin/client/MultiPackResourceManagerMixin.java index ed209646..f2bc7b61 100644 --- a/src/main/java/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java +++ b/src/main/java/ru/bclib/mixin/client/MultiPackResourceManagerMixin.java @@ -2,9 +2,9 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.FallbackResourceManager; +import net.minecraft.server.packs.resources.MultiPackResourceManager; import net.minecraft.server.packs.resources.Resource; import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.SimpleReloadableResourceManager; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -18,14 +18,14 @@ import java.io.IOException; import java.util.Map; -@Mixin(SimpleReloadableResourceManager.class) -public class SimpleReloadableResourceManagerMixin { +@Mixin(MultiPackResourceManager.class) +public class MultiPackResourceManagerMixin { @Final @Shadow - private Map namespacedPacks; - + private Map namespacedManagers; + private ResourceLocation bclib_alphaEmissionMaterial = BCLib.makeID("materialmaps/block/alpha_emission.json"); - + @Inject(method = "getResource", at = @At("HEAD"), cancellable = true) private void bclib_getResource(ResourceLocation resourceLocation, CallbackInfoReturnable info) throws IOException { if (!ModIntegrationAPI.hasCanvas()) { @@ -37,15 +37,15 @@ private void bclib_getResource(ResourceLocation resourceLocation, CallbackInfoRe if (!resourceLocation.getPath().contains("/block/")) { return; } - + String name = resourceLocation.getPath().replace("materialmaps/block/", "").replace(".json", ""); ResourceLocation blockID = new ResourceLocation(resourceLocation.getNamespace(), name); - + if (!EmissiveTextureInfo.isEmissiveBlock(blockID)) { return; } - - ResourceManager resourceManager = this.namespacedPacks.get(resourceLocation.getNamespace()); + + ResourceManager resourceManager = this.namespacedManagers.get(resourceLocation.getNamespace()); if (resourceManager != null && !resourceManager.hasResource(resourceLocation)) { info.setReturnValue(resourceManager.getResource(bclib_alphaEmissionMaterial)); } diff --git a/src/main/java/ru/bclib/mixin/client/WorldPresetMixin.java b/src/main/java/ru/bclib/mixin/client/WorldPresetMixin.java index b634e8ad..45021583 100644 --- a/src/main/java/ru/bclib/mixin/client/WorldPresetMixin.java +++ b/src/main/java/ru/bclib/mixin/client/WorldPresetMixin.java @@ -13,7 +13,7 @@ @Mixin(WorldPreset.class) public class WorldPresetMixin { @Inject(method = "create", at = @At("HEAD")) - private void bclib_create(RegistryAccess.RegistryHolder registryHolder, long l, boolean bl, boolean bl2, CallbackInfoReturnable info) { - BiomeAPI.initRegistry(registryHolder.registryOrThrow(Registry.BIOME_REGISTRY)); + private void bclib_create(RegistryAccess registryAccess, long l, boolean bl, boolean bl2, CallbackInfoReturnable info) { + BiomeAPI.initRegistry(registryAccess.registryOrThrow(Registry.BIOME_REGISTRY)); } } diff --git a/src/main/java/ru/bclib/mixin/common/BiomeAccessor.java b/src/main/java/ru/bclib/mixin/common/BiomeAccessor.java new file mode 100644 index 00000000..7d99eb24 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/BiomeAccessor.java @@ -0,0 +1,13 @@ +package ru.bclib.mixin.common; + +import net.minecraft.world.level.biome.Biome; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(Biome.class) +public interface BiomeAccessor { + @Accessor("biomeCategory") + @Mutable + Biome.BiomeCategory bclib_getBiomeCategory(); +} diff --git a/src/main/java/ru/bclib/mixin/common/BiomeGenerationSettingsAccessor.java b/src/main/java/ru/bclib/mixin/common/BiomeGenerationSettingsAccessor.java index fcb6ec6f..91f929b1 100644 --- a/src/main/java/ru/bclib/mixin/common/BiomeGenerationSettingsAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/BiomeGenerationSettingsAccessor.java @@ -1,9 +1,11 @@ package ru.bclib.mixin.common; +import net.minecraft.core.HolderSet; import net.minecraft.world.level.biome.BiomeGenerationSettings; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.GenerationStep.Carving; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; @@ -17,21 +19,21 @@ @Mixin(BiomeGenerationSettings.class) public interface BiomeGenerationSettingsAccessor { @Accessor("features") - List>> bclib_getFeatures(); + List> bclib_getFeatures(); @Accessor("features") @Mutable - void bclib_setFeatures(List>> value); + void bclib_setFeatures(List> value); @Accessor("featureSet") - Set bclib_getFeatureSet(); - - @Accessor("featureSet") - void bclib_setFeatureSet(Set features); + void bclib_setFeatureSet(Supplier> featureSet); + + @Accessor("flowerFeatures") + void bclib_setFlowerFeatures(Supplier>> flowerFeatures); @Accessor("carvers") - Map>>> bclib_getCarvers(); + Map>> bclib_getCarvers(); @Accessor("carvers") - void bclib_setCarvers(Map>>> features); + void bclib_setCarvers(Map>> features); } diff --git a/src/main/java/ru/bclib/mixin/common/BiomeSourceMixin.java b/src/main/java/ru/bclib/mixin/common/BiomeSourceMixin.java index d407b585..5372c899 100644 --- a/src/main/java/ru/bclib/mixin/common/BiomeSourceMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BiomeSourceMixin.java @@ -1,5 +1,6 @@ package ru.bclib.mixin.common; +import com.google.common.base.Suppliers; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.BiomeSource.StepFeatureData; @@ -12,6 +13,7 @@ import java.util.List; import java.util.Set; +import java.util.function.Supplier; @Mixin(BiomeSource.class) public abstract class BiomeSourceMixin implements BiomeSourceAccessor { @@ -19,10 +21,10 @@ public abstract class BiomeSourceMixin implements BiomeSourceAccessor { @Shadow public abstract Set possibleBiomes(); - @Mutable @Shadow @Final private List featuresPerStep; + @Mutable @Shadow @Final private Supplier> featuresPerStep; public void bclRebuildFeatures(){ BCLib.LOGGER.info("Rebuilding features in BiomeSource " + this); - featuresPerStep = buildFeaturesPerStep(this.possibleBiomes().stream().toList(), true); + featuresPerStep = Suppliers.memoize(() -> buildFeaturesPerStep(this.possibleBiomes().stream().toList(), true)); } } diff --git a/src/main/java/ru/bclib/mixin/common/ChunkGeneratorMixin.java b/src/main/java/ru/bclib/mixin/common/ChunkGeneratorMixin.java index 9c6058ac..c72d2676 100644 --- a/src/main/java/ru/bclib/mixin/common/ChunkGeneratorMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ChunkGeneratorMixin.java @@ -1,17 +1,23 @@ package ru.bclib.mixin.common; +import net.minecraft.core.Registry; import net.minecraft.world.level.StructureFeatureManager; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.levelgen.structure.StructureSet; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyArg; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import ru.bclib.interfaces.ChunkGeneratorAccessor; @Mixin(ChunkGenerator.class) -public class ChunkGeneratorMixin { +public class ChunkGeneratorMixin implements ChunkGeneratorAccessor { + @Shadow @Final protected Registry structureSets; private int bclib_featureIteratorSeed; @ModifyArg(method = "applyBiomeDecoration", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/WorldgenRandom;setFeatureSeed(JII)V")) @@ -23,4 +29,8 @@ private long bclib_updateFeatureSeed(long seed) { private void bclib_obBiomeGenerate(WorldGenLevel worldGenLevel, ChunkAccess chunkAccess, StructureFeatureManager structureFeatureManager, CallbackInfo ci) { bclib_featureIteratorSeed = 0; } + + public Registry bclib_getStructureSetsRegistry(){ + return structureSets; + } } diff --git a/src/main/java/ru/bclib/mixin/common/DiggerItemAccessor.java b/src/main/java/ru/bclib/mixin/common/DiggerItemAccessor.java new file mode 100644 index 00000000..8102ce94 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/DiggerItemAccessor.java @@ -0,0 +1,21 @@ +package ru.bclib.mixin.common; + +import net.minecraft.tags.TagKey; +import net.minecraft.world.item.DiggerItem; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.levelgen.placement.PlacedFeature; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Mutable; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.gen.Accessor; + +import java.util.List; +import java.util.function.Supplier; + +@Mixin(DiggerItem.class) +public interface DiggerItemAccessor { + @Accessor("blocks") + @Mutable + TagKey bclib_getBlockTag(); +} diff --git a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java b/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java index 3b73c4bf..7618432a 100644 --- a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java +++ b/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java @@ -4,12 +4,17 @@ import net.minecraft.core.MappedRegistry; import net.minecraft.core.Registry; import net.minecraft.core.RegistryAccess; +import net.minecraft.core.WritableRegistry; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.BiomeSource; +import net.minecraft.world.level.biome.MultiNoiseBiomeSource; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.synth.NormalNoise; +import org.jetbrains.annotations.NotNull; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -23,41 +28,42 @@ @Mixin(DimensionType.class) public class DimensionTypeMixin { @Inject( - method = "defaultDimensions(Lnet/minecraft/core/RegistryAccess;JZ)Lnet/minecraft/core/MappedRegistry;", + method = "defaultDimensions(Lnet/minecraft/core/RegistryAccess;JZ)Lnet/minecraft/core/Registry;", locals = LocalCapture.CAPTURE_FAILHARD, at = @At("TAIL") ) - private static void bclib_updateDimensions(RegistryAccess registryAccess, long seed, boolean bl, CallbackInfoReturnable> info, MappedRegistry mappedRegistry, Registry registry, Registry biomeRegistry, Registry noiseSettingsRegistry, Registry noiseParamRegistry) { - int id = mappedRegistry.getId(mappedRegistry.get(LevelStem.NETHER)); - mappedRegistry.registerOrOverride( - OptionalInt.of(id), - LevelStem.NETHER, - new LevelStem( - () -> registry.getOrThrow(DimensionType.NETHER_LOCATION), - new NoiseBasedChunkGenerator( - noiseParamRegistry, - new BCLibNetherBiomeSource(biomeRegistry, seed), - seed, - () -> noiseSettingsRegistry.getOrThrow(NoiseGeneratorSettings.NETHER) - ) - ), - Lifecycle.stable() + private static void bclib_updateDimensions(RegistryAccess registryAccess, long seed, boolean bl, CallbackInfoReturnable info, WritableRegistry writableRegistry, Registry registry, Registry biomeRegistry, Registry structureRegistry, Registry noiseSettingsRegistry, Registry noiseParamRegistry) { + int id = writableRegistry.getId(writableRegistry.get(LevelStem.NETHER)); + writableRegistry.registerOrOverride( + OptionalInt.of(id), + LevelStem.NETHER, + new LevelStem( + registry.getOrCreateHolder(DimensionType.NETHER_LOCATION), + new NoiseBasedChunkGenerator( + structureRegistry, + noiseParamRegistry, + new BCLibNetherBiomeSource(biomeRegistry, seed), + seed, + noiseSettingsRegistry.getOrCreateHolder(NoiseGeneratorSettings.NETHER)) + ), + Lifecycle.stable() ); - - id = mappedRegistry.getId(mappedRegistry.get(LevelStem.END)); - mappedRegistry.registerOrOverride( - OptionalInt.of(id), - LevelStem.END, - new LevelStem( - () -> registry.getOrThrow(DimensionType.END_LOCATION), - new NoiseBasedChunkGenerator( - noiseParamRegistry, - new BCLibEndBiomeSource(biomeRegistry, seed), - seed, - () -> noiseSettingsRegistry.getOrThrow(NoiseGeneratorSettings.END) - ) - ), - Lifecycle.stable() + + + id = writableRegistry.getId(writableRegistry.get(LevelStem.END)); + writableRegistry.registerOrOverride( + OptionalInt.of(id), + LevelStem.END, + new LevelStem( + registry.getOrCreateHolder(DimensionType.END_LOCATION), + new NoiseBasedChunkGenerator( + structureRegistry, + noiseParamRegistry, + new BCLibEndBiomeSource(biomeRegistry, seed), + seed, + noiseSettingsRegistry.getOrCreateHolder(NoiseGeneratorSettings.END)) + ), + Lifecycle.stable() ); } } diff --git a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java deleted file mode 100644 index 6e33274f..00000000 --- a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java +++ /dev/null @@ -1,29 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.EnchantmentMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; -import ru.bclib.api.tag.CommonBlockTags; - -@Mixin(EnchantmentMenu.class) -public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { - protected EnchantmentMenuMixin(MenuType type, int syncId) { - super(type, syncId); - } - - @Redirect(method = "lambda$slotsChanged$0(Lnet/minecraft/world/item/ItemStack;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V", at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/level/block/state/BlockState;is(Lnet/minecraft/world/level/block/Block;)Z"), - require = -1, - expect = -1 - ) - private boolean bclib_isBookshelf(BlockState state, Block block) { - return block == Blocks.BOOKSHELF ? state.is(CommonBlockTags.BOOKSHELVES) : state.is(block); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index da5ce859..98872a24 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -3,10 +3,9 @@ import com.mojang.authlib.GameProfileRepository; import com.mojang.authlib.minecraft.MinecraftSessionService; import com.mojang.datafixers.DataFixer; -import net.minecraft.core.RegistryAccess.RegistryHolder; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerResources; +import net.minecraft.server.WorldStem; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.progress.ChunkProgressListenerFactory; import net.minecraft.server.packs.repository.PackRepository; @@ -32,7 +31,7 @@ @Mixin(MinecraftServer.class) public class MinecraftServerMixin { @Shadow - private ServerResources resources; + private MinecraftServer.ReloadableResources resources; @Final @Shadow @@ -43,7 +42,7 @@ public class MinecraftServerMixin { protected WorldData worldData; @Inject(method = "*", at = @At("TAIL")) - private void bclib_onServerInit(Thread thread, RegistryHolder registryHolder, LevelStorageAccess levelStorageAccess, WorldData worldData, PackRepository packRepository, Proxy proxy, DataFixer dataFixer, ServerResources serverResources, MinecraftSessionService minecraftSessionService, GameProfileRepository gameProfileRepository, GameProfileCache gameProfileCache, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) { + private void bclib_onServerInit(Thread thread, LevelStorageAccess levelStorageAccess, PackRepository packRepository, WorldStem worldStem, Proxy proxy, DataFixer dataFixer, MinecraftSessionService minecraftSessionService, GameProfileRepository gameProfileRepository, GameProfileCache gameProfileCache, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) { DataExchangeAPI.prepareServerside(); } @@ -58,7 +57,7 @@ private void bclib_loadLevel(CallbackInfo info) { } private void bclib_injectRecipes() { - RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); + RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.managers().getRecipeManager(); accessor.bclib_setRecipesByName(BCLRecipeManager.getMapByName(accessor.bclib_getRecipesByName())); accessor.bclib_setRecipes(BCLRecipeManager.getMap(accessor.bclib_getRecipes())); } diff --git a/src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java b/src/main/java/ru/bclib/mixin/common/MultiPackResourceManagerMixin.java similarity index 67% rename from src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java rename to src/main/java/ru/bclib/mixin/common/MultiPackResourceManagerMixin.java index d2ff94df..09365589 100644 --- a/src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MultiPackResourceManagerMixin.java @@ -1,30 +1,21 @@ package ru.bclib.mixin.common; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.FallbackResourceManager; -import net.minecraft.server.packs.resources.SimpleReloadableResourceManager; -import org.spongepowered.asm.mixin.Final; +import net.minecraft.server.packs.resources.MultiPackResourceManager; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; -import java.util.Map; - -@Mixin(SimpleReloadableResourceManager.class) -public class SimpleReloadableResourceManagerMixin { - @Final - @Shadow - private Map namespacedPacks; - +@Mixin(MultiPackResourceManager.class) +public class MultiPackResourceManagerMixin { private static final String[] BCLIB_MISSING_RESOURCES = new String[] { "dimension/the_end.json", "dimension/the_nether.json", "dimension_type/the_end.json", "dimension_type/the_nether.json" }; - + @Inject(method = "hasResource", at = @At("HEAD"), cancellable = true) private void bclib_hasResource(ResourceLocation resourceLocation, CallbackInfoReturnable info) { if (resourceLocation.getNamespace().equals("minecraft")) { diff --git a/src/main/java/ru/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java b/src/main/java/ru/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java index 04a78e74..f2e20e72 100644 --- a/src/main/java/ru/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java +++ b/src/main/java/ru/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java @@ -1,18 +1,15 @@ package ru.bclib.mixin.common; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.StructureFeatureManager; import net.minecraft.world.level.biome.Biome; +import net.minecraft.world.level.biome.Climate; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.levelgen.Aquifer; -import net.minecraft.world.level.levelgen.Beardifier; -import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; -import net.minecraft.world.level.levelgen.NoiseChunk; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.NoiseSampler; +import net.minecraft.world.level.levelgen.*; import net.minecraft.world.level.levelgen.blending.Blender; import net.minecraft.world.level.levelgen.carver.CarvingContext; import org.spongepowered.asm.mixin.Final; @@ -30,11 +27,13 @@ public abstract class NoiseBasedChunkGeneratorMixin implements SurfaceProvider, NoiseGeneratorSettingsProvider { @Final @Shadow - private NoiseSampler sampler; - + private Climate.Sampler sampler; + + @Shadow @Final private NoiseRouter router; + @Final @Shadow - protected Supplier settings; + protected Holder settings; @Final @Shadow @@ -45,12 +44,12 @@ public abstract class NoiseBasedChunkGeneratorMixin implements SurfaceProvider, @Override public NoiseGeneratorSettings bclib_getNoiseGeneratorSettings(){ - return settings.get(); + return settings.value(); } @Override @SuppressWarnings("deprecation") - public BlockState bclib_getSurface(BlockPos pos, Biome biome, ServerLevel level) { + public BlockState bclib_getSurface(BlockPos pos, Holder biome, ServerLevel level) { ChunkAccess chunkAccess = level.getChunk(pos.getX() >> 4, pos.getZ() >> 4); StructureFeatureManager structureFeatureManager = level.structureFeatureManager(); NoiseBasedChunkGenerator generator = NoiseBasedChunkGenerator.class.cast(this); @@ -72,7 +71,7 @@ public BlockState bclib_getSurface(BlockPos pos, Biome biome, ServerLevel level) } Beardifier finalBeardifier = beardifier; - NoiseChunk noiseChunk = chunkAccess.getOrCreateNoiseChunk(this.sampler, () -> finalBeardifier, this.settings.get(), this.globalFluidPicker, Blender.empty()); + NoiseChunk noiseChunk = chunkAccess.getOrCreateNoiseChunk(router, () -> finalBeardifier, this.settings.value(), this.globalFluidPicker, Blender.empty()); CarvingContext carvingContext = new CarvingContext(generator, level.registryAccess(), chunkAccess.getHeightAccessorForGeneration(), noiseChunk); Optional optional = carvingContext.topMaterial(bpos -> biome, chunkAccess, pos, false); return optional.isPresent() ? optional.get() : bclib_air; diff --git a/src/main/java/ru/bclib/mixin/common/NoiseGeneratorSettingsMixin.java b/src/main/java/ru/bclib/mixin/common/NoiseGeneratorSettingsMixin.java index da9a6a4a..ad9d921d 100644 --- a/src/main/java/ru/bclib/mixin/common/NoiseGeneratorSettingsMixin.java +++ b/src/main/java/ru/bclib/mixin/common/NoiseGeneratorSettingsMixin.java @@ -26,14 +26,14 @@ public class NoiseGeneratorSettingsMixin implements SurfaceRuleProvider { private SurfaceRules.RuleSource bclib_originalSurfaceRule; private Set bclib_biomeSources = new HashSet<>(); - private void bclib_updateCutomRules(){ + private void bclib_updateCustomRules(){ bclib_setCustomRules(BiomeAPI.getRuleSources(bclib_biomeSources)); } @Override public void bclib_addBiomeSource(BiomeSource source) { bclib_biomeSources.add(source); - bclib_updateCutomRules(); + bclib_updateCustomRules(); } @Override diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java index 70b8878d..10c85644 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java @@ -27,7 +27,7 @@ private > Map> void bclib_getRecipeFor(RecipeType type, C inventory, Level world, CallbackInfoReturnable> info) { + private > void bclib_getRecipeFor(RecipeType type, C inventory, Level level, CallbackInfoReturnable> info) { Collection> values = byType(type).values(); List> list = new ArrayList<>(values); list.sort((v1, v2) -> { @@ -35,6 +35,6 @@ private > void bclib_getRecipeFor(Recip boolean b2 = v2.getId().getNamespace().equals("minecraft"); return b1 ^ b2 ? (b1 ? 1 : -1) : 0; }); - info.setReturnValue(list.stream().flatMap((recipe) -> Util.toStream(type.tryMatch(recipe, world, inventory))).findFirst()); + info.setReturnValue(list.stream().flatMap(recipe -> type.tryMatch(recipe, level, inventory).stream()).findFirst()); } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 1bd6050d..15d46beb 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -1,5 +1,6 @@ package ru.bclib.mixin.common; +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -9,6 +10,7 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.dimension.DimensionType; +import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; import net.minecraft.world.level.storage.ServerLevelData; import net.minecraft.world.level.storage.WritableLevelData; @@ -28,12 +30,12 @@ public abstract class ServerLevelMixin extends Level { private static String bclib_lastWorld = null; - protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { + protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, Holder dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(writableLevelData, resourceKey, dimensionType, supplier, bl, bl2, l); } @Inject(method = "*", at = @At("TAIL")) - private void bclib_onServerWorldInit(MinecraftServer server, Executor executor, LevelStorageAccess levelStorageAccess, ServerLevelData serverLevelData, ResourceKey resourceKey, DimensionType dimensionType, ChunkProgressListener chunkProgressListener, ChunkGenerator chunkGenerator, boolean bl, long l, List list, boolean bl2, CallbackInfo info) { + private void bclib_onServerWorldInit(MinecraftServer server, Executor executor, LevelStorageAccess levelStorageAccess, ServerLevelData serverLevelData, ResourceKey resourceKey, Holder dimensionType, ChunkProgressListener chunkProgressListener, ChunkGenerator chunkGenerator, boolean bl, long l, List list, boolean bl2, CallbackInfo ci) { ServerLevel level = ServerLevel.class.cast(this); LifeCycleAPI._runLevelLoad(level, server, executor, levelStorageAccess, serverLevelData, resourceKey, dimensionType, chunkProgressListener, chunkGenerator, bl, l, list, bl2); diff --git a/src/main/java/ru/bclib/mixin/common/StructureFeatureAccessor.java b/src/main/java/ru/bclib/mixin/common/StructureFeatureAccessor.java new file mode 100644 index 00000000..03a5a498 --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/StructureFeatureAccessor.java @@ -0,0 +1,14 @@ +package ru.bclib.mixin.common; + +import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(StructureFeature.class) +public interface StructureFeatureAccessor { + @Invoker + static > F callRegister(String name, F structureFeature, GenerationStep.Decoration step) { + throw new RuntimeException("Unexpected call"); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/StructureFeaturesAccessor.java b/src/main/java/ru/bclib/mixin/common/StructureFeaturesAccessor.java new file mode 100644 index 00000000..5ba97fdd --- /dev/null +++ b/src/main/java/ru/bclib/mixin/common/StructureFeaturesAccessor.java @@ -0,0 +1,19 @@ +package ru.bclib.mixin.common; + +import net.minecraft.core.Holder; +import net.minecraft.data.worldgen.StructureFeatures; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.level.levelgen.GenerationStep; +import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; +import net.minecraft.world.level.levelgen.feature.StructureFeature; +import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + +@Mixin(StructureFeatures.class) +public interface StructureFeaturesAccessor { + @Invoker + static > Holder> callRegister(ResourceKey> resourceKey, ConfiguredStructureFeature configuredStructureFeature) { + throw new RuntimeException("Unexpected call"); + } +} diff --git a/src/main/java/ru/bclib/mixin/common/StructureSettingsAccessor.java b/src/main/java/ru/bclib/mixin/common/StructureSettingsAccessor.java deleted file mode 100644 index bd3dc67a..00000000 --- a/src/main/java/ru/bclib/mixin/common/StructureSettingsAccessor.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.bclib.mixin.common; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.StructureSettings; -import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; -import net.minecraft.world.level.levelgen.feature.StructureFeature; -import net.minecraft.world.level.levelgen.feature.configurations.StructureFeatureConfiguration; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(StructureSettings.class) -public interface StructureSettingsAccessor { - @Accessor("configuredStructures") - ImmutableMap, ImmutableMultimap, ResourceKey>> bcl_getConfiguredStructures(); - - @Accessor("structureConfig") - Map, StructureFeatureConfiguration> bcl_getStructureConfig(); - - @Accessor("configuredStructures") - @Mutable - void bcl_setConfiguredStructures(ImmutableMap, ImmutableMultimap, ResourceKey>> configuredStructures); - - @Accessor("structureConfig") - @Mutable - void bcl_setStructureConfig(Map, StructureFeatureConfiguration> structureConfig); -} diff --git a/src/main/java/ru/bclib/mixin/common/SurfaceRulesContextAccessor.java b/src/main/java/ru/bclib/mixin/common/SurfaceRulesContextAccessor.java index b1bd7a6b..2e2e93be 100644 --- a/src/main/java/ru/bclib/mixin/common/SurfaceRulesContextAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/SurfaceRulesContextAccessor.java @@ -1,5 +1,6 @@ package ru.bclib.mixin.common; +import net.minecraft.core.Holder; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.chunk.ChunkAccess; @@ -25,10 +26,7 @@ public interface SurfaceRulesContextAccessor { int getSurfaceDepth(); @Accessor("biome") - Supplier getBiome(); - - @Accessor("biomeKey") - Supplier> getBiomeKey(); + Supplier> getBiome(); @Accessor("chunk") ChunkAccess getChunk(); diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index a5fd7f45..46b83f7a 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -3,6 +3,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; import net.minecraft.tags.TagLoader; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; @@ -13,10 +14,11 @@ @Mixin(TagLoader.class) public class TagLoaderMixin { + @Final @Shadow private String directory; - @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) + @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Ljava/util/Map;")) public Map be_modifyTags(Map tagsMap) { return TagAPI.apply(directory, tagsMap); } diff --git a/src/main/java/ru/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java b/src/main/java/ru/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java index 566f6ed0..eed9de92 100644 --- a/src/main/java/ru/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java @@ -1,6 +1,5 @@ package ru.bclib.mixin.common.shears; -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.advancements.critereon.ItemPredicate; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; @@ -24,7 +23,7 @@ public abstract class ItemPredicateBuilderMixin { @Inject(method = "matches", at = @At("HEAD"), cancellable = true) void bclib_of(ItemStack itemStack, CallbackInfoReturnable cir) { if (this.items != null && this.items.size() == 1 && this.items.contains(Items.SHEARS)) { - if (itemStack.is(CommonItemTags.SHEARS) || itemStack.is(FabricToolTags.SHEARS)){ + if (itemStack.is(CommonItemTags.SHEARS) ){ cir.setReturnValue(true); } } diff --git a/src/main/java/ru/bclib/recipes/AnvilRecipe.java b/src/main/java/ru/bclib/recipes/AnvilRecipe.java index 28343417..c40ca868 100644 --- a/src/main/java/ru/bclib/recipes/AnvilRecipe.java +++ b/src/main/java/ru/bclib/recipes/AnvilRecipe.java @@ -4,12 +4,16 @@ import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider; import net.minecraft.core.NonNullList; +import net.minecraft.core.Registry; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.TagParser; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; +import net.minecraft.tags.TagKey; import net.minecraft.util.GsonHelper; import net.minecraft.world.Container; import net.minecraft.world.InteractionHand; @@ -42,6 +46,10 @@ public class AnvilRecipe implements Recipe, UnknownReceipBookCategory ); public final static ResourceLocation ID = BCLib.makeID(GROUP); + public static void register(){ + + } + private final ResourceLocation id; private final Ingredient input; private final ItemStack output; @@ -116,7 +124,8 @@ public boolean checkHammerDurability(Container craftingInventory, Player player) public boolean matches(Container craftingInventory) { ItemStack hammer = craftingInventory.getItem(1); - if (hammer.isEmpty() || !CommonItemTags.HAMMERS.contains(hammer.getItem())) { + //TODO: 1.18.2 Test if hammer still works + if (hammer.isEmpty() || !hammer.is(CommonItemTags.HAMMERS)) { return false; } ItemStack material = craftingInventory.getItem(0); @@ -139,12 +148,13 @@ public int getAnvilLevel() { @Override public NonNullList getIngredients() { + ; NonNullList defaultedList = NonNullList.create(); - defaultedList.add(Ingredient.of(CommonItemTags.HAMMERS - .getValues() - .stream() - .filter(hammer -> ((TieredItem) hammer).getTier().getLevel() >= toolLevel) - .map(ItemStack::new))); + defaultedList.add(Ingredient.of(Registry.ITEM.stream() + .filter(item->item.builtInRegistryHolder().is(CommonItemTags.HAMMERS)) + .filter(hammer -> ((TieredItem) hammer).getTier().getLevel() >= toolLevel) + .map(ItemStack::new)) + ); defaultedList.add(input); return defaultedList; } @@ -209,7 +219,7 @@ public Builder setInput(ItemLike... inputItems) { return this; } - public Builder setInput(Tag inputTag) { + public Builder setInput(TagKey inputTag) { this.setInput(Ingredient.of(inputTag)); return this; } diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index 4a1c6155..3af5b4d1 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -4,6 +4,7 @@ import net.minecraft.core.NonNullList; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.CraftingRecipe; @@ -74,7 +75,7 @@ public GridRecipe setList(String shape) { return this; } - public GridRecipe addMaterial(char key, Tag value) { + public GridRecipe addMaterial(char key, TagKey value) { return addMaterial(key, Ingredient.of(value)); } diff --git a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java index dc9ad9b7..a981d18a 100644 --- a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java +++ b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java @@ -2,6 +2,7 @@ import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; +import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.Ingredient; @@ -59,7 +60,7 @@ public SmithingTableRecipe setBase(ItemLike... items) { return this; } - public SmithingTableRecipe setBase(Tag tag) { + public SmithingTableRecipe setBase(TagKey tag) { this.base = (Ingredient.of(tag)); return this; } @@ -70,7 +71,7 @@ public SmithingTableRecipe setAddition(ItemLike... items) { return this; } - public SmithingTableRecipe setAddition(Tag tag) { + public SmithingTableRecipe setAddition(TagKey tag) { this.addition = (Ingredient.of(tag)); return this; } diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java index 5d46ca92..8652b471 100644 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ b/src/main/java/ru/bclib/registry/ItemRegistry.java @@ -44,8 +44,8 @@ public Item registerDisc(ResourceLocation itemId, int power, SoundEvent sound) { if (!config.getBoolean("musicDiscs", itemId.getPath(), true)) { return item; } - - return register(itemId, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); + register(itemId, item); + return item; } public Item register(ResourceLocation itemId) { diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiome.java b/src/main/java/ru/bclib/world/biomes/BCLBiome.java index bbfdafaa..c5f5b5fd 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiome.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiome.java @@ -2,10 +2,13 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.TagKey; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.GenerationStep.Decoration; import net.minecraft.world.level.levelgen.SurfaceRules; @@ -15,25 +18,25 @@ import org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; import ru.bclib.api.biomes.BiomeAPI; +import ru.bclib.api.tag.TagAPI; import ru.bclib.util.WeightedList; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; +import java.util.Set; import java.util.function.Consumer; -import java.util.function.Supplier; public class BCLBiome extends BCLBiomeSettings { - private final List structures = Lists.newArrayList(); + private final Set> structureTags = Sets.newHashSet(); private final WeightedList subbiomes = new WeightedList<>(); private final Map customData = Maps.newHashMap(); private final ResourceLocation biomeID; private final Biome biome; - private Consumer surfaceInit; + private Consumer> surfaceInit; private BCLBiome biomeParent; - private Biome actualBiome; + private Holder actualBiome; /** * Create wrapper for existing biome using its {@link ResourceLocation} identifier. @@ -65,7 +68,7 @@ public BCLBiome(Biome biome) { * @param settings The Settings for this Biome or {@code null} if you want to apply default settings */ public BCLBiome(Biome biome, VanillaBiomeSettings settings) { - this(BuiltinRegistries.BIOME.getKey(biome), biome, settings); + this(BiomeAPI.getBiomeID(biome), biome, settings); } public BCLBiome(ResourceLocation biomeID, Biome biome) { @@ -164,7 +167,10 @@ public ResourceLocation getID() { return biomeID; } - + + public Holder getBiomeHolder() { + return BuiltinRegistries.BIOME.getOrCreateHolder(BiomeAPI.getBiomeKey(biome)); + } /** * Getter for biome from buil-in registry. For datapack biomes will be same as actual biome. * @return {@link Biome}. @@ -177,7 +183,7 @@ public Biome getBiome() { * Getter for actual biome (biome from current world registry with same {@link ResourceLocation} id). * @return {@link Biome}. */ - public Biome getActualBiome() { + public Holder getActualBiome() { return this.actualBiome; } @@ -196,19 +202,23 @@ public void updateActualBiomes(Registry biomeRegistry) { if (edge != null && edge != this) { edge.updateActualBiomes(biomeRegistry); } - this.actualBiome = biomeRegistry.get(biomeID); + + final ResourceKey key = biomeRegistry.getResourceKey(biomeRegistry.get(biomeID)).orElseThrow(); + this.actualBiome = biomeRegistry.getOrCreateHolder(key); if (actualBiome==null) { BCLib.LOGGER.error("Unable to find actual Biome for " + biomeID); } - if (!this.structures.isEmpty()) { - structures.forEach(s -> BiomeAPI.addBiomeStructure(BiomeAPI.getBiomeKey(actualBiome), s)); + if (!this.structureTags.isEmpty()) { + structureTags.forEach(tagKey -> TagAPI.addBiomeTag(tagKey, actualBiome.value())); } if (this.surfaceInit != null) { surfaceInit.accept(actualBiome); } } + + /** * Getter for custom data. Will get custom data object or null if object doesn't exists. @@ -276,8 +286,8 @@ public String toString() { * Adds structures to this biome. For internal use only. * Used inside {@link ru.bclib.api.biomes.BCLBiomeBuilder}. */ - public void attachStructures(List structures) { - this.structures.addAll(structures); + public void attachStructures(List> structures) { + this.structureTags.addAll(structures); } /** @@ -295,25 +305,7 @@ public void setSurface(RuleSource surface) { } }; } - - private Map>> features = new HashMap<>(0); - - /** - * Sets the biome features. - * @param features the feature list. - */ - public void setFeatures(Map>> features) { - this.features = features; - } - - /** - * Returns the built-in set of Features for this biome (as they were set with {@link #setFeatures(Map)}) - * @return List of all features - */ - public Map>> getFeatures(){ - return features; - } - + /** * Returns the group used in the config Files for this biome * diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index fef17cda..771016bb 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -1,40 +1,59 @@ package ru.bclib.world.features; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; +import net.minecraft.data.worldgen.features.FeatureUtils; +import net.minecraft.data.worldgen.placement.PlacementUtils; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.GenerationStep.Decoration; -import net.minecraft.world.level.levelgen.VerticalAnchor; +import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.Feature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.HeightRangePlacement; import net.minecraft.world.level.levelgen.placement.PlacedFeature; import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import ru.bclib.api.features.BCLCommonFeatures; import java.util.Map.Entry; import java.util.Optional; public class BCLFeature { - private PlacedFeature placedFeature; - private Decoration featureStep; - private Feature feature; - - public BCLFeature(ResourceLocation id, Feature feature, Decoration featureStep, PlacedFeature placedFeature) { + private final Holder placedFeature; + private final Decoration featureStep; + private final Feature feature; + + + public> BCLFeature(ResourceLocation id, F feature, Decoration featureStep, FC configuration, PlacementModifier[] modifiers) { + this(id, feature, featureStep, buildPlacedFeature(id, feature, configuration, modifiers)); + } + + public BCLFeature(ResourceLocation id, Feature feature, Decoration featureStep, Holder placedFeature) { this.placedFeature = placedFeature; this.featureStep = featureStep; this.feature = feature; - + if (!BuiltinRegistries.PLACED_FEATURE.containsKey(id)) { - Registry.register(BuiltinRegistries.PLACED_FEATURE, id, placedFeature); + Registry.register(BuiltinRegistries.PLACED_FEATURE, id, placedFeature.value()); } if (!Registry.FEATURE.containsKey(id) && !containsObj(Registry.FEATURE, feature)) { Registry.register(Registry.FEATURE, id, feature); } } + + private static > Holder buildPlacedFeature(ResourceLocation id, F feature, FC configuration, PlacementModifier[] modifiers) { + Holder> configuredFeature; + if (!BuiltinRegistries.CONFIGURED_FEATURE.containsKey(id)) { + configuredFeature = (Holder>)(Object)FeatureUtils.register(id.toString(), feature, configuration); + } else { + configuredFeature = BuiltinRegistries.CONFIGURED_FEATURE.getHolder(ResourceKey.create(BuiltinRegistries.CONFIGURED_FEATURE.key(), id)).orElseThrow(); + } + + if (!BuiltinRegistries.PLACED_FEATURE.containsKey(id)) { + return PlacementUtils.register(id.toString(), configuredFeature, modifiers); + } else { + return BuiltinRegistries.PLACED_FEATURE.getHolder(ResourceKey.create(BuiltinRegistries.PLACED_FEATURE.key(), id)).orElseThrow(); + } + } private static boolean containsObj(Registry registry, E obj) { Optional, E>> optional = registry @@ -57,7 +76,7 @@ public Feature getFeature() { * Get configured feature. * @return {@link PlacedFeature}. */ - public PlacedFeature getPlacedFeature() { + public Holder getPlacedFeature() { return placedFeature; } @@ -68,92 +87,4 @@ public PlacedFeature getPlacedFeature() { public Decoration getDecoration() { return featureStep; } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density) { - return BCLCommonFeatures.makeVegetationFeature(id, feature, density); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density, boolean allHeight) { - return BCLCommonFeatures.makeVegetationFeature(id, feature, density, allHeight); - } - - /** - * Deprecated, moved to {@link BCLCommonFeatures}. Will be completely removed. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, Block hostBlock, int veins, int veinSize, float airDiscardChance, VerticalAnchor minY, VerticalAnchor maxY, boolean rare) { - return BCLCommonFeatures.makeOreFeature(id, blockOre, hostBlock, veins, veinSize, airDiscardChance, HeightRangePlacement.uniform(minY, maxY), rare); - } - - /** - * Deprecated, moved to {@link BCLCommonFeatures}. Will be completely removed. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, Block hostBlock, int veins, int veinSize, VerticalAnchor minY, VerticalAnchor maxY, boolean rare) { - return BCLCommonFeatures.makeOreFeature(id, blockOre, hostBlock, veins, veinSize, 0.0f, HeightRangePlacement.uniform(minY, maxY), rare); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, Block hostBlock, int veins, int veinSize, float airDiscardChance, PlacementModifier placement, boolean rare) { - return BCLCommonFeatures.makeOreFeature(id, blockOre, hostBlock, veins, veinSize, airDiscardChance, placement, rare); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, Block hostBlock, int veins, int veinSize, PlacementModifier placement, boolean rare) { - return BCLCommonFeatures.makeOreFeature(id, blockOre, hostBlock, veins, veinSize, 0.0f, placement, rare); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeChunkFeature(ResourceLocation id, Decoration step, Feature feature) { - return BCLCommonFeatures.makeChunkFeature(id, step, feature); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeChancedFeature(ResourceLocation id, Decoration step, Feature feature, int chance) { - return BCLCommonFeatures.makeChancedFeature(id, step, feature, chance); - } - - /** - * Deprecated, use function from {@link BCLCommonFeatures} instead. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeCountFeature(ResourceLocation id, Decoration step, Feature feature, int count) { - return BCLCommonFeatures.makeCountFeature(id, step, feature, count); - } - - /** - * Deprecated, use {@link ru.bclib.api.features.BCLFeatureBuilder} instead. - * - * Creates and configures new BCLib feature. - * @param id {@link ResourceLocation} feature ID. - * @param step {@link Decoration} feature step. - * @param feature {@link Feature} with {@link NoneFeatureConfiguration} config. - * @param placementModifiers array of {@link PlacementModifier} - * @return new BCLFeature instance. - */ - @Deprecated(forRemoval = true) - public static BCLFeature makeFeature(ResourceLocation id, Decoration step, Feature feature, PlacementModifier... placementModifiers) { - PlacedFeature configured = feature.configured(FeatureConfiguration.NONE).placed(placementModifiers); - return new BCLFeature(id, feature, step, configured); - } } diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index 77f51198..77f3eb40 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -3,6 +3,7 @@ import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; +import net.minecraft.core.Holder; import net.minecraft.core.Vec3i; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; @@ -50,7 +51,7 @@ public NBTStructureFeature(BlockState defaultBlock){ protected abstract void addStructureData(StructurePlaceSettings data); protected BlockPos getGround(WorldGenLevel world, BlockPos center) { - Biome biome = world.getBiome(center); + Holder biome = world.getBiome(center); ResourceLocation id = BiomeAPI.getBiomeID(biome); if (id.getNamespace().contains("moutain") || id.getNamespace().contains("lake")) { int y = getAverageY(world, center); @@ -148,7 +149,7 @@ public boolean place(FeaturePlaceContext context) { if (!isTerrain(stateSt)) { if (merge == TerrainMerge.SURFACE) { boolean isTop = mut.getY() == surfMax && state.getMaterial().isSolidBlocking(); - Biome b = world.getBiome(mut); + Holder b = world.getBiome(mut); BlockState top = (isTop ? BiomeAPI.findTopMaterial(b) : BiomeAPI.findUnderMaterial(b)).orElse(defaultBlock); BlocksHelper.setWithoutUpdate(world, mut, top); } @@ -159,7 +160,7 @@ public boolean place(FeaturePlaceContext context) { else { if (isTerrain(state) && state.getMaterial().isSolidBlocking()) { if (merge == TerrainMerge.SURFACE) { - Biome b = world.getBiome(mut); + Holder b = world.getBiome(mut); BlockState bottom = BiomeAPI.findUnderMaterial(b).orElse(defaultBlock); BlocksHelper.setWithoutUpdate(world, mut, bottom); } diff --git a/src/main/java/ru/bclib/world/generator/BCLBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLBiomeSource.java index a329a875..d9767866 100644 --- a/src/main/java/ru/bclib/world/generator/BCLBiomeSource.java +++ b/src/main/java/ru/bclib/world/generator/BCLBiomeSource.java @@ -1,5 +1,6 @@ package ru.bclib.world.generator; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.BiomeSource; @@ -11,12 +12,12 @@ public abstract class BCLBiomeSource extends BiomeSource { protected final Registry biomeRegistry; protected final long seed; - private static List preInit(Registry biomeRegistry, List biomes){ + private static List> preInit(Registry biomeRegistry, List> biomes){ biomes.forEach(biome -> BiomeAPI.sortBiomeFeatures(biome)); return biomes; } - protected BCLBiomeSource(Registry biomeRegistry, long seed, List list) { + protected BCLBiomeSource(Registry biomeRegistry, long seed, List> list) { super(preInit(biomeRegistry, list)); this.seed = seed; diff --git a/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java index c689dcb8..95c7aac5 100644 --- a/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java +++ b/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java @@ -1,9 +1,13 @@ package ru.bclib.world.generator; +import com.mojang.datafixers.kinds.Applicative; import com.mojang.serialization.Codec; +import com.mojang.serialization.MapCodec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.resources.RegistryLookupCodec; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.BiomeCategory; @@ -19,6 +23,7 @@ import ru.bclib.config.ConfigKeeper.StringArrayEntry; import ru.bclib.config.Configs; import ru.bclib.interfaces.BiomeMap; +import ru.bclib.mixin.common.BiomeAccessor; import ru.bclib.noise.OpenSimplexNoise; import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.generator.map.hex.HexBiomeMap; @@ -29,19 +34,13 @@ import java.util.function.Function; public class BCLibEndBiomeSource extends BCLBiomeSource { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { - return instance.group(RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.biomeRegistry; - }), Codec.LONG.fieldOf("seed").stable().forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.seed; - })).apply(instance, instance.stable(BCLibEndBiomeSource::new)); - }); + public static Codec CODEC = RecordCodecBuilder.create((instance) -> instance.group(RegistryOps.retrieveRegistry(Registry.BIOME_REGISTRY).forGetter((theEndBiomeSource) -> null), Codec.LONG.fieldOf("seed").stable().forGetter((theEndBiomeSource) -> theEndBiomeSource.seed)).apply(instance, instance.stable(BCLibEndBiomeSource::new))); private static final OpenSimplexNoise SMALL_NOISE = new OpenSimplexNoise(8324); private Function endLandFunction; private final SimplexNoise noise; - private final Biome centerBiome; - private final Biome barrens; + private final Holder centerBiome; + private final Holder barrens; private BiomeMap mapLand; private BiomeMap mapVoid; private final Point pos; @@ -54,11 +53,11 @@ public BCLibEndBiomeSource(Registry biomeRegistry, long seed) { List includeVoid = Configs.BIOMES_CONFIG.getEntry("force_include", "end_void_biomes", StringArrayEntry.class).getValue(); this.possibleBiomes().forEach(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); + ResourceLocation key = biome.unwrapKey().orElseThrow().location(); String group = key.getNamespace() + "." + key.getPath(); if (!BiomeAPI.hasBiome(key)) { - BCLBiome bclBiome = new BCLBiome(key, biome); + BCLBiome bclBiome = new BCLBiome(key, biome.value()); if (includeVoid.contains(key.toString())) { BiomeAPI.END_VOID_BIOME_PICKER.addBiomeMutable(bclBiome); @@ -99,8 +98,8 @@ public BCLibEndBiomeSource(Registry biomeRegistry, long seed) { this.mapVoid = new HexBiomeMap(seed, GeneratorOptions.getBiomeSizeEndVoid(), BiomeAPI.END_VOID_BIOME_PICKER); } - this.centerBiome = biomeRegistry.getOrThrow(Biomes.THE_END); - this.barrens = biomeRegistry.getOrThrow(Biomes.END_BARRENS); + this.centerBiome = biomeRegistry.getOrCreateHolder(Biomes.THE_END); + this.barrens = biomeRegistry.getOrCreateHolder(Biomes.END_BARRENS); WorldgenRandom chunkRandom = new WorldgenRandom(new LegacyRandomSource(seed)); chunkRandom.consumeCount(17292); @@ -110,34 +109,44 @@ public BCLibEndBiomeSource(Registry biomeRegistry, long seed) { this.pos = new Point(); } - private static List getBiomes(Registry biomeRegistry) { + private static List> getBiomes(Registry biomeRegistry) { List includeLand = Configs.BIOMES_CONFIG.getEntry("force_include", "end_land_biomes", StringArrayEntry.class).getValue(); List includeVoid = Configs.BIOMES_CONFIG.getEntry("force_include", "end_void_biomes", StringArrayEntry.class).getValue(); - return biomeRegistry.stream().filter(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - - if (includeLand.contains(key.toString()) || includeVoid.contains(key.toString())) { - return true; - } - - if (GeneratorOptions.addEndBiomesByCategory() && biome.getBiomeCategory() == BiomeCategory.THEEND) { - return true; - } - - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME) { - if (bclBiome.getParentBiome() != null) { - bclBiome = bclBiome.getParentBiome(); - } - key = bclBiome.getID(); - } - return BiomeAPI.END_LAND_BIOME_PICKER.containsImmutable(key) || BiomeAPI.END_VOID_BIOME_PICKER.containsImmutable(key) || (biome.getBiomeCategory() == BiomeCategory.THEEND && BiomeAPI.isDatapackBiome(key)); + return biomeRegistry.stream() + .filter(biome -> biomeRegistry.getResourceKey(biome).isPresent()) + .map(biome -> biomeRegistry.getOrCreateHolder(biomeRegistry.getResourceKey(biome).get())) + .filter(biome -> { + ResourceLocation key = biome.unwrapKey().orElseThrow().location(); + + + if (includeLand.contains(key.toString()) || includeVoid.contains(key.toString())) { + return true; + } + + final boolean isEndBiome; + if ((Object)biome instanceof BiomeAccessor bacc) { + isEndBiome = bacc.bclib_getBiomeCategory() == BiomeCategory.THEEND; + if (GeneratorOptions.addEndBiomesByCategory() && isEndBiome) { + return true; + } + } else { + isEndBiome = false; + } + + BCLBiome bclBiome = BiomeAPI.getBiome(key); + if (bclBiome != BiomeAPI.EMPTY_BIOME) { + if (bclBiome.getParentBiome() != null) { + bclBiome = bclBiome.getParentBiome(); + } + key = bclBiome.getID(); + } + return BiomeAPI.END_LAND_BIOME_PICKER.containsImmutable(key) || BiomeAPI.END_VOID_BIOME_PICKER.containsImmutable(key) || (isEndBiome && BiomeAPI.isDatapackBiome(key)); }).toList(); } @Override - public Biome getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.Sampler sampler) { + public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.Sampler sampler) { long posX = biomeX << 2; long posZ = biomeZ << 2; long farEndBiomes = GeneratorOptions.getFarEndBiomes(); diff --git a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java index 01365eba..4cd6338f 100644 --- a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java +++ b/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java @@ -2,8 +2,10 @@ import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; +import net.minecraft.core.Holder; import net.minecraft.core.Registry; -import net.minecraft.resources.RegistryLookupCodec; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.BiomeCategory; @@ -15,6 +17,7 @@ import ru.bclib.config.ConfigKeeper.StringArrayEntry; import ru.bclib.config.Configs; import ru.bclib.interfaces.BiomeMap; +import ru.bclib.mixin.common.BiomeAccessor; import ru.bclib.world.biomes.BCLBiome; import ru.bclib.world.generator.map.MapStack; import ru.bclib.world.generator.map.hex.HexBiomeMap; @@ -23,13 +26,22 @@ import java.util.List; public class BCLibNetherBiomeSource extends BCLBiomeSource { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { - return instance.group(RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.biomeRegistry; - }), Codec.LONG.fieldOf("seed").stable().forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.seed; - })).apply(instance, instance.stable(BCLibNetherBiomeSource::new)); - }); + + public static final Codec CODEC = RecordCodecBuilder + .create(instance -> instance + .group(RegistryOps + .retrieveRegistry(Registry.BIOME_REGISTRY) + .forGetter(source -> source.biomeRegistry) + , + Codec + .LONG + .fieldOf("seed") + .stable() + .forGetter(source -> source.seed) + ) + .apply(instance, instance.stable(BCLibNetherBiomeSource::new)) + ); + private BiomeMap biomeMap; private static boolean forceLegacyGenerator = false; @@ -61,10 +73,10 @@ public BCLibNetherBiomeSource(Registry biomeRegistry, long seed) { BiomeAPI.NETHER_BIOME_PICKER.clearMutables(); this.possibleBiomes().forEach(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); + ResourceLocation key = biome.unwrapKey().orElseThrow().location(); if (!BiomeAPI.hasBiome(key)) { - BCLBiome bclBiome = new BCLBiome(key, biome); + BCLBiome bclBiome = new BCLBiome(key, biome.value()); BiomeAPI.NETHER_BIOME_PICKER.addBiomeMutable(bclBiome); } else { @@ -85,33 +97,42 @@ public BCLibNetherBiomeSource(Registry biomeRegistry, long seed) { initMap(); } - private static List getBiomes(Registry biomeRegistry) { + private static List> getBiomes(Registry biomeRegistry) { List include = Configs.BIOMES_CONFIG.getEntry("force_include", "nether_biomes", StringArrayEntry.class).getValue(); - - return biomeRegistry.stream().filter(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - - if (include.contains(key.toString())) { - return true; - } - - if (GeneratorOptions.addNetherBiomesByCategory() && biome.getBiomeCategory() == BiomeCategory.NETHER) { - return true; - } - - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME) { - if (bclBiome.getParentBiome() != null) { - bclBiome = bclBiome.getParentBiome(); - } - key = bclBiome.getID(); - } - return BiomeAPI.NETHER_BIOME_PICKER.containsImmutable(key) || (biome.getBiomeCategory() == BiomeCategory.NETHER && BiomeAPI.isDatapackBiome(key)); + + return biomeRegistry.stream() + .filter(biome -> biomeRegistry.getResourceKey(biome).isPresent()) + .map(biome -> biomeRegistry.getOrCreateHolder(biomeRegistry.getResourceKey(biome).get())) + .filter(biome -> { + ResourceLocation key = biome.unwrapKey().orElseThrow().location(); + + if (include.contains(key.toString())) { + return true; + } + + if (GeneratorOptions.addNetherBiomesByCategory() && (biome instanceof BiomeAccessor) && ((BiomeAccessor)(Object)biome).bclib_getBiomeCategory()== BiomeCategory.NETHER) { + return true; + } + + BCLBiome bclBiome = BiomeAPI.getBiome(key); + if (bclBiome != BiomeAPI.EMPTY_BIOME) { + if (bclBiome.getParentBiome() != null) { + bclBiome = bclBiome.getParentBiome(); + } + key = bclBiome.getID(); + } + final boolean isNetherBiome; + if ((Object)biome instanceof BiomeAccessor bacc) { + isNetherBiome = bacc.bclib_getBiomeCategory() == BiomeCategory.NETHER; + } else { + isNetherBiome = false; + } + return BiomeAPI.NETHER_BIOME_PICKER.containsImmutable(key) || (isNetherBiome && BiomeAPI.isDatapackBiome(key)); }).toList(); } @Override - public Biome getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.Sampler var4) { + public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.Sampler var4) { if (lastWorldHeight != worldHeight) { lastWorldHeight = worldHeight; initMap(); diff --git a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java index 9af93ebb..93b404ae 100644 --- a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java +++ b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java @@ -1,17 +1,27 @@ package ru.bclib.world.structures; import com.google.common.collect.Lists; -import net.fabricmc.fabric.api.structure.v1.FabricStructureBuilder; import net.minecraft.core.BlockPos; +import net.minecraft.core.Holder; import net.minecraft.core.QuartPos; -import net.minecraft.data.BuiltinRegistries; +import net.minecraft.core.Registry; +import net.minecraft.data.worldgen.StructureSets; +import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.TagKey; +import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.levelgen.GenerationStep; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; +import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.pieces.PieceGeneratorSupplier; +import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement; +import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadType; +import ru.bclib.api.tag.TagAPI; +import ru.bclib.mixin.common.StructureFeatureAccessor; +import ru.bclib.mixin.common.StructureFeaturesAccessor; import java.util.List; import java.util.Random; @@ -19,23 +29,40 @@ public class BCLStructureFeature { private static final Random RANDOM = new Random(354); private final StructureFeature structure; - private final ConfiguredStructureFeature featureConfigured; + private final Holder> featureConfigured; private final GenerationStep.Decoration featureStep; private final List biomes = Lists.newArrayList(); private final ResourceLocation id; - + public final TagKey biomeTag; + public final ResourceKey> structureKey; + public final ResourceKey structureSetKey; + public final RandomSpreadStructurePlacement spreadConfig; + public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation) { + this(id, structure, step, spacing, separation, false); + } + public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation, boolean adaptNoise) { this.id = id; this.featureStep = step; - this.structure = FabricStructureBuilder - .create(id, structure) - .step(step) - .defaultConfig(spacing, separation, RANDOM.nextInt(8192)) - .register(); - this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); - BuiltinRegistries.register(BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE, id, this.featureConfigured); - //TODO: 1.18 check if structures are added correctly - //FlatChunkGeneratorConfigAccessor.getStructureToFeatures().put(this.structure, this.featureConfigured); + //parts from vanilla for Structure generation + //public static final ResourceKey> JUNGLE_TEMPLE = + // BuiltinStructures.createKey("jungle_pyramid"); + //public static final Holder> JUNGLE_TEMPLE = + // StructureFeatures.register(BuiltinStructures.JUNGLE_TEMPLE, StructureFeature.JUNGLE_TEMPLE.configured(NoneFeatureConfiguration.INSTANCE, BiomeTags.HAS_JUNGLE_TEMPLE)); + //public static final Holder JUNGLE_TEMPLES = + // StructureSets.register(BuiltinStructureSets.JUNGLE_TEMPLES, StructureFeatures.JUNGLE_TEMPLE, new RandomSpreadStructurePlacement(32, 8, RandomSpreadType.LINEAR, 14357619)); + //public static final StructureFeature JUNGLE_TEMPLE = + // StructureFeature.register("jungle_pyramid", new JunglePyramidFeature(NoneFeatureConfiguration.CODEC), GenerationStep.Decoration.SURFACE_STRUCTURES); + // + + this.spreadConfig = new RandomSpreadStructurePlacement(spacing, separation, RandomSpreadType.LINEAR, RANDOM.nextInt(8192)); + this.structureKey = ResourceKey.create(Registry.CONFIGURED_STRUCTURE_FEATURE_REGISTRY, id); + this.structureSetKey = ResourceKey.create(Registry.STRUCTURE_SET_REGISTRY, id); + + this.biomeTag = TagAPI.makeBiomeTag(id.getNamespace(), "has_structure/"+id.getPath()); + this.structure = StructureFeatureAccessor.callRegister(id.toString(), structure, step); + this.featureConfigured = StructureFeaturesAccessor.callRegister(structureKey, this.structure.configured(NoneFeatureConfiguration.NONE, biomeTag, adaptNoise)); + StructureSets.register(structureSetKey, featureConfigured, spreadConfig); } /** @@ -69,7 +96,7 @@ public StructureFeature getStructure() { return structure; } - public ConfiguredStructureFeature getFeatureConfigured() { + public Holder> getFeatureConfigured() { return featureConfigured; } diff --git a/src/main/resources/assets/bclib/lang/de_de.json b/src/main/resources/assets/bclib/lang/de_de.json index bd83c0c9..5038c9bf 100644 --- a/src/main/resources/assets/bclib/lang/de_de.json +++ b/src/main/resources/assets/bclib/lang/de_de.json @@ -52,5 +52,7 @@ "title.bclib.datafixer.error": "Fehler beim Reparieren der Welt", "message.bclib.datafixer.error": "Es gab Fehler beim Reparieren der Welt. Das bedeutet, dass dieser Level wahrscheinlich in einem inkonsistenten Zustand ist und Sie ihn nicht spielen sollten. Bitte stellen Sie Ihr Backup wieder her und beheben Sie die unten aufgeführten Fehler, bevor Sie es erneut versuchen.", "title.bclib.datafixer.error.continue": "Continue and Mark as Fixed", - "title.config.bclib.main.ui.suppressExperimentalDialogOnLoad": "Disable Experimental Warning Screen on Load" + "title.config.bclib.main.ui.suppressExperimentalDialogOnLoad": "Disable Experimental Warning Screen on Load", + + "tooltip.bclib.place_on": "Lebt auf: %s" } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/lang/en_us.json b/src/main/resources/assets/bclib/lang/en_us.json index 4cd68730..977e7f06 100644 --- a/src/main/resources/assets/bclib/lang/en_us.json +++ b/src/main/resources/assets/bclib/lang/en_us.json @@ -54,5 +54,7 @@ "title.bclib.datafixer.error.continue": "Proceed and mark as fixed", "title.config.bclib.client.rendering.customFogRendering": "Custom Fog Rendering", - "title.config.bclib.client.rendering.netherThickFog": "Nether Thick Fog" + "title.config.bclib.client.rendering.netherThickFog": "Nether Thick Fog", + + "tooltip.bclib.place_on": "Survives on: %s" } \ No newline at end of file diff --git a/src/main/resources/bclib.accesswidener b/src/main/resources/bclib.accesswidener index 9fc24c46..5a5692b6 100644 --- a/src/main/resources/bclib.accesswidener +++ b/src/main/resources/bclib.accesswidener @@ -1,6 +1,7 @@ accessWidener v1 named # Classes +accessible class net/minecraft/server/MinecraftServer$ReloadableResources accessible class net/minecraft/client/Minecraft$ExperimentalDialogType accessible class net/minecraft/world/level/levelgen/SurfaceRules$Context accessible class net/minecraft/world/level/levelgen/SurfaceRules$Condition diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index ce5d3e64..041d5576 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -4,7 +4,6 @@ "package": "ru.bclib.mixin.client", "compatibilityLevel": "JAVA_17", "client": [ - "SimpleReloadableResourceManagerMixin", "EnchantingTableBlockMixin", "ClientRecipeBookMixin", "ModelManagerMixin", @@ -14,7 +13,8 @@ "ModelBakeryMixin", "WorldPresetMixin", "MinecraftMixin", - "GameMixin" + "GameMixin", + "BlockMixin" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 98e434cd..52029a3f 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -4,7 +4,6 @@ "package": "ru.bclib.mixin.common", "compatibilityLevel": "JAVA_17", "mixins": [ - "SimpleReloadableResourceManagerMixin", "BiomeGenerationSettingsAccessor", "shears.DiggingEnchantmentMixin", "shears.ItemPredicateBuilderMixin", @@ -13,7 +12,6 @@ "NoiseGeneratorSettingsMixin", "SurfaceRulesContextAccessor", "shears.TripWireBlockMixin", - "StructureSettingsAccessor", "MobSpawnSettingsAccessor", "shears.BeehiveBlockMixin", "shears.PumpkinBlockMixin", @@ -21,8 +19,8 @@ "ComposterBlockAccessor", "PotionBrewingAccessor", "RecipeManagerAccessor", + "DiggerItemAccessor", "shears.SnowGolemMixin", - "EnchantmentMenuMixin", "MinecraftServerMixin", "NetherBiomeDataMixin", "PistonBaseBlockMixin", @@ -42,7 +40,10 @@ "AnvilBlockMixin", "AnvilMenuMixin", "TagLoaderMixin", - "MainMixin" + "MainMixin", + "BiomeAccessor", + "StructureFeatureAccessor", + "StructureFeaturesAccessor" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 420a79b0..764249f2 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -37,9 +37,9 @@ "bclib.mixins.client.json" ], "depends": { - "fabricloader": ">=0.12.9", - "fabric": ">=0.44.0", - "minecraft": "1.18.x" + "fabricloader": ">=0.13.3", + "fabric": ">=0.48.0", + "minecraft": "1.18.2" }, "custom":{ "modmenu":{